Reputation: 3130
I have a ListFragment and I want to edit item when clicked in List View.
I am using this method.
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(dbHelper != null){
Item item = dbHelper.getProjectRowById(id);
Intent intent = new Intent(getActivity(), Save.class);
//Here i want to start the activity and set the data using item.
}
}
How do i set data in above method.
Thanks in advance
Upvotes: 2
Views: 285
Reputation: 11814
Use
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(dbHelper != null){
//don't do this here Item item = dbHelper.getProjectRowById(id);
Intent intent = new Intent(getActivity(), Save.class);
intent.putExtra("MyItemId", id);
}
}
In your second activity, you get the Id and load the element with
Bundle extras = getIntent().getExtras();
long id = extras.getInt("MyItemId");
Item item = dbHelper.getProjectRowById(id);
Your need dbHelper there, too. If you want only one instance of it, make it a variable of your App class.
Upvotes: 0
Reputation: 9190
You can send extra data along with an Intent when you start a new Activity.
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(dbHelper != null){
Item item = dbHelper.getProjectRowById(id);
// Put the data on your intent.
Intent intent = new Intent(getActivity(), Save.class);
// If Item implements Serializable or Parcelable, you can just send the item:
intent.putExtra("dataToEdit", item);
// Otherwise, send the relevant bit:
intent.putExtra("data1", item.getSomeDataItem());
intent.putExtra("data2", item.getAnotherDataItem());
// Or, send the id and look up the item to edit in the other activity.
intent.putExtra("id", id);
// Start your edit activity with the intent.
getActivity().startActivity(intent);
}
}
In the edit activity, you can get the Intent that started it.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Intent intent = getIntent();
if (intent.hasExtra("dataToEdit")) {
Item item = (Item) intent.getSerializableExtra("dataToEdit");
if (item != null) {
// find edittext, and set text to the data that needs editing
}
}
}
Then the user can edit that text, and you can save it to the database when they click save or whatever. Then call finish
on your save activity.
If you need to send the saved data back to the original activity (instead of, say, just requerying in onStart
), look into startActivityForResult
. If you use that, you can set a result code with setResult
before calling finish
.
Upvotes: 1