user529543
user529543

Reputation:

Only the original thread that created a view hierarchy can touch its views.onProgressUpdate

enter image description hereStarting from Android 4.0 I have the problem ( on 2.3.6 it is working).

onProgressUpdate it should be already in UI thread. I have tried activity.runOnUiThread now is with a Handler version, ofc first was without any of tham. How to fix it?

public class ReadDataTask extends AsyncTask<String, String, JSONArray> {

    private Activity activity;
    protected ProgressDialog dlg;

    private long startRead, endRead, endJson;

    public ReadDataTask(Activity activity) {
        this.activity = activity;
        dlg = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dlg.show();
        startRead = System.currentTimeMillis();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        if (values != null && values.length > 0) {
            final String msg = values[0];
            new Handler().post(new Runnable() {
                public void run() {
                    dlg.setMessage(msg);// android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                }
            });
        }
    }


    @Override
    protected JSONArray doInBackground(String... params) {
           ... long task here
           publishProgress("Converting to JSON: " + (1 + i) + " / " + dataList.size());

Upvotes: 0

Views: 7168

Answers (3)

Adnan Yousaf
Adnan Yousaf

Reputation: 362

The following worked for me.

myHandler.post(new Runnable() {
            public void run() {
                dlg.setMessage(msg);
            }
        });

Upvotes: 0

Roman Minenok
Roman Minenok

Reputation: 9368

Create handler only once in onPreExecute() which is called from UI thread and save a reference to it, than post to it in onProgressUpdate().

Handler posts to thread that it has been created on.

Upvotes: 3

user529543
user529543

Reputation:

Thanks all! The implementation of solution:

private Activity activity;
protected ProgressDialog dlg;
private Handler myHandler;

private long startRead, endRead, endJson;

public ReadDataTask(Activity activity) {
    this.activity = activity;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    myHandler = new Handler();

    dlg = new ProgressDialog(activity);
    dlg.show();
    startRead = System.currentTimeMillis();
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    if (values != null && values.length > 0) {
        final String msg = values[0];
        myHandler.post(new Runnable() {
            public void run() {
                dlg.setMessage(msg);
            }
        });
    }
}

Upvotes: 0

Related Questions