user2945300
user2945300

Reputation: 31

Index out of bounds exception in android

I am getting the below error for the attached code. The issue here is that the thread is running even after exiting the "for" loop. All i am doing is that at the click of a button, i am uploading a bunch of files to cloud. ListofDocs[] is where i have stored my list of files that I want to upload. Any help is appreciated. TIA.

11-03 21:23:27.793: E/AndroidRuntime(24480): FATAL EXCEPTION: Thread-11897
11-03 21:23:27.793: E/AndroidRuntime(24480): java.lang.ArrayIndexOutOfBoundsException: length=12; index=12
11-03 21:23:27.793: E/AndroidRuntime(24480):    at com.projects.scloud.PicsList$1$1.run(PicsList.java:99)
11-03 21:23:27.793: E/AndroidRuntime(24480):    at java.lang.Thread.run(Thread.java:856)
for(i=0; i < ListofDocs.length; i++) {
          Log.i("Value of i: ", String.valueOf(i));
        MessageText.setText("Upload Documents");

        /************* Php script path ****************/
        upLoadServerUri = "http://www.androidexample.com/media/UploadToServer.php";
        Backup.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {
                dialog = ProgressDialog.show(DocsList.this, "", "Uploading file...", true);
                new Thread(new Runnable() {
                    public void run() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                MessageText.setText("uploading started.....");
                            }
                        });                   

                        uploadFile(ListofDocs[i]);
                    }
                }).start();
            }
        });
      }

Upvotes: 1

Views: 1752

Answers (2)

user2945300
user2945300

Reputation: 31

I have changed the looping from outside the thread to inside the thread. Since the Thread executes only once, my code was getting executed only once and was incrementing the array element. The code now is working fine.

Upvotes: 0

Stephen C
Stephen C

Reputation: 719229

In order for the code to compile, i must be an instance variable, not a local variable. That means that ListofDocs[i] will refer to the value of that instance variable ... at the point in time that the thread body actually executes. But the chances are that that will be after the outer loop has incremented i to ListofDocs.length. Hence the array index is out of bounds.

You should not use an instance variable. Rather, you should use a final local variable; e.g.

for(int i=0; i < ListofDocs.length; i++) {
    final int final_i = i;
    ...
        // in the anonymous inner class
        uploadFile(ListofDocs[final_i]);
}

Upvotes: 1

Related Questions