Asyntask: why does updating UI Thread in doInbackground get an error?

when i read the doc about asyntask

, they say: "you shouldn't" update the UI thread in doInbackground because doInbackground works on different threads.

this means that this action would be dangerous because the UI thread is not thread safe. I understand. but when i try to check what happens when i update the UI thread in this function. I get the error: (but the error doesn't look like aysnchonize

but because we CANNOT do it)

   (TextView)((Activity)context).findViewById(R.id.text)).setText("StackOverFlow");
//context: reference of context object of UI Thread

      

Please explain me. We shouldn't

or mustn't

.

thank:)

+3


source to share


8 answers


what I have figured out so far with Android, ...,

we cannot update the UI thread from a background thread. Maybe this is the way they made us update the interface from a background thread.



The reason for this is very clear ... @ OS level will be there , so many threads will be running.

And also another thread from another application . And in this case, there will be chaos on the screen if we can update the interface from bg-thread

+8


source


Inside doInBackground, you won't be able to access the user interface. If you want to use the publishProgress UI access from doInBackground, you will go to onProgressUpdate to do what you want the interface to show.

Below is the code you will check for reference:



the DownloadAsyncTask class extends AsyncTask {

    ProgressDialog progressDialog;


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(Login.this, "", "Please Wait ...");
    }



    @Override
    protected Void doInBackground(String... arg0) {

        int status1 = validationuser(username);
        Log.i("MyLog", "Inside the doInBackground is came"+status1);

        if(status1 == 1)
        {
            publishProgress(status1+ "Valid User Code","1",""+status1);
        }
        else
        {
            publishProgress(status1+ " Invalid Valid User Code","0",""+status1);
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String...values){
        super.onProgressUpdate(values);

        int index = Integer.parseInt(values[2]);

        if(index == 1)
        {
            USERIDLOGIN = edittextuserName.getText().toString();
            Intent intent=new Intent(Login.this, CollectionModuleandDownload.class);
            /*Toast.makeText(Login.this, "Valid User Password", Toast.LENGTH_SHORT).show();*/
            startActivity(intent);
            progressDialog.dismiss();
        }
        else
        {
            Toast.makeText(Login.this, "Invalid Username & Password", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onPostExecute(Void result){
        super.onPostExecute(result);
        /*if(progressDialog != null)
        {
            progressDialog.dismiss();
        }*/
    }

}

      

+2


source


so you only need to update ui in OnPostExecute and OnPreExecute. here's a good example of asynctask. try it

you call it

new SaveProfile().execute();

      

that is...

private class SaveProfile extends AsyncTask<String, Void, Boolean>{

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


        //---------- so your stuff here.... non ui related

        Log.v("response from saving",response);

        if(response.equals("1")){

            return true;                
        }else{

            return false;
        }
    }

    protected void onPostExecute(Boolean result) {

         if(result) {

                      //------ UPDATE UI HERE
             Toast.makeText(ProfileCompanyActivity.this, "profile saved", 2500).show();
         }else{
             Toast.makeText(ProfileCompanyActivity.this, "an error occured", 2500).show();
         }
     }
}

      

+1


source


When a task is created, the Aysnc

method doInBackground

runs on a separate thread from the UI thread. Thus, you cannot update the UI from this method.

The method OnPostExecute

and onPreExecute

is executed on the same thread as the UI thread. For further reading go here

+1


source


If only one thread can touch the UI, Android can ensure that nothing significant gets changed while its measuring views and rendering them to the screen. This is because ... UI can only be updated on mainthread .. all objects the UI on your screen are supported by this mainthread .... now if you try to change the UI from some other thread (do it in the background) in this case .. it throws an error because ... for example if you try to change the value of the search parameter (of some widget) from another main thread .. and the user tries to put a different value ... then it is ambiguous for android .. which thread should he listen to ... hope this clears up your doubt ..

So it looks like we shouldn't try .. and because of its security .. we can't try either .. because it gives an error .. =]

0


source


doInBackground is used to do heavy computation or whatever background work you want to do in your activity. when the operation in your doinbackground method is finished on the postexecute methods, upadates your ui .. In short, the doinbackground is not used to update the ui.

0


source


I think the answer is that we shouldn't

It just doesn't seem logical to me. it is like trying to change the radio station on another car driving next to you. architecture just doesn't work .. you can choose a radio station before you go on a trip or when you stop driving and in theory you can yell at him and ask him to change stations, but you can't do it yourself.

0


source


How doInBackground () works in a separate thread and onPostExecute works in a UIMain thread, and according to the limitation provided by Android, you cannot update a UIMain thread from another thread.

Due to the above reason, you are getting the mentioned message during your application startup.

0


source







All Articles