RecyclerView具有空指针异常

时间:2016-02-18 18:08:08

标签: android android-recyclerview linearlayoutmanager

我从CMS获取一些新闻数据,并想在RecyclerView中显示它们。问题是我在使用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.access$800(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,其次是运行webservice的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);

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

有什么想法吗?

感谢。

3 个答案:

答案 0 :(得分:5)

您的RecyclerView为空。您确定要在正确的布局文件中查找正确的ID吗?我的猜测是要么让不正确的布局文件膨胀,要么就是在查找RecyclerView的错误视图ID。

答案 1 :(得分:2)

可能情况并非如此,但......作为一般规则,所有需要活动实例的初始化必须在onActivityCreated()(或片段生命周期中的下一个方法)中。在onCreateView()内部,getActivity()不保证返回非null值。在某些情况下,它返回null。

答案 2 :(得分:1)

似乎您尝试查找的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 );