Issue
I have moved my code to an async task to perform an operation on the background thread. The code is below:
public class AsynTaskActivity extends AsyncTask<HashMap<String, Integer>, Void, Void>
{
@Override
protected Void doInBackground(HashMap<String, Integer>... hashMaps)
{
HashMap<String, Integer> maps = hashMaps[0];
//
Set set = maps.entrySet();
for (Object aSet : set)
{
Map.Entry entry = (Map.Entry) aSet;
receiveBarcode(entry.getKey().toString());
}
return null;
}
}
However, when running the code base. I encounter the following error:
Process: com.touchsides.checkout.debug, PID: 7447
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)
I would assume that the doInbackground is running on a separate thread and this error should not be encountered.
Solution
In AsyncTask
you can never perform UI interaction in doInBackgound
, however you can still update your UI if you pass the progress or result in onProgressUpdate
and onPostExecute
respectively, and that's how you regain UI thread. You could try changing your AsyncTask
to something like:
public class AsynTaskActivity extends AsyncTask<HashMap<String, Integer>, String, Object> {
@Override
protected Object doInBackground(HashMap<String, Integer>... hashMaps) {
// non-ui thread
HashMap<String, Integer> maps = hashMaps[0];
Set set = maps.entrySet();
for (Object aSet : set) {
Map.Entry entry = (Map.Entry) aSet;
publishProgress(entry.getKey().toString()); // onProgressUpdate callback
}
return null; // onPostExecute callback
}
@Override
protected void onProgressUpdate(String... progress) {
// ui thread
receiveBarcode(progress);
}
@Override
protected void onPostExecute(Long result) {
// ui thread
}
}
AsyncTask is well documented, you can read more about it online.
Answered By - Aaron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.