4

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!

Grant
  • 4,413
  • 18
  • 56
  • 82
  • 1
    declare **public String commonValue** to **public static String commonValue;** or use shared preferece as sana has suggested – Akram Jun 15 '12 at 07:04
  • Is that impossible to do in this way?? – Grant Jun 15 '12 at 07:04
  • You can use Application Class for sharing Data between Activities.. Check this : http://stackoverflow.com/questions/10599775/how-do-i-make-global-changes-throughout-my-app-in-android/10599919#10599919 – Venky Jun 15 '12 at 07:04
  • Otherwise, initialize that `commonValue` as `public static String commonValue` – Praveenkumar Jun 15 '12 at 07:05
  • You can do that , but using static is not secured way , that variables are accessed easily... Also using Static creates memory leaks – Venky Jun 15 '12 at 07:06
  • OK.... I have already tried for Shared preferences it is fine. I just needed to test this way. Thank you all, with static modifier it worked! :) – Grant Jun 15 '12 at 07:11
  • 1
    @Grant : I seriously wish I had a dollar for every time I've explained this...`TestActivity obj = new TestActivity();//OBJECT OF MAIN ACTIVITY`. You can NOT create an instance of an `Activity` using 'new'. An `Activity` is either created (started) from the Android app launcher (when it's declared with the using MAIN/LAUNCHER) or it can be started with the various `startActivity(...)` methods. – Squonk Jun 15 '12 at 07:13
  • @Grant accept one answer if your problem has solved. – Akram Jun 15 '12 at 07:17

8 Answers8

4

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);
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
  • This would always require to have the context - I'd rather try to avoid that. – Tim Jun 15 '12 at 07:14
  • @TimMesserschmidt then whats the problem for require context always?? – Niranj Patel Jun 15 '12 at 07:16
  • You always have to drag around the Context - per example in a WorkerThread. I do prefer to use the strings.xml for UI strings. – Tim Jun 15 '12 at 07:17
  • You you are using findviewbyid then it aslo using one type of context dear.... so I think there is no any negative point to use context.. – Niranj Patel Jun 15 '12 at 07:20
3

Start using SharedPreferences in your app.

In your first activity you would do

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("commonValue", "DemoValue");
editor.commit();

In your second activity

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String str = settings.getString("commonValue", null);
Sana
  • 9,895
  • 15
  • 59
  • 87
  • Thanks for your answer! I've already tested this way and I just needed to try that :) – Grant Jun 15 '12 at 07:14
  • Your answer is perfect...but I didn't want use shared preferences. :) – Grant Jun 15 '12 at 07:20
  • Oh! If you had informed me, I would have put up the static object method :(, I am hungry for reps... applying to jobs :| – Sana Jun 15 '12 at 07:22
1

If the value is always the same you can create a public static final variable and access it via TestActivity.COMMON_VALUE.

If you want to pass around a value between to Activities you should use Intents and add an extra with the value you want to pass.

Tim
  • 6,692
  • 2
  • 25
  • 30
  • In response to your comment on SpK's answer about being downvoted, it was me. As I explained to him, your answer is sound for Java in general but the Android `Activity` class is a special case and creating static fields to be accessed from one `Activity` by another really isn't good practice. If a new Android programmer goes down that route and expect an `Activity` to behave as with any Java class then things are going to go badly wrong. – Squonk Jun 15 '12 at 07:33
  • Hi there Squonk, I've posted an Android way and a Java way - so there is no reason to downvote. It is often common in Android to create some kind of constants class where shared constants are used. – Tim Jun 15 '12 at 07:38
  • Hi Tim - I'm afraid it was the first sentence which caused the downvote. I agree you pointed out passing data using Intents but the idea of declaring `COMMON_VALUE` as a `static` field of an `Activity` (TestActivity in the OP's case) is the wrong approach. I agree a 'constants' class isn't a problem and I use them myself...just not static fields in an `Activity`. – Squonk Jun 15 '12 at 07:55
1

Try this -

TestActivity.java

public class TestActivity extends Activity {

 public static 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";
  }
}

another activity

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

    String str = TestActivity.commonValue;
}
Praveenkumar
  • 24,084
  • 23
  • 95
  • 173
  • It is not necessary to create a new instance of TestActivity since you're accessing a class variable. – Tim Jun 15 '12 at 07:10
  • 1
    Yes it's fine now - better for the heap to reduce object creation. I got downvoted, too (btw) ;) – Tim Jun 15 '12 at 07:11
  • No I didn't downvote ur answer I upvoted that...and I don't knw who did dat – Grant Jun 15 '12 at 07:16
  • 1
    @SpK : I downvoted from 1 to 0 - sorry (not sure who did the other one). Be careful when somebody puts a `Java` tag on an `Android` question. An `Activity` cannot be accessed by another `Activity` nor should it be instantiated using `new` or have static members etc...the whole thing will crash and burn. The `Activity` class is a special case in `Android`. – Squonk Jun 15 '12 at 07:17
  • @SpK : I hope you realise I wasn't being malicious and I'm surprised that the OP accepted your answer as I really can't seeing it working. Your logic is sound for Java in general, it's just the Activity class that's the problem. PS, I didn't downvote you again. – Squonk Jun 15 '12 at 07:24
0

As Sana has suggested, use SharedPreferences.

Alternatively, use a global constant class. If you want to stick with what you have, then you could try: String str = TestActivity.this.commonValue;

Your existing code is creating a new instance of the activity, so it's not going to have the value you had set.

BDFun
  • 531
  • 2
  • 7
0

To pass data between activities use Bundle. and methods,

intent.putExtra()

and If you want to set data to be global to your app, then create an application class, and save the data there.

jeet
  • 29,001
  • 6
  • 52
  • 53
0

We have an Application file for each app you can declare the variable there and as the Application file can get from any activity so using the public getter setter and can get/set that

there are vaious oter metjod you can sue as mention on developer.android http://developer.android.com/resources/faq/framework.html

Singleton class
A public static field/method
A HashMap of WeakReferences to Objects (almost same as my above solution )
Persistent Objects

take a look on them as well

Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

The reason why commonValue doesn't equal what you set in TestActivity onCreate method is because that function hasn't been called yet.

The solution for this is already mentioned by others. Like putting the value in a bundle.

mariomario
  • 660
  • 1
  • 9
  • 29