Thumbnails are being created in background thread but not displayed on initialization - android

When I start my application I have a Asynctask kick off which looks for any new videos and creates the thumbnails and adds them to a database. I later use the Universal Image Loader to find and set that bitmap to the view. My problem is when I start my application for the first time all the data is loaded to the database but nothing shows up in the gridview. I don't even think the adapter gets called. However, when I start the application once all the data is loaded the gridview shows all the thumbnails and it runs smoothly.
I was wondering why this happens and what I could do to fix this problem. My code is below
AsyncTask
private class DataEntry extends AsyncTask<Void, Integer, GridviewData>{
GridviewData dataentry;
DataEntry(GridviewData gridviewdata){
this.dataentry = gridviewdata;
}
#Override
protected GridviewData doInBackground(Void... params) {
cursor.moveToFirst();
do {
String videoid = cursor.getString(columnindexid);
String videopath = cursor.getString(columnindexdata);
int result = dataentry.findVideoID(videoid);
if (result == 1){
Bitmap bmthumb = ThumbnailUtils.createVideoThumbnail(videopath, MediaStore.Video.Thumbnails.MINI_KIND);
if (bmthumb != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmthumb.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] thumbnailBitmapBytes = stream.toByteArray();
dataentry.addVideoinfo(videoid, videopath, thumbnailBitmapBytes);
}
}
if (result == 0){
Log.i(TAG, "Cursor wasn't processed, no getcount");
}
if(result == 2){
//there is data already there
}
} while (cursor.moveToNext());
Log.i(TAG, "After dowhile loop");
cursor.close();
return dataentry;
}
}
Base Image Loader
public class SqliteImageDownloader extends BaseImageDownloader {
private static final String SCHEME_DB = "db";
private static final String DB_URI_PREFIX = SCHEME_DB + "://";
Cursor cursor;
public SqliteImageDownloader(Context context) {
super(context);
}
#Override
protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException {
if (imageUri.startsWith(DB_URI_PREFIX)) {
String path = imageUri.substring(19);
cursor = entry.BitFinder(path);
byte[] imageData = cursor.getBlob(0);
return new ByteArrayInputStream(imageData);
} else {
return super.getStreamFromOtherSource(imageUri, extra);
}
}
}
Cursor Adapter
class VideoAdapter extends CursorAdapter {
Cursor curs;
Context context;
public VideoAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
this.curs = c;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
String filepath = curs.getString(videopathindex);
ImageLoader.getInstance().displayImage("db://VideoandThumbs" + filepath, holder.imageview);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View eachgrid = inflater.inflate(R.layout.eachgrid, parent, false);
ViewHolder holder = new ViewHolder();
holder.imageview = (ImageView) eachgrid.findViewById(R.id.Imageview1);
eachgrid.setTag(holder);
return eachgrid;
}
}

Related

Album art is not displaying correct when I use AsyncTask class

When I display album art directly in my music app, it hangs. In stackoverflow, someone suggested me to implemented AsyncTask. So, I implemented AsyncTask to make my app faster. Right now, my app is not hanging but it is not displaying correct album art. And album arts are random means changing frequently when I scroll my listview.
Please help me.
Here is AsyncTask class :
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
private long l;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
public BitmapWorkerTask(ImageView imageView, long l) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
this.l = l;
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
//Bitmap art = getAlbumart(songlist.this, l);
Context context = songlist.this;
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
try {
final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, l);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
pfd = null;
fd = null;
}
} catch (Error ee) {
} catch (Exception e) {
}
return bm;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (bitmap != null) {
iv_art.setImageBitmap(bitmap);
} else {
iv_art.setImageResource(R.mipmap.app_splash_screen_icon);
}
}
}
}
My class which displays song in the listview :
public class MediaCursorAdapter extends SimpleCursorAdapter {
String backgroundColor = "white";
String someOtherBackgroundColor = "#FAFAFA";
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION, MediaStore.Audio.Media.ALBUM_ID},
new int[]{R.id.displayname, R.id.title, R.id.duration, R.id.iv_art});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
if (cursor.getPosition() % 2 == 0) {
view.setBackgroundColor(
Color.parseColor(backgroundColor));
} else {
view.setBackgroundColor(
Color.parseColor(someOtherBackgroundColor));
}
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
iv_art = (ImageView) view.findViewById(R.id.iv_art);
String a = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
l = Long.parseLong(a);
bwc = new BitmapWorkerTask(iv_art,l);
bwc.execute();
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
Utility d = new Utility();
String durationInMin = d.convertDuration(durationInMs);
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.songlist_listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
Its because of row reordering. The image view you want to load it into when you start a fetch is not necessarily where you want to load it at the end. The weak reference isn't helping because the view isn't being destroyed, its just not the right one anymore.
Instead of loading the data directly into the view, store it in a cache, then call notifyDataSetChanged. When you bind the row, check and see if the image is int he cache. If so, use it. If not, send the request. That will fix the majority of the issues you see, and prevent OOM errors (you can put a max memory usage on the cache).
Or use a library that does all this for you, like Volley.

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

