RecyclerView 出现空指针异常

RecyclerView with null pointer exception

我正在从我的 CMS 中获取一些新闻数据,并希望在 RecyclerView.The 中显示它们 问题是我在使用 LinearLayoutManager 的行中遇到空指针异常。这是 logcat 输出。

Caused by: java.lang.NullPointerException
  at testing.theo.manchesterunitedapp.newsandfeatures.FeaturesFragment.onCreateView(FeaturesFragment.java:65)
  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
  at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
  at android.app.Activity.performStart(Activity.java:5241)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
  at android.app.ActivityThread.access0(ActivityThread.java:135) 
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
  at android.os.Handler.dispatchMessage(Handler.java:102) 
  at android.os.Looper.loop(Looper.java:136) 
  at android.app.ActivityThread.main(ActivityThread.java:5001) 
  at java.lang.reflect.Method.invokeNative(Native Method) 
  at java.lang.reflect.Method.invoke(Method.java:515)

我正在做网络服务部分的片段非常简单。我使用回调方法。我正在初始化 ArrayList 和 RecyclerView 的 onCreateView,其次是我所在的 onActivityCreate 运行 网络服务。

public class FeaturesFragment extends Fragment {

public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "xxxxxxxxxxxx/xxxx/features_images/" ;
private List<FeaturesObject> listItemsList;

private RecyclerView mRecyclerView;
private FeaturesAdapter adapter;

public FeaturesFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.features_row, container, false);
    // Inflate the layout for this fragment
    listItemsList = new ArrayList<>();
    mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);
    //mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());

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


    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    updateFeaturesList();
}

public void updateFeaturesList() {




    //declare the adapter and attach it to the recyclerview
    adapter = new FeaturesAdapter(getActivity(), listItemsList);
    mRecyclerView.setAdapter(adapter);

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity());



    // Request a string response from the provided URL.
    JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FEATURES, new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray response) {

            Log.d(TAG, response.toString());
            //hidePD();

            // Parse json data.
            // Declare the json objects that we need and then for loop through the children array.
            // Do the json parse in a try catch block to catch the exceptions
            try {



                for (int i = 0; i < response.length(); i++) {

                    JSONObject post = response.getJSONObject(i);
                    FeaturesObject item = new FeaturesObject();
                    item.setTitle(post.getString("title"));
                    item.setImage(IMAGE_URL + post.getString("features_image"));
                    item.setArticle(post.getString("article"));



                    listItemsList.add(item);

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

            // Update list by notifying the adapter of changes
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            //hidePD();
        }
    });
    jsObjRequest.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 50000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 50000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });
    queue.add(jsObjRequest);

}
}

这部分代码导致了问题。

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

这很奇怪,因为我正在使用相同的技术在我的应用程序的另一个片段中获取数据。

有什么想法吗?

谢谢。

您的 RecyclerView 为空。您确定要在正确的布局文件中查找正确的 ID 吗?我的猜测是要么你正在膨胀不正确的布局文件,要么你正在寻找 RecyclerView.

的不正确的视图 ID

似乎您要查找的 ID 不在 features_row 上,这就是为什么您在该行上得到 NullPointerException 的原因:

mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);

如果您不断收到错误消息,您可以试试这个:

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

可能不是这种情况,但是...作为一般规则,所有需要 activity 实例的初始化都必须在 onActivityCreated() 中(或 Fragment 生命周期中的下一个方法)。 onCreateView() getActivity() 内部不保证 return 非空值。在某些情况下,它 return 为空。