Reputation: 1084
I'm sorry to write about what seems to be a common problem, but I've already been on this one task for five hours, and I simply give up.
I'm making a small android app, all it's supposed to do right now is keep a small SQLite database and be able to write/edit notes on it. Everything works fine with SQL, my problem is with the ListView. No matter what I do, it just refuses to update when I add a new note. The only way to view the new note is when I enter edit mode in another and come back out.
Here's the relevant part of the source:
public class MainActivity extends Activity {
ArrayAdapter<NoteItem> mAdapter;
public static NoteDataBase ndb;
ListView listView;
ArrayList a;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ndb = new NoteDataBase(this);
a = ndb.getAllNotes();
//LISTVIEW DO NOT TOUCH
/***********/ mAdapter = new ArrayAdapter<NoteItem>(this,
/***********/ android.R.layout.simple_list_item_1, a);
/***********/ listView = (ListView) findViewById(R.id.listView1);
/***********/ listView.setAdapter(mAdapter);
//*****************
}
//New Note button
public void newNoteAction(View view){
ndb.addNote(new NoteItem("Title", "Contents"));
a = ndb.getAllNotes();
mAdapter = new ArrayAdapter<NoteItem>
(this, android.R.layout.simple_list_item_1, a);
mAdapter.notifyDataSetChanged();
System.out.println(ndb.getAllNotes().size());
}
The print at the end is just to see if it's actually creating the new note.
I hope I gave enough info, tell me if you need anything else. I tried almost everything that I read already, but after almost five hours on one task, there's a point where I'm gonna go crazy :)
Thanks,
Shef
Upvotes: 3
Views: 2551
Reputation: 1728
public void newNoteAction(View view){
ndb.addNote(new NoteItem("Title", "Contents"));
// don't do this
// you are creating a new adapter and not binding it back to listview
// a = ndb.getAllNotes();
// mAdapter = new ArrayAdapter<NoteItem>(this, android.R.layout.simple_list_item_1, a);
mAdapter.add(new NoteItem("Title", "Contents"));
mAdapter.notifyDataSetChanged();
System.out.println(ndb.getAllNotes().size());
}
Upvotes: 3
Reputation: 30634
Looks like the problem is that you're creating a new instance of ArrayAdapter
and adding to it, which isn't associated with the ListView
.
notifyDataSetChanged()
will send events to whatever is listening - the ListView
is listening to the old adapter.
Upvotes: 1
Reputation: 631
It seems like you wanted to update the adapter but instead you're creating a new adapter. Here, if you just call listView.setAdapter(mAdapter)
again, it would set this new adapter to the ListView
and it would work.
But creating a new adapter every time isnt a good way to do it. Since you're using a database, try reading up on CursorAdapter.
Upvotes: 0