当我按下按钮打开另一个包含2个文本字段和保存并取消按钮的活动时,会弹出此错误消息。正在向保存功能中的这部分代码指出错误 -
listView.setAdapter(adapter);
完全错误
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
保存功能的Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
Button btnSave = (Button) findViewById(R.id.btnSave);
ListView listView = (ListView) findViewById(R.id.listDisp);
arrayList = new ArrayList<>();
edName = (EditText) findViewById(R.id.editName);
edMobile = (EditText) findViewById(R.id.editMobile);
adapter = new ArrayAdapter<Classes>(this, R.layout.activity_add, R.id.txtItem, arrayList);
Log.i("test", " " + arrayList.size());
listView.setAdapter(adapter);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Classes class1 = new Classes(edName.getText().toString(), edMobile.getText().toString());
arrayList.add(class1);
adapter.notifyDataSetChanged();
Log.i("test", " " + arrayList.size());
try {
FileOutputStream fos = openFileOutput("Saves.tim", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
用于加载功能的Java
private ViewPager viewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
ListView lv;
public static ArrayList<Classes> arrayList;
private ArrayAdapter<Classes> adapter;
private EditText etName, etMobile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listDisp);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etName = (EditText) findViewById(R.id.editName);
etMobile = (EditText) findViewById(R.id.editMobile);
Button btSave = (Button) findViewById(R.id.btnSave);
arrayList = new ArrayList<>();
try {
FileInputStream fis = this.openFileInput("Saves.tim");
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<Classes>) ois.readObject();
ois.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch(ClassNotFoundException ex){
ex.printStackTrace();
}
启动活动的方法
public void loadAddActivity (View v)
{
startActivity(new Intent(this,AddActivity.class));
}
答案 0 :(得分:2)
您的错误正在发生,因为listView未初始化。我看到你试图初始化它。我的猜测是,R.id.listDisp
ID不存在,或者不是R.layout.activity_add
的一部分,这是您在此课程中夸大的布局。
TL; DR。由于这一行而发生错误:
ListView listView = (ListView) findViewById(R.id.listDisp);
listDisp
不是activity_add
布局
答案 1 :(得分:1)
您的布局activity_add
可能没有ID为listDisp