In my main activity I start an AlarmManager. The Intent of this AlarmManager is a class which extends BroadcastReceiver. Now, in this BroadcastReceiver class I execute an AsyncTask in the onReceive()
method. The doInBackground()
method of this AsyncTask calls a method which starts a new instance of a Runnable. And in the run()
method of this Runnable I do some data polling and save the data to SharedPreference and/or an SQLiteDatabase.
Back in my main activity I want to know these values that have been read and saved. This works fine for some values. I read by using SharedPreferences and/or the SQLiteDatabase.
I can see that when one value changes (the polling thread is reading values that change every 5 minutes, the correct value is stored in the database, but when I read it afterwards in the main activity I just get the old value.
Here's an example of what I do:
I have a helper class called Util. This is called from the run()
method:
Util.storeT1(db, <float value>);
Here's the method:
public static void storeT1(DBAdapter db, float value) {
db.open();
long id = 0;
id = db.insertFloat("T1", value);
if (id == -1) { // if error
}
db.close();
}
In the main activity, I do:
float val = Util.getT1(db);
Here's the method:
public static float getT1(DBAdapter db) {
float i = 0;
db.open();
Cursor c = db.get("T1");
if (c.moveToFirst()) {
do {
i = c.getFloat(0);
} while (c.moveToNext());
}
c.close();
db.close();
return i;
}
In the above, db
is an instance of my DBAdapter class, which is a class handling the database. Relevant methods:
public Cursor get(String column) throws SQLException {
Cursor mCursor = db.query(DATABASE_TABLE, new String[] { column },
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public long insertFloat(String key, Float value) {
ContentValues initialValues = new ContentValues();
initialValues.put(key, value);
return db.insert(DATABASE_TABLE, null, initialValues);
}
So, how do I share data correctly between the Runnable and my Activity? I have a feeling it's because of the multiple threads, but I don't know how to fix this.
Edit:
I should mention that when I do this:
float val = Util.getT1(db);
I get the value 0.0, not the value saved from the Runnable.