I know this has been asked a lot around SO, but I just can't seem to get this working.
Situation : I have a dialog with a EditText in it with an accept button. I would like to store the value of the string with SharedPreferences when the user touch the accept button. Here's the code I have so far.
public void showDialog()
{
final Dialog dialog = new Dialog(VentilationActivity.this);
dialog.setContentView(R.layout.menu_options);
dialog.setTitle("Configuration de l'adresse IP");
dialog.setCancelable(true);
dialog.show();
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
SharedPreferences preferences = getSharedPreferences("Agrinuvo", 0);
String texte = preferences.getString("VentIpKey", "");
adressIp.setText(texte);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(adressIp, InputMethodManager.SHOW_IMPLICIT);
Button btnAccept = (Button) dialog.findViewById(R.id.button1);
btnAccept.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
EditText adressIp = (EditText) dialog.findViewById(R.id.editText1);
textIp = adressIp.getText().toString();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VentIpKey", textIp);
editor.commit();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(adressIp.getWindowToken(), 0);
dialog.dismiss();
}
});
}
And, of course this is not working. Everytime I close the dialog window and reopen it the EditText text is empty. Thanks for any help you can provide.
How about;
public void showDialog() {
....
final SharedPreferences preferences = getSharedPreferences("Agrinuvo", 0);
....
#Override
public void onClick(View v) {
....
// Use previous preferences instance instead.
// SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("VentIpKey", textIp);
editor.commit();
....
}
}
}
Anyway, it seems so that you're writing to different preferences than where you read the default value from.
Inside your onClickObserver you create a SharedPreference object for a file named after your activity's class name. At least this is what the Activity's getPreferences(int) documentation states. Try instead initializing that object the same way you do it in showDialog or making the showDialog's preferences final.
It looks like there error might be inside your onclick method in the following line
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
If you change it to
SharedPreferences preferences = getSharedPreferences("Agrinuvo", Context.MODE_PRIVATE);
It should work. The way you were calling it, you weren't getting the same preference that you requesting for your dialog.
I've used preferences in my application without too many problems for quite a while and I would suggest a couple things:
getSharedPreferences() should only be used for preferences shared between different Activities. If only your one Activity will be using the data, use this to save:
SharedPreferences settings = getPreferences (MODE_PRIVATE);
SharedPreferences.Editor ed = settings.edit();
ed.putBoolean ("BooleanKey", booleanVar);
ed.putInt ("IntKey", intVar);
ed.putFloat ("FloatKey", floatVar);
ed.putLong ("LongKey", longVar);
ed.commit();
And this to retrieve:
SharedPreferences settings = getPreferences (MODE_PRIVATE);
longVar = settings.getLong ("longKey", 0);
...
If you're going to share your preferences across Activites, that's when you'll want to use getSharedPreferences(), but you'll want to NOT user MODE_PRIVATE. Currently, I use MODE_WORLD_WRITEABLE in the code where I write the data and MODE_WORLD_READABLE where I read it, that's probably not the best way (at least, the if the warnings I'm getting from Eclipse are to be believed).
Good luck,
R.
Related
I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.
In this code I'm trying to create and save a string in SharedPreferences
Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;
enrollNewStudent.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
editor.putString("name", "Dave");
editor.commit();
startActivity(new Intent(MainActivity.this, AddNewStudent.class));
}
});
And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.
Context context = this;
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);
TextView textView = findViewById(R.id.exampleTextView);
textView.setText(toPutInTextView);
When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.
Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.
The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.
Try:
String toPutInTextView = sharedPref.getString("name", "<default_value>");
So I am making this app and I want this settings page kind of thing where the user can choose if they want the sound on or off how do I reference the playsound method in the second activity?
As you mention settings I assume you use SharedPreferences -if not please do as it is the stander way to implement settings-, in this case, it is so easy to so:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean key = sharedPreferences.getBoolean("playsound", false);
I used a switch 'button' in my code to solve the same problem like u. here is an example
SharedPreferences pref;
SharedPreferences.Editor editor;
MediaPlayer backgroundmusik;
Switch mute;
View dummysetting;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.checksound_layout);
//SHARED PREFERENCES
pref = getSharedPreferences("your_label",MODE_PRIVATE);//label to find in Manifest
editor = pref.edit();
backgroundmusik = MediaPlayer.create(this,R.raw.dingdong);
dummysetting = (View) View.inflate(this, R.layout.setmute_layout,null); //you need that dummy, when u want to check ur button when u are on a different layout other way you get nullpointer.
mute=(Switch)dummysetting.findViewById(R.id.mute);
mute.setChecked(pref.getBoolean("Musik", true));//set true or false, its the 'status' when start for the first time after u install app.
if (mute.isChecked())
{
backgroundmusik = MediaPlayer.create(Hauptmenue.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
}
}//close oncreat
now you can set on an another place in the same activity the mute button like:
setContentView(dummysetting);
mute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
backgroundmusik = MediaPlayer.create(MAinactivity.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
editor.putBoolean("Musik", true);
editor.commit();//safe the edit
}else
{
backgroundmusik.stop();
editor.putBoolean("Musik", false);
editor.commit();//safe the edit
}
}
});
}//close main.
That was just an example. i comy paste some codes from my code. If doesnt work you can ask again.
AND sharedpreferences can u use from every activity, when u declare and call them in the activity. Need just:
SharedPreferences pref;
SharedPreferences.Editor editor;
then in oncreat
pref = getSharedPreferences("your_label",MODE_PRIVATE);
editor = pref.edit();
and then when u safe as
editor.putBoolean("**Musik**", true);
editor.commit();//safe the edit
u have to ask for "Musik" again like:
pref.getBoolean("Musik", true)
to read.
My first application in android studio and i want to do this:
Description:
username:username (TextBox)
password:password (TextBox)
Keep me logged in -->CheckBox
LOGIN -->BUTTON
The first time where the user enters your username and password and click to Keep me logged in the application must be remember the username and password without the user writes again in the second time.
Could anyone give me some idea how this implement in android, I found many examples but nothing work.
You could use SharedPreferences to remember the user preference. Here it is a boolean.
SharedPreferences prefs = getDefaultSharedPreferences(this);
boolean keepLoggedIn = prefs.getBoolean(KEY_KEEP_LOGGED_IN, false);
//After user makes the selection on the checkbox,
SharedPreferences.Editor editor = getDefaultSharedPreferences(this).edit();
editor.putBoolean(KEY_KEEP_LOGGED_IN, true);
editor.commit();
I did something very similar to this recently
First, make sure to initialize your fields in question
AutoCompleteTextView mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
EditText mPasswordView = (EditText) findViewById(R.id.password);
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
Set your onClick event:
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
In order for the user password to be remembered, you have to save them somewhere. I stored them in shared preferences, but you can use a more secure method depending on your application or even encrypt before storing them http://developer.android.com/guide/topics/data/data-storage.html#pref
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
//Put the strings in the editor
editor.putString(getString(R.string.userAccount), email);
editor.putString(getString(R.string.password), password);
Now in onCreate or your other favorite android start method (depending on if you're using a fragment or activity), retrieve them
//Initialize the shared preferences, set in private mode
SharedPreferences sharedPref = getSharedPreferences("userDetails", MODE_PRIVATE);
//Retrive the values
sharedPref.getString(getString(R.string.userAccount), "")
sharedPref.getString(getString(R.string.password), "")
Got this code, which basicly updates my textviews depending on how far the user is in the quiz, which is stored in sharedPrefs. But when the correct answer is entered the prefs doesn't update. Does the commit() need too long time to set the prefs, so the activity calls the method setText() before the sharedPrefs are updated or what am i doing wrong?
private void setText() {
SharedPreferences score = this.getSharedPreferences("football", MODE_PRIVATE);
questionNumber = score.getInt("football", 0);
question.setText(questions.get(questionNumber).get(0));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCheckAnswer:
if (questions.get(questionNumber).contains(etAnswer.getText().toString())) {
Integer newQ = questionNumber += 1;
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = change.edit();
editor.putInt("football", newQ);
editor.commit();
setText();
}else{
question.setText("error occured");
}
break;
}
You're not opening the SharedPreference the same way when setting and getting.
Change this:
SharedPreferences change = this.getPreferences(Context.MODE_PRIVATE);
to this:
SharedPreferences change = this.getSharedPreferences("football", MODE_PRIVATE);
Notice the differences:
getPreferences vs getSharedPreferences
you didn't give the preference reference as "football"
Are you sure the prefs doesn't get updated or is it just that your textview isn't getting updated? If this is being done in your Activity, you should not be changing layout (your text view) from within the Activity. You should use a Handler to make UI changes.
I wonder if any one can help me, i am trying to get my head around shared preferences, i assume they are stored in the device (tablet) and can be checked to see they exist.
My code below (first one) i want a button once clicked to put a string or boolean in the shared preferences.
The second code is to see if the shared prefs exist if it does make a settext change if not ignore and look for the next string
cala1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoadPreferences();
SharedPreferences sharedpreferences = getSharedPreferences("prefman", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("cal1","c1");
editor.commit(); });
enter4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LoadPreferences();
SharedPreferences sharedpreferences = getSharedPreferences("prefman", MODE_PRIVATE);
sharedpreferences.contains("cal1");
if (sharedpreferences.getString("cal1","c1").equals("cal1"));
{
{cexist1.setText("Shared prefs exit");
}
else
I don't get why you call sharedpreferences.contains("cal1") when you ignore the return value anyway.
The Android documentation for SharedPreferences says the following:
contains(String key) Checks whether the preferences contains a
preference.
Looks like that is what you want, try using the call in you if clause.
if (sharedpreferences.contains("cal1")) {
cexist1.setText("Shared prefs exit");
}
the format of your code above is a bit messy too - makes it harder to read ;)