In first (MainActivity) I save data trough SharedPreferences:
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_SHOP, Shops.get(lv.getCheckedItemPosition()));
editor.commit();
And I can read this data from MainActivity after restart application:
if (mGameSettings.contains(GAME_PREFERENCES_SHOP))
Tv2.setText(mGameSettings.getString(GAME_PREFERENCES_SHOP, ""));
But how to read and edit this SharedPreferences from other activity?
Write the Below code in your another activity:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (sp.contains(MainActivity.GAME_PREFERENCES_SHOP)) //hoping that GAME_PREFERENCES_SHOP is a static constant defined in MainActivity
Tv2.setText(sp.getString(MainActivity.GAME_PREFERENCES_SHOP, ""));
You can use below code for getting the preference value from different Application
Context launcherContext = null;
try {
final int flags = Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE;
launcherContext = getApplicationContext().createPackageContext("com.another.package", flags);
} catch (final NameNotFoundException e) {
return ;
}
final SharedPreferences pref = launcherContext.getSharedPreferences(
"prefname",
Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
final String prefValue = pref.getString("prefname", null);
Log.i("test", prefValue);
You can read and edit with the same code. You just have to use the same Prefs file name and key for the required value.
You can declare your Pref File name as public static final String PREFS_NAME = "MyPrefsFile"; in the main activity and then access it from anywhere in the application.
Example, in other Activity:
SharedPreferences mGameSettings = getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
if (mGameSettings.contains(MainActivity.GAME_PREFERENCES_SHOP))
Tv2.setText(mGameSettings.getString(MainActivity.GAME_PREFERENCES_SHOP, ""));
Related
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 ""
In my MainActivity, I have written some code which I assume creates a file and saves a value in that file.
public static final String WHAT_I_WROTE = null;
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
//creates new SharedPreference?
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
//writes to the preferences file called saved_text?
SharedPreferences.Editor writer = saver.edit();
writer.putString(WHAT_I_WROTE, message);
writer.commit();
}
In another activity, I want to be able to read the message and display it but when I try this, it cannot resolve the symbol "saver".
String text_for_display = saver.getString(WHAT_I_WROTE);
What is the mistake I have made here and how do I correct it to read the saved string?
Thanks.
In another activity you have to again initalize the Shared preference.
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
String text_for_display = saver.getString(WHAT_I_WROTE),"any_default_value";
WHAT_WROTE = "anyText"
Add this to the other activity you have:
SharedPreferences saver = getSharedPreferences("saved_text", Context.MODE_PRIVATE);
then read it like this
String myValue = saver.getString("saved_text", "default_value");
Setting values in preference is like,
SharedPreferences.Editor editor = getSharedPreferences("saved_text", MODE_PRIVATE).edit();
editor.putString("WHAT_I_WROTE", message);
editor.commit();
Retrieve the data like,
SharedPreferences prefs = getSharedPreferences("saved_text", MODE_PRIVATE);
String text_for_display = prefs.getString("WHAT_I_WROTE", null);
Don't forget to put "context" before "getSharedPreferences" if necessary.
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();
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.
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";