【问题标题】:ImageView's picture does not set with AsyncTaskImageView的图片没有用AsyncTask设置
【发布时间】:2017-08-06 08:22:53
【问题描述】:

在我的代码中,我在我的MyTask 类中将图片设置为ImageView,该类使用AsyncTask,但是当我运行我的代码时,只有一两个ImageViews 有图片,而其他图片为空,显示默认图片。 线程有问题吗?

这是我的代码:

@Override
public View getView(final int position,  View convertView, ViewGroup parent) {
    Log.e("sara" , "this part takes time");

    LayoutInflater inflater = getLayoutInflater();

    convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
    iv = (ImageView) convertView.findViewById(R.id.icon);
   file = new File(Uri.parse(getItem(position).toString()).getPath());
    new myTask().execute();

    return convertView;
}

        private class myTask extends AsyncTask <Void , Void ,Bitmap> {

            @Override
            protected Bitmap doInBackground(Void... params) {

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                try {
                    BitmapFactory.decodeStream(new FileInputStream(file), null, options);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                options.inJustDecodeBounds = false;
                options.inSampleSize = 2;
                try {
                    bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                return bmp;
            }

            @Override
            protected void onPostExecute(Bitmap aVoid) {

                iv.setImageBitmap(aVoid);
            }
        }

【问题讨论】:

  • 您的日志中是否有任何错误..?
  • 要不要在 asyncTask.不需要使用位图。你可以简单地使用滑动方法。

标签: java android multithreading android-asynctask


【解决方案1】:

这是因为每次调用 getView() 方法时都会覆盖 iv(imageview) 对象,并且因为 MyTask 是一个异步任务,其中 doInBackground() 在后台线程上异步调用,而 onPostExecute() 在主线程上调用在那之后。所以 onPostExecute 只会更新当前的 imageview。您必须在网格的每个图像视图上设置位图。此解决方案应该适合您:

@Override
   public View getView(final int position,  View convertView, ViewGroup parent) {
        Log.e("sara" , "this part takes time");


        LayoutInflater inflater = getLayoutInflater();


        convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
      ImageView  iv = (ImageView) convertView.findViewById(R.id.icon);
       File file = new File(Uri.parse(getItem(position).toString()).getPath());
        new myTask(iv, file).execute();


        return convertView;
    }


            private class MyTask extends AsyncTask <Void , Void ,Bitmap> {
               Imageview iv;
                File file;
             public void MyTask(Imageview iv, File file)
                 {
                   this.iv=iv;
                   this.file= file;
                  }
                @Override
                protected Bitmap doInBackground(Void... params) {

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    try {
                        BitmapFactory.decodeStream(new FileInputStream(file), null, options);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    options.inJustDecodeBounds = false;
                    options.inSampleSize = 2;
                    try {
                        bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    return bmp;
                }


                @Override
                protected void onPostExecute(Bitmap aVoid) {

                    iv.setImageBitmap(aVoid);
                }
            }

【讨论】:

    【解决方案2】:

    我认为您正在尝试使用 url 加载图像

    您可以使用最适合加载图像的图像加载器参考(例如通用图像加载器)

    这是你可以拥有的代码

    首先从下面下载通用图像加载器库 https://github.com/nostra13/Android-Universal-Image-Loader

    您必须将此方法添加到您的应用程序级类中,这样您就不需要多次编写

     public static void initImageLoader(Context context) {
            // This configuration tuning is custom. You can tune every option, you
            // may tune some of them,
            // or you can create default configuration by
            // ImageLoaderConfiguration.createDefault(this);
            // method.
            ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(
                    context);
            config.threadPriority(Thread.NORM_PRIORITY - 2);
            config.denyCacheImageMultipleSizesInMemory();
            config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
            config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
            config.tasksProcessingOrder(QueueProcessingType.LIFO);
            config.writeDebugLogs(); // Remove for release app
    
            // Initialize ImageLoader with configuration.
            ImageLoader.getInstance().init(config.build());
        }
    

    然后在 Adapter 类中您只需添加以下代码即可加载图像

    // For Image Display options - Failed , Success and Error
    // Add this is in your adapter constructor  
    DisplayImageOptions userimgoptions = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.profile_pic_no_border)
                    .showImageForEmptyUri(R.drawable.profile_pic_no_border)
                   .showImageOnFail(R.drawable.profile_pic_no_border).cacheInMemory(true)
                    .cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
    

    // 在你的 getview 方法中,只需使用此信号行代码来加载图像

    ImageLoader.getInstance().displayImage(modelFeeds.getUserAvatarOriginal(), myHolder.img_profilepicture, userimgoptions);
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      使用 Glide Library 设置 Imageview

      第 1 步:在 build.gradle 文件中包含依赖项

      compile 'com.github.bumptech.glide:glide:3.7.0'
      

      Step2:在Java文件中包含Glide

      String fileName = "1.jpg";
      String completePath = Environment.getExternalStorageDirectory() + "/" + 
       fileName;
      
      File file = new File(completePath);
      Uri imageUri = Uri.fromFile(file);
      
        Glide.with(this)
              .load(imageUri)
              .placeholder(R.drawable.no_media)
                      .into(imgView);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-24
        相关资源
        最近更新 更多