I\'ve done Gallery of images displayed on emulator by static(i.e images from drawable
folder).Now i need to add some images into the list of gallery, dynamically fr
In your case, you can try make your image array a dynamic list, ex: ArrayList. Upon the arrival of new item, add it to the list, and call notifyDataSetChanged() (method of the adapter), and your gallery list will be refreshed.
Depends on your case, I found that it is better to use AsyncTask here to update the list, and call notifyDataSetChanged.
The adapter class would looks similarly to this
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
ArrayList<Bitmap> bitmapList;
private Context cont;
public AddImgAdp(Context c, ArrayList<Bitmap> bitmapList) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
this.bitmapList = bitmapList;
}
public int getCount() {
return bitmapList.size();
}
public Object getItem(int position) {
return bitmapList.get(position);
}
public long getItemId(int position) {
return bitmapList.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
// imgView.setImageResource(Imgid[position]);
imgView.setImageBitmap(bitmapList.get(position));
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
Let me know if any errors, I am way to depending on IDE.
Write the file path where the image is saved.
Environment.getExternalStorageDirectory() gives path of sdcard.
File f1 = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test2.png");
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, o);
imgView.setImageBitmap(bitmap);
If your image is too big size than bitmap will give error so for that you have to write below code to resize image. Pass the file in below function
Bitmap bitmap = decodeFile(f1);
imgView.setImageBitmap(bitmap);
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 150;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}