Search code examples
javaandroidsharedpreferences

How to assign unique string value in shared preferences


I am using shared preferences to store my caller details in my app as follows. Whenever there is a call, I am saving the following details of the caller.

 sharedPrefCallLog = getSharedPreferences("CallLogPref", Context.MODE_PRIVATE);
    editorCallLogPref = sharedPrefCallLog.edit();
    editorCallLogPref.putString("name", Name);
    editorCallLogPref.putString("num", Number);
    editorCallLogPref.putString("city",City); 
    editorCallLogPref.apply();

Everything works fine for the first call. When the second call is received, the details of the first call are cleared and replaced with the second one. How could I save everything? I would like to save details up to the last 10 calls?

Should I use different approach other than sharedPref?


Solution

  • If you need to save upto 10 call records only (small data set), then shared preferences are fine.

    You need to assign a unique key to your records.

    private void saveCallLog(final int callRecordID){
        // key here is callRecordID
        sharedPrefCallLog = getSharedPreferences("CallLogPref", Context.MODE_PRIVATE);
        editorCallLogPref = sharedPrefCallLog.edit();
        editorCallLogPref.putString("name_"+ callRecordID, Name);
        editorCallLogPref.putString("num_"+ callRecordID, Number);
        editorCallLogPref.putString("city_"+ callRecordID,City);
        editorCallLogPref.apply();
    }
    

    To get call Log details use

    private void getCallDetails(int callRecordID){
        sharedPrefCallLog.getString("name_"+ callRecordID, null);
        sharedPrefCallLog.getString("num_"+ callRecordID, null);
        sharedPrefCallLog.getString("city_"+ callRecordID, null);
    
    }