Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/178.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ListView返回为空_Java_Android_Listview - Fatal编程技术网

Java ListView返回为空

Java ListView返回为空,java,android,listview,Java,Android,Listview,我试图用Android中的片段中的ArrayList填充ListView,但没有成功。我收到一个错误,提示java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' 我应该在哪里初始化列表视图,以便为创建的onActivityCreated方法做好准备 Fragment.java private static fina

我试图用Android中的
片段中的
ArrayList
填充
ListView
,但没有成功。我收到一个错误,提示
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'

我应该在哪里初始化
列表视图
,以便为创建的
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);
                    }
                });
    }

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

只需移动这个初始化:

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;
}

编辑:您在listview中使用了错误的
id
,请将其替换为
R.id.listview

当您使用
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" />
是指这条线吗

adapter = new ArrayAdapter(getActivity(),R.layout.fragment_system_conditions, R.id.listView, alerts);
那些
R.layout
R.id
参数都不正确

您可以定义或使用

ArrayAdapter(上下文、int资源、列表对象)

其中,
资源
对应于一个文本视图,如
android.R.layout.simple\u list\u item\u 1
,在这种情况下,
对象
列表中的每个对象都将是
toString()

我不熟悉安卓系统。我有多个片段我想最后一点你可以在这里设置它:onStart()你试着把它放在什么地方?我仍然得到一个空指针,但这次在适配器上
java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)“在空对象引用上
这只意味着我们离解决方案更近了一步,你不同意吗?让我再看一看……避免使用
getView().findViewById
并像我的回答中那样使用
rootview.findViewById
。还要尝试将此
adapter=new ArrayAdapter(getActivity(),R.layout.fragment\u system\u条件,R.id.listView,警报);低压设置适配器(适配器)lv.setAdapter(adapter)
可以移动错误,但它仍然存在于该行。哈哈,伙计,你使用了错误的id,被@cricket_007发现了。用listview的正确id替换
R.id.sysCondView
fragment\u system\u conditions.xml
是否包含带有
android:id=“@+id/sysCondView”
的列表视图?这是您将获得NullOk的一个原因,因此您正在尝试查找
R.id.sysCondView
。。。。但是您的ListView的id为
R.id.ListView
。。。什么是sysCondView
?好地方@cricket\u 007。我还没有看到包含xml的编辑版本。伟大的工作人员,我已经在这里跟踪你4个月左右,当你有3k代表。大风扇:不同的错误,但至少你现在有了列表视图。问题在于适配器。我更新了我的答案。谢谢你的帮助,非常感谢。我上周刚开始使用安卓系统。对于基础知识,肯定有一个学习曲线。我花了几个月的时间才习惯,但中的示例非常详细。
<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" />
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);
ArrayAdapter (Context context, int resource, List<T> objects)