Reputation: 1967
I have two activities - one displays data from SQLite, and the other adds data there. I can switch between them with tabs. The problem is that if I add a new item I don't know how to refresh the list, because it's in a different activity class and I can't access it in my adding class. How can this be solved?
Here is my two classes:
List:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
final ShoppingSQL shoppingSQL = new ShoppingSQL(this);
final List<ShoppingData> list = shoppingSQL.getAll();
final ArrayAdapter<ShoppingData> adapter = new ArrayAdapter<ShoppingData>(
this, android.R.layout.simple_list_item_1, list);
setListAdapter(adapter);
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
shoppingSQL.delete((int)list.get(position).getId());
adapter.remove(list.get(position));
adapter.notifyDataSetChanged();
return true;
}
});
}
Add:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
public void ButtonOnClick(View v) {
ShoppingSQL shoppingSQL = new ShoppingSQL(this);
ShoppingData data = new ShoppingData();
data.setName("test");
shoppingSQL.add(data);
Dialog d = new Dialog(this);
d.setTitle("Added!");
d.show();
}
I also have a little sidequestion. In my first (list) activity, Eclipse made every variable final when I accessed them in "onLongClick" - why is that and can that be avoided? Also any comment on what I should look in to as well and make my code better or any other mistakes I made would be very good.
Upvotes: 2
Views: 1054
Reputation: 8978
I'd keep it simple. Just send an intent from Add class to List class and then your list will be populated again with new items.
Upvotes: 2
Reputation: 1547
What you want to use is a CursorLoader that is connected to your SQLite DB (see http://developer.android.com/reference/android/content/CursorLoader.html). Then, you can use, e.g., a ListView whose adapter synchronizes with the CursorLoader. This is done (more or less) automatically using the listener pattern.
In the activity that adds the data, you then need to notify all listeners that the data has changed. Typically, you do this by calling notifyChange (see http://developer.android.com/reference/android/content/ContentResolver.html#notifyChange%28android.net.Uri,%20android.database.ContentObserver,%20boolean%29).
You might also want to think about implementing your own content provider.
Upvotes: 1