我有一个应用程序,我想存储一个项目列表,我认为数据库可以做。我发现了新的Room API并尝试使用它,尽管我在使用它时遇到了一些麻烦。我有一个后台服务,应该写入数据库的条目。我读到了使用单例模式的建议,但我似乎无法让它工作。当我尝试检索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
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);
}
后台服务,保存到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是从db读取的,使用Async任务所以它不会阻止UI private void updateTemperature(){ Log.d(TAG,&#34; updateTemperature&#34;);
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();
}
也许它与某种情况有关?
编辑:
刚刚在构建数据库时尝试添加.allowMainThreadQueries()
,现在它可以运行了。所以出于某种原因我的异步任务不起作用?
答案 0 :(得分:0)
您的AsyncTask似乎有误。你应该在doInBackground中返回你想要处理的列表,然后在onPostExecute中预期它。为什么总是返回0?