2013-12-17 63 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的值。

如果您完全不理解,可能是因为我没有发布我的整个代码。但我会帮你解决你的问题。

相关问题