Display and parse images from DB to listview - android

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

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

how to set image stored in database to imageView in 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?

skimagedecoder::factory returned null, Skipping frames in Android

I am using a GridView to display the images of albumart, for that i am creating a adapter, below is the code of my getView function of adapter
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
FrameLayout albumLayout = (FrameLayout)layoutInflater.inflate(R.layout.album, viewGroup, false);
ImageView imageview = (ImageView)albumLayout.findViewById(R.id.iconItem);
int albumId = keys[position];
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
Bitmap image = null;
try {
image = MediaStore.Images.Media.getBitmap(resolver, albumArtUri);
//image = Bitmap.createScaledBitmap(image, 80, 80, true);
} catch (IOException e) {
image = BitmapFactory.decodeResource(context.getResources(), R.drawable.musicimage);
}
imageview.setImageBitmap(image);
String albumName = albumMap.get(albumId);
TextView albumNameView = (TextView)albumLayout.findViewById(R.id.textItem);
albumNameView.setText(albumName);
albumLayout.setTag(albumId);
return albumLayout;
}
I have 4 fragments inside a ViewPager and when i swipe to the album page then it gets stuck there and i am getting skimagedecoder::factory returned null, Skipping frames in logs.
Can anyone suggest me how to resolve this and how can i make it more efficient so that while swiping the view should not get stuck.

Show Image From URL in Android?

How can I convert Image URL to any showable type, I want to show it with my CustomAdapter just like "Category_Name" and "Category_Description" as in the following code ;
JSONArray jsonResponse = new JSONArray(result); // Result is my JSON
asd = new String[3][jsonResponse.length()];
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject js = jsonResponse.getJSONObject(i);
asd[0][i]= js.getString("Category_Name"); // Fetch Category Name
asd[1][i]= js.getString("Category_Description"); // Fetch Category Description
asd[2][i]= js.getString("Image"); // Fetch Image URL
RowItem item = new RowItem(R.drawable.abc_ab_bottom_solid_dark_holo, asd[0][i], asd[1][i]);
// I delivered asd[0][i] as a title and asd[1][0] as a post content..
rowItems.add(item);
}
adapter = new CustomListViewAdapter(MainActivity.this,R.layout.list_item, rowItems);
listView.setAdapter(adapter);
How Can I use Fetched Image URL and show it just like title , post content.
Custom Adapter ;
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc()); // RowItem Setter Getter Method
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
You will have to download the image and set it to the imageView
To download and set the image:
public void downloadImageFromUrl(ImageView iv, String path){
InputStream in =null;
Bitmap bmp=null;
int responseCode = -1;
try{
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download the image
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
if(bmp!=null)
iv.setImageBitmap(bmp);
}
}
catch(Exception e){
Log.e("Exception",e.printStackTrace());
}
}
Try this .It helped me a lot in parsing image and making my custom adapter.Hope it will also help you.

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