简体   繁体   English

具有空指针异常的RecyclerView

[英]RecyclerView with null pointer exception

I am getting some news data from my CMS,and want to display them in a RecyclerView.The problem is that I am getting a null pointer exception in the line where I using the LinearLayoutManager. 我从CMS中获取了一些新闻数据,并希望在RecyclerView中显示它们。问题是我在使用LinearLayoutManager的行中收到了空指针异常。 Here is the logcat output. 这是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)

The Fragment where I am doing the webservice part is quite simple. 我在其中进行Web服务的片段非常简单。 I use to callback methods. 我使用回调方法。 The onCreateView where I am initialising the ArrayList and the RecyclerView,and secondly the onActivityCreate where I am running the webservice. 我要在其中初始化ArrayList和RecyclerView的onCreateView,然后是我正在运行Web服务的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);

}
}

This part of the code causes the problem. 这部分代码会导致问题。

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

This is strange,as I am using the same techiques to obtain data in another fragment of my app. 这很奇怪,因为我使用相同的技术来获取应用程序另一个片段中的数据。

Any ideas? 有任何想法吗?

Thanks. 谢谢。

Your RecyclerView is null. 您的RecyclerView为空。 Are you sure you're looking for the correct id in the correct layout file? 您确定要在正确的布局文件中寻找正确的ID吗? My guess is either you are inflating the incorrect layout file, or you're looking for the incorrect view id for the RecyclerView . 我的猜测是您正在填充错误的布局文件,或者正在寻找RecyclerView的错误视图ID。

Probably this is not the case but... As a general rule all initialization that need instance of the activity must be in onActivityCreated() (or the next methods in the Fragment lifecycle). 可能不是这种情况,但是...通常,所有需要活动实例的初始化都必须在onActivityCreated() (或Fragment生命周期中的下一个方法)。 Inside onCreateView() getActivity() is not guaranteed to return non-null value. onCreateView()内部,不能保证getActivity()返回非空值。 In some scenarios it returns null. 在某些情况下,它返回null。

Seems like the id that you are trying to find it's not on features_row that's why you get NullPointerException on that line : 好像您要查找的id不在features_row ,这就是为什么在该行上获得NullPointerException的原因:

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

If you keep getting error you could try this : 如果您仍然遇到错误,可以尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM