Search code examples
androiddatabasesqliteandroid-contentprovidersugarorm

How to implement the notifyDatasetChange with Sugar ORM


I have been wondering how your model define using sugar ORM can de notified of data set changed such as with android Content Providers. I have a situation where i updated a model record in one activity and move to the previous activity, but the data is not reloaded when i move to the previous activity. Don't know how the model can be aware that the data has change(updated) and automatically reload it self.


Solution

  • What you are actually talking about is a SyncAdapter implementation on an ORM like SugarOrm which to my knowledge am not sure if sugar has such an implementation. You will have to do a custom implementation to achieve such a functionality. Here's a few approaches that may work for you.

    1. You can should load your data/models in the onResume method of your activities/fragments. Here we may garantee that you have the latest snapshot of the data in the database and even when you come back from a different activity, it should already be updated.
      1. You can implement a static Broadcast receiver for your activities like so

    public class MyModel extends SugarRecord implements Serializable{

    int m_id;
    String m_name;
    
    public MyModel(){}
    
    public void setter(...){...}
    public Object getter(){...}
    

    }

    Activity 1 inside onCreate(...)

    BroadcastReceiver dataBroadcast = new BroadcastReceiver{

    public void onReceive(Context context, Intent intent){
        //retrieve the data model here from the intent or setdata for your adapter by loading all the data from the database
        MyModel model = intent.getSerializableExtra("MYDATA");
    }
    

    };

    registerBroadCast(dataBroadcast, new IntentFilter("DATA_CHANGED"));

    inside on Destroy() unregisterReceiver(dataBroadcast);

    Activity 2 inside your update/create model method for example

    void createMyModel(){
        MyModel m = new MyModel();
        m.setMname("ice");
        long saveId = m.save();
        if(saveId > 0){
    //fire the broadcast which activity 1 will receive and process accrodingly
            Intent mIntent = new Intent("DATA_CHANGED");
            mIntent.putSerializable("MYDATA", m);       
            sendBroadcast(mIntent)  
        }
    }