android - create gallery with photos from sdcard - android

I am trying to create gallery with photos from sdcard. I have a database table. One of the columns in the table has a path to a photo.
I am following this link as a guideline, but this sample code retrieves image ids from res/drawable directory. I am not sure how to modify it to make my code work.
http://saigeethamn.blogspot.com/2010/05/gallery-view-android-developer-tutorial.html
But as mentioned, I want to display photos with whatever images exist in the database table. The following code is ImageAdapter.
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.milestone_style);
imageBackground = ta.getResourceId(R.styleable.milestone_style_android_galleryItemBackground, 1);
ta.recycle();
}
#Override
public int getCount() {
return imagePhotosLocations.length;
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View arg1, ViewGroup arg2) {
if (milestones != null && !milestones.isEmpty()) {
Milestone milestone = milestones.get(0);
String imageFileLocation = milestone.getFileLocation();
System.out.println("imageFileLocation="+imageFileLocation);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 26;
Bitmap b;
ImageView iv = new ImageView(ctx);
try {
if (imageFileLocation.startsWith("content://")) {
b = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(imageFileLocation)), null, options);
} else {
b = BitmapFactory.decodeFile(imageFileLocation, options);
}
iv.setImageBitmap(b);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150, 120));
// milestoneImageView.setBackgroundResource(imageBackground);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return iv;
}
return null;
}
}
And this is one of the methods in activity.
private String[] imagePhotosLocations;
private void init() {
milestones = getMilestones();
imagePhotosLocations = new String[milestones.size()];
int index = 0;
for (Milestone milestone : milestones) {
imagePhotosLocations[index++] = milestone.getFileLocation();
}
}
private void initializeGallery() {
milestoneImageView = (ImageView) this.findViewById(R.id.imagePhoto);
Gallery milestoneGallery = (Gallery) this.findViewById(R.id.milestoneGallery);
if (milestoneGallery == null) {
throw new IllegalArgumentException("milestoneGallery can not be null.");
}
milestoneGallery.setAdapter(new ImageAdapter(this));
milestoneGallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int which, long arg3) {
String imageFileLocation = imagePhotosLocations[which];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 26;
Bitmap b;
try {
if (imageFileLocation.startsWith("content://")) {
b = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(imageFileLocation)), null, options);
} else {
b = BitmapFactory.decodeFile(imageFileLocation, options);
}
milestoneImageView.setImageBitmap(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}

Here are the steps which I used,
First check if the SD card is mounted.
Query your database.Details on this can be found here:
SQLite tutorial.
The Query returns a cursor for the result set.
Use a custom Cursor Adapter (Refer: Custom Cursor Adapter)
Some times if the image is too large ,loading the image into bitmap may exceed VM budget. So refer this article Avoiding out of memory issue while loading image
So the cursor adapter returns an image view as its done in your code.
finally bind this custom adapter to your gallary.
hope this answers your question.

Related

How to set captured image in ListView?

