java–Android领域不正确的线程

java–Android领域不正确的线程,第1张

概述我有2个服务,其中一个是生产者(将对象保存到领域),以及其他从领域读取此对象并在计划任务中将它们发送到REST服务.我的例外:java.lang.IllegalStateException:Realmaccessfromincorrectthread.Realmobjectscanonlybeaccessedonthethreadtheywerecreated.服务

我有2个服务,其中一个是生产者(将对象保存到领域),以及其他从领域读取此对象并在计划任务中将它们发送到REST服务.

我的例外:

java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created. 

服务1:

 this.scheduler.schedule("*/2 * * * *", new Runnable() {        public voID run() {            List<Location> locations = dataStore.getAll(Location.class);            for(Location l : locations) {                try {                    serverEndpoint.putLocation(l);                    l.removeFromrealm();                } catch (SendingException e) {                    Log.i(this.getClass().getname(), "Sending task is active!");                }            }        }    });

服务2:

private LocationListener locationListener = new androID.location.LocationListener() {    @OverrIDe    public voID onLocationChanged(Location location) {        TLocation transferLocation = new TLocation();        transferLocation.setLat( location.getLatitude() );        transferLocation.setLng(location.getLongitude());        dataStore.save(transferLocation);    }}

DataStore实现:

public voID save(RealmObject o) {    this.realm.beginTransaction();    this.realm.copyToRealm(o);    this.realm.commitTransaction();}public <T extends RealmObject> List<T> getAll(Class<T> type) {    return this.realm.allObjects(type);}

解决方法:

您应该为每个线程使用自己的Realm实例:

// query and use the result in another threadThread thread = new Thread(new Runnable() {    @OverrIDe    public voID run() {        // Get a Realm instance for this thread        Realm realm = Realm.getInstance(context);...

来自Realm的文档:

The only rule to using Realm across threads is to remember that Realm,
RealmObject or RealmResults
instances cannot be passed across threads.

Using a Realm across Threads

总结

以上是内存溢出为你收集整理的java – Android领域不正确的线程全部内容,希望文章能够帮你解决java – Android领域不正确的线程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1119974.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存