Try to get all image from sdcard to show in gallery view - android

I'm trying to get all of the image that stored in sdcard to show in a gallery view by the code below. But when I use ImageFilter nothing shows up, just a blank screen without any error. Any suggestion?
public class Galmix extends Activity {
/** Called when the activity is first created. */
private Gallery g;
private ImageView imv;
private Uri[] mUrls;
String[] mFiles=null;
class ImageFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".JPG"));
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File images = new File("/sdcard/");
File[] imagelist = images.listFiles(new ImageFilter());
// File[] imagelist = images.listFiles();
// File[] imagelist = images.listFiles(new FilenameFilter(){
// #Override
// public boolean accept(File dir, String name){
// return ((name.endsWith(".JPG")));
// }
// });
// File images = new File(Environment.getExternalStorageDirectory().toString());
// images.mkdirs();
// File[] imagelist = images.listFiles();
mFiles = new String[imagelist.length];
for(int i= 0 ; i< imagelist.length; i++){
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for(int i=0; i < mFiles.length; i++){
mUrls[i] = Uri.parse(mFiles[i]);
}
// i = (ImageView)findViewById(R.id.ImageView01);
// i.setImageResource(mImageIds[0]);
g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setFadingEdgeLength(40);
// g.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// imv.setImageURI(mUrls[position]);
// }
// });
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mUrls.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageURI(mUrls[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}

I would suggest that u make use of MediaStore . Also check for permissions in ur manifest file

Did you check that File images = new File("/sdcard/"); is returning the actual sdcard root folder? Try using File images = Environment.getExternalStorageDirectory(); instead.
Also, add a line Log.d ("Galmix", mFiles[i]); after mFiles[i] = imagelist[i].getAbsolutePath(); so you know if you are getting the file list or not.
Also, try
return (name.toUpperCase().endsWith(".JPG"));

This might be helpful:
Drawable mImage;
// you can use loop over here
mImage = Drawable.createFromPath("pathName");
//create one Imageview & set its resource mImage

Related

Gridview of image from sdcard directory

I want show image in gridview from sdcard directory.i use this code.But when i load image by type : bitmap.getView in gridview adapter need Integer[] array.how i can fix it?
public class LoadPic extends Activity {
Integer[] imageIDs = {
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user
};
int numberOfImages=0;
Bitmap[] m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_pic);
Intent gett = getIntent();
String _area = gett.getStringExtra("area");
String _domain = gett.getStringExtra("domain");
String _block = gett.getStringExtra("block");
String _melk = gett.getStringExtra("melk");
String _build = gett.getStringExtra("build");
String _apar = gett.getStringExtra("apar");
String _senfi = gett.getStringExtra("senfi");
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File img = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
if(img.exists())
{
Bitmap bit = BitmapFactory.decodeFile(img.getAbsolutePath());
}
}
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
//---returns the number of images---
public int getCount() {
return numberOfImages;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(7, 7, 7, 7);
} else {
imageView = (ImageView) convertView;
}
/**/
imageView.setImageResource(imageIDs[position]);
/**/
return imageView;
}
}
}
please help how i can use image in this class(adapter).
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/
replace
public int getCount() {
return numberOfImages;
}
with
public int getCount() {
return imageIDs.length();
}
First properly explain what do want to set Drawable or Bitmap?
If Bitmap then this is how you should set bitmap(make a list of bitmaps and then):
imageView.setImageBitmap(bitmaps[position]);
if Drawable then(make list of drawable id's)
imageview.setImageResource(drawables[position]);
This is how make bitmap list:
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File f = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
if(bmp!=null){
bitmaps.add(bmp);
}
}

loading images from folder into gallery view in android

