How to wait for the Api's response to load data dynamically onto recycler Views in Android

I was trying to load the data dynamically from the api's response onto the recycler views and I keep getting this error. I got the response and I don't think it's the problem with async code because when I debugged I got the response and the array is not empty before text in the array is inflated onto a view. Any help would be Appreciated.

screenshot of the error

Card_List_View_Admins.java

package com.craftofcode.amrita_event;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonArrayRequest;
import com.craftofcode.amrita_event.adapter.EventListAdapter;
import com.craftofcode.amrita_event.apiModel.MySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class Card_list_View_Admins extends AppCompatActivity {

    Cache cache;
    Network network;
    RequestQueue requestQueue;

    public EventListAdapter adapter;
//    public String[] Title = {"Peppy paneer Pizza", "Paneer Makhni Pizza", "Cheese Burst Pizza", "Corn Pizza","papperoni pizza","farm house pizza", "vegie deilight pizza","chicken pizza", "tandoori pizza","custom pizza"};
//    public String[] Club = {"Peppy paneer Pizza", "Paneer Makhni Pizza", "Cheese Burst Pizza", "Corn Pizza","papperoni pizza","farm house pizza", "vegie deilight pizza","chicken pizza", "tandoori pizza","custom pizza"};
//    public String[] Date = {"250","260","240.5","350","312","250","260","240.5","350","312"};
    int[] EventImages = {
            R.drawable.p1,
            R.drawable.p2,
    };
    private LinkedList<String> _id;
    private LinkedList<Integer> EventImage;
    //Image URL variable for now
    private LinkedList<String> Url;
    private LinkedList<String> EventTitle;
    private LinkedList<String> Clubname;
    private LinkedList<String> DateEvent;


    RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_list_view_admins);
        // Image Url String for now

        // setting up the Request Queue
        SettingUpRequestQueue();

        SharedPreferences TOKEN = getSharedPreferences("TOKEN", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = TOKEN.edit();

        //pushing token to shared preference
        edit.putString("user-auth-token", "replaced-with-Token");
        edit.commit();

        // Api call is being made Here
        String AdminUsersEventsEndpoint = "https://amrita-events.herokuapp.com/api/admin-users-portal";

        JsonArrayRequest EventCardRequest = new JsonArrayRequest
                (Request.Method.GET, AdminUsersEventsEndpoint, null, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        _id = new LinkedList<>();
                        EventImage = new LinkedList<>();
                        Url = new LinkedList<>();
                        EventTitle = new LinkedList<>();
                        Clubname = new LinkedList<>();
                        DateEvent = new LinkedList<>();

                        System.out.println(response);
                        for(int i = 0; i < response.length(); i++){
                            try {
                                EventImage.addLast(EventImages[i]);
                                System.out.println(response.getJSONObject(i));
                                JSONObject event = response.getJSONObject(i);
                                _id.addLast(event.get("_id").toString());
                                Url.addLast(event.get("ImageUrl").toString());
                                EventTitle.addLast(event.get("Title").toString());
                                Clubname.addLast(event.get("OrganizingClub").toString());
                                DateEvent.addLast(event.get("Date").toString());

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

                        System.out.println(EventTitle);
                        recyclerView = findViewById(R.id.recyclerView);

                        adapter = new EventListAdapter(getApplicationContext(), EventTitle, EventImage, Clubname, DateEvent);
                        recyclerView.setAdapter(adapter);
                        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));


                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error

                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                SharedPreferences TOKEN = getSharedPreferences("TOKEN", Context.MODE_PRIVATE);
                params.put("user-auth-token", TOKEN.getString("user-auth-token","Theif..!"));
                return params;
            }
        };

        //adding the request to Queue
        MySingleton.getInstance(this).addToRequestQueue(EventCardRequest);

    }

    private void SettingUpRequestQueue() {
        cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); //1Mb cap
        network = new BasicNetwork(new HurlStack());
        requestQueue = new RequestQueue(cache, network);
        requestQueue.start();
    }

}

EventListAdapter.java

package com.craftofcode.amrita_event.adapter;


import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.craftofcode.amrita_event.R;

import java.util.LinkedList;

public class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ItemViewHolder> {
    private final LinkedList<String> EventTitle;
    private final LinkedList<Integer> EventImage;
    private final LinkedList<String> OrgClub;
    private final LinkedList<String> EventDate;
    private LayoutInflater ItemLayoutInflater;
    public Context context;


     class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public ImageView ImageEvent;
        public TextView EventTitle;
        public TextView OrgClub;
        public TextView Date;

        //support for buttons
         public Button DeleteButton;
         public Button UpdateButton;
        final EventListAdapter EventsAdapter;

        public ItemViewHolder(View EventView, EventListAdapter EventsAdapter){
            super(EventView);
            ImageEvent = EventView.findViewById(R.id.image);
            EventTitle = EventView.findViewById(R.id.title);
            OrgClub = EventView.findViewById(R.id.club);
            Date = EventView.findViewById(R.id.date);
            DeleteButton = EventView.findViewById(R.id.delbutton);
            UpdateButton = EventView.findViewById(R.id.updbutton);
            this.EventsAdapter = EventsAdapter;
            EventView.setOnClickListener(this);

            DeleteButton.setOnClickListener(this);
            UpdateButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("mess" , "Herllo click");
                    Log.d("mess", String.valueOf(getAdapterPosition()));
                }
            });
        }

        @Override
        public void onClick(View v) {
//            Intent intent = new Intent(context, Expanded_Card_Admins.class);
//            //ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context, v, "ContainerTransform");
//            context.startActivity(intent);
        }
    }

    public EventListAdapter(Context context, LinkedList<String> EventTitle, LinkedList<Integer> EventImage, LinkedList<String> OrgClub,LinkedList<String> EventDate){
        ItemLayoutInflater = LayoutInflater.from(context);
        this.EventTitle = EventTitle;
        this.EventImage = EventImage;
        this.OrgClub = OrgClub;
        this.EventDate = EventDate;
        this.context = context;
    }
    public EventListAdapter.ItemViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
        View ItemView = ItemLayoutInflater.inflate(R.layout.admin_card_view,parent,false);
        return new ItemViewHolder(ItemView, this);
    }

    @Override
    public void onBindViewHolder(EventListAdapter.ItemViewHolder holder, int position) {
        String CurrentEventName = EventTitle.get(position);
        int CurrentEventImage = EventImage.get(position);
        String CurrentOrgClub = OrgClub.get(position);
        String CurrentEventDate = EventDate.get(position);
        holder.EventTitle.setText(CurrentEventName);
        holder.ImageEvent.setImageResource(CurrentEventImage);
        holder.OrgClub.setText(CurrentOrgClub);
        holder.Date.setText(CurrentEventDate);

        //onclick listener here
    }

    @Override
    public int getItemCount() {
        return EventTitle.size();
    }
}

1 answer

  • answered 2021-10-24 20:06 Puneet Grover

    This problem is not in your adapter/java code. I doubt this is in your layout file "admin_card_view" Please double check this layout file, most probably there will have some dependency which is not satisfied yet

    As per mentioned in error - It could be at line no. 19 and in MaterialCardView. Make sure you have dependency added in your build.gradle file for the same

    Please add this in app level build.gradle, clean and rebuild project once and then run your app

    implementation "androidx.cardview:cardview:1.0.0"

    Hope it will resolve your problem

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum