Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 索引0无效,大小为0_Android_Sqlite - Fatal编程技术网

Android 索引0无效,大小为0

Android 索引0无效,大小为0,android,sqlite,Android,Sqlite,我的应用程序有问题。上面说无效索引为0,大小为0。这是logcat 09-01 12:58:47.903: E/AndroidRuntime(15196): FATAL EXCEPTION: main 09-01 12:58:47.903: E/AndroidRuntime(15196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mapeh.subject/com.mapeh.su

我的应用程序有问题。上面说无效索引为0,大小为0。这是logcat

   09-01 12:58:47.903: E/AndroidRuntime(15196): FATAL EXCEPTION: main
   09-01 12:58:47.903: E/AndroidRuntime(15196): java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.mapeh.subject/com.mapeh.subject.assessment.MusicLessonAssessment}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.os.Handler.dispatchMessage(Handler.java:99)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.os.Looper.loop(Looper.java:137)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at android.app.ActivityThread.main(ActivityThread.java:5041)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at java.lang.reflect.Method.invokeNative(Native Method)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at java.lang.reflect.Method.invoke(Method.java:511)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   09-01 12:58:47.903: E/AndroidRuntime(15196):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at dalvik.system.NativeStart.main(Native Method)
  09-01 12:58:47.903: E/AndroidRuntime(15196): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at java.util.ArrayList.get(ArrayList.java:304)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at com.mapeh.subject.musiclesson.GamePlay.getNextQuestion(GamePlay.java:102)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at com.mapeh.subject.assessment.MusicLessonAssessment.onCreate(MusicLessonAssessment.java:34)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at android.app.Activity.performCreate(Activity.java:5104)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
  09-01 12:58:47.903: E/AndroidRuntime(15196):  ... 11 more
代码如下:

  private Question currentQ;
private GamePlay currentGame;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.musiclessonassessment);
    /**
     * Configure current game and get question
     */
    currentGame = ((MapehSubjectApplication)getApplication()).getCurrentGame();
    currentQ = currentGame.getNextQuestion();  <~~~~~ Error here
    Button nextBtn = (Button) findViewById(R.id.next);
    nextBtn.setOnClickListener(this);

    /**
     * Update the question and answer options..
     */
    setQuestions();

}


/**
 * Method to set the text for the question and answers from the current games
 * current question
 */
private void setQuestions() {
    //set the question text from current question
    String question = Utility.capitalise(currentQ.getQuestion()) + "?";
    TextView qText = (TextView) findViewById(R.id.question);
    qText.setText(question);

    //set the available options
    List<String> answers = currentQ.getQuestionOptions();
    TextView option1 = (TextView) findViewById(R.id.answer1);
    option1.setText(Utility.capitalise(answers.get(0)));

    TextView option2 = (TextView) findViewById(R.id.answer2);
    option2.setText(Utility.capitalise(answers.get(1)));

    TextView option3 = (TextView) findViewById(R.id.answer3);
    option3.setText(Utility.capitalise(answers.get(2)));

    TextView option4 = (TextView) findViewById(R.id.answer4);
    option4.setText(Utility.capitalise(answers.get(3)));
}


@Override
public void onClick(View arg0) {
    //Log.d("Questions", "Moving to next question");

    /**
     * validate a checkbox has been selected
     */
    if (!checkAnswer()) return;


    /**
     * check if end of game
     */
    if (currentGame.isGameOver()){
        //Log.d("Questions", "End of game! lets add up the scores..");
        //Log.d("Questions", "Questions Correct: " + currentGame.getRight());
        //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
        Intent i = new Intent(this, GameOver.class);
        startActivity(i);
        finish();
    }
    else{
        Intent i = new Intent(this, MusicLessonAssessment.class);
        startActivity(i);
        finish();
    }
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_BACK :
        return true;
    }

    return super.onKeyDown(keyCode, event);
}


/**
 * Check if a checkbox has been selected, and if it
 * has then check if its correct and update gamescore
 */
private boolean checkAnswer() {
    String answer = getSelectedAnswer();
    if (answer==null){
        //Log.d("Questions", "No Checkbox selection made - returning");
        return false;
    }
    else {
        //Log.d("Questions", "Valid Checkbox selection made - check if correct");
        if (currentQ.getAnswer().equalsIgnoreCase(answer))
        {
            //Log.d("Questions", "Correct Answer!");
            currentGame.incrementRightAnswers();
        }
        else{
            //Log.d("Questions", "Incorrect Answer!");
            currentGame.incrementWrongAnswers();
        }
        return true;
    }
}


/**
 * 
 */
private String getSelectedAnswer() {
    RadioButton c1 = (RadioButton)findViewById(R.id.answer1);
    RadioButton c2 = (RadioButton)findViewById(R.id.answer2);
    RadioButton c3 = (RadioButton)findViewById(R.id.answer3);
    RadioButton c4 = (RadioButton)findViewById(R.id.answer4);
    if (c1.isChecked())
    {
        return c1.getText().toString();
    }
    if (c2.isChecked())
    {
        return c2.getText().toString();
    }
    if (c3.isChecked())
    {
        return c3.getText().toString();
    }
    if (c4.isChecked())
    {
        return c4.getText().toString();
    }

    return null;
}
游戏性

