Adding Bitmaps dynamically to gridview in android - 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)
{
}});
}

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);
}
}

getting image id from ImageAdapter

I'am new to android and I've a project of making a grid view of images and onclick on image it shows it , thats the ImageAdapter class code
public class ImageAdapter extends BaseAdapter{
private static LayoutInflater inflater = null;
private Activity activity;
private String mode = "";
int[] images=null ;
public ImageAdapter(Activity act, String mode , int[] images){
inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = act;
this.mode = mode;
this.images= images ;
}
public ImageView getImage(int pos)
{
ImageView im = (ImageView) getItem(pos);
return im ;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return new Integer(images[position]);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if(mode.equalsIgnoreCase("grid")){
if (view == null) {
view = inflater.inflate(R.layout.each_image1, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
} else if(mode.equalsIgnoreCase("gallery")){
if (view == null) {
view = inflater.inflate(R.layout.each_image_gallery, null);
}
ImageView iv = (ImageView)view.findViewById(R.id.imageView);
iv.setImageResource(images[position]);
}
return view;
}
}
thats my grid activity
public class GridActivity extends Activity {
GridView grid = null;
public static ImageAdapter adapter1 ;
public static ImageAdapter adapter2 ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
adapter1= new ImageAdapter(GridActivity.this, "grid" , Images.images1);
adapter2 = new ImageAdapter(GridActivity.this, "grid" , Images.images2);
Intent i = this.getIntent();
if (i!=null)
{
String unique = i.getExtras().getString("Unique");
if (unique.equals("islam"))
{
Toast.makeText(GridActivity.this, "islam", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter1);
}
if (unique.equals("natural"))
{
Toast.makeText(GridActivity.this, "nat", Toast.LENGTH_LONG).show();
grid = (GridView)findViewById(R.id.gridView1);
grid.setAdapter(adapter2);
}
}
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
}
}
and this is the activity where it supposes to show any clicked on image
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getExtras().getInt("selectedIntex");
// ImageAdapter adapter = new ImageAdapter(imgPrevActivity.this, "image prev", null);
long Id= GridActivity.adapter1.getItemId(pos);
im.setImageResource((int) Id);
}
}
i've tried to get the position of image clicked on from the grid
then getting the Id from the position
and setting the image view to that ID
but it doesnt work !!
thats where the images are put in arrays
public class Images {
public static int[] images1 = {
R.drawable.buds, R.drawable.cherry_34,
R.drawable.clouds_2, R.drawable.coffee_beans_2,
R.drawable.death_valley_sand_dunes
};
public static int[] images2= {
R.drawable.morning_glory_pool,
R.drawable.pink_flowers, R.drawable.sun_flower,
R.drawable.sunrise_3, R.drawable.yellow_rose_3,
};
}
You have to pass your image resource id with intent. The list item id of adapter is useless because you have new Activity on the screen.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long id) {
Intent i = new Intent(GridActivity.this, imgPrevActivity.class);
i.putExtra("selectedIntex", grid.getAdapter().getItem(pos);
startActivity(i);
Toast.makeText(GridActivity.this,"ddd",Toast.LENGTH_LONG).show();
}
});
and change your code in your ImgPreviewActivity:
public class imgPrevActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.each_image1);
ImageView im = (ImageView)findViewById(R.id.imageView);
int pos = getIntent().getIntExtra("selectedIntex", 0);
im.setImageResource(pos);
}
}
I think it should work

Implementing lazy loading for simplecursoradapter

