Reputation: 17
I have two activities MainActivity
and Additem
in MainActivity I have this method:
public void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
null,null,null,null,null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[] { TaskContract.Columns.TASK},
new int[] { R.id.taskTextView},
0
);
ListView listView = (ListView)findViewById(R.id.list);
listView.setAdapter(listAdapter);
}
It updates the tasklist
on the Mainscreen
.
But when I use updateUI()
; in Additem
, on saving the task it returns back but the app crashes en restarts itself.
As error I got this:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
This is my code where I use updateUI() in Additem:
public void saveItem(View view){
EditText editText = (EditText)findViewById(R.id.editText);
String task = editText.getText().toString();
Log.d("Additem", task);
helper = new TaskDBHelper(Additem.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values,
SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
finish();
}
Could someone help me with this problem?
Thanks in advance,
Kind regards, Selin
Upvotes: 1
Views: 237
Reputation: 8034
Your listview is null and when you call it from other activity [when the MainActivity is paused/stopped] you are actually doing null.setAdapter
which is causing crash.
You should post some sort of event to MainActivity and update the list/adapter when MainActivity resumes. OR you can always refresh/update the adapter in onCreate
/onResume
of MainActivity.
Upvotes: 2
Reputation: 3783
I would suggest you to initialize the listView
and listAdapter
in your MainActivity
and in update UI just refresh your view by using
listAdapter.notifyDataSetChanged()
Upvotes: 0