13

As i am working on displaying images saved in sdcard folder, I found the following link.

Displaying images in gridview from SDCard.

I am using the following code to get images from specified folder in sdcard,but here i am getting 0 count.

MyCode.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();

But here as per the following link all the images saved in SD card are displaying. But here i want to display images which are saved in particular folder, as like i created "My_images" folder & saved images in that folder. I want to display images from that folder & need to display in gridview as per link.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
user2384424
  • 187
  • 1
  • 3
  • 13
  • I think that you should narrow downyour question and be more specific. better to ask about how to read files or how to display file but search first, i bet everything you need is already out there. maybe see https://stackoverflow.com/q/8646984/1338846 – Sampo Sarrala - codidact.org May 28 '18 at 22:23

4 Answers4

34

You can get the path of files from a particualr folder as below

Once you get the path of files you ca display the images in 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());

            }
        }
}

Remember to add permissionin manifest file

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

By having write permission will have read permission by default.

Example

main.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;


}
    }

Snap shot

enter image description here

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Thanks for the code. But here as per the link 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, columns, null,null, orderBy); here by using this line "MediaStore.Images.Media.EXTERNAL_CONTENT_URI" getting all images saved in sdcard. Is there any possibility of modifying this line to get images saved in particular folder. – user2384424 May 15 '13 at 05:58
  • @user2384424 generally you get the path of the files froma folder and display the image. the code i posted above get the path of all files under a folder in sdcard. Note: the folder should contain only images or else you need to filter the file paths – Raghunandan May 15 '13 at 06:05
  • @user2384424 you can check this link for filtering .png files.http://stackoverflow.com/questions/15853611/how-can-i-add-sdcard-images-to-coverflow/15853710#15853710. you can use a or operator to match .jpg also string pattern= ".png|.jpg". Modify the above according to your needs. – Raghunandan May 15 '13 at 06:26
  • Got a small prob. As i am executing the code from the link provide the gridview alignment is looking good but if i am replacing with your code alignment is not getting. Can you one help me with this... Images are show above.... – user2384424 May 15 '13 at 06:46
  • modify the xml according to your needs. see the snap shot and the xml above. i only deleted the button no changes from the code in the link. code you layout for your screen size. What you do you mean by alignment problem. post a snap shot and your xml code. – Raghunandan May 15 '13 at 06:47
  • As first time i am using stackoverflow i need to have 10 reputations to post an image... sorry.. i dont have any reputations to post images.. – user2384424 May 15 '13 at 06:50
  • post your xml code atleast – Raghunandan May 15 '13 at 06:52
  • i copied your xml code only... – user2384424 May 15 '13 at 06:57
  • what is the problem in alignment then. as you can see the snap shot it works fine on my samsung galxy s3. with out posting the xml code i can't help you any further – Raghunandan May 15 '13 at 07:06
  • ur snap shot is not visible here.. getting like image error... – user2384424 May 15 '13 at 07:35
  • as soon as after getting 10 reputations i will send you the screen shots.. with in couple of minutes... i hope you will help me then... – user2384424 May 15 '13 at 07:36
1

Use Universal Image Loader

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

Give Image url as your sd card image path.

/**
     *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) {
        }
    }
Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
OMAK
  • 1,031
  • 9
  • 25
  • are you sure it will load images from sd card? Have you tried it? – Chintan Rathod May 15 '13 at 05:54
  • Ya sure its working fine – OMAK May 15 '13 at 05:57
  • can you post some code here so that I can also use that. Because I only try to load images from internet only. I tried to load from sdcard but failed. It will help me if it works fine. – Chintan Rathod May 15 '13 at 05:58
  • will try this... obvious its a huge library which handles images very efficiently in memory. I used to download it from internet but it can also show images from specific path in device, it will solve my problem of memory overflow. :) – Chintan Rathod May 15 '13 at 06:36
  • 1
    @ChintanRathod you can dispaly images from sdcard. get the path of files . store it in arraylist. pass the arraylist to the constructor of the adapter class. in getview imageLoader.displayImage(data.get(position).toString(), image,options);// data is the arraylist here, image is the imageview, options is the dispaly options of UIL – Raghunandan May 15 '13 at 07:11
1

it is not possible to display particular folder images using the mediastore method. because every images stored in the mediastore has different unique id to identify it.

but you can do by create your own method to identify what are the images in the particular folder and then get the create thumbnail images.

Hideme Sri
  • 193
  • 9
  • do you have any examples, rough sketch of how to do that, i am trying to do that here [link](http://stackoverflow.com/questions/38324578/how-to-load-the-thumbnails-for-the-pictures-stored-in-particular-folder-in-exter), can you please help ! – Umair Jul 12 '16 at 10:53
-1

Here I am posting code to retrieve file names from "particular directory". You need to do some other task your self.

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

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

String files[] = imgDir.list();

Now check whether "files[]" is null or not.

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

You have list of files with their path, fetch out bitmap from them and display in grid.

NoTe:

To print full path use following code.

imgDir.getAbsolutePath() + File.separator + files[i]);
Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93