0

According to this stack overflow question

This code should return all the values in the preferences

 Map<String, ?> allEntries = sPref.getAll();
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
    } 

But I only get the preferences that I added at the last, it does not get the entire preference file keys and values

This is my Stack Trace

08-30 15:14:10.858 30290-30290/com.vivid.sharedpreferences D/map values: name: Nithin
08-30 15:14:10.858 30290-30290/com.vivid.sharedpreferences D/map values: email: Nithin

I had previously added two values of name and email, but that does not appear here. Can anyone help me solve this problem?

This is my program

  sPref = this.getSharedPreferences("com.vivid",this.MODE_PRIVATE);
    sEditor = sPref.edit();


 btnSave.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

         sEditor.putString(PREF_NAME,edtName.getText().toString());
         sEditor.putString(PREF_EMAIL,edtEmail.getText().toString());
         sEditor.commit();
     }
 });


    btnRetrieve.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (sPref.contains(PREF_NAME)){

                edtName.setText(sPref.getString(PREF_NAME,null));
            }


            if (sPref.contains(PREF_EMAIL)){

                edtEmail.setText(sPref.getString(PREF_EMAIL,null));
            }
        }
    });


    btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            sEditor.clear();
            sEditor.commit()
        }
    });


}

public void getAllValues(){

    Map<String, ?> allEntries = sPref.getAll();
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
    }
}

@Override
protected void onStop() {
    super.onStop();

    getAllValues();
}
Android
  • 542
  • 2
  • 5
  • 13

1 Answers1

2

I had previously added two values of name and email, but that does not appear here

This is expected behavior. You can not set multiple values for a key. If you write a new value with the same key, the old value is overwritten.

Tim
  • 41,901
  • 18
  • 127
  • 145