13

当我正在显示保存在 sdcard 文件夹中的图像时,我找到了以下链接。

从 SDCard 在 gridview 中显示图像

我正在使用以下代码从 sdcard 中的指定文件夹获取图像,但在这里我得到 0 个计数。

我的代码.java

    String[] projection = {MediaStore.Images.Media._ID};
    
    final String[] columns = { MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            projection, 
            MediaStore.Images.Media.DATA + " like ? ",
            new String[] {"/my_images"},  
            null);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    this.thumbnailsselection = new boolean[this.count];

    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }
    imageAdapter = new ImageAdapter();
    secure_gallery_grid.setAdapter(imageAdapter);
    imagecursor.close();

但这里按照以下链接显示所有保存在 SD 卡中的图像。但在这里我想显示保存在特定文件夹中的图像,就像我创建“My_images”文件夹并在该文件夹中保存图像一样。我想显示该文件夹中的图像并需要根据链接在 gridview 中显示。

4

4 回答 4

34

您可以从以下特定文件夹中获取文件的路径

获得文件路径后,您可以在 gridview 中显示图像

ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;

public void getFromSdcard()
{
    File file= new File(android.os.Environment.getExternalStorageDirectory(),"TMyFolder");

        if (file.isDirectory())
        {
            listFile = file.listFiles();


            for (int i = 0; i < listFile.length; i++)
            {

                f.add(listFile[i].getAbsolutePath());

            }
        }
}

记得在清单文件中添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

默认情况下,拥有写权限将拥有读权限。

例子

主要的.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">

<GridView
    android:id="@+id/PhoneImageGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:gravity="center"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp" />

   </RelativeLayout>

gelleryitem.xml

   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_centerInParent="true" />
<CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" />
    </RelativeLayout>

AndroidCustomGalleryActivity.java

   public class AndroidCustomGalleryActivity extends Activity {
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getFromSdcard();
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);


}
public void getFromSdcard()
{
    File file= new File(android.os.Environment.getExternalStorageDirectory(),"MapleBear");

        if (file.isDirectory())
        {
            listFile = file.listFiles();


            for (int i = 0; i < listFile.length; i++)
            {

                f.add(listFile[i].getAbsolutePath());

            }
        }
}

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(
                    R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);

            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }


        Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
        holder.imageview.setImageBitmap(myBitmap);
        return convertView;
    }
}
class ViewHolder {
    ImageView imageview;


}
    }

快照

在此处输入图像描述

于 2013-05-15T05:51:14.893 回答
1

使用通用图像加载器

https://github.com/nostra13/Android-Universal-Image-Loader.git

将 Image url 作为您的 sd 卡图像路径。

/**
     *adapter class for view pager
     *
     */
    private class ImagePagerAdapter extends PagerAdapter {
        LayoutInflater inflater;
        public ImagePagerAdapter() {
            inflater=getActivity().getLayoutInflater();
        }

        @Override
        public int getCount() {
            return viewPagerList.size();
        }
        @Override
        public void finishUpdate(View container) {
        }
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View imageLayout = inflater.inflate(R.layout.item_pager_image, container, false);
            ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
            final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
            String loadURL=null;
            if(connectivityManager.hasDataConnectivity()){
                loadURL=viewPagerList.get(position).getModelImageUrl();
            }
            else {
                String fileName=viewPagerList.get(position).getModelImageUrl();
                fileName = fileName.replace(':', '/');
                fileName = fileName.replace('/', '_');
                loadURL="file://"+Environment.getExternalStorageDirectory()+"/"+folder+"/"+fileName;
            }
            BaseActivity.imageLoader.displayImage(loadURL, imageView, options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    spinner.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    String message = null;
                    switch (failReason) {
                    case IO_ERROR:
                        message = "Input/Output error";
                        break;
                    case OUT_OF_MEMORY:
                        message = "Out Of Memory error";
                        break;
                    case NETWORK_DENIED:
                        message = "Downloads are denied";
                        break;
                    case UNSUPPORTED_URI_SCHEME:
                        message = "Unsupported URI scheme";
                        break;
                    case UNKNOWN:
                        message = "Unknown error";
                        break;
                    }
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

                    spinner.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingComplete(final String imageUri, View view, final Bitmap loadedImage) {
                    spinner.setVisibility(View.GONE);
                    Logger.show(Log.INFO, "@@@@@@@", imageUri);
                    String uniqueUrlName = imageUri.replace(':', '/');
                    uniqueUrlName = uniqueUrlName.replace('/', '_');

                    File file = new File(Environment.getExternalStorageDirectory()
                            .toString()
                            + "/"
                            + folder
                            + "/"
                            + uniqueUrlName);
                    if(!file.exists()){
                        new Thread(new Runnable() {

                            public void run() {
                                String imageUrlString="file://"+GetModels.getModelURL(imageUri,folder,loadedImage,context);
                                Logger.show(Log.INFO, context.getClass().getName(), "image loaded my folfer"+ imageUrlString);
                            }
                        }).start();
                    }
                    Logger.show(Log.INFO, context.getClass().getName(), "image loaded loader "+ StorageUtils.getCacheDirectory(context));

                }  
            });

            imageView.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {

                    Bundle b=new Bundle();
                    b.putString("ProductName", viewPagerList.get(pos).getModelName());
                    b.putString("ProductPrice", viewPagerList.get(pos).getModelPrice());
                    b.putString("ProductUrl",viewPagerList.get(pos).getModelLink() );
                    String loadURL=null;
                    if(connectivityManager.hasDataConnectivity()){
                        loadURL=viewPagerList.get(pos).getModelImageUrl();
                    }
                    else {
                        String fileName=viewPagerList.get(pos).getModelImageUrl();
                        fileName = fileName.replace(':', '/');
                        fileName = fileName.replace('/', '_');
                        loadURL="file://"+Environment.getExternalStorageDirectory()+"/"
                                +folder+"/"+fileName;
                    }
                    b.putString("ProductImage", loadURL);
                    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager
                            .beginTransaction();
                    fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left,R.anim.slide_in_left, R.anim.slide_out_right);
                    ProductOverview commentFragment = new ProductOverview();
                    commentFragment.setArguments(b);
                    fragmentTransaction.replace(R.id.product_container, commentFragment);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

                }
            });
            ((ViewPager) container).addView(imageLayout, 0);
            return imageLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }
        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }
于 2013-05-15T05:53:20.913 回答
1

使用 mediastore 方法无法显示特定的文件夹图像。因为存储在 mediastore 中的每个图像都有不同的唯一 ID 来识别它。

但是您可以通过创建自己的方法来识别特定文件夹中的图像,然后获取创建缩略图图像。

于 2013-05-15T06:29:12.910 回答
-1

在这里,我发布代码以从“特定目录”中检索文件名。你需要自己做一些其他的任务。

File imgDir = new File(Environment.getExternalStorageDirectory()+ File.separator + "directory");

if (!imgDir.exists())
    imgDir.mkdir();

String files[] = imgDir.list();

现在检查“files[]”是否为空。

if (files == null)
    // no files
else{
    count = files.length;
    //do something
}

您有文件列表及其路径,从中获取位图并显示在网格中。

笔记:

要打印完整路径,请使用以下代码。

imgDir.getAbsolutePath() + File.separator + files[i]);
于 2013-05-15T05:52:04.663 回答