onProgressUpdate 上的 ArrayIndexOutOfBoundsException 错误

Posted

技术标签:

【中文标题】onProgressUpdate 上的 ArrayIndexOutOfBoundsException 错误【英文标题】:ArrayIndexOutOfBoundsException error on onProgressUpdate 【发布时间】:2016-03-24 10:52:38 【问题描述】:

我在函数 onProgressUpdate 上有“ArrayIndexOutOfBoundsException”错误 我认为一切正常,但找不到问题。 当这个任务要运行 logcat 说 ArrayIndexOutOfBoundsException Lenght=0 index=0 !!!我在这样的链接中看到了这段代码:

How to implement file upload progress bar in android

Upload large file with progress bar and without OutOfMemory Error in Android

我先测试了上传任务,它工作正常......但是当我添加进度条时它崩溃了...... 请帮我解决

public class InsertFile extends AsyncTask<String, Integer, String> 

final String name;
final Context parent;
String sourceFileUri;
String upLoadServerUri;
int allByte,perBytes=0;
SeekArc skarc;
private ProgressDialog dialog;

public InsertFile(Context c,String uri,String name,String folder2Up, SeekArc s)
    parent = c;
    sourceFileUri=uri;
    this.name=name;
    upLoadServerUri="*******************************";
    //skarc=s;
    dialog = new ProgressDialog(parent);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setMessage("Uploading photo, please wait.");
    dialog.setMax(100);
    dialog.setCancelable(true);



@Override
protected String doInBackground(String... params) 

    try 

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        publishProgress();
        if (sourceFile.isFile()) 

            try 
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new           FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE",
                        "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("bill", sourceFileUri);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                        + name + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();
                allByte=bytesAvailable;
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                perBytes=0;
                perBytes=((allByte-bytesAvailable)*100)/allByte;

                while (bytesRead > 0) 
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    perBytes=((allByte-bytesAvailable)*100)/allByte;
                    publishProgress(Integer.valueOf(perBytes));
                

                // send multipart form data necesssary after file
                // data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                //serverResponseCode = conn.getResponseCode();
                //String serverResponseMessage = conn
                //       .getResponseMessage();

                //if (serverResponseCode == 200) 

                // messageText.setText(msg);
                //Toast.makeText(ctx, "File Upload Complete.",
                //      Toast.LENGTH_SHORT).show();

                // recursiveDelete(mDirectory1);

                //

                int serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) 
                    Handler handler = new Handler(parent.getMainLooper());
                    handler.post(new Runnable() 
                        public void run() 
                            Toast.makeText(parent, "File is uploaded", Toast.LENGTH_LONG).show();
                        
                    );
                
                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();


            catch(Exception e)

                e.printStackTrace();

            
        
        else
            Handler handler =  new Handler(parent.getMainLooper());
            handler.post(new Runnable() 
                public void run() 
                    Toast.makeText(parent, "No file", Toast.LENGTH_LONG).show();
                
            );
        

    

    catch (final Exception ex) 

        ex.printStackTrace();
        Handler handler =  new Handler(parent.getMainLooper());
        handler.post(new Runnable() 
            public void run() 
                Toast.makeText(parent, ex.toString(), Toast.LENGTH_LONG).show();
            
        );
    

    return "Executed";


@Override
protected void onProgressUpdate(Integer... values) 
    dialog.setProgress(values[0]);


@Override
protected void onPostExecute(String result) 
    dialog.dismiss();


@Override
protected void onPreExecute() 
    dialog.show();

【问题讨论】:

您没有在第一个publishProgress() 调用中传递任何值,但您正试图在onProgressUpdate() 中检索该调用的第一个参数。看起来你真的不需要第一次调用,所以你可以删除它,或者你可以传递0 是的......谢谢你......我没有看到那行......但是在修复这个之后我运行了应用程序,看到进度条很快就填满了上传......所以这里有什么问题??? 【参考方案1】:

似乎您正在发布没有参数的进度,因此您的 onProgressUpdate() 值数组为空。

【讨论】:

以上是关于onProgressUpdate 上的 ArrayIndexOutOfBoundsException 错误的主要内容,如果未能解决你的问题,请参考以下文章

Android,AsyncTask 不调用 onProgressUpdate 和 onPostExecute

onProgressUpdate() 中的 NullPointerException

在从 Internet 下载数据期间,在 AsyncTask 的 onProgressUpdate 中显示确定的 ProgressBar

如何更新所有片段? onProgressUpdate 不更新所有片段

如何使用 Runnable 回调替换 AsyncTask onProgressUpdate()

AsyncTask doinbackground onProgressUpdate onCancelled onPostExecute的基本使用