Search code examples
javaandroidandroid-alarms

Saving multiple instances of alarms


I have an alarm manager which I am having difficulty figuring out a way to

A) store a unique ID for each pending intent alarm
B) a name to identify each alarm with and 
C) a number which represents an alarm sound to be used. 

I was using SharedPreferences for this matter but they can only do one instance of an alarm and I would want to store this data for multiple instances of alarms. I need to persist this data even when the app is closed so that when the user opens the app once again, details of the alarms already set can be seen.

alarm1 -> 2431 -> 12
alarm2 -> 8412 -> 42
alarm3 -> 5425 -> 52

Solution

  • You can always use SQLlite database for storing the values in tables. On the other hand if you insist on saving it in Shared Preference, you can use save an array in SharedPreference and Load an array from it as follows:

    public String[] loadArray(String arrayName) {  
        SharedPreferences prefs = getSharedPreferences("preferencename", 0);  
        int size = prefs.getInt(arrayName + "_size", 0);  
        String array[] = new String[size];  
        for(int i=0;i<size;i++)  
            array[i] = prefs.getString(arrayName + "_" + i, null);  
        return array;  
    }  
    
    public boolean saveArray(String[] array, String arrayName) {   
        SharedPreferences prefs = getSharedPreferences("preferencename", 0);  
        SharedPreferences.Editor editor = prefs.edit();  
        editor.putInt(arrayName +"_size", array.length);  
        for(int i=0;i<array.length;i++)  
            editor.putString(arrayName + "_" + i, array[i]);  
        return editor.commit();  
    }
    

    So for saving an array call:

    String [] alarmNames; // Load the array with values
    saveArray(alarmNames, "nameOfAlarms");
    
    String [] alarmIds; // Load the array with values
    saveArray(alarmIds, "idOfAlarms");
    
    String [] alarmSounds; // Load the array with values
    saveArray(alarmSounds, "soundOfAlarms");
    

    To load the array from shared preferences

    String [] arrName = loadArray("nameOfAlarms");
    String [] arrID = loadArray("idOfAlarms");
    String [] arrSound = loadArray("soundOfAlarms");
    

    See How to properly use load array and save array methods? and Save ArrayList to SharedPreferences for more.

    Hope this helps.