Displaying images from specific folder in sd card in grid view
Sorry for Answering late...
Below I am posting the final solution
public class Album3 extends Activity {
File [] mediaFiles;
File imageDir;
static GridView gridView;
ImageAdapter adapter;
Intent in;
ImageButton btncam;
String name = null;
ArrayList<Bitmap> bmpArray = new ArrayList<Bitmap>();
ArrayList<String> fileName = new ArrayList<String>();
public static final String TAG = "Album3Activity";
public void onCreate(Bundle savedInstanceState)
{
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
super.onCreate(savedInstanceState);
if((imageDir.exists()))
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.grid);
mediaFiles = imageDir.listFiles();
//Log.d("Length of images",""+mediaFiles.length);
for(File file : mediaFiles)
{
bmpArray.add(convertToBitmap(file));
fileName.add(readFileName(file));
//Log.d(TAG + "bmpArray Size", ""+bmpArray.size());
//Log.d(TAG, "call to convertToBitmap");
}//for
adapter = new ImageAdapter(this, bmpArray, fileName);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(adapter);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED
, Uri.parse(Environment.getExternalStorageDirectory().toString()+"/diplomat")));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
in = new Intent(getApplicationContext(), FullScreen.class);
in.putExtra("id", position);
startActivity(in);
}
});
}//if
else
{
setContentView(R.layout.no_media);
}
}//onCreate
public static Bitmap convertToBitmap(File file)
{
URL url = null;
try
{
url = file.toURL();
} catch (MalformedURLException e1)
{
//Log.d(TAG, e1.toString());
}//catch
Bitmap bmp = null;
try
{
bmp = BitmapFactory.decodeStream(url.openStream());
//bmp.recycle();
}catch(Exception e)
{
//Log.d(TAG, "Exception: "+e.toString());
}//catch
return bmp;
}//convertToBitmap
public String readFileName(File file){
String name = file.getName();
return name;
}//readFileName
}//class
how to display images saved in sdcard folder in android
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
loading images from SD card directory in GridView
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;
}
}
show folder content in gridview
after days of working I made a working code
for main layout i used :
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
another layout to display images in image view :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:id="@+id/imageV"
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="@mipmap/ic_launcher" />
here is the main activity :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//getting folder path
var gpath: String = Environment.getExternalStorageDirectory().absolutePath
var spath = "specificFolderName"
var path = File(gpath + File.separator + spath)
//getting all images from that path
var list = imageReader(path)
//get gridview from resources
var gv = findViewById<GridView>(R.id.gridview)
//set gridview adapter from ImageA class
gv.adapter = ImageA(this, list)
}
fun imageReader(root: File): ArrayList<File> {
val fileList: ArrayList<File> = ArrayList()
val listAllFiles = root.listFiles()
if (listAllFiles != null && listAllFiles.size > 0) {
for (currentFile in listAllFiles) {
if (currentFile.name.endsWith(".jpg")) {
fileList.add(currentFile.absoluteFile)
}
}
}
return fileList
}
}
here is adapter class :
class ImageA (c: Context, list: ArrayList<File>) : BaseAdapter() {
var list:ArrayList<File> = list
private var mcontext: Context? = c
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var convertV = LayoutInflater.from(mcontext).inflate(R.layout.single_grid,
parent, false)
var iv = convertV.findViewById<ImageView>(R.id.imageV)
var bitmap = MediaStore.Images.Media.getBitmap(mcontext?.contentResolver,
Uri.fromFile(list[position]))
iv.setImageBitmap(bitmap)
return convertV
}
override fun getItem(position: Int): Any {
return list[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return list.size
}
}
Displaying images from sd card in gridview android
add this to your manifest for listview activity
android:configChanges="orientation|keyboardHidden"
if this not helps then add this piece of code for your image file to sample the bitmap
private Bitmap decodeFile(File f){
FileOutputStream os = null;
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
try {
b = BitmapFactory.decodeStream(fis, null, o2);
} catch (OutOfMemoryError e) {
Log.d("hai","filename"+f);
System.gc();
}
fis.close();
} catch (IOException e) {
}
return b;
}
Load lot many images causes the app to run out of memory and force closes.I think this is what happening to your application.the memory issue is a complex issue android while developing an application.this can be solved by manually clearing the unused bitmaps and by using the garbage collector.
Try using System.gc();
Try recycling the bitmap using
Bitmap.recycle();
Make all the unused bitmap null.
Deallocate all the unused memory.
This all will help you a lot and also go through this link.Use memory analyzer it will help you spot out the Deallocated memory>try this link
Gridview of image from sdcard directory
If you want to show images from sdcard into your grid view use any imageloader library
Universal Image Loader
https://github.com/nostra13/Android-Universal-Image-Loader
then you need to create a string array or a model class instead of that integer array.
Please refer the below tutorials.
http://wptrafficanalyzer.in/blog/loading-thumbnail-images-in-a-gridview-and-opening-original-images-in-alertdialog-using-media-content-providers/
Related Topics
Get Image from the Gallery and Show in Imageview
Rotate an Yuv Byte Array on Android
Get File Path of Image on Android
Android: Volley Http Request Custom Header
How to Change Color of Android Listview Separator Line
Start Activity with an Animation
How to Show a Marker in Maps Launched by Geo Uri Intent
Android Room - Get the Id of New Inserted Row with Auto-Generate
Why Is My Android Emulator Keyboard in Chinese Character Mode
Oauth 2.0 Authorization for Linkedin in Android
How to Change Text Color of Simple List Item
Getting Permission Denial Exception
Pagination Not Work for the Recyclerview Within Nestedscrollview
Firebase:Differencebetween Setpersistenceenabled and Keepsynced
Android Detect Phone Lock Event