【发布时间】:2020-02-14 07:14:36
【问题描述】:
我想要一个列表视图。但我遇到了错误。
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.photoapp/com.example.photoapp.ViewAdmins}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
这是我的代码。
public class ViewAdmins extends AppCompatActivity {
SyncAdminsDatabaseHelper mSyncAdminsDatabaseHelper;
private ListView ymListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
ymListView = (ListView) findViewById(R.id.listviewadmins);
mSyncAdminsDatabaseHelper = new SyncAdminsDatabaseHelper(this);
//call method populateListView();
populateListView();
}
private void populateListView(){
//get the data to append in the list view
Cursor data = mSyncAdminsDatabaseHelper.getData();
if(data.getCount() == 0){
toastMessage("The database is empty.");
}else{
//Create an Array list
ArrayList<String> listData = new ArrayList<>();
//Store the result in array using while loop
while (data.moveToNext()){
//get the value from the database in column 1
//than add to array list
listData.add(data.getString(0));
}
System.out.println(listData);
// //create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listData);
ymListView.setAdapter(adapter);
}
}
我想将应用表中的数据显示到列表视图。但由于某种原因,我的列表视图没有正确呈现数据。
我的问题是如何从 SQLite 表中获取数据并显示在列表视图中。
以及如何在列表视图中显示多个字段。
Activity_view_admins.xml 代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewAdmins">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listviewadmins">
</ListView>
</LinearLayout>
【问题讨论】:
-
我的问题与android studio中的ListView有关。
-
你能贴出activity_view_data.xml的listview组件吗
-
我已在标题 Activity_view_admins.xml 代码下方的主要问题中添加了 xml 代码
标签: java android-studio listview adapter