3

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");
stefana
  • 2,606
  • 3
  • 29
  • 47
  • 1
    As for me, I would use bundle option. I mean, if you need only to pass something from FIRST activity to SECOND - why would you create a static variable, which would be alive much more than you need? By the way, there obviously exists a one-line solution: `String example = getIntent().getStringExtra("example")`. This seems much more clean to me. – Scadge Jan 16 '14 at 10:06
  • @Scadge that's the eye opener I needed, thanks! – stefana Jan 16 '14 at 10:08
  • Well, welcome. But anyway I'd advise you to read something about passing variables between activities, maybe like the one given in the first comment. – Scadge Jan 16 '14 at 10:09

3 Answers3

2

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.

Bhavin Nattar
  • 3,189
  • 2
  • 22
  • 30
Ruban
  • 1,514
  • 2
  • 14
  • 21
  • 1
    Be careful with static variables as Android may garbage collect them, specially when the device run low on memory. – s1m3n Jan 16 '14 at 10:42
  • @s1m3n Android may not garbage-collect them, it just kills and re-starts application's process. – Miha_x64 Jan 23 '18 at 17:52
2

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.

Stéphane
  • 11,755
  • 7
  • 49
  • 63
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
1

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")
Anjali Tripathi
  • 1,477
  • 9
  • 28