Skip to content Skip to sidebar Skip to footer

How To Share Variables Between Classes In Java

Possible Duplicate: Passing data between activities in Android so I have two activity's, and I need to save one variable in first activity, and use it in the second activity. Ca

Solution 1:

Use something like this:

    Intent intent = newIntent(this, ClassImCalling.class);
    intent.putExtra("variable", myvariable);
    startActivityForResult(intent, int_identifier);

And in the other Activity:

intent = getIntent();var=intent.getStringExtra("variable");

To return to the activity that called it (intent being same as getIntent() above):

setResult(RESULT_OK, intent);
    finish();

And when you return back to the first Activity:

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == int_identifier) {
        if (resultCode == RESULT_OK) {
            Do suff
        }else if(resultCode == RESULT_CANCELED){
            Action was cancelled :(
        }
    }
}

Solution 2:

Keep it simple. In one class you set the variable's value in other class use that class's instance to get it.

publicclassActivity1 {       

   privateStringvar;

   publicActivity1() {
      setVar("some_value");
   }

   publicStringgetVar() {
      returnthis.var;
   }

   publicvoidsetVar(Stringvar) {
      this.var = var;
   }
}

publicclassActivity2 {
   publicvoiddoSmth() {
      Activity1 a = newActivity1();
      String varValue = a.getVar();

   }
}

Solution 3:

First Activity:

    ....
    Intent intent = newIntent(this, SecondActivity.class);
    intent.putExtra(Consts.EXTRA_EDIT_MODE_KEY, 123);
    ....
    intent.putExtra(_some_key_, _some_data_);
    intent.putExtra(_some_key_, _some_data_);
    startActivity(intent);

SecondActivity:

    ..... 
    Intentintent= getIntent();
    intmode= intent.getIntExtra(Consts.EXTRA_EDIT_MODE_KEY, -1);
    ...... 

Solution 4:

As understand your requirement is to use a variable value in several Activity classes. As they mean they are JAVA classes, so you can use a static variable for your task.

Say you have a class like this,

publicclassActivity1extendsActivity{
staticString name="abc";
}

If you want to use that name variable in a other class, you can use,

publicclassActivity2extendsActivity{
String name2=Activity1.name;
}

Solution 5:

Here's one way of doing it, I guess:

classClass1 {
   privateint someValue = 0voiddoSomething(Class2 anotherObj) {
       this.someValue = 1;
       anotherObj.setValue(this.someValue);
   }
}

There's many other ways :)

Post a Comment for "How To Share Variables Between Classes In Java"