尝试使用Volley解析Json时Android应用程序崩溃

时间:2019-06-10 20:07:06

标签: java android json parsing android-recyclerview

我正在尝试使用RecyclerView和Volley在我的应用程序中显示用户列表和来自Json-url的喜欢图像的图像列表...实际上,我遵循了这个指导原则:https://codinginflow.com/tutorials/android/recyclerview-volley-picasso/part-4-get-request

错误可能来自ExampleAdapter

这是我的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);
  }
 }
}

这是我的主要活动:

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

}

我希望获得图像和用户的列表以及喜欢的数量...我希望有人可以提供帮助。我已经在这个问题上停留了最长的时间。我已经尝试了很多事情。这是错误报告:

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)

3 个答案:

答案 0 :(得分:0)

在尝试填充列表之前,应始终重新初始化列表。这将确保列表不为空,并且将确保列表以以下内容开头:

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

答案 1 :(得分:0)

我已修复...我只需要将我的Examplelist和上下文传递给ExampleAdapter的构造函数

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

}

答案 2 :(得分:-1)

在日志中,明确提到在调用getItemCount时它是NullPointerException。因此,响应中的列表为空。在设置适配器之前,请添加null检查。在您的情况下,mExamplelist为空。

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)

此处是有关NullPointerException的说明 What is a NullPointerException, and how do I fix it?