Mohit
Mohit

Reputation: 1063

SharedPreferences not saving and returning String

My activity contains an EditText which takes name of user as String inout and then I am trying to save this by SharedPreferences, so that when my activity is opened again I can call back my string and set that as Hint in my EditText.

My code:-

    SharedPreferences prefs = getSharedPreferences("Key",0);

       final EditText editname = (EditText)findViewById(R.id.editText1);
    editname.setGravity(Gravity.CENTER);
    nameofuser = prefs.getString("name", "Your Name!");
    editname.setHint(nameofuser);

    editname.setOnEditorActionListener(new OnEditorActionListener()
    {


        public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) 
        {
            if(arg1==EditorInfo.IME_ACTION_DONE)
            {
                nameofuser = editname.getText().toString();
                   Editor e=prefs.edit();
                   e.putString("name", nameofuser);
                        e.commit();             
                   editname.setCursorVisible(false);
            }
            return false;
        }
    });

Here is nameofuser is String type class variable.

Now what I want:-

What I am getting:- Everything works fine but whenever I reopen the program I get blank at edittext i.e. nothing is displayed there.

Upvotes: 0

Views: 658

Answers (2)

RajeshVijayakumar
RajeshVijayakumar

Reputation: 10622

I hope this will help you

  private void SavePreferences(String key, String value) {
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}

private void deletePreferences(String key) {

    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.remove(key);
    editor.commit();
}

private void clearAllPreferences() {
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();
}
private void showPreferences(String key){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String savedPref = sharedPreferences.getString(key, "");
    mOutputView.setText(savedPref);
   }

Upvotes: 1

Lucifer
Lucifer

Reputation: 29642

Try this way,

 if(arg1==EditorInfo.IME_ACTION_DONE)
 {
     nameofuser = editname.getText().toString();
     SharedPreferences.Editor e=prefs.edit();  // modify at this line
     e.putString("name", nameofuser);
     e.commit();             
     editname.setCursorVisible(false);
 }

Upvotes: 0

Related Questions