shivram
shivram

Reputation: 469

Android:CalledFromWrongThreadException in AsyncTask in the onProgressUpdate function

This is a very simple program which calls the asynctask on button click, which changes the textview.

But on button click it gives a CalledFromWrongException.

public class FragmentC extends Fragment {
public FragmentC() {
    }
public View contentViewC;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    contentViewC = inflater.inflate(R.layout.fragment_fragment_b, container, false);

    Button button = (Button) contentViewC.findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (MainActivity.filepath != "Nothing") {
                Frequency getFreq=new Frequency();
                getFreq.execute();
       }

        }

    });
    return contentViewC;
}
private class Frequency extends AsyncTask<Void, Float, Void> {
    @Override
    protected Void doInBackground(Void... params) {
            onProgressUpdate();
        return null;
    }

    @Override
    protected void onProgressUpdate(Float... values) {
      textToChange.setText("Demo");
    }
}

Upvotes: 0

Views: 84

Answers (1)

kalyan pvs
kalyan pvs

Reputation: 14590

Dont call onProgressUpdate() directly

You just call publishProgress() from doInBackground(), then AsynchTask call onProgressUpdate() in the UI thread.

In Android only in main thread we update the UI

For more check this onProgressUpdate() documnet

Upvotes: 1

Related Questions