Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Passing a value between activities

Tags:

android

In my Android application I have to use common string value for all activities. "commonValue" is the common string value that I want to use in all activities. Relevant code of the main activity like this :

public class TestActivity extends Activity {

 public String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    commonValue = "DemoValue";
  }
}

In my next activity I created an object of "TestActivity" class and tried to assign "testValue" string to another string named "str"

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testlist);

    TestActivity obj = new TestActivity();//OBJECT OF MAIN ACTIVITY
    String str = obj.commonValue;
 }

but the "str" value in second activity does not equal to the value assigned in my first activity. Why is that & How can I do this?

Thanks!

like image 804
Grant Avatar asked Jan 17 '23 09:01

Grant


1 Answers

Put your value in string.xml

 <string name="common_value">DemoValue</string>

and use in any activity like this..

String common_value = getApplicationContext().getString(R.string.common_value);
like image 56
Niranj Patel Avatar answered Jan 19 '23 00:01

Niranj Patel