This question already has an answer here:
-
What's the best way to share data between activities?
14 answers
Lets say I have a ListView and I set an OnItemClickListener on the list. What would be the best way to pass a variable?
Static variable:
public static String example;
// onItemClick
Intent intent = new Intent(Main.this, Details.class);
Main.example = "example";
startActivity(intent);
// in onCreate of Details
String example = Main.example;
Bundle:
// onItemClick
Intent intent = new Intent(Main.this, Details.class);
intent.putExtra("example","example");
startActivity(intent);
// in onCreate of Details
Bundle extras = getIntent().getExtras();
String example = extra.getString("example");
// or
Intent intent = getIntent();
String example = intent.getStringExtra("example");
Its always better to use the Intent
besides using static
variables. Use static variables whenever you do not want to use it long in your application through out. As it occupies memory and does not easily get garbage collected.
So, it's always better to use 'Intent' to pass variable to other Activity.
If you want the variable to be used all over the application then use static variable or singleton class ( i.e make the getter setter model class as singleton ).
Static variables won't be easily garbage collected so don't use it unless you need it.
If you want to send the data from one activity to other(not through out the application) then use bundle.
Use this code..It may be help you..
public String example;
// onItemClick
Intent intent = new Intent(Main.this, Details.class);
intent.putExtra("id",example);
startActivity(intent);
// on Details activtiy
Intent intent =getIntent().getStringExtra("id")