Reputation: 527
so I have a textview which I'm trying to update from an asynctask. The message I want to update it to correctly prints to the console but for some reason it doesn't update the textview. Here are the relevant bits of code:
public class MainActivity extends AppCompatActivity{
private MqttClient client;
private String clientId = MqttClient.generateClientId();
private TextView tv;
...
I declare the textview here, then I assign it in the onCreate() method:
tv = (TextView) findViewById(R.id.textView5);
Then in my asynctask I have this snippet which runs everytime a new message is posted to MQTT:
@Override
public void messageArrived(String topic, MqttMessage message)
throws Exception {
System.out.println(message);
if(message.toString().toLowerCase().contains(str)){
Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
Matcher matcher = regex.matcher(message.toString());
while(matcher.find()){
System.out.println(matcher.group(1));
tv.setText("testing");
}
}
}
The message correctly prints how I want it to the console but it doesn't update the textview and I'm not sure why.
Upvotes: 0
Views: 79
Reputation: 14825
You should be updating your TextView
in onPostExecute()
of your AsyncTask
.
Here is an example
protected void onPostExecute(Prams) {
tv = (TextView) findViewById(R.id.textView5);
tv.setText("testing");
}
Here the key point is you pass the result of your protected doInBackground(Params)
to onPostExecute()
and it will update your views on UiThread
.
Hope it helps
Upvotes: 1
Reputation: 7288
Make sure you are calling your callback messageArrived
on the UI Thread.
From a background thread, you can write to the log, but you can not update UI elements (like a textbox).
You can run code from a background task on the UI thread using runOnUIThread
runOnUiThread(new Runnable()
{
public void run()
{
// update UI code
}
});
In you case, that would mean moving either the call to the callback (e.g. callback.messageArrived(..)
) or setting the textview (tv.setText("testing");
) from the runnable
Upvotes: 1