Images from server does not show in listview

Hello I am using listview and display images from server into it.
But the problem is that all loaded images are displayed in last item one by one instead display on respective position.
please help me to display that images in respective position
public class Offer_adapter extends ArrayAdapter<String> {
Context context1;
String[] offer_title;
String[] offerimg1;
String[] mrp;
String[] offerprice;
String[] you_save;
String[] imgURLArray;
Bitmap bitmap;
ImageView offerimg;
int a;
LayoutInflater inflater1;
public Offer_adapter(Context context1, String[] offer_title, String[] offerimg1, String[] mrp, String[] you_save, String[] offerprice) {
super(context1, R.id.offer_list, offer_title);
this.context1 = context1;
this.offer_title = offer_title;
this.offerimg1 = offerimg1;
this.mrp = mrp;
this.offerprice = offerprice;
this.you_save = you_save;
}
private static class ViewHolder {
String offerimg;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
inflater1 = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater1.inflate(R.layout.offer_list, null);
viewHolder = new ViewHolder();
}
android.util.Log.v("abhi", "" + position);
imgURLArray = new String[position + 1];
for (int i = 0; i <= position; i++) {
android.util.Log.v("abhijit", "" + position);
imgURLArray[i] = "http://www.surun.co/preost/mod_offer/images/" + offerimg1[position];
android.util.Log.v("abhi", "" + imgURLArray[position]);
}
a=position;
viewHolder = (ViewHolder) convertView.getTag();
TextView offertitle = (TextView) convertView.findViewById(R.id.ofrtitle);
TextView offermrp = (TextView) convertView.findViewById(R.id.offeroriginal);
offermrp.setPaintFlags(offermrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView offersave = (TextView) convertView.findViewById(R.id.saveoffer);
TextView ofrprice = (TextView) convertView.findViewById(R.id.priceoffer);
offerimg = (ImageView) convertView.findViewById(R.id.ofr_img);
offertitle.setText(offer_title[position]);
offermrp.setText("Original Price: \u20B9" + mrp[position]);
offersave.setText("You Save: \u20B9" + you_save[position]);
ofrprice.setText("Offer Price: \u20B9" + offerprice[position]);
// Bitmap imageBitmap = null;
new DownloadAsyncTask().execute(imgURLArray[position]);
Log.v("abhi","async");
return convertView;
}
private class DownloadAsyncTask extends AsyncTask<String, String, Bitmap> {
protected Bitmap doInBackground(String... args) {
try {
Log.v("abhi","in do background");
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, 270, 375, true);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap !=null) {
offerimg.setImageBitmap(bitmap);
} else {
offerimg.setImageResource(R.drawable.nooffer);
}
}
}
}
All images are shown in last item one after another. I just want to show it on respective position.
you should use lazyloading instead of downloading image as bitmap.
Bitmap will create problem sometime or will give you outofmemory error in some devices
There are lots of image loading library available for android.
Have a look at these
https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader

Implementing Picasso not loading image

