[英]RecyclerView Update
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. 我有一个要更新的回收站视图,它喜欢从服务器获取发布数据并将其添加到阵列列表并使用notifyDataSetChanged()函数更新Adapter的Instagram Posts,但是当它想要更新时会出现此错误。
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. 我以为是因为AsyncTask而发生错误,然后我将其更改为runOnUiThread()函数,但是此方法首先获取所有数据,然后创建View,并且由于该应用启动时间太长。 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. 其他解决方案是使一个类从AsyncTask扩展出来,重写doInBackground和后执行方法。 Fetch data on doInBackground() and update ui onPostExecute()
在doInBackground()上获取数据并更新ui onPostExecute()
Guide: https://developer.android.com/reference/android/os/AsyncTask 指南: https : //developer.android.com/reference/android/os/AsyncTask
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.