如何使用Picasso在asynctask onPost方法中下载图像并将图像存储在内部存储器中

时间:2017-04-20 06:19:23

标签: android bitmap android-asynctask picasso

我正在尝试从url下载图像并将该图像存储到内部存储器中。我正在使用picasso库(版本:'2.5.0')。但是onBitmapLoaded()没有第一次调用。我看到了这个链接Picasso first run not call onBitmapLoaded in for loop。但这对我不起作用。请帮帮我

final List<Target> targets = new ArrayList<Target>();
@Override
protected void onPostExecute(String sResult) {
   for (int i = 0; i < arraylist.length(); i++) {
         DownloadImage(arraylist.get(i));
    }
}

 public void DownloadImage(String ImageUrl){
     final String imageDir = Environment.getExternalStorageDirectory() + "/Images/";
    sPath = "";
    Target target = new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {

            FileOutputStream fos = null;
            try {
                File myDir = new File(imageDir);
                if (!myDir.exists()) {
                    myDir.mkdirs();
                }
                myDir = new File(myDir, fileName);
                fos = new FileOutputStream(myDir);

                sPath = myDir.getAbsolutePath();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                mStudent.setPhoto(sPath);
                mStudentDB.addOrUpdateStudent(mStudent);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            targets.remove(this);

        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            targets.remove(this);
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    };
    Picasso.with(activity)
            .load(ImageUrl)
            .into(target);
 }

0 个答案:

没有答案