Asyntask: why update UI Thread in doInbackground will meet error?

二次信任 提交于 2020-01-02 07:52:51

问题


when I read document about asyntask, they say that: "should not" update UI thread in doInbackground because doInbackground work on different thread.

that means : this action will dangerous because UI Thread isn't thread-safe. I understand it. but when I try for test what happen when I update UI Thread in this function. I receive error: (but error doesn't not look like because 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 for me. Does we shouldn't or mustn't .

thanks :)


回答1:


what I have understand so far with android is...,

we can't update UI thread from background thread. May be it is the case they have stopped us to update UI from background thread.

The reason for that is very clear... @ OS level there will be so many thread will be running.

And also different thread from different application, And in that case It will be chaos on the screen, if we can update UI from bg-thread




回答2:


Inside the doInBackgroundyou will not get the UI access. If You Want to take UI access publishProgress from doInBackgroundyou will go to the onProgressUpdate from there do what you wan to show on UI.

Below is the Code you will check for your reference :

class DownloadAsyncTask 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();
        }*/
    }

}



回答3:


so you have to update ui only on the OnPostExecute & OnPreExecute. here's a good example of asynctask. give it a try

you call it by

new SaveProfile().execute();

then this...

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();
         }
     }
}



回答4:


When you create a Aysnc task the doInBackground method runs in the separate thread from UI thread. So you cannot update the UI from this method.

The OnPostExecute and onPreExecute method execute in the same thread as UI thread. For further reading go here




回答5:


If only one thread is allowed to touch the user interface, Android can guarantee that nothing vital is changed while it’s measuring views and rendering them to the screen It is because .. User Interface can be updated only on mainthread..all the user interface objects in your screen are maintained by this mainthread....now if you try to change the user interface from some other thread(do in background)in this case.. it causes error because..for example.. if you try to change the seekbar(some widget) value from other than main thread.. and the user is trying to put a different value...then it is ambiguous for android.. as to which thread it should listen... hope it clarifies your doubt..

So, it is like we should'nt try to.. and because of its security.. we cannot try also.. as it gives error.. =]




回答6:


doInBackground is used to perform heavy calculations or any background work you want to perform in your activity. when the operation in your doinbackground method finished the on postexecute methods upadates your ui.. in short doinbackground is not used to update ui.




回答7:


I think the answer is that we mustn't

It just doesn't seem logical to me.. its like trying to change the radio station at another car driving beside you.. the architecture just doesn't work that way.. you can decide on a radio station before you set off to your road trip or when you stop driving and theoretically you can yell to him and ask him to change the station but you cannot do it yourself.




回答8:


As doInBackground() runs on separate thread and onPostExecute runs on UIMain thread and as per constraint provided by Android you cannot update UIMain Thread from other thread.

Because of above mentioned reason you are getting mentioned message while you are running your application.



来源:https://stackoverflow.com/questions/9801322/asyntask-why-update-ui-thread-in-doinbackground-will-meet-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!