帮助ListView数据库

时间:2010-04-06 17:49:56

标签: database android listview

我遇到问题@运行此代码:App Force Closing ..

Sprinter.Java

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class Sprinter extends ListActivity {
    /** Called when the activity is first created. */
    final static String MY_DB_NAME = "Sprinter"; 
    final static String MY_DB_TABLE = "Stations"; 

    @Override 
   public void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.main);       

    SQLiteDatabase myDB = null; 
    try { 
         myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); 

         myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + "_id integer primary key autoincrement, name varchar(100);"); 

         myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Oceanside Transit Center');"); 

         myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Coast Highway');"); 

         Cursor mCursor = myDB.rawQuery("SELECT name" + " FROM " + MY_DB_TABLE, null); 

         startManagingCursor(mCursor); 

         ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[] { "name" }, new int[] { R.id.Name }); 

         this.setListAdapter(adapter); 

         this.getListView().setTextFilterEnabled(true); 
       } finally { 
         if (myDB != null) { 
              myDB.close(); 
         } 
       } 
   }     
}

main.xml中

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

    <TextView
    android:id="@id/android:empty"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="No Data"
    />
</LinearLayout>

list_item.xml

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

     <TextView android:id="@+id/Name" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"> 
     </TextView> 
</LinearLayout> 

1 个答案:

答案 0 :(得分:1)

对于SimpleCursorAdapter,您还需要选择名为_id的主ID。你只需要在光标中使用它,你不必使用它。

Cursor mCursor = myDB.rawQuery("SELECT _id, name" + " FROM " + MY_DB_TABLE, null);