Marco Moderatto
Marco Moderatto

Reputation: 59

Pass a string between activities

Hi i want to pass a string through two ativities I've been looking for it in another answers and tried this one:

public class GlobalVars extends Activity {
private static String winename;

public static String getWineName(){
    return winename;
}
public static void setWineName(String s){
    winename=s;
}

}

And set the string in activity 1 as this:

EditText searchbox=(EditText) findViewById(R.id.buscarmainText);
String searchb=searchbox.getText().toString();
GlobalVars.setWineName(searchb);

But, when I call the getWineName method in activity 2 it seems that the string winename is empty, is called like this:

public String sbuscar=GlobalVars.getWineName();

Don't know what am I doing wrong.

Upvotes: 0

Views: 122

Answers (2)

kaneda
kaneda

Reputation: 6189

You should put your global vars on a holder class like this.

public class GlobalVars {
     public static final String KEY_WINENAME = "winename";
     private static HashMap<String, String> globalVars = new HashMap<String, String>();

     public static String getGlobalVariable(String key) {
         return globalVars.get(key);
     }
}

Then from any component from your app you can make a call to GlobalVars.getGlobalVariable(GlobalVars.KEY_WINENAME);

If you just want to pass the String from one activity to the next one you should use an Intent as Ram kiran has answered. Usually it's the best practice.

Also you should look at where this piece of code is getting called:

EditText searchbox=(EditText) findViewById(R.id.buscarmainText);
String searchb = searchbox.getText().toString();
GlobalVars.setWineName(searchb); 

For instance, if you change the orientation you may be not maintaining the EditText state, so that the text inside it get empty again and your code is called again emptying the variable. If you are unsure put a log line inside setWinename() to check if it's been called twice.

Upvotes: 1

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21181

Its better to pass string between activities with intents

In your first activity class:

Intent i = new Intent(this, activity2.class);
i.putExtra("KEY",YourData);

In next activity class

Bundle extras = getIntent().getExtras();
if(extras !=null) {
    String value = extras.getString("KEY");
}

Upvotes: 2

Related Questions