简体   繁体   中英

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. 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.

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
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");

    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. So for some reason my Async task isn't working?

Your AsyncTask seems to be wrong. You should return the list you would like to handle in doInBackground and then expect it in onPostExecute. Why do you always return 0?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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