androidlistviewandroid-studiocustom-listsandroid-storage

How to set Image local storage path to ListView in Android


enter image description here

My CustomList AdapterCode...

private final Activity context;

private List<String> list;

public CustomListAdapter(Activity context, List<String> list) {
    super(context, R.layout.list_single);

    this.context = context;
    this.list = list;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.list_single, null, true);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);


    if (list != null) {
        for (int i = 0; i < list.size(); i++) {

            File imgFile = new File(list.get(i));

            if (imgFile.exists()) {

                ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                imageView.setImageBitmap(myBitmap);
            }
        }
    }

    return rowView;
}

@Override
public int getCount() {
    return list.size();
}

}

I am receiving a list of imagePath like

d: Array path/storage/sdcard/DCIM/Camera/IMG_20170210_163055.jpg

d: Array path/storage/sdcard/DCIM/Camera/IMG_20170210_163037.jpg

d: Array path/storage/sdcard/DCIM/Camera/IMG_20170217_175804.jpg

d: Array path/storage/sdcard/DCIM/Camera/IMG_20170217_175802.jpg

d: Array path/storage/sdcard/DCIM/Camera/IMG_20170210_163056.jpg

Now I want to show these paths to list view either using a custom adapter or using ArrayAdapter.


Solution

  • Let's say you are sending an ArrayList of paths tp your custom adapter. Now in the getView() method of custom adapter, add the following:

    File imgFile = new  File(myList.get(position));
    
    if(imgFile.exists()){
    
        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    
        ImageView myImage = (ImageView) convertView.findViewById(R.id.imageviewTest);
        //the imageview of your custom list item
    
        myImage.setImageBitmap(myBitmap);
    
    }
    

    Let me know if you need help with custom adapter

    NOTE: If you have a lot of images, I would suggest you to use library like Picasso or Glide

    Do no use a for loop inside getview. GetView is itself called everytime a row is created.

    View rowView = inflater.inflate(R.layout.list_single, null, true);
    TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
    
    
    if (list != null) {
    
            File imgFile = new File(list.get(position));
    
            if (imgFile.exists()) {
    
                ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                imageView.setImageBitmap(myBitmap);
            }
    }
    return rowView;