How to set text of text view in another thread
Solution 1:
You need a reference to that textview and then do:
textView.post(new Runnable() {
public void run() {
textView.setText(yourText);
}
});
in Kotlin:
val textView: TextView = findViewById(R.id.textView)
textView.post(Runnable { textView.setText(yourText) })
Solution 2:
Use runOnUiThread
for updating the UI control. In your case:
runningActivity.runOnUiThread(new Runnable() {
public void run() {
tv.setText(p + " %");
}
});
Edited:
Activity mActivity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mActivity= this;
...
..//The rest of the code
} //close oncreate()
thread{
mActivity.runOnUiThread(new Runnable() {
public void run() {
tv.setText(p + " %");
}
});
}
Solution 3:
Either you can use runOnUiThread
or use Handler
to set text in TextView.
Solution 4:
You can use handle
:
handler.post(new Runnable() {
public void run() {
textView.setText(yourText);
}
});
But your textView
and yourText
must be class fields.
In your thread (activity) where you create textView
use:
Handler handler = new Handler();
And pass handler
into another thread.