2012-05-21 61 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();