Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable or pass variable via Bundle? [duplicate]

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");
like image 245
stefana Avatar asked Sep 22 '26 05:09

stefana


2 Answers

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.

like image 83
GrIsHu Avatar answered Sep 24 '26 18:09

GrIsHu


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.

like image 20
Ruban Avatar answered Sep 24 '26 20:09

Ruban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!