简体   繁体   中英

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?

Any suggestion would be really helpful, thanks:)

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM