How to display image from database to listview? - android

I'm new to android development. I am able to restore string from my sqite Database to my listview. Now I want to add image to my listview via the image's path that I saved to my Database(I was able to save the path already, my only problem is how do I add that path in my code below). Here's my code:
private void populateFields() {
// if the row is not null from the database.
if (mRowId != null) {
cursor = studentsDbAdapter.queueStud(mRowId);
String[] from = new String[]{StudentsDbAdapter.KEY_StudentName,StudentsDbAdapter.KEY_StudentID,StudentsDbAdapter.KEY_Course,StudentsDbAdapter.KEY_Year,StudentsDbAdapter.KEY_Contact,StudentsDbAdapter.KEY_Email};
int[] to = new int[]{R.id.textstud,R.id.textstudID};
cursorAdapter = new SimpleCursorAdapter(this, R.layout.stud_row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
}
}
I don't know if this is gonna help but in my other activity where I saved the image's path I was able to restore the image by using the following code:
public void showpic() {
//LoginDataBaseAdapter db = studentsDbAdapter.open();
boolean emptytab = false;
boolean empty = studentsDbAdapter.checkPic(null, emptytab);
//Cursor cursor = loginDataBaseAdapter.fetchProfileImageFromDatabase();
if(empty==false) {
String pathName = studentsDbAdapter.getImapath(studID);
File image = new File(pathName);
if (image.exists()) {
ImageView imageView= (ImageView) findViewById(R.id.studpic);
imageView.setImageBitmap(BitmapFactory.decodeFile(image.getAbsolutePath()));
}
}
}

You have to make custom adapter.
In adapter you can display image like this,
public static void ShowPicture(String fileName, ImageView pic) {
File f = new File(Environment.getExternalStorageDirectory(), fileName);
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ",String.format( "ShowPicture.java file[%s]Not Found",fileName));
return;
}
Bitmap = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}

How are you storing your image in DB ?
If Stored as blob, use BitmapFactory to convert it to Bitmap and set it to ImageView.
Or if it is stored as Base64 encoded string, then decode it and convert it to Bitmap.

Related

URL image to imageview to drawable

ImageView img1;
img1 = (ImageView) findViewById (R.id.img1);
URL newurl = new URL("http://10.0.2.2:80/Gallardo/Practice/files/images/donut.jpg");
Bitmap mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
img1.setImageBitmap(mIcon_val);
I get image from url but I want to store it to my drawable, how?
Everything in the apk will be read only.
So you can't write to drawable.
you have to use "blob" to store image.
ex: to store a image in to db
public void insertImg(int id , Bitmap img ) {
byte[] data = getBitmapAsByteArray(img); // this is a function
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
to retrieve a image from db
public Bitmap getImage(int i){
String qu = "select img from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);
if (cur.moveToFirst()){
byte[] imgByte = cur.getBlob(0);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
cur.close();
}
return null ;
}
You can also check this saving image to database
You can construct Drawable by using this constructor:
Drawable drawable = new BitmapDrawable(getResources(), mIcon_val);
You can set it to the ImageView like so:
img1.setImageDrawable(drawable);
Its not possible to place image in drawable folder while running the apk.. Saving an image to SDcard is possible..

Setting images in bindView (Cursor Adapter) how to differentiate between Uri that has image data and the the one that does not

I am trying to set images in my ListView in the bindView method of the cursor adapter, actually the whole data (relating to a contact) is pre-fetched in a database table. I query this table to fetch my image uri ( For every contact there is an image Uri regardless if there is an image or not). Now for those contacts which do not have an image I want to display a default image. However I tried with the following code, but my images are repeated in views which dont have images in Uri location by images which have data in Uri locations ( Other contacts images).
Following is my code:
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView) view.getTag(R.id.textView1)).setText(cursor.getString(cursor.getColumnIndexOrThrow("Name")));
((TextView) view.getTag(R.id.textView2)).setText(cursor.getString(cursor.getColumnIndexOrThrow("BirthDate")));
((TextView) view.getTag(R.id.textView1)).setTypeface(tf);
((TextView) view.getTag(R.id.textView2)).setTypeface(tf);
String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
Uri IMAGE_URI = Uri.parse(image);
InputStream stream = Contacts.openContactPhotoInputStream(context.getContentResolver(), IMAGE_URI);
if (stream == null) {
((ImageView) view.getTag(R.id.imageView1)).setBackgroundResource(R.drawable.arrow_01);
}
if(stream != null){
BufferedInputStream buf = new BufferedInputStream(stream);
Bitmap my_btmp = BitmapFactory.decodeStream(buf);
((ImageView) view.getTag(R.id.imageView1)).setImageBitmap(my_btmp);
}
}
Any ideas?
try this, it should resolve your issue.
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView) view.getTag(R.id.textView1)).setText(cursor.getString(cursor.getColumnIndexOrThrow("Name")));
((TextView) view.getTag(R.id.textView2)).setText(cursor.getString(cursor.getColumnIndexOrThrow("BirthDate")));
((TextView) view.getTag(R.id.textView1)).setTypeface(tf);
((TextView) view.getTag(R.id.textView2)).setTypeface(tf);
String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
Uri IMAGE_URI= Uri.withAppendedPath(image, Contacts.Photo.CONTENT_DIRECTORY);
Bitmap map = getBitMapfromUri(context,IMAGE_URI.toString(),128,128); // Put your desirable height, whatever you want
if(map == null){
// Load your default Image
}else{
((ImageView) view.getTag(R.id.imageView1)).setImageBitmap(map);
}
}
public Bitmap getBitMapfromUri(Context context, String uri,
int width, int height) {
Bitmap map = null;
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(
Uri.parse(uri));
Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
opts.inPurgeable = true;
opts.inInputShareable = true;
map = Bitmap.createScaledBitmap(
BitmapFactory.decodeStream(is, null, opts), width, height,
false);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(is!=null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
Solved:
Thanks to Techfist for giving me a hint:
This statement is important:
IMAGE_URI= Uri.withAppendedPath(IMAGE_URI, Contacts.Photo.CONTENT_DIRECTORY);
And then finally in the bindView:
((ImageView) view.getTag(R.id.imageView1)).setImageURI(IMAGE_URI);
if (((ImageView) view.getTag(R.id.imageView1)).getBackground()== null){
((ImageView) view.getTag(R.id.imageView1)).setBackgroundResource(R.drawable.arrow_01);
}

Setting ImageView from cursor

I'm trying to set the imageView from Uri (in a sqlite database column) returned by cursor but its not working.
Code:
mCursor = mydb.rawQuery("select * from events;", null);
if (mCursor != null ) {
mCursor.moveToFirst();
String[] from = new String[]{DbHandler.column_id, DbHandler.column_name, DbHandler.column_location, DbHandler.column_date, DbHandler.img_loc};
int[] to = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4, R.id.photoInDb};
SimpleCursorAdapter simpleCurs = new SimpleCursorAdapter(this, R.layout.listviewfinal, mCursor, from, to);
simpleCurs.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int i) {
if (view instanceof ImageView) {
ImageView image = (ImageView) view;
// just to see what is returned by this!
Log.d("orange", "images: " + cursor.getString(i));
Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(cursor.getString(i)), 320, 240);
image.setImageBitmap(thumbImage);
return true;
}
return false;
}
});
listView.setAdapter(simpleCurs);
Any ideas?
Try this code,It should work if you are getting image path correctly.
Bitmap thumbImage = BitmapFactory.decodeFile(imagePath);
image.setImageBitmap(thumbImage );
EDIT:
I think you are having some problem with getting image path. Do as follows to get the path.
String imagePath= Environment.getExternalStorageDirectory().toString() "folderpath/imageaname.jpg";
In your case folderpath is DCIM/OrangeClubPhotos/ and image name is 1370853592867.jpg
Writer these simple lines
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
or try this
File imgFile = new File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}

