Android-java.lang.IndexOutOfBoundsException:索引1无效,大小为1

Android-java.lang.IndexOutOfBoundsException:索引1无效,大小为1,android,sqlite,Android,Sqlite,我正在创建测验应用程序,并将SQLite数据库文件导入到我的Android项目中,如下所示: 它只有一个id,实际的问题,当正确的答案,3个错误的答案和问题的难度。id有数字,问题和答案有文本类型,因为我想在它们的字段中添加数字和文本,难度有数字类型。因此,我只是将此文件导入名为dbQuestion的assets文件夹,并尝试运行我的应用程序,按下Play按钮,它会打开数据库中的第一个问题,但当我选中单选按钮并按下Next question时,我发现以下错误: 08-08 06:42:15.2

我正在创建测验应用程序,并将SQLite数据库文件导入到我的Android项目中,如下所示:

它只有一个id,实际的问题,当正确的答案,3个错误的答案和问题的难度。id有数字,问题和答案有文本类型,因为我想在它们的字段中添加数字和文本,难度有数字类型。因此,我只是将此文件导入名为dbQuestionassets文件夹,并尝试运行我的应用程序,按下Play按钮,它会打开数据库中的第一个问题,但当我选中单选按钮并按下Next question时,我发现以下错误:

08-08 06:42:15.266: D/AndroidRuntime(2459): Shutting down VM
08-08 06:42:15.266: W/dalvikvm(2459): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-08 06:42:15.367: E/AndroidRuntime(2459): FATAL EXCEPTION: main
08-08 06:42:15.367: E/AndroidRuntime(2459): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tmm.android.chuck/com.tmm.android.chuck.QuestionActivity}: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.os.Looper.loop(Looper.java:137)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread.main(ActivityThread.java:5103)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at java.lang.reflect.Method.invokeNative(Native Method)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at java.lang.reflect.Method.invoke(Method.java:525)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at dalvik.system.NativeStart.main(Native Method)
08-08 06:42:15.367: E/AndroidRuntime(2459): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
08-08 06:42:15.367: E/AndroidRuntime(2459):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at java.util.ArrayList.get(ArrayList.java:308)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at com.tmm.android.chuck.quiz.GamePlay.getNextQuestion(GamePlay.java:112)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at com.tmm.android.chuck.QuestionActivity.onCreate(QuestionActivity.java:39)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.Activity.performCreate(Activity.java:5133)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-08 06:42:15.367: E/AndroidRuntime(2459):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-08 06:42:15.367: E/AndroidRuntime(2459):     ... 11 more
08-08 06:42:19.576: D/dalvikvm(2485): GC_FOR_ALLOC freed 67K, 6% free 2844K/3016K, paused 187ms, total 197ms
08-08 06:42:20.756: D/gralloc_goldfish(2485): Emulator without GPU emulation detected.
这就是我的DbHelper.class的外观:

package com.tmm.android.chuck.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.tmm.android.chuck.quiz.Question;

/**
 * @author robert.hinds
 * 
 */
public class DBHelper extends SQLiteOpenHelper {

