how to set image stored in database to imageView in android? - android

I want to set image address that is stored in database to image view
I have this code but I don't know do it, I get name column to TextView but I can't set image address to imageview
Please help me!
Source code:
#Override
public View getView(int arg0, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
View v1 = view;
if (v1 == null) {
v1 = inflate.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.txt_name = (TextView) v1.findViewById(R.id.item_name);
holder.src = (TextView) v1.findViewById(R.id.textView1);
holder.img = (ImageView) v1.findViewById(R.id.item_img);
v1.setTag(holder);
} else {
holder = (ViewHolder) v1.getTag();
}
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(arg0);
holder.txt_name.setText(song.get("name"));
return v1;
}
static class ViewHolder {
TextView txt_name,src;
ImageView img;
}

it depends on how you saved your image
assuming it's 64base array you can do like that
byte[] imageBytes = Base64.decode(song.getImageBytes(), Base64.DEFAULT);
Bitmap pic = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
imageView.setImageBitmap(pic);

What do you mean with "image adress" ?
Is it a local image saved in your device with local path stored in your database or an URL and you need to download the image ?
If local path : Show Image View from file path?
If you have an URL and you need to download image : How to load an ImageView by URL in Android?

Related

Contact Image in listview is repeating when use a Baseadapter

I am building an application where I am storing all contact data in my sqlite database and populating that data in listview.
In the process the contact images are repeating and is displayed without any ordering.
The adapter:
private class ContactAdapter extends SimpleCursorAdapter
{
//Context context;
ArrayList<HashMap<String, String>> data;
private Cursor c;
private Context context;
LayoutInflater inflater;
public ContactAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolderContact viewHolder;
//viewHolder = new ViewHolderContact();
if(convertView==null)
{
viewHolder = new ViewHolderContact();
convertView = inflater.inflate(R.layout.layout_contactlist, null);
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.ivimage);
viewHolder.imgNext = (ImageView) convertView.findViewById(R.id.imgnext);
viewHolder.textView_Name = (TextView)convertView .findViewById(R.id.txtname);
// view.imgad.setScaleType(ImageView.ScaleType.FIT_XY);
/*view.imgad.setScaleType(ImageView.ScaleType.FIT_XY);
//view.imgad.setPadding(0,10,0,0);
//view.imgad.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,100));
//LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,90);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,90);
lp.setMargins(0,20,0,0);
view.imgad.setLayoutParams(lp);
*/
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolderContact)convertView.getTag();
}
this.c.moveToPosition(position);
String contactid = this.c.getString(this.c.getColumnIndex("_id"));
String contactname = this.c.getString(this.c.getColumnIndex("contactname"));
String contactnumber = this.c.getString(this.c.getColumnIndex("contactnumber"));
String contactimage= this.c.getString(this.c.getColumnIndex("contactimage"));
String isInstalled= this.c.getString(this.c.getColumnIndex("isInstalled"));
//System.out.println("Isinstalled--->"+isInstalled);
if(isInstalled.equals("Y"))
{
viewHolder.imgNext.setVisibility(View.GONE);
}
if (contactimage == null || contactimage.equals("")) {
if (Build.VERSION.SDK_INT >= 16) {
viewHolder.imageView.setBackground(getResources().getDrawable(R.drawable.ic_launcher));
}
else {
viewHolder.imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher));
}
// If there is no image in the database "NA" is stored instead of a blob
// test if there more than 3 chars "NA" + a terminating char if more than
// there is an image otherwise load the default
} //iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
else{
try {
Bitmap bmp=getContactBitmapFromURI(ContactList.this,Uri.parse(contactimage));
Bitmap round=getRoundedShape(bmp);
viewHolder.imageView.setImageBitmap(round);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
viewHolder.textView_Name.setText(contactname);
return convertView;
}
class ViewHolderContact {
TextView textView_Name;
ImageView imageView,imgNext;
}
}
c is the cursor instance
The method getContactBitmapFromURI(Context context, Uri uri)
public static Bitmap getContactBitmapFromURI(Context context, Uri uri) throws FileNotFoundException {
InputStream input = context.getContentResolver().openInputStream(uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
Output:
When I scroll then the output becomes:
As you can see that the image is not properly displayed.They are repeating or/and disappearing.Please help.
Possibly this is the case of Image caching save your Image in a cache after decode it into Bitmap. Please go through the url to how to cache Image : http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
Listview reuse views. I think the problem is in the cursor. Maybe you can try setting the data first at the method getItem(). You can also try by doing notifyDataChanged when reached a certain position, if images change then is going to be a good point to start of.
I think thats because of your if else part . In first case you are setting background of image and in second case you are setting src of image . The seImageBitmap() method set the bitmap as src . Change one of the case . Use same in both cases .So i suggest Use Circle image view for getting rounded image and use UILoader or Picasso
to load the images . In that way you will get rid of caching and outofmemory error too ..
You can get image url fro uri like this
private String getPathFromUri(Uri uri) {
String url = null;
Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.Media.DATA }, null, null, null);
if (cursor.moveToFirst()) {
url = cursor.getString(0);
}
return url;
}

