使用SimpleCursorAdapter的android listView.setAdapter错误

时间:2015-03-23 09:08:40

标签: android android-listview cursor simplecursoradapter

我试图通过游标检索数据,将数据从数据库表显示到listView,将光标传递给SimpleCursorAdapter并将适配器设置为listView,如下所示。 由于listAdapter.setAdapter(适配器)上的问题,应用程序崩溃。

- 我确认使用

在聊天表格中有数据

- 捕获异常,ex.getMessage为null,但它表示行号为listAdapter.setAdapter(适配器) 代码:

  ChatsActivity.java
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    Conn connection = new Conn();
    SQLiteDatabase db = connection.getDB(this, "chats", 1);
    //returns readable database

    Cursor result = db.rawQuery("SELECT * FROM chats", null);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.other,
            result,
            new String[]{"_id", "lastContent"},
            new int[]{R.id.textView1, R.id.textView2});

        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        setContentView(listView);

    }
}  

2 Other.xml

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

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Main"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:text="Sub"
    android:textAppearance="?android:attr/textAppearanceMedium" />  </RelativeLayout>

Activity_chats.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ChatsActivity">


<ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/listView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />  </RelativeLayout>

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

下面:

setContentView(listView);

不是将listView传递给setContentView,而是在从布局访问值之前将Activity_chats.xml布局ID作为活动布局传递:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.Activity_chats);
        ....
    }