ListView返回null

时间:2016-06-01 15:22:40

标签: java android listview

我尝试使用ListViewArrayList填充Fragment,并且它无法正常运行。我收到的错误是java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

我应该在哪里初始化ListView,以便为onActivityCreated方法做好准备?

Fragment.java

    private static final String TAG = SystemConditionsFragment.class.getSimpleName();

    private OnFragmentInteractionListener mListener;

    private ListView lv;

    private ListAdapter adapter;

    private ArrayList<String> alerts;

    private ProgressDialog progDailog;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SystemConditionsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SystemConditionsFragment newInstance(String param1, String param2) {
        SystemConditionsFragment fragment = new SystemConditionsFragment();
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_system_conditions, container, false);
    lv = (ListView) rootView.findViewById(R.id.listView);
    return rootView;
}

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

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

    @Override
    public void refresh() {

        progDailog = ProgressDialog.show(getActivity(), "Loading","Please wait...", true);
        progDailog.setCancelable(false);

        progDailog.dismiss();

        final ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JsonOrgModule());

        Log.d(TAG, "Requesting events data");
        VolleyUtils.makeJsonObjectRequest(getActivity().getApplicationContext(),
                "events",
                new VolleyResponseListener() {

                    @Override
                    public void onError(String message) {
                        Log.e(TAG, "Error requesting events: " + message);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, "Received events response " + response);

                        DataRestResponse<SysCondRecord> data = mapper.convertValue(
                                response,
                                new TypeReference<DataRestResponse<SysCondRecord>>() {});
                        // Group by timestamp
                        ImmutableMultimap<DateTime, SysCondRecord> indexedData =
                                Multimaps.index(data.getData(),
                                        new Function<SysCondRecord, DateTime>() {
                                            @Override
                                            public DateTime apply(SysCondRecord record) {
                                                return record.getTimeStamp();
                                            }
                                        });
                        alerts = new ArrayList<>();
                        final List<DateTime> timestamp = new ArrayList<>();
                        for (SysCondRecord record : data.getData()) {
                            timestamp.add(record.getTimeStamp());
                            alerts.add(record.getMessage());
                        }

                        adapter = new ArrayAdapter(getActivity(),R.layout.fragment_system_conditions, R.id.listView, alerts);


                        lv.setAdapter(adapter);
                    }
                });
    }

fragment_system_conditions.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_below="@+id/sysCondView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="36dp" />

修改

我其实是在使用错误的身份证,我很糟糕!但我似乎让事情变得更糟......

FATAL EXCEPTION: main
Process: xx.xxx.com, PID: 26183


java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

3 个答案:

答案 0 :(得分:2)

使用findViewById时,需要查看android:id属性的XML。

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"               <!-- This line -->
    android:layout_below="@+id/sysCondView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="36dp" />

此外,@+id语法仅用于添加 ID到资源,当您想要引用它们时,只使用"@id/sysCondView"(不使用{ {1}})。

+中的引用之前,您还应该拥有该ID的实际视图。

第二个问题

RelativeLayout

指的是这一行

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

这两个adapter = new ArrayAdapter(getActivity(),R.layout.fragment_system_conditions, R.id.listView, alerts); R.layout参数都不正确。

您可以定义your own custom adapter,也可以使用

R.id

ArrayAdapter (Context context, int resource, List<T> objects) 对应于resource等TextView,android.R.layout.simple_list_item_1列表中的每个对象都为objects

答案 1 :(得分:0)

我倾向于初始化onResume()中的View项,因此当屏幕方向改变时,它们会重新连接。但是,如果可以的话,我也会尽量避免碎片,让事情变得更复杂,当然如果你只有一个。

答案 2 :(得分:0)

只需移动此初始化:

lv = (ListView) getView().findViewById(R.id.listView);

进入onCreateView,如此:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_system_conditions, container, false);
    lv = (ListView) rootView.findViewById(R.id.listView);
    return rootView;
}

编辑:您使用错误的id列表视图,将其替换为R.id.listView