i am not able to access my folder Diary in which images are saved,
i want to display all the images from this folder into gallery,
please give some suggestion how to do it
//get the gallery view---------------------------------------------------------------------
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this, SDCard()));
//displaying first image on image view
Bitmap bm = BitmapFactory.decodeFile( ((List<String>) tFileList).get(0).toString());
picView.setImageBitmap(bm);
msg="first image of gallry";
showToastMessage(msg);
g.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Bitmap bm = BitmapFactory.decodeFile( ((List<String>) tFileList).get(position).toString());
picView.setImageBitmap(bm);
}
});
}
private List<String> SDCard()
{
tFileList = new ArrayList<String>();
try
{
File dir = Environment.getExternalStorageDirectory();
File f = new File( dir, "/Diary/");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
tFileList.add(file.getPath());
}
}
catch(Exception e)
{
e.printStackTrace();
msg="Folder Not Found";
showToastMessage(msg);
}
return tFileList;
}
public class ImageAdapter extends BaseAdapter
{
int mGalleryItemBackground;
private Context mContext;
private List<String> FileList;
public ImageAdapter(Context c, List<String> fList)
{
mContext = c;
FileList = fList;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground,0);
a.recycle();
}
public int getCount()
{
return FileList.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return (position);
}
public View getView(int position, View convertView,ViewGroup parent)
{
ImageView i = new ImageView(mContext);
Bitmap bm = BitmapFactory.decodeFile(
FileList.get(position).toString());
i.setImageBitmap(bm);
i.setLayoutParams(new Gallery.LayoutParams(70,50));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
what to do in this case,where i am going wrong

Unable to display the image selected in gallery view

I have an issue with showing the preview of image selected in the gallery view. I have a gallery of images from sd card, on clicking an image its preview should be shown below the gallery view(Not in seperate activity via intent). I am able to show the gallery with images but nothing is happening on clicking image.
public class NewActivity extends Activity {
GalleryBaseAdapter myGalleryBaseAdapter;
Gallery myPhotoGallery;
int[] mFiles = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPhotoGallery = (Gallery)findViewById(R.id.photogallery);
myGalleryBaseAdapter = new GalleryBaseAdapter(this);
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = ExternalStorageDirectoryPath;
String files;
File folder = new File (path);
final File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System .out.println(files);
}
}
for (File file : listOfFiles) {
myGalleryBaseAdapter.add(file.getPath());
}
myPhotoGallery.setAdapter(myGalleryBaseAdapter);
myPhotoGallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
mFiles = new int[listOfFiles.length];
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap bitmapImage = BitmapFactory.decodeFile("/sdcard/" + mFiles[position]);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setImageBitmap(bitmapImage);
}
});
}
public class GalleryBaseAdapter extends BaseAdapter {
ArrayList<String> GalleryFileList;
Context context;
GalleryBaseAdapter(Context cont){
context = cont;
GalleryFileList = new ArrayList<String>();
}
#Override
public int getCount() {
return GalleryFileList.size();
}
#Override
public Object getItem(int position) {
return GalleryFileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm = BitmapFactory.decodeFile(GalleryFileList.get(position));
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new Gallery.LayoutParams(150, 150));
layout.setGravity(Gravity.CENTER);
ImageView imageView = new ImageView(context);
imageView.setLayoutParams(new Gallery.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bm);
layout.addView(imageView);
return layout;
}
public void add(String newitem){
GalleryFileList.add(newitem);
}
}
}
Can anybody please tell me what is the mistake in my code. Thanks in advance.
Wait but.... your mFiles variable in onItemClick is an array of int empty !?! You are trying to decode a path which is a concatenation between "/sdcard" and a mFiles'row, but... where are you populating that array ? I think you have to specify file path like "listOfFiles[position].getPath()"

Adding Bitmaps dynamically to gridview in android

I am trying to add bitmap images in gridview but continuously getting exceptions. when i try to do this in layouts it works fine. I am unable to get it. Here is the code what i am doing is:
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv=(GridView)this.findViewById(R.id.gv);
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
ImageView iv= new ImageView(this);
// iv.setId(i);
Bitmap bm=Bitmap.createBitmap(src,j*(src.getWidth()/2),j*(src.getHeight()/3),src.getWidth()/3,src.getHeight()/3);
iv.setImageBitmap(bm);
gv.addView(iv);
}
}
}
Kindly Any help is welcome :))
for adding data in Gridview, you have to set adapter
gridview.setAdapter(adapter);
see example http://developer.android.com/guide/tutorials/views/hello-gridview.html
Here is an idea. You can create a ImageAdapter and add a SetImages function. Then you add your ImageAdapter to the GridView, prepare the images and set the through the ImageAdapter.
For sample:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
GridView gridview=(GridView)this.findViewById(R.id.gridView);
Integer[] mThumbIds = {
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo
};
ImageAdapter myAdapter = new ImageAdapter(this);
myAdapter.SetImages(mThumbIds);
gridview.setAdapter(myAdapter);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] pics;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return pics.length;
}
public Object getItem(int position) {return null;}
public long getItemId(int position) {return 0;}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
//You can set some params here
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(pics[position]);
return imageView;
}
public void SetImages(Integer[] id){
pics = id.clone();
}
}
I don't know if this is the right approach but it works :D
public class ImageAdapter extends BaseAdapter
{
private Context context;
private List<String> path_images = new ArrayList<String>();
public ImageAdapter( Context context, List<String> path_images ){ this.context = context; this.path_images = path_images; }
#Override public int getCount ( ){ return images.size(); }
#Override public Object getItem (int i){ return BitmapFactory.decodeFile( path_images.get(i) ); }
#Override public long getItemId(int i){ return 0; }
#Override public View getView(int i, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView( context );
imageView.setImageBitmap( BitmapFactory.decodeFile( paht_images.get(i) ) );
imageView.setScaleType( ImageView.ScaleType.CENTER_CROP );
imageView.setLayoutParams(new GridView.LayoutParams( 145, 145 ));
return imageView;
}
}
private void present_all_images()
{
final String FS = File.separator;
final String directory = Environment.getExternalStorageDirectory().toString() + FS + "directory";
List<String> path_images = new ArrayList<String>();
path_images.add( directory + FS + "image01.png" );
path_images.add( directory + FS + "image02.png" );
path_images.add( directory + FS + "image03.png" );
grid_data = (GridView)findViewById(R.id.gallery_grid_data);
grid_data.setAdapter( new ImageAdapter( this, path_images ) );
grid_data.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
}});
}

