samedi 2 mai 2015

How to using cursor in loop?

The problem is i can't load my image and maybe i got problem on here. Maybe this code make error "java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0" sorry i cant describe what is my problem T_T. Im new in android.

quest.setImage(Utility.getPhoto(cursor.getBlob(1))); //maybe i got problem here

DbHelper.java

public List<Question> getAllQuestions(){
            List<Question> quesList = new ArrayList<Question>();
            String selectQuery = "SELECT * FROM " + TABLE_QUEST + " ORDER BY RANDOM() LIMIT 5";
            dbase=this.getReadableDatabase();
            Cursor cursor = dbase.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            //==============================================
            if (cursor.moveToFirst()) {
                do {
                    Question quest = new Question();

                    quest.setID(cursor.getInt(0));
                    quest.setImage(Utility.getPhoto(cursor.getBlob(1)));
                    quest.setQUESTION(cursor.getString(2));
                    quest.setANSWER(cursor.getString(3));
                    quest.setOPTA(cursor.getString(4));
                    quest.setOPTB(cursor.getString(5));
                    quest.setOPTC(cursor.getString(6));
                    quesList.add(quest);
                } while (cursor.moveToNext());
            }
            // return quest list
            return quesList;
        }

Question.java

    public Bitmap getBitmap(){
     return bmp;
}
    public void setImage(Bitmap img){
    bmp = img;
}

Utility.java

public class Utility {
    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getPhoto(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}

Aucun commentaire:

Enregistrer un commentaire