I have an ArrayList which is bound to the listview, the custom row has a textview and an imageview, now when I click on any row I have given two functionality
1. Toast message to display position: which is displaying properly.
2. Open camera to capture an image and set that particular image to the row which was clicked.
Now the problem which I am facing is :
The image gets set but always to the last row and not to the row where it was clicked and when I click on the last row to capture image while setting the image it says IndexOutofBoundException
The code I have tried :
public class DocumentsKYCAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<DocumentItem> gridName;
ArrayList<Integer> selectedDocumentId = new ArrayList<Integer>();
ArrayList<String> selectedDocumentNames = new ArrayList<String>();
ArrayList<Bitmap> selectedImages = new ArrayList<Bitmap>();
private Bitmap[] gridImage;
Documents_KYC activity;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Imageview";
private Uri fileUri;
ImageView imageView;
public static byte[] b;
public static String encodedImageStr1;
int imageCapturedPosition;
public DocumentsKYCAdapter(Documents_KYC activity,
ArrayList<DocumentItem> gridName,ArrayList<Integer>
selectedDocumentId,ArrayList<String> selectedDocumentNames) {
this.activity = activity;
this.gridImage = gridImage;
this.gridName = gridName;
this.selectedDocumentNames = selectedDocumentNames;
this.selectedDocumentId = selectedDocumentId;
}
#Override
public int getCount() {
return selectedDocumentNames.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
View grid;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.documents_kyc_row, null);
} else {
grid = (View) convertView;
}
final String documentItemName =
selectedDocumentNames.get(position);
final int documentItemId = selectedDocumentId.get(position);
TextView textView = (TextView) grid.findViewById(R.id.gridName);
imageView = (ImageView) grid.findViewById(R.id.gridImage);
imageView.setTag(position);
textView.setText(documentItemName);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageCapturedPosition = position;
Toast.makeText(activity,"Id"+documentItemId+"
,Position"+imageCapturedPosition,Toast.LENGTH_LONG).
show();
imageView.getTag(position);
captureImage();
}
});
return grid;
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
activity.startActivityForResult(intent, MEDIA_TYPE_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
try {
if (requestCode == MEDIA_TYPE_IMAGE && resultCode ==
activity.RESULT_OK) {
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bitmap = Utility.decodeFile(fileUri.getPath(),
options);
FileOutputStream out = null;
try {
out = new FileOutputStream(fileUri.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
ByteArrayOutputStream baos = new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80,
baos);
b = baos.toByteArray();
encodedImageStr1 = Base64.encodeToString(b,
Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
selectedImages.add(bitmap);
imageView.setImageBitmap(selectedImages.
get(imageCapturedPosition));
} else if (resultCode == activity.RESULT_CANCELED) {
Toast.makeText(activity,
"User cancelled image capture",
Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(activity,
"Sorry! Failed to capture image",
Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Custom Class :
public class BitmapModel {
Bitmap imageId;
ArrayList<String> documentNamesList;
public ArrayList<String> getDocumentNamesList() {
return documentNamesList;
}
public void setDocumentNamesList(ArrayList<String> documentNamesList) {
this.documentNamesList = documentNamesList;
}
public Bitmap getImageId() {
return imageId;
}
public void setImageId(Bitmap imageId) {
this.imageId = imageId;
}
}
Your issue is in the line -
selectedImages.add(bitmap);
Here whenever you add an image to your arrayList it always adds at the last position and then when you do imageView.setImageBitmap(selectedImages.get(imageCapturedPosition)); It tries to get the value for the position you selected which is not necessarily the last position.
The better way for you to do is create a Custom Class with Bitmap and selectedDocumentNames as part of the class then each object of the class would represent a name and an image associated with it.
Now when you capture the image, assign the image to the class Bitmap and then populate your listview with that Bitmap.
The workaround for your present code code be to either add the image into a particular position in array denoted by imageCapturedPosition or create a hashmap of type position,bitmap and then store it with the selected position. though i would not recommend any of these workarounds as they would cause other problems in future like memory leaks and positional movements in arrays etc and you would have to take care of these things

Getting itemid from list<string>

i'm working on wallpaper app
i implemented this code in order to load my pictures from assets
loading-images-from-assets-folder
it's working great but i have issue with getting itemid from the list to use the id to display one of these images in fullscreenactivity or setting wallpaper
public long getItemId(int position) {
return position ;
}
here is my code
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private List<String> list;
private AssetManager assetManager;
public ImageAdapter(Context c, List<String> list) {
mContext = c;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
} catch (IOException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return imageView;
}
public class Gs3Wallpaper extends Activity {
private ImageButton Gs3Button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.GridView1);
try {
gridView.setAdapter(new ImageAdapter(this ,getImage()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public List<String> getImage()throws IOException {
AssetManager assetManager = getAssets();
String[] files = assetManager.list("gallary");
List<String> list = new ArrayList<String>();
for (String it : files) {
list.add("gallary"+File.separator + it);
}
return list;
i don't know how to get the id from the list i tried to use list.get(position) but it returns string not int so i can't pass that to setImageResource for example
any suggestions?
What you can do is set the image or a path to the image, depending on how you are doing it, in a HashMap in getView() when you set the list item. Use the position for the key and the image as the value
public class MyClass
{
HashMap<String, Bitmap> imageMap = new HashMap<String, Bitmap>();
...
then set it in your getView()
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
String posString = String.valueOf(position);
imageMap.put(posString, bm);
} catch (IOException e) {
....
}
Something like this should work for you. Then just use the position to get that bitmap out of the HashMap

Image from sd card to gallery

I want to get an image from sd card and place it in gallery view.For that i had converted that image to bitmap but it shows certain errors..
code for conversion of the image.. I am attaching the complete code it showing a null pointer exception
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
System.out.println("Enter the activity");
try{
String filepath = "/sdcard/";
File imagefile = new File(filepath + "abcdoutput.jpg");
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
System.out.println("cnvrtn");
}
catch(Exception e) {
e.printStackTrace();
}
Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
position = 0;
imgView = (ImageView) findViewById(R.id.ImageView01);
imgView.setImageBitmap(bitmapimage);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
imgView.setImageResource(data[position]);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressWarnings("deprecation")
public boolean onLongClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
DisplayImage.this).create();
alertDialog.setTitle("Confirmation");
alertDialog
.setMessage("Do you want to set this image as wallaper?");
alertDialog.setButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Bitmap bitmap = BitmapFactory.decodeResource(
getResources(), data[position]);
try {
DisplayImage.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
});
alertDialog.show();
return true;
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = null;
GalItemBg = typArray.getResourceId(
0, 0);
typArray.recycle();
}
public int getCount() {
return data.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 imgView = new ImageView(cont);
imgView.setImageResource(data[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
Use this to get the image back from the array and set it:
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
imgView.setImageBitmap(bitmap);
try and simple with one line code
String imagePath=Environment.getExternalStorageDirectory().toString()+"/abcdoutput.jpg";
imgView.setImageDrawable(Drawable.createFromPath("imagePath"));

fetching multiple image from urls

I have an application which allow to download 3 images and show them into a gallery
In order to do this , i use a thread in order to download the images and a handler in order to put the images into the gallery
The problem is that the images are not displayed(imageviews are empty) into the gallery (even if i see 3 imageview for my 3 images)
I do not know if this is because the connection is very slow (I develop on a mobile) or if it's because the ui is displayed before images are downloaded
Thank you very much for your help
public class ChoiceLanguage extends Activity {
private TextView nomLangue;
private ArrayList<Language> listeLangues;
private ArrayList<String> listImages;
private Gallery gallery;
private String URL="******************";
private Drawable mNoImage;
Bitmap bitmap;
ImageView imgView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice_language);
listeLangues= getIntent().getParcelableArrayListExtra("listeLangues");
listImages=buildListImages();
gallery = (Gallery) findViewById(R.id.galleryImg);
gallery.setAdapter(new AddImgAdp(this));
gallery.setSpacing(10);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.out.println("URL "+ listImages.get(position) );
}
});
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
in=conn.getInputStream();
return in;
}
private Bitmap downloadImage( ImageView iView, String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedInputStream bis ;
try {
in = openHttpConnection(url);
bis= new BufferedInputStream(in, 8192);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private ArrayList<String> buildListImages() {
ArrayList<String> listImg = new ArrayList<String>();
for(Language l : listeLangues) {
listImg.add(URL+l.getImagePath());
}
return listImg;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return listImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imgView = new ImageView(cont);
} else {
imgView = (ImageView)convertView;
}
ThreadDownload progressDl= new ThreadDownload(position);
progressDl.start();
imgView.setLayoutParams(new Gallery.LayoutParams(150, 150));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
private class SetImg extends Handler {
public void handleMessage(Message msg) {
imgView.setImageBitmap(bitmap);
}
}
private class ThreadDownload extends Thread {
SetImg img= new SetImg();
int position ;
public ThreadDownload(int position)
{
super();
this.position=position;
}
public void run() {
bitmap = downloadImage(imgView,listImages.get(position));
img.sendEmptyMessage(0);
}
}
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view

Only one image is appearing in every grid of gridview [duplicate]

This question already has answers here:
Displaying images from specific folder in sd card in grid view
(4 answers)
Closed 3 years ago.
I had developed an application where I want to display images inside grid view from specific folder of sd card. The application is working but only 1st image from folder is appearing in every grid, while I want all images should display. I am not getting where I went wrong.
Below, I am posting my code:
Album Activity:
public class Album3Activity extends Activity {
static File [] mediaFiles;
static File imageDir;
GridView gridView;
ImageAdapter adapter;
Intent in;
public static final String TAG = "Album3Activity";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
prepareList();
adapter = new ImageAdapter(this, mediaFiles);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(adapter);
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);
}
});
}//onCreate
public static Bitmap prepareList() {
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
mediaFiles = imageDir.listFiles();
Bitmap bmp = null;
for(File imagePath:mediaFiles){
try{
bmp = BitmapFactory.decodeStream(imagePath.toURL().openStream());
}catch(Exception e){
Log.d(TAG, "Exception: "+e.toString());
}//catch
}//for
Log.d(TAG, "prepareList() called");
return bmp;
}//prepareList
}//class
Image Adapter:
public class ImageAdapter extends BaseAdapter{
Activity act;
File[] mFiles;
public static final String TAG = "ImageAdapter";
public ImageAdapter(Activity act, File[] mFiles){
super();
this.act = act;
this.mFiles = mFiles;
}//ImageAdapter
public int getCount() {
return mFiles.length;
}//getCount
public Object getItem(int postion) {
return mFiles[postion];
}//getItem
public long getItemId(int position) {
return 0;
}//getItemId
public static class ViewHolder{
ImageView iv;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater li = act.getLayoutInflater();
if(convertView == null){
view = new ViewHolder();
convertView = li.inflate(R.layout.gridview_row, null);
view.iv = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}//if
else{
view = (ViewHolder)convertView.getTag();
}//else
Bitmap bmp = Album3Activity.prepareList();
view.iv.setImageBitmap(bmp);
Log.d(TAG, "getView called");
return convertView;
}//getView
}//ImageAdapter
Note prepareList method, it is not returning bitmap according to the position or index of the imageview, so it would return same image all the time, change it to accept an index parameter, and return bitmap accordingly, as:
public static Bitmap prepareList(int index) {
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
mediaFiles = imageDir.listFiles();
File imagePath=imageDir[index];
Bitmap bmp = null;
try{
bmp = BitmapFactory.decodeStream(imagePath.toURL().openStream());
}catch(Exception e){
Log.d(TAG, "Exception: "+e.toString());
}//catch
Log.d(TAG, "prepareList() called");
return bmp;
}//prepareList
In getView everytime your are calling album3Activity.prepareList() so it will return single image for all the grid. Try with the passing the particular imagepath in mFiles[position] each time and get the bitmap or get all the bitmap at once and store it in arrayList and pass the arraylist to adapter and use it in getView.
Try this..it may help you..

Categories

Resources