[英]Android RecyclerView Adapter not initialize
起初為我的英語不好對不起。 我正在使用Android RecyclerView。 從我的Activity向服務器發送數據請求,並通過調用onCreate方法中的sendRequestForHistory()方法從服務器獲取響應。 調用sendRequestForHistory()之后,然后初始化我的數據適配器,但這里的ArrayList為空。 在sendRequestForHistory()方法中,從服務器獲取數據並添加到ArrayList。 我的代碼是這樣的。
public class HistoryActivity extends AppCompatActivity {
private Toolbar toolbar;
private ProgressDialog PD;
private RecyclerView recyclerView;
private HistoryAdapter historyAdapter;
private Boolean isInternetPresent = false;
private ConnectionDetector cd;
private TextView tvEmptyView;
private ArrayList<ItemHistory> itemHistories;
protected Handler handler;
private LinearLayoutManager linearLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
dbHelper= new DatabaseHelper(this);
handler = new Handler();
itemHistories = new ArrayList<ItemHistory>();
toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle(brandName);
setSupportActionBar(toolbar);
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view_history);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
sendRequestForHistory();
// Here itemHistories is empty.
historyAdapter = new HistoryAdapter(itemHistories, recyclerView);
recyclerView.setAdapter(historyAdapter);
historyAdapter.notifyDataSetChanged();
}
private void sendRequestForHistory() {
//send request to server and get response history data
// then history dada add to itemHistories ArrayList
itemHistories.add(new ItemHistory(requestReceiver[i], requestAmount[i],requestCost[i]);
}
}
希望對您有幫助,您正在撥打互聯網,這就是為什么當收到回復時您可以添加
private void sendRequestForHistory() {
ApiClient.getArticles(page, category_name, type).enqueue(new Callback<List<Article>>() {
@Override
public void onResponse(Call<List<Article>> call, Response<List<Article>> response) {
if(response.isSuccessfull()){
for(Article article: response.body().getList()){
historyAdapter.addItem(article);
}
}else{
Toast.makeText(getContext(),response.message(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<Article>> call, final Throwable t) {
Toast.makeText(getContext,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
這是您的Adapter類,請在適配器的內部而不是外部添加“ Adding”功能,因為這會使您的代碼看起來更加糟糕和復雜。
public class HistoryAdapter{
private ArrayList<Article> articleList;
public HistoryAdapter(......){
articleList = new ArrayList<>();
.....
}
.....
.....
public void addItem(Article article){
articleList.add(article);
notifyDataSetChanged();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.