Textview Padding Changes When Position Changes in Listview

I am trying to create a listview item with an imageview to the right of a textview.. lets say if the text was 3 lines i want the text of the first 2 lines to begin after the image view with some padding.. and the third line to be at the bottom of the image with no padding..
I used this code in my list adapter to do this..
TextView commenterName = (TextView) row
.findViewById(R.id.commenter_name);
commentText = (TextView) row.findViewById(R.id.tv);
ImageView commenterPhoto = (ImageView) row
.findViewById(R.id.commenterPhoto);
Display display = ((WindowManager) row.getContext()
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
FlowTextHelper.tryFlowText(commentsArray.get(pos).getComment(),
commenterPhoto, commentText, display, 0);
commenterName.setText(commentsArray.get(pos).getCommenter());
commentText.setTextColor(context.getResources().getColor(R.color.Black));
commentText.setGravity(Gravity.RIGHT);
this working fine.. but when scrolling the list view the text loses its padding and get over the image and out of the screen..
UPDATE:
This was the part causing the problem.. i put the else condition to set the default photo but the problem still exist..
String path = url.substring(url.lastIndexOf("/") + 1, url.length());
sd = new File(Environment.getExternalStorageDirectory()
+ Constants.user_images_path + path);
if (sd.exists()) {
Bitmap thumbnail = null;
try {
//File filePath = context.getFileStreamPath(url);
FileInputStream fi = new FileInputStream(sd);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
thumbnail = BitmapFactory.decodeStream(fi, null, options);
if(thumbnail != null)
holder.commenterPhoto.setImageBitmap(thumbnail);
else
holder.commenterPhoto.setBackgroundResource(R.drawable.commenter_default);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}
I don't know why this is happening.. Can you help me please?
OK.. I solved the problem by setting my imageView background in the condition of convertview in my getView() method before setting the tag of my holder.. just like this:
View row = convertView;
if (row == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = infalInflater.inflate(resource, null);
holder = new ViewHolder();
holder.commentText = (TextView) row.findViewById (R.id.tv);
holder.commenterPhoto = (ImageView) row.findViewById (R.id.commenterPhoto);
holder.commenterName = (TextView) row.findViewById (R.id.commenter_name);
holder.date = (TextView) row.findViewById (R.id.date);
holder.show = (ImageButton) row.findViewById(R.id.show);
String path = url.substring(url.lastIndexOf("/") + 1, url.length());
sd = new File(Environment.getExternalStorageDirectory()
+ Constants.user_images_path + path);
Bitmap thumbnail = null;
if (sd.exists()) {
try {
//File filePath = context.getFileStreamPath(url);
FileInputStream fi = new FileInputStream(sd);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
thumbnail = BitmapFactory.decodeStream(fi, null, options);
if(thumbnail != null)
holder.commenterPhoto.setImageBitmap(thumbnail);
else
holder.commenterPhoto.setBackgroundResource(R.drawable.commenter_default);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}else{
Toast.makeText(context, "No Image Found", Toast.LENGTH_LONG).show();
}
row.setTag(holder);
}
else{
holder = (ViewHolder) row.getTag();
}
Be careful with if...else blocks inside the getView() method in the adapter. If you set the background color in red of a LinearLayout inside an if statement you should put the "original" color in the else statement. This is caused by the ListView recycling views. You can see it better explained here
Try to add an "else" in the if(sd.exist()) block. I have supposed that this code is in getView().

findViewById returns NULL with imageView

I have a gridViewAdapter class that creates a view when there is none and I set an Id to it. Here is the getView() section of that class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
view.setId(R.id.iconImageView_id);
}
if(checked == true){
isSdReadable();
Log.i("GridViewAdapter", "checkbox is checked");
} else {
Log.i("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
I have a ids.xml in the values section of my resources here:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="iconImageView_id"/>
</resources>
Then I am trying to get the imageView in another class here:
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = new FileOutputStream(file);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "The icon for use in gridView is saved");
out.close();
// Load back the image file to confirms it works
Bitmap bitmap = BitmapFactory.decodeFile( file.getAbsolutePath() );
ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id);
imageView1.setImageBitmap( bitmap );
Log.i("AppInfoAdapter", "The icon image has been set into the gridView");
}
But I get a NPE on this line:
imageView1.setImageBitmap( bitmap );
telling me that the imageView is returning null
Why is this? How can I fix this?
ADDED:
I am getting the imageView in another adapter class here:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.activityInfo.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = new FileOutputStream(file);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "The icon for use in gridView is saved");
out.close();
// Load back the image file to confirms it works
Bitmap bitmap = BitmapFactory.decodeFile( file.getAbsolutePath() );
ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id);
imageView1.setImageBitmap( bitmap );
Log.i("AppInfoAdapter", "The icon image has been set into the gridView");
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}

