延迟从凌乱的服务器下载图像

时间:2017-07-24 12:04:43

标签: android download android-recyclerview android-volley

我尝试使用排球从服务器下载图像并在recyclerview中显示它们。 它工作正常但下载图像非常低。 (每幅图像的大小约为50 kb)。 我能做什么? 是否有更好的优化代码?

这是我的助手班:

public class StartActivity {

  // for recyclerView - downLoad Data
  private static final int LIMIT = 6;
  OnLoadMoreListener onLoadMoreListener;
  int idImage = 1;
  private List<StructUser> structList = new ArrayList<>();
  private AdapterUser adapter;
  private int CURRENT_ITEM = 1;
  private Context context;
  private String TAG = StartActivity.class.getSimpleName();

  //----------------------------------------------------
  public StartActivity(Context context) {
    this.context = context;
  }

  public void getDataAndSetInRecyclerView(RecyclerView recyclerView) {
    loadData(CURRENT_ITEM);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));

    adapter = new AdapterUser(recyclerView, structList, context);


    onLoadMoreListener = new OnLoadMoreListener() {
      @Override
      public void onLoadMore() {

        structList.add(null);
        adapter.notifyDataSetChanged();

        new Handler().postDelayed(new Runnable() {
          @Override
          public void run() {
            structList.remove(structList.size() - 1);
//            adapter.notifyItemRemoved(structList.size());
            loadData(CURRENT_ITEM);
          }
        }, 2000);

      }
    };

    adapter.setOnLoadMoreListener(onLoadMoreListener);
    recyclerView.setAdapter(adapter);
  }

  private void loadData(final int CURRENT_ITEM) {
    String url = Config.DATA_URL + CURRENT_ITEM;
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
      new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {
          ActivityMain.hideProgressBar();
          try {


            for (int i = 0; i < response.length(); i++) {
              JSONObject jsonObject = response.getJSONObject(i);
              StructUser structUser = new StructUser();


              if (!jsonObject.isNull(Config.TAG_TITLE))
                structUser.setNetworkImageView(jsonObject.getString(Config.TAG_TITLE));
              if (!jsonObject.isNull(Config.TAG_IMAGE_URL)) {
                structUser.setNetworkImageView(Config.IMG_SERVER + idImage + ".png");
                idImage++;
              }
              structList.add(structUser);


            }
            adapter.notifyDataSetChanged();

            adapter.setLoaded();

            // not show progressBar at end of list when get all data

            if (response.toString().contains("[]")) {
              adapter.reachEndList();
              Toast.makeText(context, "not More Data to Show", Toast.LENGTH_SHORT).show();
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
        // hide progressBar
        ActivityMain.hideProgressBar();

        Log.e(TAG, "Login Error: " + error.getMessage());
        Toast.makeText(context,
          error.getMessage(), Toast.LENGTH_LONG).show();

      }
    });
    AppController.getInstance().addToRequestQueue(jsonArrayRequest, TAG);
    this.CURRENT_ITEM = this.CURRENT_ITEM + LIMIT;
  }


}

这是我的适配器:

public class AdapterUser extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  private final int VIEW_TYPE_ITEM = 0;
  private final int VIEW_TYPE_LOADING = 1;
  public int visibleThreshold = 2;
  boolean isLoading;
  private int lastVisibleItem, totalItemCount;
  private List<StructUser> structList = new ArrayList<>();
  private OnLoadMoreListener mOnLoadMoreListener;
  private Context context;

  // load image from server -------------------------------------------------
  private static ImageLoader imageLoader = ImageLoader.getInstance();
  public static DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showImageOnLoading(R.mipmap.ic_cloud_download)
    .showImageForEmptyUri(R.mipmap.ic_picture)
    .showImageOnFail(android.R.drawable.ic_dialog_alert)
    .cacheInMemory(true)
    .cacheOnDisk(false)
    .considerExifParams(true)
    .bitmapConfig(Bitmap.Config.RGB_565)
    .build();
  //---------------------------------------------------------------


  public AdapterUser(RecyclerView mRecyclerView, List<StructUser> structList, Context context) {

    this.context = context;
    this.structList = structList;
    final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
      @Override
      public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        totalItemCount = linearLayoutManager.getItemCount();
        lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();



        if (!isLoading && totalItemCount <= visibleThreshold + (lastVisibleItem)) {
          if (mOnLoadMoreListener != null) {
            mOnLoadMoreListener.onLoadMore();
          }
          isLoading = true;
        }
      }
    });
  }


  public void setLoaded() {
    isLoading = false;
  }

  public void reachEndList() {
    isLoading = true;
  }

  //========================================================
  @Override
  public int getItemViewType(int position) {
    return structList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
  }

  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    if (viewType == VIEW_TYPE_ITEM) {
      View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_start_activity , viewGroup, false);
      return new UserViewHolder(view);
    } else if (viewType == VIEW_TYPE_LOADING) {
      View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
      return new LoadingViewHolder(view);
    }
    return null;
  }

  @Override
  public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof UserViewHolder) {
      UserViewHolder userViewHolder = (UserViewHolder) holder;
      StructUser user = structList.get(position);
      userViewHolder.title.setText(user.getTitle());

// load image from server
      imageLoader.displayImage(user.getNetworkImageView(), userViewHolder.networkImageView, options);




    } else if (holder instanceof LoadingViewHolder) {
      LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
      loadingViewHolder.progressBar.setIndeterminate(true);
    }
  }

  @Override
  public int getItemCount() {
    return structList == null ? 0 : structList.size();
  }

  public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
    this.mOnLoadMoreListener = mOnLoadMoreListener;
  }


  class UserViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    // for download & cash image
    public ImageView networkImageView;

    public UserViewHolder(View itemView) {
      super(itemView);
      title = (TextView) itemView.findViewById(R.id.txtTitle);
      networkImageView = (ImageView) itemView.findViewById(R.id.networkImageView);

    }
  }

  class LoadingViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    public LoadingViewHolder(View itemView) {
      super(itemView);
      progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
    }

  }



}

1 个答案:

答案 0 :(得分:0)

使用Glide下载图片...

Glide.with(ActivityName.this)
.load(image_url)
.into(imageView_object);

它将下载图像并在ImageView中设置。