0

我有两张表,分别是Subjectchapter。我需要通过传递Subject_id来显示chapter_name。我的问题是如何做到这一点?当我传递值 id 不返回任何东西。 请给点提示。 这是我的代码供参考。


 public List<ObjectiveWiseQuestion> getAllChapter(long subId)
    {
     List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
     String selectQuery=("select chapterName from chapter where subject_id ='"+ subId +"'");
      db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst())
        {
            do {
                ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();

                owq.setChapterName(cursor.getString(2));
                LocwiseProfileList.add(owq);
            } while(cursor.moveToNext());
            db.close();

        }

        return LocwiseProfileList;
    }

它还显示了非法状态异常。

4

2 回答 2

1

将您的代码更改为:

 public List<ObjectiveWiseQuestion> getAllChapter(long subId)
        {
         List<ObjectiveWiseQuestion>LocwiseProfileList=new ArrayList<ObjectiveWiseQuestion>();
         String selectQuery=("select chapterName from chapter where subject_id =?");

          db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, new String[]{subId}); //  The secure way of executing raw queries
            if (cursor.moveToFirst())
            {
                do {
                    ObjectiveWiseQuestion owq= new ObjectiveWiseQuestion();
    //Get column index like this
                    owq.setChapterName(cursor.getString(cursor.getColumnIndexOrThrow("subject_id")));  
                    LocwiseProfileList.add(owq);
                } while(cursor.moveToNext());
    cursor.close();                
    db.close();

                    }
 return LocwiseProfileList;
    }

我已将您的查询更改为使用安全方式。

此外,不应使用cursor.getString(0) 或 cursor.getString(2) 。因为 sqlite 文档指出,查询结果中的列没有必要与创建表时的顺序相同。这有时会给你错误,但不是每次

于 2012-03-27T09:56:25.420 回答
0

改变:

owq.setChapterName(cursor.getString(2));

对此:

/* read value from first column (chapterName) i.e. at index 0 */
owq.setChapterName(cursor.getString(0));

并且不要忘记在关闭数据库之前关闭光标:

cursor.close();
db.close();
于 2012-03-27T09:43:15.050 回答