Android RecyclerView适配器未初始化

时间:2016-10-06 23:14:17

标签: java android android-recyclerview

首先抱歉我的英语不好。 我正在使用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]);

  }
}

1 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助,你正在拨打互联网电话,这就是为什么当收到回复然后你可以添加

x = e.originalEvent.touches[0].pageX; //<-- In a function like function(e){}
//Same for y.
y = e.originalEvent.touches[0].pageY;
if (x == y)
{
  //Click
}
else
{
  //Swipe
}

这个你的Adapter类请在你的适配器中添加“添加”功能而不是外部因为它会使你的代码看起来更糟糕和复杂。

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();
        }
    });
}