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

时间:2019-03-05 14:20:03

标签: android sms postdelayed

我想在FOR循环中引入函数postDelayed(),但编译器不再识别以下变量: Jarray, 一世, 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 个答案:

答案 0 :(得分:0)

问题1

不能在循环中使用最终变量。您可以像下面这样

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

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

问题2

您在内部类/匿名类内部访问的任何变量都必须是最终的。因此,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();
}