使用asyncTask

时间:2018-01-19 19:46:13

标签: java android

我正在努力加强我对asyncTask的了解,所以我按照教程下载了一个图片,但我不明白的事情,我得到一个错误的ArrayOutofBound索引,所以如果有人告诉我原因,我会很感激 这是代码,请告诉我他为什么要迭代进度条最大值

    public class MainActivity extends AppCompatActivity {
           ProgressBar progessBar;
           ImageView MyImage;
           private final String IMAGE_URL =    "http://www.101apps.co.za/images/headers/101_logo_very_small.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MyImage = findViewById(R.id.imageView);
    ImageButton downloaad = findViewById(R.id.imageButton);
    downloaad.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new downloadFile(MainActivity.this).execute(IMAGE_URL);
        }
    });

}
public class downloadFile extends AsyncTask<String , Integer , String>{
    private  int PROGRESS_BAR_MAX = 100;
    Context context;
    public downloadFile(Context cxt){
         this.context = cxt;
    }
    @Override
    protected String doInBackground(String... strings) {
        String result = "";
        String path = context.getFilesDir() + File.pathSeparator + "downloadFile.png";
        HttpURLConnection httpURLConnection = null;
        try{
            final URL url  = new URL(strings[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            int length = httpURLConnection.getContentLength();
            InputStream IS = (InputStream) url.getContent();
            byte[] imageData = new byte[length];
            Log.d("aho" , "" + length);
            int buffersize = (int) Math.ceil(length/(double)PROGRESS_BAR_MAX);
            int download = 0;
            for(int i = 1 ; i < PROGRESS_BAR_MAX ; i++){
                long read = IS.read(imageData , download , buffersize);
                download += read;
                publishProgress(i);

            }

            BufferedInputStream bufferedReader = new BufferedInputStream(httpURLConnection.getInputStream());
            FileOutputStream Fo = new FileOutputStream(path);
            int data = bufferedReader.read();
            while(data != -1){
                Fo.write(data);
                data = bufferedReader.read();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpURLConnection == null){
                httpURLConnection.disconnect();
            }
        }
        publishProgress(PROGRESS_BAR_MAX);
        return path;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progessBar = findViewById(R.id.progressBar);
        progessBar.setMax(PROGRESS_BAR_MAX);


    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progessBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s != null) {
            progessBar.setVisibility(View.INVISIBLE);
            Bitmap bitmap = BitmapFactory.decodeFile(s);
            MyImage.setImageBitmap(bitmap);

        }
    }
}
}

这是堆栈跟踪         01-20 03:37:40.607 4075-4096 / com.gamecodeschool.bodybuilder E / AndroidRuntime:FATAL EXCEPTION:AsyncTask#1                                                                               过程:com.gamecodeschool.bodybuilder,PID:4075                                                                               java.lang.RuntimeException:执行doInBackground()时发生错误                                                                                   在android.os.AsyncTask $ 3.done(AsyncTask.java:353)                                                                                   在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)                                                                                   at java.util.concurrent.FutureTask.setException(FutureTask.java:252)                                                                                   在java.util.concurrent.FutureTask.run(FutureTask.java:271)                                                                                   在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:245)                                                                                   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)                                                                                   at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:636)                                                                                   在java.lang.Thread.run(Thread.java:764)                                                                                引起:java.lang.ArrayIndexOutOfBoundsException:size = 1123 offset = 1116 byteCount = 12                                                                                   在com.android.okhttp.okio.Util.checkOffsetAndCount(Util.java:29)                                                                                   在com.android.okhttp.okio.RealBufferedSource $ 1.read(RealBufferedSource.java:368)                                                                                   在com.gamecodeschool.bodybuilder.MainActivity $ downloadFile.doInBackground(MainActivity.java:66)                                                                                   在com.gamecodeschool.bodybuilder.MainActivity $ downloadFile.doInBackground(MainActivity.java:45)                                                                                   在android.os.AsyncTask $ 2.call(AsyncTask.java:333)                                                                                   在java.util.concurrent.FutureTask.run(FutureTask.java:266)

1 个答案:

答案 0 :(得分:0)

这是因为您的读取循环正在循环进度计数而不是正在下载的资源的大小。循环超过资源的大小(确保检查读取错误)并根据读取的数量与总长度计算进度。