Android Studio: Java- making a global variable - java

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?

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);

Related

Set<String> losing data when restored from SharedPreferences after app is restarted

Im using SharedPreference on android to store a Set of Strings. It is stored and retrived fine to my knowledge but when the app is restarted some data is lost. Strings are add one by one and before adding them I retrieve the set, add a String and then store it again.
This is how I store it:
Set<String> emptySet = null;
SharedPreferences prefs = getContext().getSharedPreferences(getContext().getString(R.string.pref_disagree_key), Activity.MODE_PRIVATE);
String newIdAgreed = getItem(position).getId();
if (prefs.contains(getContext().getString(R.string.pref_disagree_key))) {
Set<String> updateSet = prefs.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet);
updateSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), updateSet);
editor.commit();
} else {
Set<String> newSet = new HashSet<String>();
newSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), newSet);
editor.commit();
}
And this is how I get it back:
if (prefsDisagree.contains(getContext().getString(R.string.pref_disagree_key))){
disagree_set = new HashSet<String>(prefsDisagree.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet));
for (String item: disagree_set){
//stuff done here
}
}
I saw some similar questions about this topic but none of the answers solved my problem. Any ideas?
The StringSet is not persistent when you are trying to edit it all again after it was saved and therefore newer data that was just added wont get saved when you quit the app and open it again.
It is actually documented: getStringSet
You need to copy first the StringSet and then insert/add data to the copied StringSet:
Set<String> s = new HashSet<String(prefs.getStringSet(
getContext().getString(R.string.pref_disagree_key),
emptySet));

How SharedPreference.Editor actually work in Android?

I am trying to save some String data using SharedPreference.
Here is my code
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
// LOAD
String str = mySharedPref.getString("hello", ""); // I expect "world"
But it only has an empty string!
Meanwhile,
SharedPreference.Editor editor = mySharedPref.edit();
editor.putString(...);
editor.commit();
This worked....
I thought mySharedPref.edit() returns a reference and makes the code above and below the same.
I am confused now. X(
See this solution
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
in your code:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
You called edit() each time you put a String but you didn't call commit() after it so your changes is not saved. You should change to this:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world")
.putString("my", "code");
.commit();
edit() method in SharedPreference returns NEW INSTANCE of the Editor interface. I found the comment explaining it in SharedPreferences.java file came with sdk.
Any actions performed on the new instance will be independent from other instances.
In the first part of my code, by calling edit() multiple times, I was performing actions on each independent instance.
It was interesting to notice that edit() returns a new instance instead of a reference.
/**
* Create a new Editor for these preferences, through which you can make
* modifications to the data in the preferences and atomically commit those
* changes back to the SharedPreferences object.
*
* Note that you must call {#link Editor#commit} to have any
* changes you perform in the Editor actually show up in the
* SharedPreferences.
*
* #return Returns a new instance of the {#link Editor} interface, allowing
* you to modify the values in this SharedPreferences object.
*/
Editor edit();

sharedpref add strings into table

i trying to insert my string into my database tables ,but it doesnt appear, so any advice on this how do i string my text so it able to appear on android database table
btnplayer = (Button) findViewById(R.id.button1);
tw1 = (TextView)findViewById(R.id.PX2);
btnplayer.setOnClickListener(new View.OnClickListener() {
SharedPreferences myPrefs = getSharedPreferences("PREF_COUNT", 0);
SharedPreferences.Editor myEditor = myPrefs.edit();
public void onClick(View v) {
String Player = myPrefs.getString("tw1",name);
DataStorage.this.btnplayer.setText("add name [" + Player + "]");
myEditor.putString("Player", Player);
myEditor.commit();
Please make your question more clear.
If you want store your data in database in android, you can go for SQLite database available in android http://developer.android.com/training/basics/data-storage/databases.html
but I suggest use sharedpreferences if only strings need to store.
I didn't get the meaning behind this statement String Player = myPrefs.getString("tw1",name); if you already have stored the same value (first time there will be no value so you will getting back the default "name" and then you will again store that name with the new key called "Player"). Where are you storing "tw1"? Exactly what issue you are facing?

SharedPreferences Android

I have this method :
private void deleteExam(String i) {
SharedPreferences prefsContatore = getSharedPreferences("esameKey"+i, Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
editorContatore.putString("esameKey"+i, "0");
editorContatore.commit();
}
Go? Can I call recursively "esameKey"+i?
getSharedPreferences access to a file and create if it does not exist. Every time you pass a different i a new file is created. Create it once:
SharedPreferences prefsContatore = getSharedPreferences("mySharedPrefFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
first argument of putString is a key the second paramter is the value you want to store
editorContatore.putString("esameKey"+i, "0");
this way you are putting for every i the value of 0. Is really that what you want?

Android shared preference not working

I am developing an Android app where I am trying to save some values using the sharedPreference concept. I am just trying the basic things for saving something into the SharedPreference. But its not working. Here is what am trying to do:
SharedPreferences preferences = getSharedPreferences(SHARED_PREF_NAME,0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREF_USER_NAME, "username");
editor.putString(SHARED_PREF_PASSWORD, "password");
editor.commit();
System.out.println("SHARED_PREF_USER_NAME ::" +
preferences.getString(SHARED_PREF_USER_NAME, ""));
System.out.println("SHARED_PREF_PASSWORD ::" +
preferences.getString(SHARED_PREF_PASSWORD, ""));
Just below the code, I am trying to print the values that were saved into the SharedPreference. But am getting the empty string.
Your code seams to be ok, I ran it on a test project and got the correct output. Maybe it's about your preference strings? Do they contain spaces?
Means if String SHARED_PREF_USER_NAME = "user name" then Change it to "username" and Try.
You can use this code.
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREF_NAME,0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username",SHARED_PREF_USER_NAME);
editor.putString("password",SHARED_PREF_PASSWORD);
editor.commit();
System.out.println("SHARED_PREF_USER_NAME ::" +
preferences.getString(SHARED_PREF_USER_NAME, ""));
System.out.println("SHARED_PREF_PASSWORD ::" +
preferences.getString(SHARED_PREF_PASSWORD, ""));

Categories