Reputation: 117
So, I have MainActivity with ArrayList< MyObject>, ListView for display it and EditActivity to get UI for editing items. Adapter for ListView extends ArrayAdapter< MyObject>. When user click on item I want to start EditActivity with object for editing. How could I put the object to EditActivity? I have:
Intent i = new Intent(this, EditActivity.class);
startActivity(i);
how could I get the object in EditActivity? Of course, I could declare ArrayList< MyObject> as static and put index of the item with:
Intent i = new Intent(this, EditActivity.class);
i.putExtra("index", iItemIdex);
startActivity(i);
and then, in EditActivity, get it like:
int iIndex = getIntent().getExtras().getInt("index");
MyObject o = MainActivity.MyArray.get(iIndex);
but I guess that is not best decision :-)
Upvotes: 1
Views: 821
Reputation: 9367
You don't have to declare your List static. Here is the code you should have to get it to work (one possibility) :
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
MyObjectClass obj = (MyObjectClass) arg0.getAdapter().getItem(arg2);
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("myKey", obj);
startActivity(intent);
}
This way there is no useless static variables, and you are using the method the way it has been made for. One of the easiest and cleanest solution IMO.
Be carefull, to use this method, your have to redefine the getItem(int)
method in your custom ArrayAdapter
. You should do this :
@Override
public MyObjectClass getItem(int position) {
return this.myList.get(position);
}
EDIT : Then if you want to be able to remove items, I think you should put the whole list containing your objects in the intent (don't declare it static). Then just call add()/remove() methods, and when you want to update UI to show the modifed list, just call notifyDataSetChanged() on your custom ArrayAdapter, for example when returning in MainActivity :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
yourListAdater.notifyDataSetChanged();
/* Assuming you have a reference pointing to your adapter in your MainActivity, if you don't just do: ((MyCustomAdapterClass) myListView.getAdapter()).notifyDataSetChanged(); */
}
Upvotes: 0
Reputation: 9778
If you want to edit a ListView
, you just edit the ArrayAdapter
by using its add
, insert
, remove
, and clear
functions on the Adapter.
After you've done that, you call the notifyDataSetChanged()
to notify that the contents of the ArrayAdapter
have changed. Your ListView
will be updated with the new values.
Upvotes: 1