getting string from preferences - android

So I have EditTextPreference in my Preferences, I want to type something in and save it, then i want to get that text in Activity. My key of EditTextPreference is B1. I tried this code :
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String samples = getPrefs.getString("B1", "");
b1.setText(samples);
<EditTextPreference
android:dialogTitle="Button 1"
android:key="B1"
android:summary="Set text on button 1"
android:title="Set text on button 1" />
I get java.lang.NullPointerException between those
String samples = getPrefs.getString("B1", "lol");
b1.setText(samples);

Declare:
SharedPreferences pref = this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
Put a value (can be int, String, etc)
String tom = "tom";
pref.edit().putString("tom", tom).commit(); // To set a value to SharedPreferences
Get a value (remember the type)
String name = pref.getString("tom", null); // To get a value from SharedPreferences
See SharedPreferences

Try this
Home.java
public class Home extends Activity {
public SharedPreferences prefs;
String mValues;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mValues= prefs.getString("male", "female");
}
}
Preferences.java
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.setting);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
Editor editor = sharedPref.edit();
if(key.equalsIgnoreCase("B1")){
editor.putString("male","my value");
}
editor.commit();
}
}
Let me know if it works for you.

In order to write to SharedPreferences you can use:
Editor editor = getPrefs.edit();
editor.putString("B1", "you value here");
editor.commit();

Related

Storing values in SharedPreferences on button click

How can I store already existing string value in SharedPreferences on button click? I have a TextView and a button: the TextView contains certain string and I want to store that in SharedPreferences on button click.
To write it:
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Yourkey", textView.getText()+"");
editor.commit();
}
});
And to read it:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String string = sharedPref.getString("Yourkey","default");
Here are methods which I use everytime to store data in shared-preferences:
private SharedPreferences app_prefs;
private final String DEVICE_TOKEN = "device_token";
public PreferenceHelper(Context context) {
app_prefs = context.getSharedPreferences(AndyConstants.PREF_NAME,
Context.MODE_PRIVATE);
this.context = context;
}
public void putDeviceToken(String deviceToken) {
Editor edit = app_prefs.edit();
edit.putString(DEVICE_TOKEN, deviceToken);
edit.commit();
}
public String getDeviceToken() {
return app_prefs.getString(DEVICE_TOKEN, null);
}
In the first method I create the shared-preferances object, in the second method I use it to put data and in third method to get data any where you need.

usea savePreferences in dynamically layout -android

I'm making an app that contains a dynamically layout and it generates textView's in run time, I need that when I close the application all the textView has been added, don't erase; I think I can do that whit savePreferences(), but What parameters I have to use?
private void savePreferences(What parameter here, What parameter here) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.commit();
}
Thank you
Shared Preferences should work. Try this...
public class sample extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
// THIS IS WHERE YOU STORE THE TEXTVIEW DATA
// THERE ARE MANY ' editor.put...(...) ' methods
// ie. editor.putInt(...) , editor.putString(...)
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}

Shared preferences not working correctly

I'm trying to store some strings in a shared preference file and then retrieve them in another activity, except it doesn't seem to be working. Any guidance as to where im going wrong would be much appreciated. Many thanks.
public void save(View view) {
SavePreferences("name", nameS);
SavePreferences("current", currentS);
SavePreferences("goal", goalS);
SavePreferences("CurrentBmi", cBmiS);
SavePreferences("goalBmi", gBmiS);
Toast.makeText(this, "profile Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public class Progress extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String test = sharedPreferences.getString("name", "");
String test2 = sharedPreferences.getString("current", "");
TextView testy = (TextView) findViewById(R.id.textView1);
testy.setText(test);
TextView testz = (TextView) findViewById(R.id.test2);
testz.setText(test2);
}
With the code you have you are limiting the access of sharedpreferences to activity(context) level.
Values saved in activity Activity MainActivity will not be available in activity Progress since you are using getPreferences(MODE_PRIVATE);
Change this to
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
or
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
getPreferences:
public SharedPreferences getPreferences (int mode)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

how to save some value in sharedpreferences and get that in next activity

I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)

How to retrieve the default value of a preference defined in the XML file

How do you get the default value of a single Android Shared Preference as it is explicitly defined in the corresponding XML file? E.g.:
<CheckBoxPreference
android:defaultValue="false"
android:key="fulldb"
android:summary="No selection rules apply"
android:title="Use Full Database" />
Like this..
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false); //default value if nothing is in the preference is the last parameter false.
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
See below:
To Store the Value:
public static SharedPreferences myPrefs;
public static SharedPreferences.Editor prefsEditor;
myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putBoolean("FullResultIsOn", true); // value to store
prefsEditor.commit();
Now to retrive the value:
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
fullResultSound = myPrefs.getBoolean("FullResultIsOn", false);
Enjoy. :)
Thanks.

Categories

Resources