2010-01-16 50 views
2

我的編程知識很苗條,前幾天我發現了Java和Android SDK。Begginner使用ListAdapters/SQLite數據庫

我有一個SQLiteDatabase,一個SQLiteOpenHelper,和光標正常工作 (指我想我明白瞭如何創建/使用SQLiteOpenHelper打開一個數據庫,讓我的數據庫查詢,並獲得光標)

目前,我正在將i + labName + labCity包裝成單個結果字符串,並顯示爲單個TextView R.id.label

是否可以將labName綁定到R.id.label,並將labCity綁定到另一個TextView R.id.label2?

這裏是我的ListActivity的代碼我需要幫助:

public class MainLabList extends ListActivity implements OnItemClickListener { 

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

    // DB 
    GestionDB gdb = new GestionDB(this, GestionDB.DATABASE_NAME, null, GestionDB.DATABASE_VERSION); 
    SQLiteDatabase theDB = gdb.getWritableDatabase(); 

    // Cursor 
    String[] columns = {GestionDB.LAB_NAME, GestionDB.LAB_ADDRESS_CITY}; 
    Cursor c = 
     theDB.query(GestionDB.TABLE_NAME, columns, null, null, null, null, null); 

    //////// 
    this.setTitle(" " + c.getCount() + " Labs in Local Database"); 
    ArrayList<String> results = new ArrayList<String>(); 
    int i = 0; 
    c.moveToFirst(); 

    /* Loop through all Results */ 
    do { 
     i++;   
     String labName = c.getString(c.getColumnIndex(GestionDB.LAB_NAME)); 
     String labCity = c.getString(c.getColumnIndex(GestionDB.LAB_ADDRESS_CITY)); 

     /* Add current Entry to results. */ 
     results.add("" + i + ": " + labName 
         + " (" + labCity + ")"); 
    } while (c.moveToNext()); 

    //need rework    
    ListView lvLabListing = (ListView) findViewById(android.R.id.list); 
    ArrayAdapter<String> labListAdapter = new ArrayAdapter<String>(this, 
      R.layout.listing, R.id.label, results); 
    lvLabListing.setAdapter(labListAdapter); 
    lvLabListing.setOnItemClickListener(this); 
    // 

    // don't forget to close the database 
    gdb.close(); 

,我想的listing.xml修改:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="wrap_content" android:layout_width="fill_parent"> 
<ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon"></ImageView> 
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label"></TextView> 
</LinearLayout> 

我GestionDB類很簡單,只需定義一些列如果數據庫不存在,以及一些變量。

回答

0

您應該使用CursorAdapter,或許是SimpleCursorAdapterHere is an example

+0

您的源代碼示例很有幫助。 我使用了一個SimpleCursorAdapter,但是卡住了一些異常:java.lang.IllegalArgumentException:列'_id'不存在。 如果您的查詢沒有_ID列,則會出現此異常。 非常感謝我的第一個問題:)解決 – Dullahx 2010-01-16 17:10:06

+0

是的,這是'CursorAdapter'系列的限制之一 - 你必須在名爲'_ID'的結果集中有一列可以轉換爲'long' 。 – CommonsWare 2010-01-16 17:25:08