I have a recycler view that i want to update it.It likes Instagram Posts that gets post datas from a Server and add it to Array list and update Adapter with notifyDataSetChanged() function.but when it want to update gets this error.
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7905)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1276)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.view.View.requestLayout(View.java:22139)
at android.support.v7.widget.RecyclerView.requestLayout(RecyclerView.java:3970)
at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:5060)
at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:11540)
at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:6762)
at com.example.MainActivity$2.run(MainActivity.java:179)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:257)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)
This is my code
AsyncTask.execute(new Runnable() {
@Override
public void run() {
while (true) {
String name = getHtml.getUrlContent("URL" + something);
something += 1;
list.add(new Model(Model.IMAGE_TYPE, name));
adapter.notifyDataSetChanged();
}
}
});
I thought that errors occurred because of AsyncTask and then i changed it to runOnUiThread() function but this method first gets all data and then create View and because of that app gets too long to start. What can i do?
Your approach is not the greatest, may have many issues but you can use
runOnUiThread(new Runnable() {
void run() {
adapter.notifyDataSetChanged();
}
});
Other solution would be make a class Extend it from AsyncTask, override doInBackground and on post execute method. Fetch data on doInBackground() and update ui onPostExecute()
Guide: https://developer.android.com/reference/android/os/AsyncTask
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.