2012-04-12 49 views
1

我需要幫助創建一個顯示數據庫sql的元素的列表視圖。 首先創建一個帶有3個字段的TextView的小型XML佈局:Text1,Text2 and Text3 和我的活動中的一個列表視圖。 後,我已經在接口Android:在ListView上的Sqlite

public interface TableRegistry extends BaseColumns{ 

    String TABLE_NAME = "Registry"; 

    String TYPE = "Type"; 
    String DATE = "Date"; 
    String STATUS = "Status"; 
    String NUMBER = "Number"; 
    String MESSAGE = "Message"; 
    String OTHER = "Other"; 

    String[] COLUMNS = new String[] 
       { _ID, TYPE, DATE, STATUS, NUMBER, MESSAGE, OTHER }; 
      } 

分組列我創建的數據庫類後..

public class APdatabaseClass extends SQLiteOpenHelper { 

    private static final String DATABASE_NAME = "APdatabase"; 
    private static final int DATABASE_VERSION = 1; 

    public APdatabaseClass(Context context) { 
     super(context, DATABASE_NAME , null, DATABASE_VERSION); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

     String sql = "CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT," + 
       " {2} TEXT NOT NULL,{3} TEXT NOT NULL,{4} TEXT NOT NULL,{5} TEXT NOT NULL,{6} TEXT NOT NULL, {7} TEXT NOT NULL);"; 
      db.execSQL(MessageFormat.format(sql, TableRegistry.TABLE_NAME, TableRegistry._ID, 
       TableRegistry.TYPE, TableRegistry.DATE, TableRegistry.STATUS, TableRegistry.NUMBER, TableRegistry.MESSAGE, TableRegistry.OTHER)); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

     // Drop older table if existed 
     db.execSQL("DROP TABLE IF EXISTS " + TableRegistry.TABLE_NAME); 

     // Create tables again 
     onCreate(db);  
    } 

現在我如何連接我的數據庫在我與SimpleCursorAdapter什麼活動的ListView?我需要填充3個TextView字段:

TableRegistry.TYPE, TableRegistry.DATE, TableRegistry.STATUS. 

在此先感謝!

回答

2

好像你要一點點額外的工作。下面是我做它通常爲:

首先在你的數據庫幫助創建方法來獲取信息,你想:

public Cursor fetchListData() { 
    return mDb.query(TableRegistry.TABLE_NAME, new String[] { TableRegistry._ID, 
     TableRegistry.TYPE, TableRegistry.DATE, TableRegistry.STATUS }, null,null, 
     null, null, null); 
} 

然後你要創建的列表的任何類:

APdatabaseClass mDbHelper = new APdatabaseClass(getActivity()); 
mDbHelper.open(); 

Cursor c = fetchListData(); 
getActivity().startManagingCursor(c); 

String[] from = new String[] { TableRegistry.TYPE, TableRegistry.DATE, TableRegistry.STATUS }; 
int[] to = new int[] { R.id.Text1, R.id.Text2, R.id.Text3 }; 
SimpleCursorAdapter data = new SimpleCursorAdapter(getActivity(), R.layout.yourlistlayout, c, from, to); 
setListAdapter(data); 

請注意,這假定您正在使用ListFragment或ListActivity。如果不是,那麼設置適配器的方式會稍有不同。

希望這會有所幫助!

+0

感謝您的回答! – Tony 2012-04-13 19:34:01

0

是的,你現在可以通過使用raqQuery()方法來引發查詢,你將得到Cursor結果。

現在,您必須遍歷遊標並獲取數據。

例如,

Cursor cur = db.raqQuery("Select * from myTable",null); 
if (cur != null) { 
    if (cur.moveToFirst()) { 
     do { 
      cur.getString(cur.getColumnIndex("Name"))); // "Name" is the field name in table 
     } while (cur.moveToNext()); 
    } 
} 
+0

謝謝你的回答! – Tony 2012-04-13 19:34:10