[英]RecyclerView Update
我有一個要更新的回收站視圖,它喜歡從服務器獲取發布數據並將其添加到陣列列表並使用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)
這是我的代碼
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();
}
}
});
我以為是因為AsyncTask而發生錯誤,然后我將其更改為runOnUiThread()函數,但是此方法首先獲取所有數據,然后創建View,並且由於該應用啟動時間太長。 我能做什么?
您的方法不是最好的方法,可能有很多問題,但是您可以使用
runOnUiThread(new Runnable() {
void run() {
adapter.notifyDataSetChanged();
}
});
其他解決方案是使一個類從AsyncTask擴展出來,重寫doInBackground和后執行方法。 在doInBackground()上獲取數據並更新ui onPostExecute()
指南: https : //developer.android.com/reference/android/os/AsyncTask
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.