2

In my application, there is a SqlLite database with a table containing a list of messages. Each message has a "sender" and a "body".

I have an activity containing a ListView that simply displays all of the messages in the database using a cursor and cursor adapter. Here is the relevant code:

    Cursor cursor = mDbAdapter.fetchAllMessages();
    String[] from = { MessageDbAdapter.KEY_SENDER, MessageDbAdapter.KEY_BODY };
    int[] to = { R.id.TextSender , R.id.TextMessage };
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.messagerow, cursor, from, to);
    mMessageList.setAdapter(adapter);

In my application, there is a service running in the background that can insert new messages to the database at any time (the user may or may not be looking at the list activity).

My question is the following: if the user is viewing the list activity and a new message is added to the database, how can I make the ListView reflect this change (display the newly added message)

I have considered making the service fire a broadcast when a message has been added to the database. Then, when the activity receives this broadcast, perform the query again. However, I fear that it is inefficient to fetchAllMessages() when I know that only 1 message has been added, especially since messages might be added often

jwheels
  • 517
  • 1
  • 7
  • 23
  • How about registering a broadcast receiver that will listen to an Intent sent by your Service. When that Intent is received, update the ListView within your Activity. – hooked82 Aug 22 '11 at 15:26
  • please read my new edit to the question. – jwheels Aug 22 '11 at 15:27
  • You can call get getChildAd(int index) and update the single row, if only one was updated. See this post: http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row – hooked82 Aug 22 '11 at 15:38
  • You might want to consider using a Loader, it simplifies these problems – Pikaling Aug 22 '11 at 15:49
  • You can try to just call Cursor.requery() from your reciever method. And then call adapter.notifyDataSetChanged(), and as Vicki said...loader might come in handy since the startManagingCursor(Cursor c) is being deprecated. – nahwarang Aug 22 '11 at 19:15

0 Answers0