How to get data from thread to activity in android
Here is my Thread
public class ReadPaycardThread implements Runnable {
String applicationLabel = null;
}
I want to use this variable value in the activity.
Runnable isn't a Thread, it's just a "piece of code to execute" but it could be executed in any Thread.
class MainActivity extends Activity {
Handler mMainHandler;
public onCreate(..) {
mMainHandler = new Handler(Looper.getMainLooper()) {
@UiThread @MainThread
public void handleMessage(Message message) {
switch (message.what) {
case 1234: {
final String cApplicationLabel = (String)message.obj;
//YOU CAN USE THIS STRING IN ANY PLACE OF MainActivity like "TextView.setText(cApplicationLabel)"
break;
}
}
}
}
}
@AnyThread
public boolean sendToActivity() {
if (mMainHandler == null) return false;
final String cApplicationLabel = "TEST LABEL";
return mMainHandler.sendMessage(Message.obtain(mMainHandler, 1234, cApplicationLabel));
}
}
You can call "sendToActivity()" from everywhere you "see" it, and it will delivers a String to MainActivity