Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 以有效的UI性能持久化数据的有效方法_Java_Android_Database - Fatal编程技术网

Java 以有效的UI性能持久化数据的有效方法

Java 以有效的UI性能持久化数据的有效方法,java,android,database,Java,Android,Database,想象一个显示用户统计信息的应用程序。我可以有这样一个对象: public class Statistic { private int id,value; } 在不同的应用程序执行之间,该值应保持不变。使用持久化系统的数据库时,databaseAdapter可能具有: public void saveStatisticValue(int id,int newValue); public int getStatisticValue(int id); 如果由于数据库延迟而从UI线程调用,

想象一个显示用户统计信息的应用程序。我可以有这样一个对象:

public class Statistic {
     private int id,value;
}
在不同的应用程序执行之间,该值应保持不变。使用持久化系统的数据库时,databaseAdapter可能具有:

public void saveStatisticValue(int id,int newValue);
public int getStatisticValue(int id);
如果由于数据库延迟而从UI线程调用,则在对象的getter/setter方法中使用对数据库适配器的调用可能会影响应用程序的性能。例如,如果我想显示一个包含所有统计信息的活动,那么每个统计对象的getter的数据库延迟可能会导致ANR

public class Statistic {

    ....

    public synchronized void setValue(int newValue) {
        dbAdapter.saveStatisticValue(this.getId(),newValue);
    }
    public synchronized int getValue() {
        return dbAdapter.getStatisticValue(this.getId());
    }

    ....

 }
是否有某种方法可以减少这种模型对数据库的影响


正如您已经观察到的,模型的geter/setter方法应该是异步的

例如,getter_statics的API可以是:

Request getStatics(RequestCallback callback);

interface RequestCallback {
        void notify(int id ,int value);
}
调用
requestCallback
的线程与调用
getStatics
的线程相同,通常是UI线程

Android中提供了两个类来帮助您实现这种常见模式:和。请仔细阅读这份文件,以便彻底理解

您还可以查看文章。

是的,它被称为。正是为了这个目的。您可以重写doInBackground方法并在那里执行数据库工作。完成后,可以在重写的onPostExecute方法中更新ui。