【问题标题】:How to fix the restart of a activity that crashes in Android?如何修复在 Android 中崩溃的活动的重新启动?
【发布时间】:2016-02-12 00:56:12
【问题描述】:

我以编程方式创建了 5 个单选组,每个组有 4 个单选按钮。答案是数据库查询的结果。我添加了一个重启按钮和一个OnClickListener。我想当有人点击按钮时,重新开始我的活动。当应用程序第一次启动时,它工作正常,但是当我按下按钮重新加载活动时,我收到此错误:Unable to start activity ComponentInfo{...}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4 这怎么可能,第一次完美工作,重新加载活动时崩溃?我怎样才能解决这个问题? 这是我的代码:

answerGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
    answerGroup[i] = new RadioGroup(this);
    answerGroup[i].setOrientation(RadioGroup.VERTICAL);
    int j = 0;
    for (Answer an : answers) {
        if (qn.getID() == an.getQuestion_id_answer()) {
            answer[j] = new RadioButton(this);
            answer[j].setText(an.getAnswer());
            answerGroup[i].addView(answer[j]);
            j++;
        }
    }
    linearLayout.addView(answerGroup[i]);
    i++;
}

restartButton = new Button(this);
restartButton.setText(R.string.restartButton);
linearLayout.addView(restartButton);

restartButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = getIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        startActivity(intent);
    }
});

谢谢!

【问题讨论】:

    标签: java android loops android-activity onclicklistener


    【解决方案1】:

    In Intent 意图 = getIntent();你需要设置类似的参数

    Intent intent = getIntent(getApplicationContext(),NameOfYourClass.class)
    

    如果您在 SDK 11+ 上调用,请尝试重新创建 Activity

    super.recreate();
    

    但是,如果这都不起作用,我认为您的表格中有一些错误。尝试使用 ArrayList。

    【讨论】:

    • 谢谢你,但它不起作用。我收到此错误:get intent in activity cannot be applied。还有其他想法吗?
    • 如何使用super.recreate();?而不是startActivity(intent);?
    • 是的,只需在您的按钮中调用它
    • 它也不起作用。表格中没有错误,因为当应用程序第一次启动时,它工作正常。只有当我尝试重新创建活动时,模拟器才会崩溃。是的,我正在使用ArrayList。
    猜你喜欢
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多