0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
cantona_7
  • 1,127
  • 4
  • 21
  • 40
  • 4
    https://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – IntelliJ Amiya Oct 10 '19 at 12:41
  • 1
    for me shared preferences is not good to do that you must use database persistece as room (https://developer.android.com/topic/libraries/architecture/room) or Realm (https://realm.io/blog/realm-for-android/) for example – SebastienRieu Oct 10 '19 at 12:45
  • [Save data using SQLite](https://developer.android.com/training/data-storage/sqlite) – Ricardo A. Oct 10 '19 at 12:50
  • I just need to save only 10 call details. Do i really need database ? – cantona_7 Oct 10 '19 at 12:55

1 Answers1

1

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

}
Rishabh Dhawan
  • 519
  • 1
  • 3
  • 11