ListView使用Fragment返回null [英] ListView returning null using Fragment

查看:84
本文介绍了ListView使用Fragment返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试以XML布局检索 ListView 组件时,将启动NullPointerException.

When i try to retrieve the ListView coponent in XML layout, an NullPointerException is launched.

ListView lv = (ListView) view.findViewById(R.id.lvAlerts);

我正在使用Fragments,欢迎任何帮助.

I'm using Fragments, any help is welcome.

1)布局文件(tab_frag_alerts.xml)

1) Layout File (tab_frag_alerts.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinnerAlertCategory"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/lvAlerts"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

2)布局文件(alert_row.xml)

2) Layout file (alert_row.xml)

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="1dip" >


        <TextView
            android:id="@+id/alertId"
            style="@style/vehicleDefaultFont.plate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_text_view" />

        <TextView
            android:id="@+id/createdIn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_text_view" />
    </TableRow>

</TableLayout>

3)片段Java类:

3) Fragment Java Class:

package br.com.log2br.tabs;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import br.com.log2br.R;
import br.com.log2br.db.AlertDbAdapter;

public class AlertsTabFragment extends Fragment {

    String TAG = getClass().getName();
    private AlertDbAdapter dbHelper;
    private SimpleCursorAdapter dataAdapter;
    private Spinner spinnerAlertCategory;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Log.i(TAG, "Loading onCreateView()");

        view = inflater.inflate(R.layout.tab_frag_alerts, container, false);

        dbHelper = new AlertDbAdapter(getActivity());
        dbHelper.open();

        dbHelper.deleteAllAlerts();

        dbHelper.insertAlerts();

        spinnerAlertCategory = (Spinner) view.findViewById(R.id.spinnerAlertCategory);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.alerts_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerAlertCategory.setAdapter(adapter);

        spinnerAlertCategory.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                String itemSelected = parent.getItemAtPosition(pos).toString();

                if(!itemSelected.equals(R.string.text_hint_alert_spinner)) {

                    Cursor cursor = dbHelper.fetchAllAlerts();

                    if(cursor != null && cursor.getCount() > 0) {

                        String[] columns = new String[] {
                                AlertDbAdapter.KEY_ALERT_ID,
                                AlertDbAdapter.KEY_CREATED_IN,
                        };

                        int[] to = new int[] { 
                                R.id.alertId,
                                R.id.createdIn,
                        };

                        dataAdapter = new SimpleCursorAdapter(
                                view.getContext(),
                                R.layout.alert_row, 
                                cursor, 
                                columns, 
                                to,
                                0); 

                        ListView lv = (ListView) view.findViewById(R.id.lvAlerts);
                        lv.setAdapter(dataAdapter); //null pointer here :((

                    } else {

                        Log.i(TAG, "Found no alerts.");
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

        return view;
    }   
}

4)Logcat

07-21 12:37:09.044: E/AndroidRuntime(8393): FATAL EXCEPTION: main
07-21 12:37:09.044: E/AndroidRuntime(8393): java.lang.NullPointerException
07-21 12:37:09.044: E/AndroidRuntime(8393):     at br.com.log2br.tabs.AlertsTabFragment$1.onItemSelected(AlertsTabFragment.java:119)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.widget.AdapterView.access$200(AdapterView.java:49)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.os.Handler.handleCallback(Handler.java:615)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.os.Looper.loop(Looper.java:137)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at android.app.ActivityThread.main(ActivityThread.java:4745)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at java.lang.reflect.Method.invokeNative(Native Method)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at java.lang.reflect.Method.invoke(Method.java:511)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-21 12:37:09.044: E/AndroidRuntime(8393):     at dalvik.system.NativeStart.main(Native Method)
07-21 12:47:18.904: E/Trace(9446): error opening trace file: No such file or directory (2)

我的光标包含一个_id字段.我仔细检查了光标,它有4行.

推荐答案

之所以发生这种情况,是因为您使用了错误的View变量来找到 ListView .

This is happening because you are using the wrong View variable to find the ListView.

ListView lv = (ListView) view.findViewById(R.id.lvAlerts);

此处的view变量是指:

The view variable here refers to:

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

您需要参考此视图:

view = inflater.inflate(R.layout.tab_frag_alerts, container, false);

您应该更改声明:

View view;    //change view to some other name

或者,

public void onItemSelected(AdapterView<?> parent, View someOtherView, int pos, long id) {

这篇关于ListView使用Fragment返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