After I decided to implement Universal Image Loader, because I had implemented a method that convert URL to Drawable, but since I don't know how many images it will return my SQLite query I decided to implement an Image Loader...
The thing is I'm stuck at the moment, cause I thought I did all what the GitHub say but at the time I load the Image it stays white and never loads.
On my Adapter class I've changed the line of the drawable as :
Picasso.with(context)
.load(Uri.parse(String.valueOf(item.icon)))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
It works, beucase it shows yo me the ic_launcher icon... but never changes to the real image.
On my class where I fetch the data I have this (on my OnCreate()) :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new MyAsyncTask().execute();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// progress.dismiss();
}
});
}
}).start();
}
Then I created an inner class where I fetch the data into my ListView... but it doesn't works. I don't know If I've to delte those methods since I've changed it to Picasso.
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
Conexion = new MarketSQLite(getActivity(), "market", null, 1);
mItems = new ArrayList<ListViewItem>();
db = Conexion.getReadableDatabase();
Cursor c;
c = db.rawQuery("Select NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
FOTO = Imagehandler(URLTest);
Log.e("", "" + c.getString(i));
// initialize and set the list adapter
// Toast.makeText(getActivity(), "Title" + Title + "Preu" + Preu + "Percent" + percent + "Cheese is " + data_f, Toast.LENGTH_LONG).show();
}
mItems.add(new ListViewItem(FOTO, Title, Preu.toString(), percent, data_f));
}while (c.moveToNext());
}
c.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
myAdapter = new ListViewDemoAdapter(getActivity(), mItems);
setListAdapter(myAdapter);
}
}
Where ImageHandler is a method that I've created before this is :
protected Drawable Imagehandler(String url) {
try {
url=url.replaceAll(" ", "%20");
InputStream is = (InputStream)this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e)
{
System.out.println(url);
System.out.println("error at URI"+e);
return null;
}
catch (IOException e)
{
System.out.println("io exception: "+e);
System.out.println("Image NOT FOUND");
return null;
}
}
protected Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
I don't know why isn't the image loading on my ListView if it shows all of the rest of data...
Instead of Drawable, try to get url string in your adapter like
Change From
public ListViewItem(Drawable icon, String title, String precio, String descuento, String date) {
this.icon = icon;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
To
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon_url = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
and use Picasso where you are loading your imageview like this -
Picasso.with(context)
.load(icon_url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
1) Your ListViewItem class should be like this -
public class ListViewItem {
public final String icon; // the drawable for the ListView item ImageView
public final String title; // the text for the ListView item title
public final String precio; // the price for the ListView item
public final String descuento; // the price for the discount for the ListView item
public final String date; //the date for the sale for the ListView item
// the text for the ListView item description
public ListViewItem(String icon_url, String title, String precio, String descuento, String date) {
this.icon = icon_url;
this.title = title;
this.precio = precio;
this.descuento = descuento;
this.date = date;
}
}
2) ListViewDemoAdapterClass
public class ListViewDemoAdapter extends ArrayAdapter<ListViewItem> {
Context context;
public ListViewDemoAdapter(Context context, List<ListViewItem> items) {
super(context, R.layout.listview_item, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
viewHolder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tvDatas);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListViewItem item = getItem(position);
Picasso.with(context)
.load(item.icon)
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(viewHolder.ivIcon);
viewHolder.tvTitle.setText(item.title);
viewHolder.tvDiscount.setText(item.descuento);
viewHolder.tvPrice.setText(item.precio);
viewHolder.tvDate.setText(item.date);
return convertView;
}
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDiscount;
TextView tvPrice;
TextView tvDate;
}
}
ListFragment code, just add this
Cursor c;
c = db.rawQuery("Select
NOM_OFER,PREU_OFERTA,DATA_F,FOTO,PERCENTDESCOMPTE from T_OFERTA", null);
c.moveToFirst();
if (c != null) {
do {
for (int i = 0; i < c.getColumnCount(); i++) {
Title = c.getString((c.getColumnIndex("NOM_OFER")));
Preu = c.getColumnIndex("PREU_OFERTA");
percent = c.getString((c.getColumnIndex("PERCENTDESCOMPTE")));
data_f = c.getString((c.getColumnIndex("DATA_F")));
URLTest = c.getString((c.getColumnIndex("FOTO")));
Hope this helps :)
you just need to add your picasso code snippet as the following in your ImageHandler method and nothing else-
Picasso.with(context)
.load(url))
.resize(180, 180)
.placeholder(R.drawable.ic_launcher).into(your_imageview);
you don't need to download the image or make the bitmap or convert that into drawable to load from url. hope this helps you.

doInBackground (Agenda. .. params) does not return bitmap image in listView

I'm 3 days ago now looking for an answer and find no satisfying.
I created a listview to populate it with a picture and a text, the way the image is saved in sqlite database and image is in sd card of the phone, but only that not all rows from the database has a path to image so I'm placing a default image, but the problem is that even the images that are the path, not returning to this image, follows my adapter code below:
public class AgendaListAdapter extends ArrayAdapter<Agenda> {
private LayoutInflater inflater;
private List<Agenda> lista;
private Agenda agenda;
int resources;
//constructor
public AgendaListAdapter(Context context, int resource, List<Agenda> lista){
super(context, resource, lista);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.resources = resource;
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Agenda getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
agenda = lista.get(position);
//cria uma referencia para viewHolder
//creates a reference to
ViewHolder viewHolder;
//verifica se a view esta sendo reusada ou não
//verifies that the view is being reused or not
if(convertView == null){
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.linha_listar_telefones, null);
viewHolder.mNome = (TextView) convertView.findViewById(R.id.nome);
viewHolder.mImagem = (ImageView) convertView.findViewById(R.id.listar_contato_imagem);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
if(agenda != null){
if(viewHolder.mNome != null){
viewHolder.mNome.setText(agenda.nome);
}
if(viewHolder.mImagem != null){
viewHolder.mImagem.setTag(lista.get(position));
Log.w("Livro", "Positiom: "+position);
Log.e("Livro", "Viewhol.imagem não é nulo "+viewHolder.mImagem);
new loadImageTask(viewHolder.mImagem).execute();
}
}
return convertView;
}
private static class ViewHolder{
protected TextView mNome;
protected ImageView mImagem;
}
Bitmap b = null;
private class loadImageTask extends AsyncTask<Agenda, Void, Bitmap>{
private ImageView imv;
private String path;
public loadImageTask(ImageView imv) {
this.imv = imv;
this.path = agenda.caminho_imagem;
}
#Override
protected Bitmap doInBackground(Agenda... params) {
Log.w("Livro", "path: "+path);
File file = new File(
Environment.getExternalStorageDirectory().getAbsolutePath() + path);
if(file.exists()){
b = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return b;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null && imv != null){
Log.i("Livro", "Result do onPostExcute não é nulo: "+result);
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(result);
}else{
Log.i("Livro", "Result do onPostExcute é nulo: "+result);
imv.setImageResource(R.drawable.foto_pessoa);
}
}
}
}
In the logcat path returning this: content ://media/external/images/media/16
The variable file is returning the following result: / storage/emulated/sdcard0content ://media/external/images/media/16
I know the result of this wrong file, but would transform into uri path and pass a uri to file?
Thanks guys!!!
The path //media/external/images/media/16 is a Media Uri...You have to get the actual file path from the Uri and then set the image to the ImageView.
Get the real file path from Media Uri as below and the returned path is absolute file path...
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Get Bitmap from the path returned by getRealPathFromURI() method as below...
Context mContext;
public loadImageTask(Context context, ImageView imv) {
this.mContext = context;
this.imv = imv;
this.path = agenda.caminho_imagem;
}
#Override
protected Bitmap doInBackground(Agenda... params) {
Log.w("Livro", "path: "+path);
File file = new File(getRealPathFromURI(mContext, path));
if(file.exists()){
b = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return b;
}
And pass the context of the activity through the asynctask constructor as below...
new loadImageTask(context, viewHolder.mImagem).execute();

Categories

Resources