doushizhou4477 2015-11-20 17:59
浏览 147
已采纳

尝试将JSON数据加载到RecyclerView时,为什么会出现NullPointerException?

I am trying to load JSON data into RecyclerView but I keep getting a NullPointerException. Can anyone please tell me what I am doing wrong? I have been trying to get this working for days now but I can't seem to find the issue. Here is my code:

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/listItemLayout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/yesButton"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:background="#00FF00" />

        <ImageButton
            android:id="@+id/noButton"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:background="#FF0000" />

    </LinearLayout>

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/image_1"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:orientation="horizontal">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/thumbnail"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:scaleType="fitXY"
                android:src="@drawable/placeholder" />

            <TextView
                android:id="@+id/pUsername"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp"
                android:gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="username" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/postMenu"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="#000"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

fragment_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff" />

</LinearLayout>

FragmentHome.java:

public class FragmentHome extends Fragment {

    private final String postsUrl = "http://www.example.com/fetch_posts.php";

    private ProgressDialog progressDialog;

    private static final String TAG = "RecyclerViewExample";
    private List<ListItems> listItemsList = new ArrayList<>();

    private RecyclerView mRecyclerView;
    private MyRecyclerAdapter adapter;

    public FragmentHome() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (container == null) {
            return null;
        }
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mRecyclerView.addItemDecoration(
            new HorizontalDividerItemDecoration.Builder(getActivity())
                    .color(Color.BLACK)
                    .build());

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

        updateFeed();

        return view;
    }

    public void updateFeed() {
        showPD();

        adapter = new MyRecyclerAdapter(getActivity(), listItemsList);
        mRecyclerView.setAdapter(adapter);

        RequestQueue request = Volley.newRequestQueue(getActivity());

        adapter.clearAdapter();

        JsonArrayRequest req = new JsonArrayRequest(postsUrl, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                try {
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject post = (JSONObject) response.get(i);

                        ListItems item = new ListItems();
                        item.setImage_1(post.getString("image_1"));
                        item.setUsername(post.getString("username"));
                        listItemsList.add(item);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePD();
                Toast.makeText(getActivity(), "Volley Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        request.add(req);
    }

    private void showPD() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading...");
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }
    }

    private void hidePD() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePD();
    }

}

fetch_posts.php:

<?php

    $db = mysql_connect("localhost", "username", "password");
    if (!$db) {
        die('Could not connect to db: '.mysql_error());
    }

    mysql_select_db("app_db", $db);

    $result = mysql_query("SELECT * FROM posts", $db);

    $json_response = array();

    while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $row_array['id'] = $row['id'];
        $row_array['username'] = $row['username'];
        $row_array['image_1'] = $row['image_1'];
        $row_array['occasion'] = $row['occasion'];
        $row_array['date/time'] = $row['date/time'];
        $row_array['yes'] = $row['yes'];
        $row_array['no'] = $row['no'];

        array_push($json_response, $row_array);
    }
    echo json_encode($json_response);

    fclose($db);

?>

And this is the logcat error:

