问题
For example, i have 3 activities.. I also use Tab host with separate activity when switch tab widget.
1) FoodTypeListActivity.class
:there is a list of food type i.e. Breakfast, Dinner, Lunch..
2) MainTabActivity.class
: Tabhost which has 3 tab widget
3) FoodListActivity.class
: this activity is one of tab widget
I have a headlabel in layout of MainTabActivity.class
which will show type of food as Textview from the previous activity(FoodTypeListActivity.class
)
The problem is; i want to send the name of type of food from (FoodTypeListActivity.class
) to set as headlabel in (MainTabActivity.class
) and send id of food type (FoodTypeListActivity.class
) to (FoodListActivity.class
)
How do i implement putExtra to send data to different activity in on ListItem click of FoodTypeListActivity.class
Now i have the the following code in FoodTypeListActivity.class
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(position==0){
Intent i = new Intent(FoodTypeListActivity.this, MainTabActivity.class);
i.putExtra("foodTypeID", 3);
i.putExtra("foodTypeName", "Breakfast");
startActivity(i);
}
}
});
Thanks you
回答1:
You should just use shared preference.
In your listview click use this to put the values in shared preference.
SharedPreferences items = getSharedPreferences("my_food_data", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("foodTypeID", 3);
editor.putString("foodTypeName", "Breakfast");
editor.commit(); //VERY important
Now to pull the data out in ANY activity use..
SharedPreferences items = getSharedPreferences("my_food_data", 0);
int foodId = settings.getInt("foodTypeId", 0);
String foodTitle = items.getString("foodTypeName", "No Name"); //the default value of of "no name will be used if nothing is in the preference file.
I think this works well for what you are trying to do.
回答2:
That looks exactly correct. Now on your receiving activity just use the following code to retrieve your value.
int foodTypeId = getIntent().getIntExtra("foodTypeID", -1);
String foodTypeName= getIntent().getStringExtra("foodTypeName");
The -1 is the default value if there is not value with the given key. That default value should never actually be needed unless you forget to pass in a value using the given key.
来源:https://stackoverflow.com/questions/8782765/how-to-put-extras-to-different-activity