Static variable or pass variable via Bundle? [dupl

2019-04-11 21:53发布

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");

3条回答
Viruses.
2楼-- · 2019-04-11 22:15

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")
查看更多
女痞
3楼-- · 2019-04-11 22:26

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.

查看更多
不美不萌又怎样
4楼-- · 2019-04-11 22:33

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.

查看更多
登录 后发表回答