我正在 4.0.3 上开发 Android 应用程序,并且有几个 ListActivities 使用他们自己的 CursorAdapters。如果我只使用一个自定义 CursorAdapter 一切正常,但是当我使用更多时,我的应用程序崩溃。
错误堆栈:
04-10 15:41:08.897: W/dalvikvm(2239): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
04-10 15:41:08.956: E/AndroidRuntime(2239): FATAL EXCEPTION: main
04-10 15:41:08.956: E/AndroidRuntime(2239): java.lang.NullPointerException
04-10 15:41:08.956: E/AndroidRuntime(2239): at com.tsystems.openconf.database.adapter.ConferenceListCursorAdapter.bindView(ConferenceListCursorAdapter.java:38)
04-10 15:41:08.956: E/AndroidRuntime(2239): at android.widget.CursorAdapter.getView(CursorAdapter.java:250)
...
Android 似乎无法处理几个 ListActivities。
我继承的所有 ListActivity 类都包括以下代码,除了 CursorAdapter 类:
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate called");
super.onCreate(savedInstanceState);
Log.d(TAG, "create DatabaseOpenHelper");
DatabaseOpenHandler helper = new DatabaseOpenHandler(this);
Log.d(TAG, "get writeable database access");
database = helper.getWritableDatabase();
Log.d(TAG, "create Cursor for database access");
data = database.query(DatabaseConstants.TABLE_CONFERENCES, fields,
null, null, null, null, null);
Log.d(TAG, "set ConferenceListCursorAdapter");
setListAdapter(new ConferenceListCursorAdapter(this, data));
}
我自定义的继承 CursorAdapter 看起来像这样并覆盖了 bindView 和 newView 方法:
public class ConferenceListCursorAdapter extends CursorAdapter {
// logging identifier
private static final String TAG = ConferenceListCursorAdapter.class.getSimpleName();
private Cursor cursor;
private Context context;
private final LayoutInflater inflater;
public ConferenceListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, true);
this.inflater = LayoutInflater.from(context);
this.context = context;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Log.d(TAG, "bindView of ConferenceListAdapter called");
TextView test = (TextView) view.findViewById(R.id.conference_list_id);
test.setText(Long.toString(cursor.getLong(cursor.getColumnIndex(DatabaseConstants.CONFERENCES_STARTTIMEINMILLIS))));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.conference_list_item, parent, false);
}
}
编辑
在第 38 行写入:
test.setText(Long.toString(cursor.getLong(cursor.getColumnIndex(DatabaseConstants.CONFERENCES_STARTTIMEINMILLIS))));
看起来Android找不到TextView,因此在设置文本时会抛出NPE。测试TextView的id是写在R类里的,Android应该能找到。那么为什么它会抛出 NPE 呢?
我的布局 xml 文件的代码片段:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/conference_list_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>