Reputation: 5
What is the difference? I am learning from tutorial how to pass a string from one to another activity and this person uses following code in order to take info from EditText of Data and pass it to TextView of OpenedClass:
public class Data {
EditText sendET;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bSA:
String bread=sendET.getText().toString();
Bundle basket=new Bundle();
basket.putString("key", bread);
Intent a= new Intent(Data.this, OpenedClass.class);
a.putExtras(basket);
startActivity(a);
break;
}
}
//end here is the other class
public class OpenedClass{
@Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
setContentView(R.layout.send);
Bundle gotBasket=getIntent().getExtras();
gotBread=gotBasket.getString("key");
question.setText(gotBread);
}
}
Can't I just replace last 3 lines in OpenedClass with:
question.setText(Data.sendET.getText().toString());
and avoid creating Bundle, adding Extras, etc in Data class. What is the difference and why should i go for the more complicated one as visually it brings the same result.
Upvotes: 0
Views: 31
Reputation: 35661
If your activity loses focus (a phone call comes in perhaps), there is no guarantee that your activity will still be in memory when it resumes.
If the system kills it for any reason, everything in the activity is lost. The Extras however, will be retained as part of the Activity. You can then recreate your state.
To make it easier to handle my Extras\Activities, I usually add a static method to them to handle the bundle creation and Launch.
Starting an Activity is then as simple as calling this method.
e.g
public static void Launch(Activity oldActivity, int parameter) {
Intent i = new Intent(oldActivity, ThisActivity.class);
i.putExtra("PARAM", parameter);
oldActivity.startActivity(i);
}
Upvotes: 0
Reputation: 969
The EditText in the Data (I will assume it extends Activity), will have a reference of that Activity's context. If you make sendET static, you will statically reference the context of that activity. When that Data activity is finished, you will leak its context through the static sendET EditText
Upvotes: 1