Unable to invoke no-args constructor for interface android.app.IAlarmManager

10,045

You cannot use Gson simply if you have instances of a third class declared inside your custom class.

In your case you have instance of Calendar inside your class AnAlarm. Remove it and try again!

If you are forced to use it anyway, please make use of instance creator for your class. See this article: https://futurestud.io/tutorials/gson-advanced-custom-instance-creator

Share:
10,045
Muzzammil Hussain
Author by

Muzzammil Hussain

Updated on June 07, 2022

Comments

  • Muzzammil Hussain
    Muzzammil Hussain about 2 years

    I've gone through many articles but none of them answered my case. I am trying to get an ArrayList of my custom class type AnAlarm from already stored SharedPreferences. I've stored the ArrayList alarms in the SharedPreferences as a Json String and now I am trying to get this ArrayList by using the following code:

                String alarms_temp_string=preferences.getString("alarms",null);
                if(alarms_temp_string==null){
                   alarms =new ArrayList<AnAlarm>();
                   }
    
                Gson gson = new Gson();
                Type type=new TypeToken<ArrayList<AnAlarm>> (){}.getType();
                ArrayList<AnAlarm> alarms=gson.fromJson(alarms_temp_string,type);
                adapter=new RecyclerViewAdapter(alarms);
    

    But I am getting the following exception:

       java.lang.RuntimeException: Unable to invoke no-args constructor for interface android.app.IAlarmManager. Registering an InstanceCreator with Gson for this type may fix this problem.
    

    on this line of code:

    ArrayList<AnAlarm> alarms=gson.fromJson(alarms_temp_string,type);
    

    When I comment the above line, the remaining program runs smoothly.

    Following is my custom class AnAlarm code:

    public class AnAlarm {
    
        private Calendar calendar;
    
        public AnAlarm(){}
    
        public AnAlarm(Calendar calendar) {
    
            this.calendar = calendar;
    
        }
    
        public Calendar getCalendar() {
            return calendar;
        }
    
        public void setCalendar(Calendar calendar) {
            this.calendar = calendar;
        }
    
    
    }
    

    In this class there is also a no-Arguments constructors as well as all getters and setters are present. Why am I getting this issue? Thanks in advance!