Display and parse images from DB to listview

I have to display data from mysql database in the listview of my android app. I have successfully parsed the textual data and displayed it in custom listview but the image are not being parsed and displayed in the list. I have tried using imageloader, file cache, memory cache, but still have not succeeded.
If anyone have any idea about what is missing or what should be added to it, any help would be appreciated.
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView tourname;
TextView duration;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_row1, parent, false);
// Get the position from the results
// Locate the TextViews in listview_item.xml
tourname = (TextView) itemView.findViewById(R.id.themeTourList_title);
duration = (TextView) itemView.findViewById(R.id.themeTourList_price);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.themeTourList_image);
// Capture position and set results to the TextViews
try
{
tourname.setText(mJSONArray.getJSONObject(position).getString("tour_name"));
duration.setText(""+mJSONArray.getJSONObject(position).getString("nights")+" Nights - "+mJSONArray.getJSONObject(position).getString("days")+" Days");
try{
URL url = new URL("www.futurolicht.com/"+mJSONArray.getJSONObject(position).getString("pic"));
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)(url).getContent());
flag.setImageBitmap(bitmap);
}
Try using the below method to Download Images:
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);

java.lang.outofmemory error at bitmap factory.decodefile in Android

First i call MediaStore.ACTION_IMAGE_CAPTURE intent to open camera then i get the saved captured image path from this function.
private String getLastImageId(){
String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
if(imageCursor.moveToFirst()){
int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
//imageCursor.close();
return fullPath;
}else{
return "";
}
}
then i pass that path to a product object attribute as a parameter.
add that object to product list
that list is displayed by a customized adapter.
i am displaying the product title and image in the listView
in customized adapter class i get the product fetch product title and path from it
make a bitmap from path and asign it to the product holder that contain a image view
working this way for first photo is fine but on the second photo it gives the exception of java.lang.outofmemory i have also tried the solution given at
java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android
doing so as in product adapter
public class ProductAdopter extends ArrayAdapter<Product> {
Context context;
int layoutResourceId;
ArrayList<Product> data = null;
public ProductAdopter(Context context, int layoutResourceId, ArrayList<Product> product_data) {
// TODO Auto-generated constructor stub
super(context, layoutResourceId, product_data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = product_data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ProductHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((MainActivity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ProductHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (ProductHolder)row.getTag();
}
Product product = data.get(position);
holder.txtTitle.setText(product.getName());
File imgFile = new File(product.icon);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.imgIcon.setImageBitmap(myBitmap);
//myBitmap.recycle();
}
return row;
}
static class ProductHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
if(imgFile.exists()){
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
holder.imgIcon.setImageBitmap(myBitmap);
//myBitmap.recycle();
}
Use inSampleSize to load scales bitmaps to memory. Using powers of 2 for inSampleSize values is faster and more efficient for the decoder. However, if you plan to cache the resized versions in memory or on disk, it’s usually still worth decoding to the most appropriate image dimensions to save space.
For more see Loading Large Bitmaps Efficiently
You will run into out of memory issues if you try to decode big images yourself.
Try using Universal Image loader. It will take care of all image loading from local storage or the internet.
https://github.com/nostra13/Android-Universal-Image-Loader
OutOfMemory can be tiring
here are some few options that you can look
try {
//Create your bitmap here
} catch (OutOfMemoryError ooM) {
// You got out of memory now do something to recycle images
// Yes you can catch OOM.
recycle();
}
If you do not have many images to handle then you can try this.
BitmapFactory.Options op = new BitmapFactory.Options();
op.inSampleSize = 8;
return BitmapFactory.decodeFile("<YOUR IMAGE FILE HERE>", op);
A combination of above can be useful if you have many images

Categories

Resources