我制作了仅包含ListView
的布局。在我的主要布局中,我有一个按钮。单击该按钮后,我需要带有ListView
的布局以弹出包含ListView
的项目。 ListView
将从数据库中读取数据,但目前我只处理伪数据。
我尝试将数组适配器传递给ListView
,但它总是告诉我它是一个空对象。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tableview);
//machines
machinesListButton = findViewById(R.id.machine_show);
final ArrayList<String> arrayList = new ArrayList<>();
machinesListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arrayList.add("test1");
arrayList.add("test2");
Dialog dialog = new Dialog(FileActivity.this);
dialog.setContentView(R.layout.activity_file_machines_list);
dialog.setTitle("title");
dialog.setCancelable(true);
machinesListView = findViewById(R.id.machinesListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList);
machinesListView.setAdapter(arrayAdapter);
machinesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
dialog.show();
}
});
}
这是错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mobics.medical, PID: 32538
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.mobics.medical.FileActivity$1.onClick(FileActivity.java:110)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25889)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)enter code here
答案 0 :(得分:1)
您可以尝试:
machinesListView = dialog.findViewById(R.id.machinesListView);
这是因为您的列表视图ID R.id.machinesListView
处于这种布局activity_tableview