11-20 12:54:52.337 2064-2064/? D/dalvikvm: Late-enabling CheckJNI
11-20 12:54:52.357 2064-2070/? E/jdwp: Failed sending reply to debugger: Broken pipe
11-20 12:54:52.357 2064-2070/? D/dalvikvm: Debugger has detached; object registry had 1 entries
11-20 12:54:52.401 2064-2064/? D/dalvikvm: GC_FOR_ALLOC freed 87K, 5% free 3778K/3936K, paused 3ms, total 3ms
11-20 12:54:52.401 2064-2064/? I/dalvikvm-heap: Grow heap (frag case) to 6.169MB for 2536932-byte allocation
11-20 12:54:52.413 2064-2073/? D/dalvikvm: GC_FOR_ALLOC freed <1K, 3% free 6255K/6416K, paused 12ms, total 12ms
11-20 12:54:52.421 2064-2067/? D/dalvikvm: GC_CONCURRENT freed <1K, 3% free 6255K/6416K, paused 0ms+1ms, total 9ms
11-20 12:54:52.521 2064-2067/? D/dalvikvm: GC_CONCURRENT freed 305K, 6% free 6817K/7188K, paused 0ms+2ms, total 18ms
11-20 12:54:52.577 2064-2064/? D/libEGL: loaded /system/lib/egl/libEGL_genymotion.so
11-20 12:54:52.577 2064-2064/? D/: HostConnection::get() New Host Connection established 0xb94e8d78, tid 2064
11-20 12:54:52.601 2064-2064/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-20 12:54:52.601 2064-2064/? D/libEGL: loaded /system/lib/egl/libGLESv2_genymotion.so
11-20 12:54:52.641 2064-2064/? W/EGL_genymotion: eglSurfaceAttrib not implemented
11-20 12:54:52.645 2064-2064/? E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from GradienCache
11-20 12:54:52.645 2064-2064/? E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384
11-20 12:54:52.653 2064-2064/? E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-20 12:54:52.657 2064-2064/? E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384
11-20 12:54:52.657 2064-2064/? D/OpenGLRenderer: Enabling debug mode 0
11-20 12:54:52.773 2064-2064/? W/EGL_genymotion: eglSurfaceAttrib not implemented
11-20 12:54:53.037 2064-2064/? W/EGL_genymotion: eglSurfaceAttrib not implemented
11-20 12:54:53.141 2064-2064/? D/RecyclerViewExample: [{"yes":"3","occasion":"Birthday Party","id":"1","image_1":"https:\/\/s-media-cache-ak0.pinimg.com\/236x\/e3\/33\/4a\/e3334aa897d8c612dccba223b22ee90d.jpg","username":"alexiz","no":"1","date\/time":"2015-11-19 14:22:00"},{"yes":"3","occasion":"Birthday Party","id":"2","image_1":"https:\/\/i.ytimg.com\/vi\/qJSQ1y7hR2g\/maxresdefault.jpg","username":"alexiz","no":"10","date\/time":"2015-11-19 09:14:06"},{"yes":"3","occasion":"Club","id":"3","image_1":"https:\/\/i.ytimg.com\/vi\/qJSQ1y7hR2g\/maxresdefault.jpg","username":"gell","no":"1","date\/time":"2015-11-04 09:14:06"},{"yes":"8","occasion":"Baby Shower","id":"4","image_1":"https:\/\/i.ytimg.com\/vi\/qJSQ1y7hR2g\/maxresdefault.jpg","username":"jkfldj","no":"1","date\/time":"2015-11-11 09:14:06"}]
11-20 12:54:53.161 2064-2064/? D/dalvikvm: GC_FOR_ALLOC freed 326K, 6% free 7097K/7488K, paused 4ms, total 4ms
11-20 12:54:53.165 2064-2064/? I/dalvikvm-heap: Grow heap (frag case) to 15.575MB for 9000012-byte allocation
11-20 12:54:53.169 2064-2073/? D/dalvikvm: GC_FOR_ALLOC freed <1K, 3% free 15886K/16280K, paused 3ms, total 3ms
11-20 12:54:53.173 2064-2067/? D/dalvikvm: GC_CONCURRENT freed 5K, 3% free 15880K/16280K, paused 0ms+0ms, total 4ms
11-20 12:54:53.225 2064-2064/? D/AndroidRuntime: Shutting down VM
11-20 12:54:53.225 2064-2064/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4d43b20)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime: FATAL EXCEPTION: main
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime: Process: com.example.app, PID: 2064
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime: java.lang.NullPointerException
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at com.android.volley.toolbox.NetworkImageView.loadImageIfNecessary(NetworkImageView.java:160)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at com.android.volley.toolbox.NetworkImageView.onLayout(NetworkImageView.java:209)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.RecyclerView$LayoutManager.layoutDecorated(RecyclerView.java:7036)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1429)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1334)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:563)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2847)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3145)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1627)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.View.layout(View.java:14817)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4631)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:544)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5001)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-20 12:54:53.225 2064-2064/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

EDIT --------------------------------------------------

MyRecyclerAdapter.java:

public class MyRecyclerAdapter extends RecyclerView.Adapter<ListRowViewHolder> {

    private List<ListItems> listItemsList;
    private Context mContext;
    private ImageLoader mImageLoader;

    private int focusedItem = 0;

    public MyRecyclerAdapter(Context context, List<ListItems> listItemsList) {
        this.mContext = context;
        this.listItemsList = listItemsList;
    }

    @Override
    public ListRowViewHolder onCreateViewHolder(final ViewGroup viewGroup, int position) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
        ListRowViewHolder holder = new ListRowViewHolder(v);

        holder.recLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("List Size", Integer.toString(getItemCount()));
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(final ListRowViewHolder listRowViewHolder, int position) {
        ListItems listItems = listItemsList.get(position);
        listRowViewHolder.itemView.setSelected(focusedItem == position);

        listRowViewHolder.getLayoutPosition();

        listRowViewHolder.thumbnail.setImageUrl(listItems.getProfilePicture(), mImageLoader);
        listRowViewHolder.thumbnail.setDefaultImageResId(R.drawable.placeholder);

        listRowViewHolder.image_1.setImageUrl(listItems.getImage_1(), mImageLoader);
        listRowViewHolder.image_1.setDefaultImageResId(R.drawable.placeholder);

        listRowViewHolder.username.setText(Html.fromHtml(listItems.getUsername()));
    }

    public void clearAdapter() {
        listItemsList.clear();
        notifyDataSetChanged();
    }

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

}
  • 写回答

1条回答 默认 最新

  • doujia4619 2015-11-20 18:30
    关注

    I found where my issue was. I declared my mImageLoader variable in my MyRecyclerAdapter class but I never assigned it. Once I did that, it seems to be working. Images still look funny but I can work with that. Here is the line that I needed to add before listRowViewHolder.thumbnail.setImageUrl(listItems.getProfilePicture(), mImageLoader); line in onBindViewHolder.

    Line added:

    mImageLoader = MySingleton.getInstance(mContext).getImageLoader();
    

    Thank you sourabhbands, I couldn't have found the error without you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 综合布线实例设计,就好看好看不恐怖可好滤镜好聚
  • ¥15 使用moviepy库视频合并时出错
  • ¥30 FLUENT液固传质UDF
  • ¥15 怎么看梯度直方图以,怎么判断梯度消失/爆炸,怎么解决
  • ¥15 aspnetdll文件访问拒绝
  • ¥15 wpf中在模版中寻找元素
  • ¥15 MFC平台生成指定圆
  • ¥15 jmeter出现403
  • ¥500 求华为P30PRO手机硬盘数据恢复
  • ¥15 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关