从服务器加载数据时如何处理用户界面

How to handle user interface while data is loading from server

我正在从服务器下载图像和数据,它在几秒钟后出现并填充了包含图像地址的对象的数组列表,而且你知道 recyclerView 的 onBindViewHolder 比从服务器获取数据更快。

因此在 onBindViewHolder 中,我使用 picasso 从 arraylist 中的地址加载数据,在这种情况下(你知道 onBindViewHolder 运行速度比从服务器获取数据快)当 arraylist 仍然为空时(因为数据不是来自服务器)picasso 尝试访问 arraylist 中的对象并结束 outOfboundException

我想要 onbindViewHolder(或者可能是 picasso)等到数据到来并且 arraylist 不为空然后开始通过 picasso 加载图像我该怎么做,我的实现:

 Picasso.with(mContext)
                    .load(NetworkUtils.getList().get(getAdapterPosition()).getImage()).placeholder(R.drawable.flower)
                    .into(mMovieImageView);

截击响应:

public void onResponse(Object o) {
    try {
        JSONObject jsonObject = new JSONObject(o.toString());
        arrayData = jsonObject.getJSONArray("results");

    } catch (JSONException e) {
        e.printStackTrace();
    }

    for(int i =0; i < 50; i++) {

        data = new ModelDataClass();

        try {
            if (arrayData.equals("")) {
                Log.i("mainactivity " , "null array data");
            }
            else{
                response = arrayData.getJSONObject(i);
                data.setTitle(response.getString("original_title"));
                data.setRating(response.getDouble("vote_average"));
                data.setDescription(response.getString("overview"));
                data.setImage(response.getString("poster_path"));}

            }catch(JSONException e){
                e.printStackTrace();
            }
            list.add(data);

        }

您必须在 onResponse 方法中设置 UI,当您已经从服务器获取数据并对其进行解析时。这是最佳的用户体验实践。在加载时向用户显示进度条或模拟。

public void onRequestStart(){
  showProgressBar(true);
}

public void onResponse(){
 //fetch your data
 //add your data to list or arrayList
 showProgressBar(false);
 setupRecycler(list);
}

public void setupRecycler(List<Object> response){
 YourRecyclerViewAdapter adapter = new YourRecyclerViewAdapter(response);
 recyclerView.setLayoutManager(...); // your layout manager
 recyclerView.setAdapter(adapter);
}