Saturday, 15 September 2012

android - Sharing data between Runnable and Activity -



android - Sharing data between Runnable and Activity -

in main activity start alarmmanager. intent of alarmmanager class extends broadcastreceiver. now, in broadcastreceiver class execute asynctask in onreceive() method. doinbackground() method of asynctask calls method starts new instance of runnable. , in run() method of runnable info polling , save info sharedpreference and/or sqlitedatabase.

back in main activity want know these values have been read , saved. works fine some values. read using sharedpreferences and/or sqlitedatabase.

i can see when 1 value changes (the polling thread reading values alter every 5 minutes, right value stored in database, when read afterwards in main activity old value.

here's illustration of do:

i have helper class called util. called run() method:

util.storet1(db, <float value>);

here's 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 main activity, do:

float val = util.gett1(db);

here's method:

public static float gett1(dbadapter db) { float = 0; db.open(); cursor c = db.get("t1"); if (c.movetofirst()) { { = c.getfloat(0); } while (c.movetonext()); } c.close(); db.close(); homecoming i; }

in above, db instance of dbadapter class, class handling 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(); } homecoming mcursor; } public long insertfloat(string key, float value) { contentvalues initialvalues = new contentvalues(); initialvalues.put(key, value); homecoming db.insert(database_table, null, initialvalues); }

so, how share info correctly between runnable , activity? have feeling it's because of multiple threads, don't know how prepare this.

edit:

i should mention when this:

float val = util.gett1(db);

i value 0.0, not value saved runnable.

android android-sqlite

No comments:

Post a Comment