2013-12-17 65 views
0

我有三列,第一個id,第二個標題和第三個主體。如何獲得SQLite數據庫列值在android中爲列表

像這樣

id   title   body 
1   t1   b1 
2   t2   b2 
3   t3   b3 

所以,我想在列表標題和顯示與ListView和如果我點擊標題T2然後顯示相應的可點擊的標題的身體。

我做了什麼。

DatabaseHelper.java

public Cursor retriveTitle(String [] title) { 
     Cursor c = null; 
     c = myDataBase.rawQuery(
       "select id,title from book,", title); 
     return c; 
    } 

Main.java

private void displayTitle() { 
     try { 
      myDataBase = (new DatabaseHelper(this)).getWritableDatabase(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b ", new String[] { "" }); 

     String test=cursor.getString(cursor 
       .getColumnIndex("title")); 
     //How to display title of book in listview 
    } 

得到這個:

01-18 14:20:03.401: E/AndroidRuntime(6704): Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters. 

我已經使用的數據庫文件,根據此博客帖子:Using your own SQLite database in Android applications

回答

0

試用

Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b",null); 
    curosr.moveToFirst(); 
    String test=cursor.getString(cursor 
      .getColumnIndex("title")); 
0

我覺得您的查詢應該使用 「其中」 聲明

c = myDataBase.rawQuery("select id,title from book where title=?", title); 

當然,你想傳遞一定數量的參數

c = myDataBase.rawQuery("select id,title from book where title in (?, ?, ?)", new String[]{title1, title2, title3}); 

但是,如果標題的數量可能會有所不同,則需要動態創建一個字符串機智h足夠的問號。看到這個帖子

IN clause and placeholders

如果你仍然得到CS出錯,也許提供了更多的日誌可能會有幫助。另外,如果說明哪條線路不通,請告訴它是哪條線路。我們在這裏看不到行號

祝你好運

0

下面是它的工作方式。在另一個類中,我創建了一個List類型的方法,並在sqlite數據庫列表中添加了列ID爲&的項目名稱。

下面是檢索所選項目的列標識的代碼片段。

public List<String> list; 
    adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter 
    listTask.setAdapter(adapt); 

    listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) { 

     Integer id = list.get(position).getId(); 
     //position is the position of the item in the list. 
     } 
    }); 

結果:該項目在列表中的第3個位置。其數據庫column_id(自動增量)值爲12,因爲我刪除了以前的項目。所以你期望的結果是12,這是變量id的值。

如果您完全不理解,可能是因爲我沒有發佈我的整個代碼。但我會幫你解決你的問題。

相關問題