我正在尝试将JSON数据加载到RecyclerView中,但我不断收到NullPointerException。谁能告诉我我做错了什么?我一直试图让这个工作好几天,但我似乎无法找到问题。这是我的代码:
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);
?>
这是logcat错误:
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);
}
}
答案 0 :(得分:1)
我找到了我的问题所在。我在MyRecyclerAdapter类中声明了我的mImageLoader变量,但我从未分配过它。一旦我这样做,它似乎工作。图像看起来仍然很有趣,但我可以使用它。这是我需要在listRowViewHolder.thumbnail.setImageUrl(listItems.getProfilePicture(),mImageLoader)之前添加的行; onBindViewHolder中的行。
添加了一行:
mImageLoader = MySingleton.getInstance(mContext).getImageLoader();
谢谢sourabhbands,没有你我找不到错误。