2012-05-21 152 views
1

在我的應用程序中,我有1個數據庫,我需要使用ListView顯示數據庫中的數據。任何人都請幫助我。數據庫列表視圖

這是我如何從數據庫中獲取數據:

db.open(); 
    Cursor c = db.getAllTitles(); 
    if (c.moveToFirst()) { 
     do { 
      //in this i have to display the data 
      DisplayTitle(c) 
     } while (c.moveToNext()); 
    }   
+0

試試這個 > ['http://stackoverflow.com/questions/9785563/how-to-write-reusable-code-for-database-in-android/9785657#9785657'][1] [1]:http://stackoverflow.com/questions/9785563/how-to-write-reusable-code-for-database-in-android/9785657#9785657 – Hasmukh

回答

1

你的情況適合SimpleCursorAdapterListView 有關詳情,請這個link

1

SimpleCursorAdapter可以被用來獲得從所述ListViewdatabase顯示的數據。

下面是實現您的要求的示例代碼:

int[] names = new int[] {R.id.Full_Name,R.id.name}; 
private static final String fields[] = {"DatabaseColumn_Name1", "DatabaseColumn_Name2"}; 
    ListView = (ListView)findViewById(R.id.list1); 
    DataBaseHelper myDbHelper = new DataBaseHelper(null); 
    myDbHelper = new DataBaseHelper(this); 
    String sql ="SELECT STATEMENT"; 
    Cursor cdata = myDbHelper.getView(sql); 
    if (cdata != null) 
{ 
    cdata.moveToFirst(); 
    while (cdata.isAfterLast() == false) { 
     String tx = (cdata.getString(2)); 
     cdata.moveToNext(); 
} 
startManagingCursor(cdata); 
CursorAdapter adaptr = new MyCursorAdapter( 
      getApplicationContext(), R.layout.listview1, cdata, fields, names); 
1

可以storw數據在ArrayList和和膨脹thelayout使用basedapter

1
private void fillData() { 
    Cursor notesCursor = mDbHelper.fetchAllNotes(); 
    startManagingCursor(notesCursor); 


    // Create an array to specify the fields we want to display in the list (only TITLE) 
    String[] from = new String[]{NoteDb.KEY_TITLE, NoteDb.KEY_SDATE, NoteDb.KEY_STIME}; 

    // and an array of the fields we want to bind those fields to (in this case just text1) 
    int[] to = new int[]{R.id.text1 , R.id.dateInNotes, R.id.timeInNotes}; 

    // Now create a simple cursor adapter and set it to display 
    SimpleCursorAdapter notes = 
     new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to); 
    setListAdapter(notes); 

    //notesCursor.close(); 

} 
1
nombresC = (Cursor) ayudabbdd.getCursorNombres(); 
     startManagingCursor(nombresC); 
     nombresC.moveToFirst(); 

     //Para crear un simpleCursorAdapter necesitamos 
     //Contexto this 
     //Layour donde se mostrara el resultado, generalmente un textview 
     //Cursor 
     //Cual sera el campo que recibiremos de la BBDD 
     //Donde tenemos que poner esa informacion, generalmente el ID correspondiente al textvies del layour del segundo parametro 



     String[] deNombre = new String[]{DataBaseHelper.CNOMBRE}; 
     int[] aNombre = new int[]{R.id.nombreLugar}; 
     lugaresNombre = new SimpleCursorAdapter(this, R.layout.entrada_lista, nombresC, deNombre, aNombre); 
     setListAdapter(lugaresNombre); 
     listaview= getListView();