Imagine a app showing the user statistics. I could have an Object like:
public class Statistic {
private int id,value;
}
Where the value should persist between different app executions. Using an database for the persistent system the databaseAdapter could have a:
public void saveStatisticValue(int id,int newValue);
public int getStatisticValue(int id);
Using that calls to the DataBase Adapter in the getter/setter method of the object could impact in the app performance if called from the UI thread due to the database delay. For example if I want to show an Activity with all the Statistics, the database delay of the getter of each Statistic object could result in a ANR.
public class Statistic {
....
public synchronized void setValue(int newValue) {
dbAdapter.saveStatisticValue(this.getId(),newValue);
}
public synchronized int getValue() {
return dbAdapter.getStatisticValue(this.getId());
}
....
}
Is there some kind of approach for reduce the database impact for this kind of models?
Thanks
As you already has observed, the geter/setter method to the Models should be asynchronized.
For example , the API to getter_statics could be :
The
requestCallbackwill be called in the same thread as thegetStaticshas been called, usually it is the UI thread.Two class are provided in Android facilitate you to implement this common pattern: Handler and SyncTask. Please read the document to get a thorough understanding.
You can also to check out this article.