更新:

DBAdapter中的代码片段:

代码:

我不知道我遗漏了什么,但我相信我的数据库有记录,我仔细检查了一下。非常感谢你的帮助。谢谢。

从这两条线索:

at com.mapeh.subject.musiclesson.GamePlay.getNextQuestion(GamePlay.java:102)

Question next = questions.get(this.getRound());   <~~~~~ Error here

显然,this.getRound返回0,但问句是空的,所以位置0处没有问句。因此出现异常。

您可能没有在GamePlay类中的questions list objectmember变量上添加任何问题,导致列表大小为空,并尝试对其进行索引,导致ArrayIndexOutOfBounds异常,因为您在代码中的任何地方都没有使用addQuestions。。。方法。

我以前见过。。有点像这个:

试试这个: 1.再次检查是否已更新数据库。 2.使用sqlite浏览器查看数据库表中的值是否正确

完成此操作后,在emulator上运行应用程序时,如果所有值均为1,请检查“难度”上的值。转到“设置”并选择“轻松”。。如果值为2,则选择“中等”,依此类推


希望这有帮助..

那么我该怎么办?使用addQuestions方法我会怎么做?我建议您在列表中填写所需的问题,可能是在游戏性初始化部分。我的观点是,你必须在你的列表中有问题才能对它们进行索引。嗨,这些问题已经来自我预先填充的数据库。请查看我的更新帖子。当然你的数据库可能会被填充,但是你什么时候用数据库中的数据填充你的游戏对象呢?也就是说,何时何地使用getQuestionSet的结果调用setQuestions或addQuestion?在你的问题中添加更多的代码。你仍然不会在游戏实例的成员列表中添加任何问题。我建议您在游戏性实例获取后调用:currentGame.setQuestionsArrayListDBAdapter.getQuestionSet;|要在currentGame中创建一个包含问题的列表,您不需要在类中初始化list变量,因为它是在方法getQuestionSet中完成的,并且您正在以这种方式设置列表,该列表返回为GamePlay的实例列表。因此,我如何调试这些问题?
    public List<Question> getQuestionSet(int difficulty, int numQ){
        List<Question> questionSet = new ArrayList<Question>();
        Cursor c = myDataBase.rawQuery("SELECT * FROM tblQuestions WHERE Lesson = " + 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(5));
            q.setOption1(c.getString(2));
            q.setOption2(c.getString(3));
            q.setOption3(c.getString(4));
            q.setRating(difficulty);
            questionSet.add(q);
        }
        return questionSet;
    }
 /**
 * Listener for game menu
 */
@Override
public void onClick(View v) {
    Intent i;

    switch (v.getId()){
    case R.id.assess :
        //once logged in, load the main page
        //Log.d("LOGIN", "User has started the game");

        //Get Question set //
        List<Question> questions = getQuestionSetFromDb();

        //Initialise Game with retrieved question set ///
        GamePlay c = new GamePlay();
        c.setQuestions(questions);
        c.setNumRounds(getNumQuestions());
        ((MapehSubjectApplication)getApplication()).setCurrentGame(c);  

        //Start Game Now.. //
        i = new Intent(this, MusicLessonAssessment.class);
        startActivityForResult(i, Constants.PLAYBUTTON);
        break;

    case R.id.exit :
        finish();
        break;
    }

}


/**
 * Method that retrieves a random set of questions from
 * the database for the given difficulty
 * @return
 * @throws Error
 */
private List<Question> getQuestionSetFromDb() throws Error {
    int diff = getDifficultySettings();
    int numQuestions = getNumQuestions();
    DBAdapter myDBAdapter = new DBAdapter(this);
    try {
        myDBAdapter.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        myDBAdapter.openDataBase();
    }catch(SQLException sqle){
        throw sqle;
    }
    List<Question> questions = myDBAdapter.getQuestionSet(diff, numQuestions);
    myDBAdapter.close();
    return questions;
}


/**
 * Method to return the difficulty settings
 * @return
 */
private int getDifficultySettings() {
    SharedPreferences settings = getSharedPreferences(Constants.SETTINGS, 0);
    int diff = settings.getInt(Constants.DIFFICULTY, Constants.MUSIC);
    return diff;
}

/**
 * Method to return the number of questions for the game
 * @return
 */
private int getNumQuestions() {
    SharedPreferences settings = getSharedPreferences(Constants.SETTINGS, 0);
    int numRounds = settings.getInt(Constants.NUM_ROUNDS, 10);
    return numRounds;
}
at com.mapeh.subject.musiclesson.GamePlay.getNextQuestion(GamePlay.java:102)

Question next = questions.get(this.getRound());   <~~~~~ Error here