3

我使用了Recycler View來顯示我的數據列表。我調用Web服務並從服務器獲取數據,並使用服務器數據更新當前的ArrayList。 這是我如何填寫我當前ArrayList中的數據。通過RecyclerView中的notifyDataSetChanged發佈更新數據

mAlUotesDatas.clear(); 
mAlUotesDatas = (ArrayList<BillBoardData>) webservice.data; 
mUotesAdaptor.notifyDataSetChanged(); 

和應用notifyDataSetChanged()以反映數據的列表中,但它並不反映列表。在mAlUotesDatas它顯示更新的數據,但它不顯示更新的數據列表。

之後,我改變它像

mAlUotesDatas.clear(); 
mAlUotesDatas.addAll(res.data); 
mUotesAdaptor.notifyDataSetChanged(); 

這工作得很好。對我而言,這很令人驚訝,它是如何工作的,雖然兩者在web服務調用後都有更新的數據。

任何人都可以幫助我理解這是怎麼回事。

這是我的班。

package com.mimran.aphorismus.models; 

import android.os.Bundle; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.mimran.aphorismus.R; 
import com.mimran.aphorismus.adapters.QuotesAdaptor; 

import java.util.ArrayList; 

public class DataFragment extends Fragment { 

private RecyclerView mRcvQuotes; 
private QuotesAdaptor mUotesAdaptor; 
private ArrayList<BillBoardData> mAlUotesDatas; 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    mRcvQuotes = (RecyclerView) links(R.id.rcv_quotes); 
    mUotesAdaptor = new QuotesAdaptor(mContext, mAlUotesDatas); 
    mRcvQuotes.setAdapter(mUotesAdaptor); 

    return inflater.inflate(R.layout.my_view, container, false); 
} 

public void webserviceCall() { 
    public void onResponse() 
    { 
     if (response.isSuccess()) { 
      mAlUotesDatas.clear(); 
      //mAlUotesDatas = (ArrayList<BillBoardData>) res.data; 
      mAlUotesDatas.addAll(res.data); 
      mUotesAdaptor.notifyDataSetChanged(); 
     } 
    } 

} 
} 
+0

如果有幫助請接受答案,請:) – mklimek

回答

2

它不起作用,因爲您不會將項目添加到適當的數據收集實例。

Adapter在具有特定數據收集實例的構造函數中進行初始化,並且它始終處理它。

在此之後:

mAlUotesDatas = (ArrayList<BillBoardData>) webservice.data; 

mAlUotesDatas是不同的集合的引用比Adapter的實例。

然後:

mUotesAdaptor.notifyDataSetChanged(); 

實際上通知適配器有關這並沒有改變在「舊」收集數據的變化。

當您使用clearaddAll時,它的工作原理是因爲您使用相同的實例並且正在替換其中的項目。

相關問題