Search code examples
javaandroidarraylistandroid-volleypicasso

How to handle user interface while data is loading from server


I'm downloading images and data from server, it comes after few seconds and populates arraylist that has objects containing address of image, and you know recyclerView's onBindViewHolder is faster than data fetching from server.

So in onBindViewHolder im using picasso to load data from addresses in arraylist, in this case (you know onBindViewHolder runs faster than fetching data from server) when still arraylist is empty(because data is not come from server) picasso try to accesses object in arraylist and ended up outOfboundException

I want onbindViewHolder(or picasso maybe) wait till data come and arraylist is not empty then start loading images through picasso how can I do that, my implementation:

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

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

        }

Solution

  • You have to setup your UI in onResponse method, when you already got the data from server and parsed it. This is the best UX practice. In the time of loading show a progress bar or analog to the user.

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