ListView使用Fragment返回null

时间:2013-07-22 00:16:13

标签: android android-listview android-fragments

当我尝试在XML布局中检索 ListView 组件时,会启动NullPointerException。

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

我正在使用片段,欢迎任何帮助。

1)布局文件(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)

<?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类:

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行。

1 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您使用了错误的View变量来查找ListView

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

这里的视图变量是指:

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

您需要参考此view

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) {