0

好的,所以我想我可能对如何解决这个问题有一些见解,但我不确定。我有一段代码首先声明一个 RadioButton[],然后是一个将其设置为特定事物的方法,然后是另一个检查哪个 RadioButton 被选中的方法。

RadioButton[] rB = null;

String geUrl(RadioButton[] rBp) {
    for(int radind = 0; radind < rBp.length; radind++) {
        Log.d("APP", "rBp value is " + rBp.toString());
        Log.d("APP", "In for loop, index = " + radind + ", length = " + rBp.length);
        if (rBp[radind].isChecked()) {
            String url = rB[radind].getText().toString();
            Log.d("APP", "Detected url, " + url);
            return url;
        }
    }
    return "err";
}

public void refresh() {
    if (rB != null) {
        rG.removeAllViews();
    }
for(int index = 0; index < tempWikiDB.size() ; index++) {
    rB = new RadioButton[tempWikiDB.size()];
    rB[index]  = new RadioButton(this);
    rG.addView(rB[index]);
    rB[index].setText(tempWikiDB.toArray()[index].toString());
}

}

为 geUrl 方法提供了足够的参数。但是,在运行时,我得到了 if (rBp[radind].isChecked()) 行的空指针异常。我认为这是因为 RadioButton[] rB = null; 不是我应该如何声明变量,但我不知道如何。

这是日志猫:

11-23 05:48:27.911: E/AndroidRuntime(1189): FATAL EXCEPTION: main
11-23 05:48:27.911: E/AndroidRuntime(1189): java.lang.NullPointerException
11-23 05:48:27.911: E/AndroidRuntime(1189):     at com.spng453.wikicenter.SearchWiki.geUrl(SearchWiki.java:37)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at com.spng453.wikicenter.SearchWiki$1.onClick(SearchWiki.java:74)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.view.View.performClick(View.java:4202)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.view.View$PerformClick.run(View.java:17340)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.os.Handler.handleCallback(Handler.java:725)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.os.Looper.loop(Looper.java:137)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at android.app.ActivityThread.main(ActivityThread.java:5039)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at java.lang.reflect.Method.invokeNative(Native Method)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at java.lang.reflect.Method.invoke(Method.java:511)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-23 05:48:27.911: E/AndroidRuntime(1189):     at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

4

在每次循环迭代for中初始化数组时,将此行从循环中取出rB

rB = new RadioButton[tempWikiDB.size()];
于 2012-11-23T05:52:00.373 回答