android retrieve contact image thumbnail

I have to display thumbnails of contacts of my contacts in a listview which has a custom cursor adapter implementation. First I did it using asynctask and in the doInBackground method, I used the following snippet to get the bitmap of thumbnail.
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(params[0]));
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(
mContext.getContentResolver(), uri);
if (input != null) {
mThumb = BitmapFactory.decodeStream(input);
} else {
mThumb = defaultPhoto;
}
It gives me correct bitmap.
Later, I came to know about Universal Image Loader. I implemented a custom BaseImageDownlaoder as in the following snippet. `public class ContactImageDownloader extends BaseImageDownloader{
private static final String SCHEME_CONTACT_IMAGE = "content";
private static final String DB_URI_PREFIX = SCHEME_CONTACT_IMAGE + "://";
private Context mContext;
public ContactImageDownloader(Context context) {
super(context);
mContext = context;
}
#Override
protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException {
if (imageUri.startsWith(DB_URI_PREFIX)) {
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(
mContext.getContentResolver(), Uri.parse(imageUri));
ByteArrayOutputStream output = new ByteArrayOutputStream();
if (input!=null) {
IoUtils.copyStream(input, output);
} else {
//default image
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wiresimage);
bitmap.compress(CompressFormat.JPEG, BUFFER_SIZE, output);
}
byte[] imageData = output.toByteArray();
input.close();
return new ByteArrayInputStream(imageData);
} else {
return super.getStreamFromOtherSource(imageUri, extra);
}
}`
}
But it doesn't retrieve the image. In the log, it shows java.io.FileNotFoundException: File does not exist; URI: content://com.android.contacts/contacts/567, calling user: com.c
So, now in order to verify my implementation (to check if my custom BaseImageDownloader is wrong), I put the snippet I used in asynctask's doInBackground method to bindView method of cursor adapter. But still, the InputStream is null i.e. FileNotFoundException. But everything works right in Asynctask. Please help. Thanks!

how to pick a image file from sdcard and then how to send it to the server?

//below
In my application i have a button select image from sdcard and on clicking it, I want to explore all the images then user will select any image after this the selected image file will be uploaded to server.
And also i have an another button from camera on clicking it, first i want to take a snapshot, and then uploaded to server, please tell me any way by example??
Here is the code I use to query the phone's MediaStore and return a cursor object containing all images. After that you may upload them to your server, but I suggest you take care of this first part in an AsyncTask.
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
//Load images from SDCARD and display
#Override
protected Object doInBackground(Object... params) {
//setProgressBarIndeterminateVisibility(true);
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
//No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
//Error fetching image, try to recover
}
}
cursor.close();
return null;
}
it is very easy to browse the image by deafult gallery using the
intent so by using the intent you can easily choose the image from sd
card and from your file browser.

Categories

Resources