-2

I am trying to display in my App a list of image with user and number of like from Json-url using RecyclerView and Volley ...actually I followed this tutoriel:https://codinginflow.com/tutorials/android/recyclerview-volley-picasso/part-4-get-request

probably the error came from ExampleAdapter

this is my ExampleAdapter:

public class ExampleAdapter extends 
 RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {

private Context mContext;
private ArrayList<ExampleItem> mExampleList;

public ExampleAdapter(Context context, ArrayList<ExampleItem> examplelist){

}

@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
    return new ExampleViewHolder(v);

}

@Override
public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String imageUrl = currentItem.getmImageUrl();
String creatorName = currentItem.getMcreator();
int likeCount= currentItem.getmLikes();

holder.mTextViewCreator.setText(creatorName);
holder.mTextViewLikes.setText("Likes: "+likeCount);
Picasso.with(mContext).load(imageUrl).fit().centerInside().into(holder.mImageView);
}

@Override
public int getItemCount() {
   //Probably the error came from here
    return mExampleList.size();
}

public class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextViewCreator;
public TextView mTextViewLikes;

public ExampleViewHolder(@NonNull View itemView) {
    super(itemView);
    mImageView=itemView.findViewById(R.id.image_view);
    mTextViewCreator=itemView.findViewById(R.id.text_view_creator);
    mTextViewLikes=itemView.findViewById(R.id.text_view_likes);
  }
 }
}

and this is my Mainactivity :

package com.example.jsontest;

import...

public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExamplelist;
private RequestQueue mRequestQueue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mExamplelist= new ArrayList<>();
    mRequestQueue= Volley.newRequestQueue(this);
    //Call Parsing the json data function
    parseJSON();

}
// Parsing the json data function
private void parseJSON(){
    String url = "https://pixabay.com/api/?key=5303976-fd6581ad4ac165d1b75cc15b3&q=kitten&image_type=photo&pretty=true";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("hits");
                        for (int i=0;i<jsonArray.length();i++){
                            JSONObject hit = jsonArray.getJSONObject(i);

                            String creatorName = hit.getString("user");
                            String imageUrl = hit.getString("webformatURL");
                            int likeCount = hit.getInt("likes");

                            mExamplelist.add(new ExampleItem(imageUrl,creatorName,likeCount));
                        }
                        mExampleAdapter = new ExampleAdapter(MainActivity.this, mExamplelist);
                        mRecyclerView.setAdapter(mExampleAdapter);

                    } catch (JSONException e)
                    {
                        Log.d("bibicha","me te5demchi zid chouf ");
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

  mRequestQueue.add(request);
}

}

I expected to get a list of image and user and number of like ...I hope someone can help. Ive been stuck on this for the longest time. Ive tried many things.Here is the error report:

Process: com.example.jsontest, PID: 12700
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
    at com.example.jsontest.ExampleAdapter.getItemCount(ExampleAdapter.java:49)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3834)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1083)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
    at android.view.View.layout(View.java:20672)
    at android.view.ViewGroup.layout(ViewGroup.java:6194)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
    at android.view.Choreographer.doCallbacks(Choreographer.java:761)
    at android.view.Choreographer.doFrame(Choreographer.java:696)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – George Jun 10 '19 at 20:48

3 Answers3

0

You should alway re-initialize your list before you try to fill it. This will ensure that the list is not null, and it will ensure that the list is empty to start with:

            public void onResponse(JSONObject response) {
                try {

                    //Always re-initialize your list before retrieving the data.
                    mExamplelist = new ArrayList<ExampleItem>();

                    JSONArray jsonArray = response.getJSONArray("hits");
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject hit = jsonArray.getJSONObject(i);

                        String creatorName = hit.getString("user");
                        String imageUrl = hit.getString("webformatURL");
                        int likeCount = hit.getInt("likes");

                        mExamplelist.add(new ExampleItem(imageUrl,creatorName,likeCount));
                    }
                    mExampleAdapter = new ExampleAdapter(MainActivity.this, mExamplelist);
                    mRecyclerView.setAdapter(mExampleAdapter);

                } catch (JSONException e)
                {
                    Log.d("bibicha","me te5demchi zid chouf ");
                    e.printStackTrace();
                }
            }
Michael Dougan
  • 1,698
  • 1
  • 9
  • 13
0

I fix it... I just need to pass my Examplelist and the context to the constructor of ExampleAdapter

//constructor
public ExampleAdapter(Context context, ArrayList<ExampleItem> examplelist){
    mContext = context;
    mExampleList = exampleList;

}

-1

In logs it's clearly mentioned that it's NullPointerException when calling getItemCount. So, list is null from your response. Please add null check before you set an adapter. In your case mExamplelist is null.

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
    at com.example.jsontest.ExampleAdapter.getItemCount(ExampleAdapter.java:49)

Here is a post explaining about NullPointerException What is a NullPointerException, and how do I fix it?

Sankar
  • 1,685
  • 2
  • 16
  • 27