简体   繁体   English

在Activity中使用AsyncTask失败

[英]Using AsyncTask in Activity fails

I have an application in which I wanted to store a list of items and I figured a database would do. 我有一个应用程序,我想在其中存储项目列表,并确定数据库可以做到。 I found out about the new Room API and tried using it, though I'm having some trouble getting it working. 我发现了新的Room API,并尝试使用它,尽管在使其正常工作时遇到了一些麻烦。 I have a background service which is supposed to write entries to the database. 我有一个后台服务,应该将条目写入数据库。 I read that using the singleton pattern was recomended, but I can't seem to get it working. 我读到建议使用单例模式,但似乎无法正常工作。 When I try to retrieve all entries in my MainActivity, the list I get back is always empty, indicating that I wasn't able to save them from the start. 当我尝试检索MainActivity中的所有条目时,返回的列表始终为空,表明我从一开始就无法保存它们。

Singleton db class 单例数据库类

@Database(entities = {TemperatureReading.class}, version = 1)
public abstract class DatabaseSingleton extends RoomDatabase {

    private static DatabaseSingleton INSTANCE;

    public abstract TemperatureReadingDao temperatureReadingDao();

    public static DatabaseSingleton getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), DatabaseSingleton.class, "fireTempDatabase")
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Entity 实体

@Entity
public class TemperatureReading {
    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "dateTime")
    private long dateTime;

    @ColumnInfo(name = "location")
    private String readingLocation;

    @ColumnInfo(name = "value")
    private float value;

    public long getDateTime() {
        return dateTime;
    }

    public void setDateTime(long dateTime) {
        this.dateTime = dateTime;
    }

    public String getReadingLocation() {
        return readingLocation;
    }

    public void setReadingLocation(String readingLocation) {
        this.readingLocation = readingLocation;
    }

    public float getValue() {
        return value;
    }

    public void setValue(float value) {
        this.value = value;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
}

EntityDAO 实体DAO

@Dao
public interface TemperatureReadingDao {

    @Query("SELECT * FROM temperatureReading")
    List<TemperatureReading> getAll();

    @Query("SELECT * FROM temperatureReading ORDER BY uid desc limit 1")
    TemperatureReading getLatest();

    @Insert
    void insertAll(TemperatureReading... temperatureReading);

    @Update
    void update(TemperatureReading... temperatureReading);

    @Delete
    void delete(TemperatureReading temperatureReading);
}

Background service which saves to db 保存到数据库的后台服务

private void saveTempDatabase(float tmpMessageAsFloat, long tmpMessageDateTime) {
    Log.d(TAG, "saveTempDatabase");
    TemperatureReading tr = new TemperatureReading();
    tr.setDateTime(tmpMessageDateTime);
    tr.setReadingLocation("XXX"); //TODO
    tr.setValue(tmpMessageAsFloat);
    DatabaseSingleton.getAppDatabase(getApplicationContext()).temperatureReadingDao().insertAll(tr);
}

MainActivity were db is read from, uses Async task so it doesn't block UI private void updateTemperature() { Log.d(TAG, "updateTemperature"); MainActivity是从中读取db的对象,使用Async任务,因此不会阻止UI私有void updateTemperature(){Log.d(TAG,“ updateTemperature”);

    new AsyncTask<Void, Void, Integer>() {
        @Override
        protected Integer doInBackground(Void... params) {

            List<TemperatureReading> tr = DatabaseSingleton.getAppDatabase(MainActivity.this).temperatureReadingDao().getAll(); //List is always empty, no matter how many times I have called the saveTempDatabase() method in the service class.
            return 0;
        }

        @Override
        protected void onPostExecute(Integer agentsCount) {

        }
    }.execute();
}

Maybe it has to do with the context somehow? 也许与上下文有关?

EDIT: 编辑:

Just tried adding .allowMainThreadQueries() when building the database and now it works. 刚刚尝试在构建数据库时添加.allowMainThreadQueries() ,现在它可以工作了。 So for some reason my Async task isn't working? 因此,由于某种原因,我的异步任务无法正常工作?

Your AsyncTask seems to be wrong. 您的AsyncTask似乎是错误的。 You should return the list you would like to handle in doInBackground and then expect it in onPostExecute. 您应该在doInBackground中返回要处理的列表,然后在onPostExecute中使用它。 Why do you always return 0? 为什么总是返回0?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM