ImageView's picture does not set with AsyncTask - java

Here in my code I'm setting a picture into an ImageView in my MyTask class which is using AsyncTask, but as I run my code just one or two ImageViews has pictures and the others are empty showing the default picture.
Is there any problems with the thread?
Here is my code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.e("sara" , "this part takes time");
LayoutInflater inflater = getLayoutInflater();
convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
iv = (ImageView) convertView.findViewById(R.id.icon);
file = new File(Uri.parse(getItem(position).toString()).getPath());
new myTask().execute();
return convertView;
}
private class myTask extends AsyncTask <Void , Void ,Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
try {
bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap aVoid) {
iv.setImageBitmap(aVoid);
}
}

This is because you are overriding the iv(imageview) object every time when getView() method is called and because MyTask is an asynch task in which doInBackground() is called asynchronously on background thread and onPostExecute() called on main thread after that. So the onPostExecute will only update the current imageview. You have to set the bitmap on every image view of grid. This solution should work for you:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.e("sara" , "this part takes time");
LayoutInflater inflater = getLayoutInflater();
convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
ImageView iv = (ImageView) convertView.findViewById(R.id.icon);
File file = new File(Uri.parse(getItem(position).toString()).getPath());
new myTask(iv, file).execute();
return convertView;
}
private class MyTask extends AsyncTask <Void , Void ,Bitmap> {
Imageview iv;
File file;
public void MyTask(Imageview iv, File file)
{
this.iv=iv;
this.file= file;
}
#Override
protected Bitmap doInBackground(Void... params) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
try {
bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap aVoid) {
iv.setImageBitmap(aVoid);
}
}

i consider that you are try to load an image using a url
you can user image loader reference (such as universal image loader) which is best for loading images
here is the code you can have
first of download the universal image loader library from the below
https://github.com/nostra13/Android-Universal-Image-Loader
You have to add this method your application level class so you don't need to write multiple times
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you
// may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(
context);
config.threadPriority(Thread.NORM_PRIORITY - 2);
config.denyCacheImageMultipleSizesInMemory();
config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
config.tasksProcessingOrder(QueueProcessingType.LIFO);
config.writeDebugLogs(); // Remove for release app
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config.build());
}
Then in Adapter class you have to just add the below code to load image
// For Image Display options - Failed , Success and Error
// Add this is in your adapter constructor
DisplayImageOptions userimgoptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.profile_pic_no_border)
.showImageForEmptyUri(R.drawable.profile_pic_no_border)
.showImageOnFail(R.drawable.profile_pic_no_border).cacheInMemory(true)
.cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
// in you getview method just use this signle line code to load image
ImageLoader.getInstance().displayImage(modelFeeds.getUserAvatarOriginal(), myHolder.img_profilepicture, userimgoptions);
i hope this will help you

Set the Imageview using Glide Library
Step1: Include the Dependencies in your build.gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'
Step2: Include the Glide in Java file
String fileName = "1.jpg";
String completePath = Environment.getExternalStorageDirectory() + "/" +
fileName;
File file = new File(completePath);
Uri imageUri = Uri.fromFile(file);
Glide.with(this)
.load(imageUri)
.placeholder(R.drawable.no_media)
.into(imgView);

Related

image view not showing the image with using thread

I'm using this code to show Images, as I run it without thread It works correctly but with using thread I just get Image views without any picture inside them. its important for me to use thread for this part of my program because its very slow :(
here is my code :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.e("sara" , "this part takes time");
LayoutInflater inflater = getLayoutInflater();
convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
iv = (ImageView) convertView.findViewById(R.id.icon);
final File file = new File(Uri.parse(getItem(position).toString()).getPath());
//File file = new File("/text.jpg");
Runnable runnable = new Runnable() {
#Override
public void run() {
Bitmap bmp = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
try {
bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
iv.setImageBitmap(bmp);
}
};
new Thread(runnable).start();
return convertView;
}
}
Use AsyncTask.
Doc: https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask enables proper and easy use of the UI thread. This class
allows you to perform background operations and publish results on the
UI thread without having to manipulate threads and/or handlers.
Do your heavy operation in doInBackground() and set the image to imageView in onPostExecute().

running a thread inside a class function

I need to run some parts of my code with thread. But I got problem with accessing the variables from run() function. The variables (also the function arguments) needs to be defined as final, but as I do this I cannot change their value inside run() function. For example now variable iv is not accessible in run() method.
Is there any way I could handle this problem?
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false);
ImageView iv = (ImageView) convertView.findViewById(R.id.icon);
final File file = new File(Uri.parse(getItem(position).toString()).getPath());
Runnable runnable = new Runnable() {
#Override
public void run() {
Bitmap bmp = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
try {
bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
iv.setImageBitmap(bmp);
}
};
new Thread(runnable).start();
return convertView;
}
What you need to do here is to make iv final:
final ImageView iv = (ImageView) convertView.findViewById(R.id.icon);
In this context final means that you cannot change reference to the object iv points to, but you still can call any methods of it. Also beware of creating new Thread for each view, I would suggest using thread pool represented by ExecutorService instead.

ImageView showing black/white background for transparent base64 string image

Im using DisplayingBitmap.zip downloaded from developers android site to load images asynchronously into the imageview. Im receiving base64 strings from webservice. so modified the code to convert base64 to bitmap in ImageFetcher.class from (DisplayingBitmaps) instead of downloading image from url.
NOTE: Im receiving gif images in the form of base64 string.
Converting base64 to Bitmap
public Bitmap convertBase64ToImage(String mBase64String) {
Bitmap bitmap = null;
try {
String imageDataBytes = mBase64String.substring(mBase64String.indexOf(",") + 1);
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
bitmap = BitmapFactory.decodeStream(stream);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
Converting base64 bitmap to file inorder to obtain decoded resized bitmap using processBitmap method in ImageFetcher.class(DisplayingBitmaps):
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* #param data The data to load the bitmap, in this case, a regular http URL
* #return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String data, String imageID) {
if (BuildConfig.DEBUG) {
PrintLog.error(TAG, "processBitmap --- imageID " + imageID);
}
Bitmap bitmap = null;
bitmap = convertBase64ToImage(data);
if (bitmap != null) {
File f = null;
try {
//create a file to write bitmap data
f = new File(mContext.getFilesDir(), imageID);
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100/*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
bitmap = decodeSampledBitmapFromFile(f.getAbsolutePath(), mImageWidth, mImageHeight, getImageCache());
}
return bitmap;
}
#Override
protected Bitmap processBitmap(Object data, String imageID) {
return processBitmap(String.valueOf(data), imageID);
}
decodeSampledBitmapFromFile method from ImageResizer.class
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// If we're running on Honeycomb or newer, try to use inBitmap
if (DeviceUtils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
}
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
Implementing ImageFetcher.class(DisplayingBitmaps.zip) in my class
private static final String IMAGE_CACHE_DIR = "clubsCategoryIcons";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(getActivity(), IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 10% of app memory
// The ImageFetcher takes care of loading images into our ImageView children asynchronously
mImageFetcher = new ImageFetcher(getActivity(), getResources().getDimensionPixelSize(R.dimen.image_icon_size));
mImageFetcher.setLoadingImage(R.drawable.settings_clubs);
mImageFetcher.addImageCache(getActivity().getSupportFragmentManager(), cacheParams);
}
passing this mImageFetcher object to adapter class to load images asynchronously for each item.
ClubsCategoryAdapter clubsAdapter = new ClubsCategoryAdapter(getActivity(), new ArrayList<ClubsCategoryParser.ClubsCategory>(), mImageFetcher);
recyclerView.setAdapter(clubsAdapter);
ClubsCategoryAdapter.class
public class ClubsCategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ImageFetcher mImageFetcher;
public ClubsCategoryAdapter(Context context, ArrayList<ClubsCategoryParser.ClubsCategory> clubsCategoryList, ImageFetcher mImageFetcher ) {
this.context = context;
this.clubsCategoryList = clubsCategoryList;
this.mImageFetcher = mImageFetcher;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
final ClubsCategoryParser.ClubsCategory singleItem = clubsCategoryList.get(position);
if (!TextUtils.isNullOrEmpty(singleItem.image_url)) {
mImageFetcher.loadImage(singleItem.image_url, String.valueOf(singleItem.ID), viewHolder.imgCategoryIcon);
}
loadImage method in ImageWorker.class(DisplayingBitmaps)
public void loadImage(Object data, String imageID, ImageView imageView) {
if (data == null) {
return;
}
BitmapDrawable value = null;
if (mImageCache != null) {
value = mImageCache.getBitmapFromMemCache(imageID);
}
if (value != null) {
// Bitmap found in memory cache
imageView.setImageDrawable(value);
} else if (cancelPotentialWork(data, imageView)) {
//BEGIN_INCLUDE(execute_background_task)
final BitmapWorkerTask task = new BitmapWorkerTask(data, imageID, imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task);
imageView.setImageDrawable(asyncDrawable);
// NOTE: This uses a custom version of AsyncTask that has been pulled from the
// framework and slightly modified. Refer to the docs at the top of the class
// for more info on what was changed.
task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR);
//END_INCLUDE(execute_background_task)
}
}
actual asynctask to process the image asynchronously
/**
* The actual AsyncTask that will asynchronously process the image.
*/
private class BitmapWorkerTask extends AsyncTask<Void, Void, BitmapDrawable> {
private Object mData;
private String imageID;
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(Object data, String imageID, ImageView imageView) {
mData = data;
this.imageID = imageID;
imageViewReference = new WeakReference<ImageView>(imageView);
}
/**
* Background processing.
*/
#Override
protected BitmapDrawable doInBackground(Void... params) {
//BEGIN_INCLUDE(load_bitmap_in_background)
if (BuildConfig.DEBUG) {
PrintLog.error(TAG, "doInBackground - starting work");
}
final String dataString = String.valueOf(mData);
Bitmap bitmap = null;
BitmapDrawable drawable = null;
// Wait here if work is paused and the task is not cancelled
synchronized (mPauseWorkLock) {
while (mPauseWork && !isCancelled()) {
try {
Log.e("pauseWork", "iswaiting -------------");
mPauseWorkLock.wait();
} catch (InterruptedException e) {
}
}
}
Log.e("pauseWork", "iswaiting end -------------");
// If the image cache is available and this task has not been cancelled by another
// thread and the ImageView that was originally bound to this task is still bound back
// to this task and our "exit early" flag is not set then try and fetch the bitmap from
// the cache
if (mImageCache != null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) {
bitmap = mImageCache.getBitmapFromDiskCache(imageID);
}
// If the bitmap was not found in the cache and this task has not been cancelled by
// another thread and the ImageView that was originally bound to this task is still
// bound back to this task and our "exit early" flag is not set, then call the main
// process method (as implemented by a subclass)
if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) {
bitmap = processBitmap(mData, imageID);
}
// If the bitmap was processed and the image cache is available, then add the processed
// bitmap to the cache for future use. Note we don't check if the task was cancelled
// here, if it was, and the thread is still running, we may as well add the processed
// bitmap to our cache as it might be used again in the future
if (bitmap != null) {
if (DeviceUtils.hasHoneycomb()) {
// Running on Honeycomb or newer, so wrap in a standard BitmapDrawable
drawable = new BitmapDrawable(mResources, bitmap);
} else {
// Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable
// which will recycle automagically
drawable = new RecyclingBitmapDrawable(mResources, bitmap);
}
if (mImageCache != null) {
mImageCache.addBitmapToCache(imageID, drawable);
}
}
if (BuildConfig.DEBUG) {
PrintLog.error(TAG, "doInBackground - finished work");
}
return drawable;
//END_INCLUDE(load_bitmap_in_background)
}
/**
* Once the image is processed, associates it to the imageView
*/
#Override
protected void onPostExecute(BitmapDrawable value) {
//BEGIN_INCLUDE(complete_background_work)
// if cancel was called on this task or the "exit early" flag is set then we're done
if (isCancelled() || mExitTasksEarly) {
value = null;
}
final ImageView imageView = getAttachedImageView();
if (value != null && imageView != null) {
if (BuildConfig.DEBUG) {
PrintLog.error(TAG, "onPostExecute - setting bitmap");
}
setImageDrawable(imageView, value);
}
//END_INCLUDE(complete_background_work)
}
#Override
protected void onCancelled(BitmapDrawable value) {
super.onCancelled(value);
synchronized (mPauseWorkLock) {
mPauseWorkLock.notifyAll();
}
}
/**
* Returns the ImageView associated with this task as long as the ImageView's task still
* points to this task as well. Returns null otherwise.
*/
private ImageView getAttachedImageView() {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask) {
return imageView;
}
return null;
}
}
Images are showing fine for the first time when installing the app, But after killing the app and loads the same page shows the image with the black/white background.
I have tried many examples and articles.. But nothing helped. I don't know why its coming with the black/white background after killing/exiting the app.
Your app is showing the image fine for the first time and displaying black background after re-openning app because "DisplayingBitmap" app caches the images to the filesystem using JPEG format. As you know JPEG doesn't support transparent mode.
Please open ImageCache class and look at the #68 line:
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
To avoid black background I changed this value to PNG format:
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.PNG;
UPDATE:
Also, you can set compressFormat to JPEG:
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(getActivity(), IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f);
cacheParams.compressFormat = Bitmap.CompressFormat.JPEG;
it works for me and hope it helps you.

Android -- Parsing an image from uri with hashmap gives me error

I need to parse the json output in my xml. Parsing is done but the image is not seen in the xml. Android log says this -
12-22 14:26:34.472: I/System.out(6037): resolveUri failed on bad bitmap uri: "base_url"/sites/default/files/pictures/picture-6175010166.jpg
Is there anything wrong in my below code can any body suggest me ?
HashMap<String, String> listview = new HashMap<String, String>();
String title = "";
String teaser="";
String createdon = "";
String profile_image = "";
try {
title = jListview.getString("title");
teaser = jListview.getString("teaser");
createdon = jListview.getString("created");
profile_image = jListview.getString("profile_image");
listview.put("title", title);
listview.put("teaser", teaser);
listview.put("created", createdon);
listview.put("profile_image", profile_image);
//listview.put("profile_image", picture);
} catch (JSONException e) {
System.out.println( "Bad Error" + e.toString());
e.printStackTrace();
}
return listview;
This is my main activity code where iam showing the result
try{
/** Getting the parsed data as a List construct */
lists = listJsonParser.parse(obj);
int imageCount = lists.size();
}
}catch(Exception e){
Log.d("Exception Main",e.toString());
}
/** Keys used in Hashmap */
String[] from = { "title","teaser","created","profile_image"};
/** Ids of views in listview_layout */
int[] to = { R.id.title,R.id.teaser,R.id.createdon,R.id.list_image};
/** Instantiating an adapter to store each items
* R.layout.listview_layout defines the layout of each item
*/
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.home_layout, from, to);
return adapter;
LoGcat:12-22 14:26:34.382: I/System.out(6037): resolveUri failed on bad bitmap uri:
your Error says Below:
12-22 14:26:34.472: I/System.out(6037): resolveUri failed on bad bitmap uri: "base_url"/sites/default/files/pictures/picture-6175010166.jpg
you need to download the image and then set it as bitmap. HERE is one of the many examples.
you can not set Direct web url to ImageView for setting ImageView src. you first create an custom Adapter by extending BaseAdapter for ListView and in getView you will need to first download image from Url as Bitmap and then set it to ImageView as:
public class CustomAdapter extends BaseAdapter{
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if(convertView == null){
LayoutInflater layoutInflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.
inflate(R.layout.layout_row, null);
}
Bitmap test = getbitpam(maptemp.get("profile_image"));
imgview=(ImageView) convertView.findViewById(R.id.img_list);
imgview.setImageBitmap(test);
return convertView;
}
}
//get image from server
public Bitmap getbitpam(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
}

