Anshuman Kaushik Anshuman Kaushik - 3 months ago 6
Java Question

How to get keys as well as values from sharedPreference file

Whenever I try to get key and values from my sharedPreference file, I get only values like I have a key name "Anshuman" whose value is "Present".

But whenever I try my code I got only "Present". How can I get "Anshuman" too.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_date_detail_activity);

SharedPreferences sharedPreferences = getSharedPreferences("Date", MODE_PRIVATE);
Map<String,?> keys = sharedPreferences.getAll();

for(Map.Entry<String,?> entry : keys.entrySet()){
Toast.makeText(this,entry.getValue().toString(),Toast.LENGTH_SHORT).show();
}

}

Answer

You can test this code :

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

enter link description here

Comments