从GridView的SD卡目录加载图像 [英] loading images from SD card directory in GridView

查看:208
本文介绍了从GridView的SD卡目录加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个应用程序,允许用户创建的外部存储设备的相册(文件夹)。现在我尝试从所述目录图像​​,并显示它们的GridView中。我使用的是AsyncTask的使用,通过listFiles(),然后创建一个位图,一旦我抓住每个图像文件的目录遍历,回收它,然后再次使用它。我的问题是,没有什么是显示在我的GridView的。我给自己定了一些日志断裂和LogCat中表明我迭代确实发生,图像检索。这使我想起我在结合位图到电网,可能在getView我Adapter类的地方犯了一个错误?或者,也许我错了。在我做错了任何帮助吗?我想评论的code尽可能多地和我已经离开了不必要的作品。谢谢

 公共类AlbumGridView扩展活动实现OnItemClickListener {私人的GridView sdcardImages;
私人ImageAdapter imageAdapter;私人显示器显示;私人位图位图;
私人位图B:文件[]图像列表;
私有静态最后弦乐TAG =AlbumGridView;
字符串路径;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    的setContentView(R.layout.album_view);    //显示=
    //((对象)getSystemService(Context.WINDOW_SERVICE)))getDefaultDisplay();    PATH = getIntent()getStringExtra(密钥)。
    Toast.makeText(这一点,路径,Toast.LENGTH_SHORT).show();
    setupViews();
    setProgressBarIndeterminateVisibility(真);
    loadImages();}保护无效的onDestroy(){
    super.onDestroy();
    最终的GridView格= sdcardImages;
    最终诠释计数= grid.getCount();
    ImageView的V = NULL;
    的for(int i = 0; I<计数;我++){
        V =(ImageView的)grid.getChildAt(ⅰ);
        ((BitmapDrawable)v.getDrawable())setCallback(空)。
    }
}//设置在GridView私人无效setupViews(){
    sdcardImages =(GridView控件)findViewById(R.id.gvAlbumView);
    // sdcardImages.setNumColumns(display.getWidth()/ 95);
    sdcardImages.setClipToPadding(假);
    sdcardImages.setOnItemClickListener(AlbumGridView.this);
    imageAdapter =新ImageAdapter(getApplicationContext());
    // imageAdapter.setImageList(路径);
    sdcardImages.setAdapter(imageAdapter);
}私人无效addImage(LoadedImage ...值){
    对于(LoadedImage图片:值){
        imageAdapter.addPhoto(图片);
        imageAdapter.notifyDataSetChanged();
    }
}//保存位图图像到一个列表,并返回该列表
@覆盖
公共对象onRetainNonConfigurationInstance(){
    最终的GridView格= sdcardImages;
    最终诠释计数= grid.getChildCount();
    最后LoadedImage [] =名单新LoadedImage [统计]    的for(int i = 0; I<计数;我++){
        最终ImageView的V =(ImageView的)grid.getChildAt(ⅰ);
        名单由[i] =新LoadedImage(
                ((BitmapDrawable)v.getDrawable())getBitmap())。
    }    返回列表;
}私人无效loadImages(){
    // TODO自动生成方法存根
    最终目标数据= getLastNonConfigurationInstance();
    如果(数据== NULL){
        新LoadImagesFromSDCard()执行();
    }其他{
        最后LoadedImage [] =照片(LoadedImage [])的数据;
        如果(photos.length == 0){
            新LoadImagesFromSDCard()执行();
        }
        对于(LoadedImage照片:照片){
            addImage(照片);
        }
    }
}公共无效onItemClick(适配器视图<>为arg0,ARG1观,诠释ARG2,长ARG3){
    // TODO自动生成方法存根}

/-------------------------------------------------------------------------------------/

  //适配器为GridView公共类ImageAdapter延伸BaseAdapter {    私人语境mContext;
    私人的ArrayList< LoadedImage>照片=新的ArrayList< LoadedImage>();    私人字符串路径;
    私人位图位图;    公共ImageAdapter(上下文的背景下){
        mContext =背景;
    }    公共无效addPhoto(LoadedImage照片){
        photos.add(照片);
    }    公众诠释的getCount(){
        返回photos.size();
    }    公共对象的getItem(INT位置){
        返回photos.get(位置);
    }    众长getItemId(INT位置){
        返回的位置;
    }    / *
     *公共文件[] setImageList(字符串路径){
     *
     * //this.path =路径; //this.imageList =图像列表; //文件imagesDir =
     *新的文件(路径); //图像列表= imagesDir.listFiles();
     *
     *文件imagesDir =新的文件(路径);图像列表= imagesDir.listFiles();
     *为(文件映像:图像列表){试位=
     * BitmapFactory.de codeStream(image.toURL()的OpenStream()); //使用位图
     *和回收之后LoadedImage LM =新LoadedImage(位图);
     * this.addPhoto(LM); bitmap.recycle();
     *
     *}赶上(IOException异常五){e.printStackTrace(); }返回图像列表;
     *
     *}
     * /    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        最后ImageView的ImageView的;
        如果(convertView == NULL){
            ImageView的=新ImageView的(mContext);
        }其他{
            ImageView的=(ImageView的)convertView;
        }
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setPadding(2,2,2,2);
        // imageView.setImageBitmap(photos.get(位置).getBitmap());
        尝试{
            ImageView的
                    .setImageBitmap(BitmapFactory
                            由Matchi.com提供回到codeStream(图像列表[位置] .toURL()
                                    .openStream()));
        }赶上(MalformedURLException的E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        返回ImageView的;
    }
}/ * ------------------------------------------------ ------------------------- * ///的AsyncTask来获得图像类LoadImagesFromSDCard扩展的AsyncTask<对象,LoadedImage,对象> {    @覆盖
    保护对象doInBackground(对象...为arg0){
        //从背景SD卡装入图像
        //显示屏幕上的每个图像        文件imagesDir =新的文件(路径);
        图像列表= imagesDir.listFiles();        对于(文件映像:图像列表)            尝试{                如果(位图!= NULL){
                    bitmap.recycle();
                    位= NULL;
                }
                位= BitmapFactory.de codeStream(image.toURL()
                        .openStream());
                Log.e(TAG,霸占图像+ image.getName());
                //然后使用位图后回收                LoadedImage LM =新LoadedImage(位图);
                // addImage(LM);
                // imageAdapter.addPhoto(LM);
                // imageAdapter.setImageList(路径);
                // imageAdapter.addPhoto(LM);
                // imageAdapter.setImageList(路径);
                // bitmap.recycle();
                // addImage(LM);
                // imageAdapter.addPhoto(LM);
                Log.e(TAG添加图片+ lm.toString());                // imageAdapter.setImageList(路径);
                addImage(LM);                // bitmap.recycle();                // bitmap.recycle();            }赶上(例外五){
                e.printStackTrace();
            }        返回null;
    }