How to make background thread for loading image in android ,gallery widget

I want to read images from URL and show it in android gallery widget.
so I wrote below code in onCreate() method .
list = GuideDAO.getAllImages(businessId);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setSpacing(2);
// Set the adapter to our custom adapter (below)
if(list.size() > 0)
{
g.setAdapter(new ImageAdapter(this,list));
}
This is my ImageAdapter
public class ImageAdapter extends BaseAdapter {
List<Images> glist = null;
private String url;
public ImageAdapter(Context c,List<Images> lst) {
mContext = c;
glist = lst;
int i=0;
for (Images id : glist) {
url = id.getImageURL(); // Getting URL
InputStream inStream = null;
if (url.startsWith("http")) {
url = url.replace(" ", "%20");
HttpURLConnection conn;
try {
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoInput(true);
conn.connect();
inStream = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
inStream = new FileInputStream(url);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true;
Bitmap b = BitmapFactory.decodeStream(inStream, null, options);
mImageCollection[i]=b;
i++;
}
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageBitmap(mImageCollection[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(136, 88));
return i;
}
private Context mContext;
private String[] mImageURLs = {};
private Bitmap[] mImageCollection = {};
}
This throw error because it not in Thread. How can I change this code so that URL reading and image loads in background?
So I have changed my ImageAdapter by using SmartImageView , which handles background thread and caching.
public class ImageAdapter extends BaseAdapter {
List<ImageGallery> glist = null;
private String url;
public ImageAdapter(Context c,List<ImageGallery> lst) {
mContext = c;
glist = lst;
int i=0;
al = new ArrayList<String>();
for (ImageGallery id : glist) {
al.add(id.getImageURL());
}
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("deepak", "getview gallery");
SmartImageView i = new SmartImageView(mContext);
i.setImageUrl(al.get(position));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(136, 88));
return i;
}
private Context mContext;
private String[] mImageURLs = {};
private ArrayList<String> al;
private Bitmap[] mImageCollection = {};
private Integer[] mImageIds = {};
}
But my getView() is not getting called now.
you can make use of Smart Image view. SmartImageView is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
Please refer the following link for more info https://github.com/loopj/android-smart-image-view .hope this may help u to accomplish ur task
I'd suggest writing an AsyncImageLoader class and having it handle image downloads from http. This way you can cache and manage everything on separate threads and have it set the image to the view once the loading is complete. Also you could use this class throughout the application if you want to download images elsewhere.
you could call something like mImageLoader.loadImage(myImageView, Url) in your adapter and it would drop it in once it was finished loading.
if you want more details let me know :)

Categories

Resources