Here I am getting stored picture paths from the database. So that I am showing the images in the gridview with the help of paths. But as it is shown in my code below, I am loading cursoradapter in the asynctask. The problem here is for the first time it is okay that it takes some time until all images are loaded.
But if user adds one more pic to the database, it again takes much time to load all images as I kept the asynctask in onResume() to make the added picture also visible. The same is the case whenever user adds each picture. Can someone suggest me a simple way to get the last added picture visible in the gridview without having to load all the pictures again. Or in the least case can some one help me implementing lazy adapter to the present cursoradapter if that is not possible?
public class ImagesScreen extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.images_screen);
gridView = (GridView)findViewById(R.id.gridView1);
String[] from = new String[] { Reminders.MOM_PATHS };
int[] to = new int[] {};
dbCon = new SQLiteConnectClass(ImagesScreen.this);
imageCursorAdapter = new ImageCursorAdapter(ImagesScreen.this, R.layout.griditem, null, from, to);
gridView.setAdapter(imageCursorAdapter);
}
protected void onResume() {
super.onResume();
new GetImages().execute((Object[]) null);
}
private class GetImages extends AsyncTask<Object, Object, Cursor> {
#Override
protected Cursor doInBackground(Object... params) {
return dbCon.getAllImages();
}
#Override
protected void onPostExecute(Cursor result) {
imageAdapter.changeCursor(result);
}
public void addpictures(View view){
// code for adding picture paths to the database by transferring to another activity.
}
}
CustomAdapter class:
public class ImageCursorAdapter extends SimpleCursorAdapter{
private int layout;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ImageAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
mLayoutInflater=LayoutInflater.from(context);
mContext = context;
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(layout, parent, false);
return v;
}
public void bindView(final View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex("id"));
final String imagepath = c.getString(c.getColumnIndex("paths"));
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
Bitmap imageBitmap = decodeFile(imgFile);
imageview.setImageBitmap(imageBitmap);
}
}
}
use this code
public class Imagegallery extends Activity implements OnItemClickListener,
OnScrollListener, OnTouchListener {
Button btn;
SQLiteDatabase sampleDB = null;
String SAMPLE_DB_NAME = "hic";
int size = 0;
TextView headertext;
Button cartbtn;
ImageView footer1, footer2, footer3, footer4, footer5;
GridView gridView;
boolean larg = false;
String products;
int j = 1;
int ii = 0;
String imagepath[];
String productname[];
int productid[] = new int[1000];
String productids[] = new String[1000];
int integerprodids[] = new int[1000];
final Context context = this;
String filename2[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentspecial);
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "aiwhic/product" + File.separator);
File[] fileName = root.listFiles();
filename2 = new String[fileName.length];
for (int j = 0; j < fileName.length; j++) {
Uri uri = Uri.fromFile(fileName[j]);
filename2[j] = fileName[j].getAbsolutePath();
Log.e("file", filename2[j]);
}
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, filename2, filename2));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
int isf = filename2[position].lastIndexOf("/");
int laf = filename2[position].lastIndexOf(".");
String filename = filename2[position].substring(isf + 1, laf);
int pos = Integer.parseInt(filename);
Intent go = new Intent(Imagegallery.this, ItemsPage.class);
Bundle bundle = new Bundle();
bundle.putInt("position", pos);
bundle.putString("whichclass", "imagegallery");
bundle.putInt("catid", 2);
go.putExtras(bundle);
startActivity(go);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
private final String[] mobileimages;
public ImageAdapter(Context context, String[] mobileValues, String[] mo) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileimages = mo;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.currentspeciallist, null);
TextView textView = (TextView) gridView
.findViewById(R.id.textView1);
textView.setText(mobileValues[position]);
textView.setVisibility(View.INVISIBLE);
ImageView imageView = (ImageView) gridView
.findViewById(R.id.imageView1);
imageView.setTag(mobileimages[position]);
new Loadimage().execute(imageView);
// imageView.setImageBitmap(BitmapFactory
// .decodeFile(mobileimages[position]));
} else {
gridView = (View) convertView;
}
return gridView;
}
public int getCount() {
return mobileimages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
class Loadimage extends AsyncTask<Object, Void, Bitmap> {
private ImageView imv;
private String path;
#Override
protected Bitmap doInBackground(Object... params) {
imv = (ImageView) params[0];
path = imv.getTag().toString();
// Bitmap thumb = BitmapFactory.decodeFile(path);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(path, opts), 120, 120, false);
return thumb;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (!imv.getTag().toString().equals(path)) {
/*
* The path is not same. This means that this image view is
* handled by some other async task. We don't do anything and
* return.
*/
return;
}
if (bitmap != null && imv != null) {
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(bitmap);
} else {
imv.setVisibility(View.GONE);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
then create a xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" >
</ImageView>
</RelativeLayout>
i am getting file path directly . u just get the name from sqlite and pass the array string
use Android-Universal-Image-Loader
and set
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
imageLoader.displayImage(imageUri(ur file path), imageView);
}

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

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

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

Categories

Resources