SharedPreferences keep getting default value - android

I keep Getting the Default value either my UI will display null or if I use integers it displays that default value as well here it is in the string form plz help
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2= PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString(newUserScore1, NewUserScore1);
editor.commit();
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);

I have added some comment to you code please check:
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2=
PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
//#Praful: here newUserScore1 seems to be integer value and you are storing
//null here. I think it it should be
//`editor.putString("NewuserScore1", newUsrScore1);`
editor.putString(newUserScore1, null);
//#Praful: call commit here
editor.commit;
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);

This line
editor.putString(newUserScore1, null);
should be
editor.putString("NewuserScore1",newUserScore1);
and also don't forget to commit your changes using editor.commit();

Whenever you working with SharedPreference never forget to call commit() to save your changes.
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString("NewuserScore1", newUserScore1);
editor.commit();

Related

Unable to get data from shared preferences

I am saving phone no. in shared preference and in another activity I am trying to get phone no. from shared preference.
private static final String KEY_PHONE = "keyphone";
SharedPreferences sharedPreferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_PHONE, "3454534565");
editor.apply();
In another activity I am using something like this:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();
My problem is here I am not getting phone no in toast message and I am getting empty toast.
Someone please let me know how can I get phone no in another activity.Any help would be appreciated.
THANKS
The Main Problem is in here : editor.putString(KEY_PHONE, "3454534565");
To Write:
SharedPreferences preferences = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KEY_PHONE", "3454534565");
editor.apply();
To Read:
SharedPreferences prfs = getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
String phone_id= prfs.getString("KEY_PHONE", "");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();
You did everything right except one thing.
When retrieving a String value you cannot just set the value field to "".
When retrieving a String, the default value is null, when retrieving boolean, default value is false and when retrieving a boolean, the default value is false.
So instead of using
String phone_id = sp.getString("keyphone","");
you need to use
String phone_id = sp.getString("keyphone", null);
You can use this to store a value in Shared Preferences:
SharedPreferences sharedPreferences =
getSharedPreferences("simplifiedcodingsharedpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =
sharedPreferences.edit();
editor.putString("keyphone", "3454534565");
editor.apply();
And then this to retrieve it:
SharedPreferences sp = getSharedPreferences("simplifiedcodingsharedpref",
Context.MODE_PRIVATE);
String phone_id = sp.getString("keyphone","");
Toast.makeText(getApplicationContext(), phone_id, Toast.LENGTH_SHORT).show();

OnButton Click Share Preferences

Below is my Code :
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
String in_time_sharedpref = In_time.getText().toString();
editor.putString("in_time_sp", in_time_sharedpref);
editor.apply();
editor.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
I want to know what wrong I am Doing in Code ?
How i can use two shared Preferences in android studio ??
You are doing wrong that you are using same reference for both shared preference.
Yes, you can use two shared Preference at one button click.
Create two shared Preference object.
SharedPreferences sp;
SharedPreferences sp2;
SharedPreferences.Editor editorSp ;
SharedPreferences.Editor editorSp2 ;
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
sp2 = getSharedPreferences("InTime", MODE_PRIVATE);
Final code will be like this:
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp2 = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor = sp2.edit();
String in_time_sharedpref = In_time.getText().toString();
editorsp2.putString("in_time_sp", in_time_sharedpref);
editorsp2.apply();
editorsp2.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
Use one sharedpreference name
"sp = getSharedPreference("attendlogin",MODE_PRIVATE);"
and use different different variable to save data
example:
SharedPreferences.Editor editor = sp.edit();
String in_time_sharedpref = In_time.getText().toString();
editor.putString("in_time_sp", in_time_sharedpref);
editor.apply();
String emp_id = sp.getString("emp_id", null);
i.e. sp should be same with name ""

Why sharedpreference value not getting in when retrieving?

I aaded three shared preferences as below code. And I am able to retrieve onl n shared preference value.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
editor.commit();
I used the following code for retrieving from another activity. I am able to retrieve only the boolean value. Other values are not there. getting the default value for the string values. please help me.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "0");
String pwd=preferences.getString("pwd", "0");
check first the value u store in preferences are stored or not
using this code
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
if(userId==null || pwd==null)
{
//data not therer
}
else
{
//do something with data
}
and let me know if any error occured..
I think you're not getting the SharedPreferences in a correct way.
See the doc for ex: https://developer.android.com/training/basics/data-storage/shared-preferences.html
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Also, you don't need to call apply() AND commit(). Just one of those is enough. See the javadoc for the differences btw them.
Use this code
String userId=preferences.getString("userId", null);
String pwd=preferences.getString("pwd", null);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
if(userId==null || userId==""||pwd==null ||pwd=="")
{
}
else
{
}
Try code in this way.
Set values in First Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("Loggedin",true);
editor.putString("userId",userid);
editor.putString("pwd",password);
editor.apply();
Retrieve value in Second Activity
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean loggedin=preferences.getBoolean("Loggedin", false);
String userId=preferences.getString("userId", "");
String pwd=preferences.getString("pwd", "");
Used in that way for retrieve values from shared preferences for your code.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Boolean loggedin=preferences.getBoolean("Loggedin", false);
//Checking the value of userId and pwd,if they are null then there is no values of userId and pwd other than default.
if (userId != null && pwd != null) {
String userId = preferences.getString("userId", "0");
String pwd = preferences.getString("pwd", "0");
} else {
String userId = "0";
String pwd = "0";
}

Android: string value is not getting in Shared Preference

I have created a shared preference for a boolean value and for a string value. The boolean value is gotten in another activity. But for the string I am only getting default value.
Home.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe = prefs.edit();
spe.putBoolean("flag", true);
spe.putString("user", "hello");
spe.commit();
welcome.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean flag= prefs.getBoolean("flag", false);
String user=prefs.getString("user","Nothing");
TextView tv = new TextView(this);
tv.setText("Flag : "+flag+(" User : "+user);
For 'user', only 'Nothing' is displaying. Where should I correct my code?
Try using:
SharedPreferences settings = getSharedPreferences(appName,0);
settings.getBoolean("flag", true);
settings.getString("user", "hello");
And to put:
SharedPreferences settings = getSharedPreferences(appName,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.putString("user","hello");
editor.commit();
This is what I use in my application, and it shares booleans/ints/strings accrossed many many Classes
Note: appName doesn't have to be the app name, like in the official tutorial.

How to set more than one shared preference, without first creating xml

I am trying to setup more than one shared preference with this method.
This will successfully create one shared pref:
static final String SUPPLIER_NUMBER = "";
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
savednumber = myPrefs.getString(SUPPLIER_NUMBER, "");
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs1.edit();
prefsEditor.putString(SUPPLIER_NUMBER, telephonenumber);
prefsEditor.commit();
This second example simply results in the second pref overriding the first....??? What am I missing here?
static final String SUPPLIER_NUMBER = "";
static final String SUPPLIER_COST = "";
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
savednumber = myPrefs.getString(SUPPLIER_NUMBER, "");
savedcost = myPrefs.getString(SUPPLIER_COST, "");
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs1.edit();
prefsEditor.putString(SUPPLIER_NUMBER, telephonenumber);
prefsEditor.putString(SUPPLIER_COST, suppliercost);
prefsEditor.commit();
I do not really want to create an xml file to get the prefs from.. I want it dynamically created, as I believe I am getting here, in the first example.. but I need to be able to add more than one preference.
Well your SUPPLIER_NUMBER and SUPPLIER_COST constants are equal (both are ""). Set them to different values and that should do the trick :)
static final String SUPPLIER_NUMBER = "number";
static final String SUPPLIER_COST = "cost";

Categories

Resources