vdegenne
vdegenne

Reputation: 13270

updating a view from a thread in Android

I have a layout with a TextView say mainTextView.

My activity file looks something like :

public class SecondActivity extends AppCompatActivity {

    private static Integer i = 0;
    private TextView tv = null;


    @override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        tv = (TextView) findViewById(R.id.mainTextView);

        new MyThread().execute();
    }


    private void notifyAChange () {
        tv.setText(i.toString());
    }



    private class MyThread extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground (String... params) {

            while (true) {

                try {
                    i++;
                    Thread.sleep(1000);
                    notifyAChange();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

This returns a FATAL EXCEPTION on runtime. I know I can't touch a view from another Thread except the original one but in that case I am touching the view from the main thread so what is wrong ?

Upvotes: 0

Views: 771

Answers (2)

Abhishek
Abhishek

Reputation: 16

Main use of asyncktask to perform long running task so there are three methods preExecute to set progress bar befor starting executing task, doinbackground to perform task like download data (main thread),post execute to perform task after completion of task you can only change UI component from Post execute while using asynctask. For more info related to asynktask refer https://developer.android.com/reference/android/os/AsyncTask.html and for Implementation and explanation refer AsynkTask ImplementationUpdate UI from Thread you can also use RunonUI therad method and Handler

Upvotes: 0

HelloSadness
HelloSadness

Reputation: 955

Nope you are in the doInBackground part of the AsyncTask (worker thread).
You are calling notifyAChange() form worker thread, not main UI thread.
You should update the UI from onPostExecute. Or you can also use runOnUiThread for the part updating the view.

Upvotes: 1

Related Questions