0

How do you make a variable that can be used across the application. For example, in Swift, you can name it by:

    var formattedPrice: String = rowData["date"] as String
    defaults.setObject(rowData, forKey: "rowData") 

and you can fetch it with:

    var variable = defaults.dictionaryForKey("rowData") as? NSDictionary

How can this behavior be mimicked in android studio?

1 Answers1

1

The example you provided looks very similar to SharedPreferences in Android. SharedPreferences allow you to store data and access said data globally within your application. Here is a simple code snippet that shows you how to save and recall an int. You can save the variable as follows:

SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("your_integer_key", yourIntegerValue);
editor.commit();

And then retrieve it anywhere in your application like so:

SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
int myIntegerValue = sharedPreferences.getInt("your_integer_key", -1);
Willis
  • 5,308
  • 3
  • 32
  • 61
  • How could you do this with a string? And also how could this be printed out, like the println("print this"), as in swift? – Teb Theestatebook Feb 09 '15 at 17:02
  • Also where do SharedPreferences get placed? Under public void onCreate(Bundle savedInstanceState) { ? – Teb Theestatebook Feb 09 '15 at 17:04
  • Also why did you define the integer as -1 when you were trying to retrieve it? Shouldn't that be defined at the editor.putInt? – Teb Theestatebook Feb 09 '15 at 17:06
  • 1. You could do this with a `String` by using the appropriate methods, i.e. `.getString` for `SharedPreferences` and `.putString` for `SharedPreferences.Editor`. Then you would simply call something like `System.out.println(yourString)`. 2. `SharedPreferences` are stored in an XML file in the app data folder. 3. `-1` is just a random value. for all the `SharedPreferences` `.get` methods you have to specify a default value to be returned in the event that the requested preference does not exist. – Willis Feb 09 '15 at 19:00
  • can it go under app - value folder? Make a file example.xml , and put above inside? – Teb Theestatebook Feb 09 '15 at 20:12
  • I'm not sure if you can change the default location; why exactly would you want to do this? – Willis Feb 09 '15 at 20:50
  • I do not want to. I just do not know where the default location is. – Teb Theestatebook Feb 09 '15 at 21:41
  • Okay I gotcha. They are stored here: `data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml` – Willis Feb 09 '15 at 21:43