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?

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

8 Comments

How could you do this with a string? And also how could this be printed out, like the println("print this"), as in swift?
Also where do SharedPreferences get placed? Under public void onCreate(Bundle savedInstanceState) { ?
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?
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.
can it go under app - value folder? Make a file example.xml , and put above inside?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.