Search code examples
androidsmspostdelayed

how to pass argument to postDelay() inside FOR loop


I want to introduce the function postDelayed() inside my FOR loop but the compiler no longer recognizes the following variables: Jarray, i, 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);

            }

thank's!


Solution

  • Issue 1

    Can't use a final variable in a loop. You can do it like below

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

    Now use index wherever you need to use i.

    Issue 2

    Any variable that you access inside an inner class/anonymous class needs to be final. So, jArray needs to be final like this.

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

    Issue 3

    When you are doing any JSON operation you need to handle the exceptions like this

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