问题
how can i pass the value or the position of the selected item in listview to a new activity tha will use that value to retrieve data from database in listview (in the new activity)
i have code that it works but always pass a null value for the position that has been passed.
my code for the first activity :
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert HERE THE VALUE IS CORRECT-----
// Toast.makeText(getApplicationContext(),
// "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
// .show();
Intent myIntent = new Intent(view.getContext(), ShowWhereToGo1.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.putExtra("id", itemPosition);
startActivityForResult(myIntent, 0);
}
});
The second activity:
Bundle extras = getIntent().getExtras();
String temp = extras.getString("id");
Toast.makeText(getApplicationContext(),
"Position :"+temp , Toast.LENGTH_LONG)
.show();
}
also i tried in the second activity that code but still pass null value:
Intent in = this.getIntent();
String name = in.getStringExtra("id");
Toast.makeText(getApplicationContext(),
"Position :"+name , Toast.LENGTH_LONG)
.show();
Is there any other way to pass and retrieve the values between activities?
回答1:
use
Bundle extras = getIntent().getExtras();
if (extras != null)
String temp = extras.getInt("id");
instead of extras.getString("id")
because you are passing Integer from ListView click
来源:https://stackoverflow.com/questions/19565957/passing-the-position-from-listview-to-new-activity