解决方案

下面是BTW解决方案,对不起花了这么长的时间我不知道其他人都在等待答案。抱歉。有关code如下。

这是AsyncTask的,将查询设备的MediaStore和检索所有照片。注意,这是检索缩略图,而不是全尺寸的图像,并且更具体地它的MICRO_KIND。还有一个Thumbnail.MINI_KIND以及

  / * ----------------------------任务异步加载PHOTOS-- -------------------------------------------------- ---- * /公共类LoadPhotos扩展的AsyncTask<对象,对象,对象> {    @覆盖
    保护对象doInBackground(对象... PARAMS){
        尝试{
            最终的String [] =列{} MediaStore.Images.Media._ID;
            最后弦乐ORDERBY = MediaStore.Images.Media._ID;            光标imagecursor = managedQuery(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,列,
                    NULL,NULL,排序依据);            INT image_column_index = imagecursor
                    .getColumnIndex(MediaStore.Images.Media._ID);            AllPhotosActivity.count = imagecursor.getCount();
            AllPhotosActivity.windows =新的位图[AllPhotosActivity.count]            的for(int i = 0; I< AllPhotosActivity.count;我++){
                imagecursor.moveToPosition(ⅰ);
                // I =指数;
                INT ID = imagecursor.getInt(image_column_index);
                窗口[I] = MediaStore.Images.Thumbnails.getThumbnail(
                        getApplicationContext()。getContentResolver(),身份证,
                        MediaStore.Images.Thumbnails.MICRO_KIND,NULL);
            }            imagecursor.close();
        }赶上(例外五){
            e.printStackTrace();
            Log.d(AllPhotosActivity
                    而获取设备上的所有照片时出错。);
        }
        返回null;    }    @覆盖
    保护无效onPostExecute(对象结果){
        // TODO自动生成方法存根
        super.onPostExecute(结果);
        处理器mHandler =新的处理程序();        mHandler.post(新的Runnable(){            公共无效的run(){                pd.dismiss();
                // imageAdapter.notifyDataSetChanged();
                // sdcardImages.setAdapter(imageAdapter);            }        });        // pd.dismiss();
        imagegrid.setAdapter(imageAdapter);
        // pd.dismiss();    }    @覆盖
    保护无效onProgressUpdate(对象...值){
        // TODO自动生成方法存根
        super.onProgressUpdate(值);
    }}

下面是为GridView那将缩略图绑定到GridView适配器。我的问题只是在我ImageAdapter的getView方法,注意我是从位图数组我叫窗口不同的索引设置我的ImageView的资源。

 公共类ImageAdapter延伸BaseAdapter {
    私人语境mContext;    公共ImageAdapter(上下文C){
        mContext = C;
    }    公共对象的getItem(INT位置){
        // TODO自动生成方法存根
        返回的位置;
    }    众长getItemId(INT位置){
        // TODO自动生成方法存根
        返回的位置;
    }    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        ImageView的I =(ImageView的)convertView;
        如果(我!= NULL){
            i.setImageBitmap(窗口[位置]);
        }其他{
            I =新ImageView的(mContext.getApplicationContext());
            // i.setPadding(3,3,3,3);
            // i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setAdjustViewBounds(真);
            // i.setMaxHeight(200);
            // i.setMaxWidth(200);
            i.setPadding(3,3,3,3);
            i.setLayoutParams(新GridView.LayoutParams(92,92));
            i.setImageBitmap(窗口[位置]);        }
        返回我;
    }    公众诠释的getCount(){
        // TODO自动生成方法存根
        返回计数;
    }
}

I've created an app that allows the user to create a photo album(Folder) on External Storage. Now I am trying to retrieve the images from said directory and display them inside a GridView. I'm using an AsyncTask to iterate through the directory of files using listFiles() and then creating a bitmap once I grab each image, recycle it, and then use it again. My problem is that nothing is showing up in my GridView. I've set up a few Log breaks and LogCat shows me that the iteration does happen and the images are retrieved. This leads me to think that I made a mistake somewhere in my Adapter class that binds the bitmaps to the Grid, possibly in getView? Or maybe I'm wrong. Any help on what I'm doing wrong? I tried to comment the code as much as possible and I've left out the unecessary pieces. Thanks

public class AlbumGridView extends Activity implements OnItemClickListener {

private GridView sdcardImages;
private ImageAdapter imageAdapter;

private Display display;

private Bitmap bitmap;
private Bitmap b;

File[] imageList;
private static final String TAG = "AlbumGridView";
String path;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.album_view);

    //display = 
    //((Object) getSystemService(Context.WINDOW_SERVICE))).getDefaultDisplay();

    path = getIntent().getStringExtra("key");
    Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
    setupViews();
    setProgressBarIndeterminateVisibility(true);
    loadImages();



}

protected void onDestroy() {
    super.onDestroy();
    final GridView grid = sdcardImages;
    final int count = grid.getCount();
    ImageView v = null;
    for (int i = 0; i < count; i++) {
        v = (ImageView) grid.getChildAt(i);
        ((BitmapDrawable) v.getDrawable()).setCallback(null);
    }
}

// Set up the GridView

private void setupViews() {
    sdcardImages = (GridView) findViewById(R.id.gvAlbumView);
    // sdcardImages.setNumColumns(display.getWidth()/95);
    sdcardImages.setClipToPadding(false);
    sdcardImages.setOnItemClickListener(AlbumGridView.this);
    imageAdapter = new ImageAdapter(getApplicationContext());
    // imageAdapter.setImageList(path);
    sdcardImages.setAdapter(imageAdapter);
}

private void addImage(LoadedImage... value) {
    for (LoadedImage image : value) {
        imageAdapter.addPhoto(image);
        imageAdapter.notifyDataSetChanged();
    }
}

// Save Bitmap images to a list and return that list
@Override
public Object onRetainNonConfigurationInstance() {
    final GridView grid = sdcardImages;
    final int count = grid.getChildCount();
    final LoadedImage[] list = new LoadedImage[count];

    for (int i = 0; i < count; i++) {
        final ImageView v = (ImageView) grid.getChildAt(i);
        list[i] = new LoadedImage(
                ((BitmapDrawable) v.getDrawable()).getBitmap());
    }

    return list;
}

private void loadImages() {
    // TODO Auto-generated method stub
    final Object data = getLastNonConfigurationInstance();
    if (data == null) {
        new LoadImagesFromSDCard().execute();
    } else {
        final LoadedImage[] photos = (LoadedImage[]) data;
        if (photos.length == 0) {
            new LoadImagesFromSDCard().execute();
        }
        for (LoadedImage photo : photos) {
            addImage(photo);
        }
    }
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

}

/-------------------------------------------------------------------------------------/

//Adapter for the GridView

public class ImageAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

    private String path;
    private Bitmap bitmap;

    public ImageAdapter(Context context) {
        mContext = context;
    }

    public void addPhoto(LoadedImage photo) {
        photos.add(photo);
    }

    public int getCount() {
        return photos.size();
    }

    public Object getItem(int position) {
        return photos.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    /*
     * public File[] setImageList(String path) {
     * 
     * //this.path = path; //this.imageList = imageList; //File imagesDir =
     * new File(path); //imageList = imagesDir.listFiles();
     * 
     * File imagesDir = new File(path); imageList = imagesDir.listFiles();
     * for (File image : imageList) try { bitmap =
     * BitmapFactory.decodeStream(image.toURL().openStream()); //use bitmap
     * and recycle afterwards LoadedImage lm = new LoadedImage(bitmap);
     * this.addPhoto(lm); bitmap.recycle();
     * 
     * } catch (IOException e) { e.printStackTrace(); } return imageList;
     * 
     * }
     */

    public View getView(int position, View convertView, ViewGroup parent) {
        final ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(mContext);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setPadding(2, 2, 2, 2);
        // imageView.setImageBitmap(photos.get(position).getBitmap());
        try {
            imageView
                    .setImageBitmap(BitmapFactory
                            .decodeStream(imageList[position].toURL()
                                    .openStream()));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return imageView;
    }
}

/*-------------------------------------------------------------------------*/

//AsyncTask to get the images

class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {

    @Override
    protected Object doInBackground(Object... arg0) {
        // Load images from SD card in Background
        // Display each image on the screen

        File imagesDir = new File(path);
        imageList = imagesDir.listFiles();

        for (File image : imageList)

            try {

                if (bitmap != null) {
                    bitmap.recycle();
                    bitmap = null;
                }
                bitmap = BitmapFactory.decodeStream(image.toURL()
                        .openStream());
                Log.e(TAG, "Grabbed Image " + image.getName());
                // use bitmap then recycle after

                LoadedImage lm = new LoadedImage(bitmap);
                // addImage(lm);
                // imageAdapter.addPhoto(lm);
                // imageAdapter.setImageList(path);
                // imageAdapter.addPhoto(lm);
                // imageAdapter.setImageList(path);
                // bitmap.recycle();
                // addImage(lm);
                // imageAdapter.addPhoto(lm);
                Log.e(TAG, "Added Image " + lm.toString());

                // imageAdapter.setImageList(path);
                addImage(lm);

                // bitmap.recycle();

                // bitmap.recycle();

            } catch (Exception e) {
                e.printStackTrace();
            }

        return null;
    }

解决方案

Here's the solution btw, sorry It took so long to I wasn't aware that others were waiting for the answer. Sorry. The relevant code is below.

This is AsyncTask that will query the device's MediaStore and retrieve all the photos. Note that this is retrieving the thumbnails and not the full size images, and more specifically it's the MICRO_KIND. There is also a Thumbnail.MINI_KIND as well.

/*----------------------------ASYNC TASK TO LOAD THE     PHOTOS--------------------------------------------------------*/

public class LoadPhotos extends AsyncTask<Object, Object, Object> {

    @Override
    protected Object doInBackground(Object... params) {
        try {
            final String[] columns = { MediaStore.Images.Media._ID };
            final String orderBy = MediaStore.Images.Media._ID;

            Cursor imagecursor = managedQuery(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                    null, null, orderBy);

            int image_column_index = imagecursor
                    .getColumnIndex(MediaStore.Images.Media._ID);

            AllPhotosActivity.count = imagecursor.getCount();
            AllPhotosActivity.windows = new Bitmap[AllPhotosActivity.count];

            for (int i = 0; i < AllPhotosActivity.count; i++) {
                imagecursor.moveToPosition(i);
                // i = index;
                int id = imagecursor.getInt(image_column_index);
                windows[i] = MediaStore.Images.Thumbnails.getThumbnail(
                        getApplicationContext().getContentResolver(), id,
                        MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            imagecursor.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("AllPhotosActivity",
                    "Error occured while fetching all photos on device.");
        }
        return null;

    }

    @Override
    protected void onPostExecute(Object result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Handler mHandler = new Handler();

        mHandler.post(new Runnable() {

            public void run() {

                pd.dismiss();
                // imageAdapter.notifyDataSetChanged();
                // sdcardImages.setAdapter(imageAdapter);

            }

        });

        // pd.dismiss();
        imagegrid.setAdapter(imageAdapter);
        // pd.dismiss();

    }

    @Override
    protected void onProgressUpdate(Object... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

}

Here's the adapter for the GridView that's going to bind your thumbnails to the gridview. My issue was simply in the getView method of my ImageAdapter, notice I'm setting my ImageView resources from different indexes of an array of Bitmaps I called windows.

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = (ImageView) convertView;
        if (i != null) {
            i.setImageBitmap(windows[position]);
        } else {
            i = new ImageView(mContext.getApplicationContext());
            // i.setPadding(3, 3, 3, 3);
            // i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setAdjustViewBounds(true);
            // i.setMaxHeight(200);
            // i.setMaxWidth(200);
            i.setPadding(3, 3, 3, 3);
            i.setLayoutParams(new GridView.LayoutParams(92, 92));
            i.setImageBitmap(windows[position]);

        }
        return i;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return count;
    }
}

这篇关于从GridView的SD卡目录加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