Setting ImageView from cursor - android

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

Related

Set Image using getAbsolutePath()

I'm trying to use custom gallery and trying to get the selected images and would like to display it in listview
This is what I'm trying to do:
if (extras != null) {
for (int i = 0; i < fetchList.size(); i++) {
Bitmap originBitmap = null;
filepath = fetchList.get(i);
newStringList.add(filepath);
imgfilename = filepath.substring(filepath.lastIndexOf("/") + 1);
Uri selectedImage = Uri.fromFile(new File(filepath));
File myFile = new File(selectedImage.getPath());
myFile.getAbsolutePath();
Toast.makeText(MainActivity.this,myFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
listimage.setImageBitmap(myFile.getAbsolutePath());
myStringList.add(imgfilename);
arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.custom_textview, R.id.listtext,
myStringList);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
}
Now my question is how do I set the image to the image view using this path ?
If I use this listimage.setImageBitmap(myFile.getAbsolutePath()); I couldnt see the image.
Path I'm getting is : /storage/emulated/0/
Pls try this way,
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);
}
Hope this will help you.
Try this
private AQuery aq = new AQuery(activity);
File imgFile = new File(filepath);
aq.id(imageView).image(imgFile, false, 300, new BitmapAjaxCallback() {
#Override
public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
iv.setImageBitmap(bm);
}
});

How to share an image on social sites from a folder

I am saving some images in a folder of internal memory and displaying these all saved images on a button click . now i want to share current open image on social site as facebook, gmail etc.I m able to share text but not image.
Code for saving image is...
RelativeLayout content = (RelativeLayout) findViewById(R.id.relative);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File myDir=new File("/sdcard/MyCollection");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
FileOutputStream outStream;
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
code for image access is .......
ImageButton sharingButton = new ImageButton(this);
sharingButton.setLayoutParams(new ViewGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT));
sharingButton.setImageResource(R.drawable.alert);
getFromfolder();
String[] projection = {MediaStore.Images.Thumbnails._ID};
cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView sdcardImages = (GridView) findViewById(R.id.gridview);
sdcardImages.setAdapter(new ImageAdapter());
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
String[] projection = {MediaStore.Images.Media.DATA};
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
String imagePath = cursor.getString(columnIndex);
}
});
}
public void getFromfolder()
{
File file= new File(android.os.Environment.getExternalStorageDirectory(),"MyCollection");
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
f.add(listFile[i].getAbsolutePath());
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return f.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(
R.layout.gelleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Bitmap myBitmap = BitmapFactory.decodeFile(f.get(position));
holder.imageview.setImageBitmap(myBitmap);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
}
First you have to fetch the image as a bitmap from the file path. Then you can pass the image to other applications through an intent. If you want a string to passed along with the image, you can pass it through the intent as EXTRA_TEXT. Add WRITE_EXTERNAL_STORAGE in the permissions. Try this:
File imgFile = new File(imagePath);
if(imgFile.exists()){
Bitmap icon = BitmapFactory.decodeFile(imagePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (Exception e) {
System.err.println(e.toString());
}
//text
share.putExtra(Intent.EXTRA_TEXT, "Text that has to be shared");
//image
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
}
To add the image as an email attachment look here, at the Intent.EXTRA_STREAM section: https://developer.android.com/guide/components/intents-common.html#Email
For Facebook look here: https://developers.facebook.com/docs/sharing/android

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..

How to display image from database to listview?

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.

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

Categories

Resources