如何在 FOR 循环中将参数传递给 postDelay()

how to pass argument to postDelay() inside FOR loop

我想在我的 FOR 循环中引入函数 postDelayed(),但编译器不再识别以下变量: 杰瑞, 一世, getString()

...
JSONObject result1 = new JSONObject(result);
            JSONArray jArray = result1.getJSONArray("doc");

            for (int i=0; i < jArray.length(); i++) {


                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        SmsManager smsManager = SmsManager.getDefault();
                        int length = message.length();

                        if (length > MAX_SMS_MESSAGE_LENGTH) {
                            ArrayList<String> messagelist = smsManager.divideMessage(message);
                            smsManager.sendMultipartTextMessage("+3311111111", null, messagelist, null, null);
                        } else {
                            smsManager.sendTextMessage("+331111111", null, message, null, null);
                        }


                        JSONObject json_data = jArray.getJSONObject(i); //here 3 errors: error: local variable jArray is accessed from within inner class; needs to be declared final / error: unreported exception JSONException; must be caught or declared to be thrown / error: local variable i is accessed from within inner class; needs to be declared final

...

                        Toast.makeText(activity, "Envoi du doc " + json_data.getString("doc_title"), Toast.LENGTH_LONG).show(); // here, error: unreported exception JSONException; must be caught or declared to be thrown
                    }
                }, 30000);

            }

谢谢!

第 1 期

不能在循环中使用最终变量。你可以像下面那样做

for (int i=0; i < jArray.length(); i++) {
    final int index = i;

现在在需要使用 i 的地方使用 index

第 2 期

您在内部 class/anonymous class 中访问的任何变量都需要是最终的。所以,jArray 需要像这样是最终的。

final JSONArray jArray = result1.getJSONArray("doc");

第 3 期

当您进行任何 JSON 操作时,您需要像这样处理异常

try{
    // Do your operation here like 
    JSONObject json_data = jArray.getJSONObject(i);
}
catch(JSONException jse){
    jse.printStackTrace();
}