Evan Evan - 1 month ago 6
Android Question

Static variable not seen in another activity

I have this problem; I'm creating an android app and I want to get what the user inputs in an EditText and display it on the app in a new Activity. But I've tried using a static variable and it's not working, it returns nothing / blank. Output shows literally: 'S STATS. Instead of TOBY'S STATS, for instance (whatever name the user inputs). Can anybody tell me what I'm doing wrong please? Thx in advance.

public class ChooseCatName extends AppCompatActivity {
public static String name;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_cat_name);

Button b = (Button) findViewById(R.id.buttonStart);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newActivity(v);
}
});

EditText e = (EditText) findViewById(R.id.editTextCatsName);
name = e.getText().toString();
}

public void newActivity(View view) {
Intent intent = new Intent(this, CatStatus.class);
startActivity(intent);
}
public static String getName(){
return name;
}
}


In new activity:

TextView textName = (TextView) findViewById(R.id.CatsTitleStats);

textName.setText(ChooseCatName.getName() + "'S STATS");

Answer

It's simple you are using e.getText().toString() in the onCreate() method where the edittext is blank...!

Fill your static variable inside the callback, you can use the below code to achive this,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose_cat_name);

    final EditText e = (EditText) findViewById(R.id.editTextCatsName);
    Button b = (Button) findViewById(R.id.buttonStart);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = e.getText().toString();
            newActivity(v);
        }
    });

}

SUGGESTION: Using static variables for this purpose is not good...! There are many different ways to do this type of thing like, passing data from intents (reffer: http://stackoverflow.com/a/5265952/4360419) or saving data temperary in preferences (http://stackoverflow.com/a/23024962/4360419)