I'm developing an android application, and I have a button which starts/pauses certain simulation process. While this process is running, I need to output some data from it real-time. But when I create a new thread for the simulation, I can't access views (let it be TextView) from this thread, because they only can be accessed from the thread where they were created. On the other hand, new thread is necessary because otherwise user wouldn't be able to do anything while simulation is running (for example, press some other buttons). Creating a new service also requires creating a new thread in this case. How should I solve this problem?
You can handle it in many ways,
Try to use AsyncTask in this, your background work done in doInBackGround() method, and your UI will not block and you can also access the views of Activity from where you call AsyncTask by its context via publishProgress() and onProgressUpdate() .
If you are using a simple Thread then using Handler or message or runOnUiThread you can update the view of main thread.
but, in your way I think AsyncTask is best for you.
You can solve the problem with android.os.Handler. Handler instance is bound to the thread that creates it, you can post Runnables to it and it will execute them in the thread it is bound to. For example:
import android.os.Handler;
import android.widget.TextView;
public class MyActivity extends Activity {
private Handler uiHandler;
private TextView simulationStatus;
@Override
public void onCreate(Bundle savedInstanceState) {
...
uiHandler = new Handler();
...
simulationStatus = (TextView) findViewById(R.id.simulationStatus);
...
}
// This method is to be executed on the simulation thread.
public void simulate() {
...
final String simulationStatusText = ...;
...
uiHandler.post(new Runnable() {
@Override
public void run() {
// This is run on the UI thread.
simulationStatus.setText(simulationStatusText);
...
}
});
}
...
}
You can also use AsyncTask. See the link for example.
They can be accessed but only read-only. What you mean is you want to trigger changes from a thread on the views. From the worker thread (non-UI) these changes cannot be triggered, you need to use .runOnUiThread()
or use Handlers
. Use these at the point where you want to show something, e.g update the textview in .runOnUiThread(),
Example:
myThread = new Thread()
{
@Override
public void run() {
//yourOperation
MyActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
if(e!=null)
{
myTextView.setText("something");
}
}});
super.run();
}
};
myThread.start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With