Android shared preference not working - java

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

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

VK SDK for android problems

I'm using Android Studio. I've downloaded VK SDK from github and added it in my project file.Also I import it
import com.perm.kate.api.Api;
I authorize, then get my friends with it
Api api = new Api(Account.access_token, Constants.API_ID);
users = api.getFriends(Account.user_id, "photo", null, null, null);
Insert them in DB
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = prefs.edit();
for(int i =0; i< users.size();++i){
editor.putString("FriendFirstName" + String.valueOf(i), users.get(i).first_name);
editor.putString("FriendLastName"+ String.valueOf(i), users.get(i).last_name);
editor.putString("FriendPhoto"+ String.valueOf(i), users.get(i).photo);
}
editor.commit();
After, I can get any of my friend's name and it's working fine:
Names.add(prefs.getString("FriendFirstName" + String.valueOf(i), null)
+" "+prefs.getString("FriendLastName" + String.valueOf(i), null) );
BUT whenever I try get the photo or photo_medium_rec or any kind of photo it gives me null
Toast.makeText(getActivity(),String.valueOf(prefs.getString("FriendPhoto0", null))
,Toast.LENGTH_LONG).show();//NULL
Why is it giving null?
Addition
I'm new in programming, so here are some of my dumb questions about VK SDK. What should I use Api or Request methods like this:
VKRequest request = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.9f)), 0, 0);
Is there any difference between them? How to use Request? And how get my personal user information? I couldn't fined any methods in Api to get it.
Try to use official VK SDK (link).
And maybe it will be helpfull (link)

Android Studio: Java- making a global variable

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

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?

Categories