Reputation: 1800
I have try to update my TextView in Thread, but not able to do, below code shows my try
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
String add = null;
public void run() {
add = Util.getLocationCityName(String.valueOf(ltlng.latitude),String.valueOf(ltlng.longitude));
handler.post(new Runnable() {
public void run() {
LogUtil.d("add" + add);//i can get the add value
vImei.setText(add);
}
});
}
};
new Thread(runnable).start();
i can able to get the add value which is inside handler but values are not update to my textview, dont know what mistake i have done
Upvotes: 0
Views: 104
Reputation: 15821
Try to init Handler with looper
final Handler handler = new Handler(Looper.getMainLooper());
Also you can try :
private LooperThread mLooperThread;
class LooperThread extends Thread
{
public Handler mHandler;
public void run()
{
Looper.prepare();
mHandler = new Handler()
{
public void handleMessage(Message msg)
{
vImei.setText(msg.getData().getString("ADD"));
}
};
Looper.loop();
}
}
create Looper :
mLooperThread = new LooperThread();
mLooperThread.start();
and when you need to update :
Bundle bundle = new Bundle();
bundle.putString("ADD", add);
Message msg = Message.obtain();
msg.setData(bundle);
mLooperThread.mHandler.sendMessage(msg);
Upvotes: 2
Reputation: 2825
Please try this,
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
String add = null;
public void run() {
add = Util.getLocationCityName(
String.valueOf(ltlng.latitude),
String.valueOf(ltlng.longitude));
runOnUiThread(new Runnable(){
public void run() {
LogUtil.d("add" + add);//i can get the add value
vImei.setText(add);
}
});
}
};
new Thread(runnable).start();
Upvotes: 1
Reputation: 6460
An other solution which solves your problem is the usage of an AsyncTask
AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>(){
@Override
protected String doInBackground(Void... params) {
// runs on its own thread
return Util.getLocationCityName(
String.valueOf(ltlng.latitude),
String.valueOf(ltlng.longitude));
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// runs on the UI Thread to Update your Views
LogUtil.d("add" + result);
vImei.setText(result);
}
};
asyncTask.execute();
Upvotes: 1
Reputation: 397
//Global Initialize
String add = "";// not null
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
add = Util.getLocationCityName(
String.valueOf(ltlng.latitude),
String.valueOf(ltlng.longitude));
handler.post(new Runnable() {
public void run() {
LogUtil.d("add" + add);//i can get the add value
vImei.setText(add);
}
});
}
};
new Thread(runnable).start();
I hope it helps you.. :)
Upvotes: 1