【问题标题】:How to handle user interface while data is loading from server从服务器加载数据时如何处理用户界面
【发布时间】:2018-01-16 13:09:29
【问题描述】:

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

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

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

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

Volley 的响应:

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

        }

【问题讨论】:

    标签: java android arraylist android-volley picasso


    【解决方案1】:

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

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

    【讨论】:

    • 我们不能使用 rxjava 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多