NullPointerException in Gallery

I am trying make a gallery which contains all images in the assets folder, but I keep getting a NullPointerException error,can anyone tell me what's wrong?
public class MyGallery extends Activity {
private GridView gv;
private SlidingDrawer sd;
private ImageView im;
private int[] icons={R.drawable.download,R.drawable.setwallpaper,
R.drawable.list,R.drawable.other};
private String[] items={"下载到本地","设置为桌面","列表查看","支持本APP"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gv = (GridView)findViewById(R.id.grid);
sd = (SlidingDrawer)findViewById(R.id.drawer);
im=(ImageView)findViewById(R.id.openicon);
/* 使用告定义的MyGridViewAdapter设置GridView里面的item内容 */
MyGridViewAdapter adapter=new MyGridViewAdapter(this,items,icons);
gv.setAdapter(adapter);
/* 设定SlidingDrawer被打开的事件处理 */
sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener()
{
#Override
public void onDrawerOpened()
{
im.setImageResource(R.drawable.closedrawer);
}
});
/* 设置SlidingDrawer被关闭的事件处理 */
sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener()
{
#Override
public void onDrawerClosed()
{
im.setImageResource(R.drawable.showdrawer);
}
});
Log.d("tag", "抽屉初始化成功");
Gallery g = (Gallery) findViewById(R.id.mygallery);
/*新增几ImageAdapter并设定给Gallery对象*/
g.setAdapter(new ImageAdapter(this,getImage()));
/*设定一个itemclickListener事件*/
g.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
}
});
Log.d("tag", "图片初始化成功");
}
private List<String> getImage()
{
/* 设定目前所在路径 */
List<String> it=new ArrayList<String>();
File f=new File("file:///android_asset/");
File[] files=f.listFiles();
Log.d("tag", "读取asset资源");
/* 将所有文件存入ArrayList中 */
for(int i=0;i<files.length;i++)
{
File file=files[i];
if(getImageFile(file.getPath()))
it.add(file.getPath());
}
return it;
}
private boolean getImageFile(String fName)
{
boolean re;
/* 取得扩展名 */
String end=fName.substring(fName.lastIndexOf(".")+1,
fName.length()).toLowerCase();
/* 按扩展名的类型决定MimeType */
if(end.equals("jpg")||end.equals("gif")||end.equals("png")
||end.equals("jpeg")||end.equals("bmp"))
{
re=true;
}
else
{
re=false;
}
return re;
}
/*改写BaseAdapter自定义一ImageAdapter class*/
public class ImageAdapter extends BaseAdapter
{
/*声明变量*/
int mGalleryItemBackground;
private Context mContext;
private List<String> lis;
/*ImageAdapter的构造符*/
public ImageAdapter(Context c,List<String> li)
{
mContext = c;
lis=li;
/* 使用res/values/attrs.xml中的<declare-styleable>定义
* 的Gallery属性.*/
TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
/*取得Gallery属性的Index id*/
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
/*让对象的styleable属性能够反复使用*/
a.recycle();
}
/*几定要重写的方法getCount,传回图片数目*/
public int getCount()
{
return lis.size();
}
/*一定要重写的方法getItem,传回position*/
public Object getItem(int position)
{
return position;
}
/*一定要重写的方法getItemId,传并position*/
public long getItemId(int position)
{
return position;
}
/*几定要重写的方法getView,传并几View对象*/
public View getView(int position, View convertView,
ViewGroup parent)
{
/*产生ImageView对象*/
ImageView i = new ImageView(mContext);
/*设定图片给imageView对象*/
Bitmap bm = BitmapFactory.decodeFile(lis.
get(position).toString());
i.setImageBitmap(bm);
/*重新设定图片的宽高*/
i.setScaleType(ImageView.ScaleType.FIT_XY);
/*重新设定Layout的宽高*/
i.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
/*设定Gallery背景图*/
i.setBackgroundResource(mGalleryItemBackground);
/*传回imageView对象*/
return i;
}
}
}
I am really grateful.
Are you trying to load images from assets folder in your project ??? Well, in that case try reading asset files through AssetManager. I think this might help

Categories

Resources