0

Subjectchapterという 2 つのテーブルがあります。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;
    }

また、 illegalState Exceptionも示しています。

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 に答える