This question already has an answer here:
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");
Use this code..It may be help you..
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.
Its always better to use the
Intent
besides usingstatic
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.