    // The Android's default system path of your application database
    private static String DB_PATH = "/data/data/com.tmm.android.chuck/databases/";
    private static String DB_NAME = "dbQuestion";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to
     * access to the application assets and resources.
     * 
     * @param context
     */
    public DBHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     * */
    public void createDataBase() throws IOException {

        boolean dbExist = checkDataBase();
        if (!dbExist) {
            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();

            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        File dbFile = myContext.getDatabasePath(DB_NAME);
        return dbFile.exists();
    }

    /**
     * Copies your database from your local assets-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled. This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
    }

    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Add your public helper methods to access and get content from the
    // database.
    // You could return cursors by doing "return myDataBase.query(....)" so it'd
    // be easy
    // to you to create adapters for your views.

    public List<Question> getQuestionSet(int difficulty, int numQ) {
        List<Question> questionSet = new ArrayList<Question>();
        Cursor c = myDataBase.rawQuery(
                "SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty
                        + " ORDER BY RANDOM() LIMIT " + numQ, null);
        while (c.moveToNext()) {
            // Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
            Question q = new Question();
            q.setQuestion(c.getString(1));
            q.setAnswer(c.getString(2));
            q.setOption1(c.getString(3));
            q.setOption2(c.getString(4));
            q.setOption3(c.getString(5));
            q.setRating(difficulty);
            questionSet.add(q);
        }
        return questionSet;
    }
}
package com.tmm.android.chuck.db;
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.List;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.SQLException;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteOpenHelper;
导入com.tmm.android.chuck.quick.Question;
/**
*@作者robert.hinds
* 
*/
公共类DBHelper扩展了SQLiteOpenHelper{
//应用程序数据库的Android默认系统路径
私有静态字符串DB_PATH=“/data/data/com.tmm.android.chuck/databases/”;
私有静态字符串DB_NAME=“dbQuestion”;
私有SQLiteDatabase-myDataBase;
私有最终上下文myContext;
/**
*构造函数获取并保留所传递上下文的引用,以便
*访问应用程序资产和资源。
* 
*@param上下文
*/
公共DBHelper(上下文){
super(上下文,DB_名称,null,1);
this.myContext=上下文;
}
/**
*在系统上创建一个空数据库,并用自己的数据库重写它
*数据库。
* */
public void createDataBase()引发IOException{
布尔值dbExist=checkDataBase();
如果(!dbExist){
//通过调用此方法,空数据库将被创建到
//默认系统路径
//你的应用程序,所以我们可以覆盖它
//数据库与我们的数据库。
这是.getReadableDatabase();
试一试{
copyDataBase();
}捕获(IOE异常){
抛出新错误(“复制数据库时出错”);
}
}
}
/**
*检查数据库是否已存在,以避免每次重新复制文件
*打开应用程序的时间。
* 
*@如果存在则返回true,如果不存在则返回false
*/
私有布尔校验数据库(){
File dbFile=myContext.getDatabasePath(DB_名称);
返回dbFile.exists();
}
/**
*将数据库从本地资产文件夹复制到刚创建的
*系统文件夹中的空数据库,从中可以访问和
*已处理。这是通过传输ByTestStream来完成的。
* */
私有void copyDataBase()引发IOException{
//打开本地数据库作为输入流
InputStream myInput=myContext.getAssets().open(DB_NAME);
//刚创建的空数据库的路径
字符串outFileName=DB_路径+DB_名称;
//打开空数据库作为输出流
OutputStream myOutput=新文件OutputStream(outFileName);
//将字节从输入文件传输到输出文件
字节[]缓冲区=新字节[1024];
整数长度;
而((长度=myInput.read(缓冲区))>0){
写入(缓冲区,0,长度);
}
//关闭溪流
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase()引发SQLException{
//打开数据库
字符串myPath=DB_PATH+DB_NAME;
myDataBase=SQLiteDatabase.openDatabase(myPath,null,
SQLiteDatabase.OPEN_READONLY);
}
@凌驾
公共同步作废关闭(){
if(myDataBase!=null)
myDataBase.close();
super.close();
}
@凌驾
public void onCreate(SQLiteDatabase db){
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
}
//添加公共助手方法以访问和获取
//数据库。
//您可以通过执行“returnmydatabase.query(..”)来返回游标,因此
//放轻松
//为您的视图创建适配器。
公共列表getQuestionSet(int难度,int numQ){
List questionSet=new ArrayList();
游标c=myDataBase.rawQuery(
“从难度=”+难度的问题中选择*
+“随机顺序()限制”+numQ,null);
while(c.moveToNext()){
//Log.d(“问题”,“在DB中发现的问题:”+c.getString(1));
问题q=新问题();
q、 设置问题(c.getString(1));
q、 setAnswer(c.getString(2));
q、 setOption1(c.getString(3));
q、 setOption2(c.getString(4));
q、 setOption3(c.getString(5));
q、 设定(难度);
问题集。添加(q);
}
返回问题集;
}
}
Gameplay.class:

/**
 * 
 */
package com.tmm.android.chuck.quiz;

import java.util.ArrayList;
import java.util.List;

/**
 * @author robert.hinds
 * 
 * This class represents the current game being played
 * tracks the score and player details
 *
 */
public class GamePlay {

    private int numRounds;
    private int difficulty;
    private String playerName;
    private int right;
    private int wrong;
    private int round;

    private List<Question> questions = new ArrayList<Question>();

    /**
     * @return the playerName
     */
    public String getPlayerName() {
        return playerName;
    }
    /**
     * @param playerName the playerName to set
     */
    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }
    /**
     * @return the right
     */
    public int getRight() {
        return right;
    }
    /**
     * @param right the right to set
     */
    public void setRight(int right) {
        this.right = right;
    }
    /**
     * @return the wrong
     */
    public int getWrong() {
        return wrong;
    }
    /**
     * @param wrong the wrong to set
     */
    public void setWrong(int wrong) {
        this.wrong = wrong;
    }
    /**
     * @return the round
     */
    public int getRound() {
        return round;
    }
    /**
     * @param round the round to set
     */
    public void setRound(int round) {
        this.round = round;
    }
    /**
     * @param difficulty the difficulty to set
     */
    public void setDifficulty(int difficulty) {
        this.difficulty = difficulty;
    }
    /**
     * @return the difficulty
     */
    public int getDifficulty() {
        return difficulty;
    }
    /**
     * @param questions the questions to set
     */
    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }

    /**
     * @param q the question to add
     */
    public void addQuestions(Question q) {
        this.questions.add(q);
    }

    /**
     * @return the questions
     */
    public List<Question> getQuestions() {
        return questions;
    }


    public Question getNextQuestion(){

        //get the question
        Question next = questions.get(this.getRound());
        //update the round number to the next round
        this.setRound(this.getRound()+1);
        return next;
    }

    /**
     * method to increment the number of correct answers this game
     */
    public void incrementRightAnswers(){
        right ++;
    }

    /**
     * method to increment the number of incorrect answers this game
     */
    public void incrementWrongAnswers(){
        wrong ++;
    }
    /**
     * @param numRounds the numRounds to set
     */
    public void setNumRounds(int numRounds) {
        this.numRounds = numRounds;
    }
    /**
     * @return the numRounds
     */
    public int getNumRounds() {
        return numRounds;
    }

    /**
     * method that checks if the game is over
     * @return boolean
     */
    public boolean isGameOver(){
        return (getRound() >= getNumRounds());
    }


}
/**
* 
*/
包com.tmm.android.chuck.quick;
导入java.util.ArrayList;
导入java.util.List;
/**
*@作者robert.hinds
* 
*此类表示当前正在玩的游戏
*跟踪分数和球员详细信息
*
*/
公共类游戏{
私人整数;
私人智力困难;
私人弦乐演奏者姓名;
私权;
私密性错误;
私人整数回合;
私有列表问题=新建ArrayList();
/**
*@返回玩家名称
*/
公共字符串
c.moveToFirst()
c.moveToFirst()
while (!cursor.isAfterLast()) 
{
}
Cursor c = myDataBase.rawQuery(
                    "SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty
                            + " ORDER BY Question_ID " + numQ);
c.moveToNext();
 while (!c.isAfterLast()) {
            // Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
            Question q = new Question();
            q.setQuestion(c.getString(1));
            q.setAnswer(c.getString(2));
            q.setOption1(c.getString(3));
            q.setOption2(c.getString(4));
            q.setOption3(c.getString(5));
            q.setRating(difficulty);
            questionSet.add(q);
            c.moveToNext();
        }