I'm trying to develop an Android 3.1 tablet application.
This app will have a lot of images, and I have followed Processing Bitmaps Off the UI Thread tutorial, but I've done something wrong because I get:
java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.Gallery$LayoutParams
This is my code:
I set up Gallery on an Activity
mFactGallery = (Gallery)mView.findViewById(R.id.factGallery);
mFactGallery.setAdapter(new ImageGalleryAdapter(mActivity, ImageView.ScaleType.FIT_END, 180, 90));
ImageGalleryAdapter.java
public class ImageGalleryAdapter extends BaseAdapter
{
private ArrayList<String> mImagesPath;
private Context mContext;
private int mWidth;
private int mHeight;
public ArrayList<String> getmImagesPath()
{
return mImagesPath;
}
public void setmImagesPath(ArrayList<String> mImagesPath)
{
this.mImagesPath = mImagesPath;
}
public void addImage(String imagePath)
{
mImagesPath.add(imagePath);
}
public ImageGalleryAdapter(Context context, ImageView.ScaleType scaleType, int width, int height)
{
mContext = context;
mWidth = width;
mHeight = height;
mScaleType = scaleType;
mImagesPath = new ArrayList<String>();
}
#Override
public int getCount()
{
return mImagesPath.size();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// Get a View to display image data
ImageView imageView;
// if it's not recycled, initialize some attributes
if (convertView == null)
{
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else
{
imageView = (ImageView) convertView;
// Recicla el Bitmap.
Bitmap bm = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
if (bm != null)
bm.recycle();
}
String filePath = mImagesPath.get(position);
if (BitmapTools.cancelPotentialWork(filePath, imageView))
{
String[] params = {filePath, Integer.toString(mWidth), Integer.toString(mHeight)};
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable =
new AsyncDrawable(mContext.getResources(), filePath, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(params);
}
return imageView;
}
}
BitmapWorkerTask.java
public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap>
{
private final WeakReference<ImageView> imageViewReference;
public String imgPath = "";
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params)
{
imgPath = params[0];
int width = Integer.valueOf(params[1]).intValue();
int height = Integer.valueOf(params[2]).intValue();
return BitmapTools.decodeSampledBitmapFromDisk(imgPath, width, height);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap)
{
if (isCancelled())
{
bitmap = null;
}
if (imageViewReference != null && bitmap != null)
{
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask =
BitmapTools.getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask && imageView != null)
{
imageView.setImageBitmap(bitmap);
}
}
}
}
AsyncDrawable.java
public class AsyncDrawable extends BitmapDrawable
{
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, String filepath,
BitmapWorkerTask bitmapWorkerTask)
{
super(res, filepath);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask()
{
return bitmapWorkerTaskReference.get();
}
}
What am I doing wrong?
replace GridView.LayoutParams with Gallery.LayoutParams as follows, that will solve your problem
imageView.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
In ImageGalleryAdapter.java, this is wrong:
imageView.setLayoutParams(new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
Use the correct LayoutParams class, it should be
imageView.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
(The superclass of LayoutParams is Gallery instead of GridView)
Related
This is my code in which the image is not showing properly:
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.PhotoViewHolder> implements SizeCalculatorDelegate {
ArrayList<String> source_title = new ArrayList<String>();
private final double[] mImageAspectRatios;
private Context mContext;
public double aspectRatioForIndex(int index) {
// Precaution, have better handling for this in greedo-layout
if (index >= getItemCount()) return 1.0;
return mImageAspectRatios[getLoopedIndex(index)];
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
public PhotoViewHolder(ImageView imageView) {
super(imageView);
mImageView = imageView;
}
}
public MoviesAdapter(Context context, ArrayList<String> image) {
mContext = context;
this.source_title = image;
mImageAspectRatios = new double[source_title.size()];
// calculateImageAspectRatios();
}
#Override
public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
return new PhotoViewHolder(imageView);
}
#Override
public void onBindViewHolder(final PhotoViewHolder holder, int position) {
Picasso.with(mContext).load(source_title.get(position)).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
holder.mImageView.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d("bitmapfailed", "errorDrawable " + errorDrawable);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d("onPrepareLoad", "placeHolderDrawable " + placeHolderDrawable);
}
});
}
#Override
public int getItemCount() {
return source_title.size();
}
// private void calculateImageAspectRatios() {
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
//
// for (int i = 0; i < source_title.size(); i++) {
//
// int value = Integer.parseInt(source_title.get(i));
//
// BitmapFactory.decodeResource(mContext.getResources(), value, options);
// mImageAspectRatios[i] = options.outWidth / (double) options.outHeight;
// }
// }
// Index gets wrapped around <code>Constants.IMAGES.length</code> so we can loop content.
private int getLoopedIndex(int index) {
return index % source_title.size(); // wrap around
}
}
and this is the original demo code
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.PhotoViewHolder> implements SizeCalculatorDelegate {
private static final int IMAGE_COUNT = 500; // number of images adapter will show
private final int[] mImageResIds = Constants.IMAGES;
private final double[] mImageAspectRatios = new double[mImageResIds.length];
private Context mContext;
#Override
public double aspectRatioForIndex(int index) {
// Precaution, have better handling for this in greedo-layout
if (index >= getItemCount()) return 1.0;
Log.d("index", mImageAspectRatios + "");
return mImageAspectRatios[getLoopedIndex(index)];
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
public PhotoViewHolder(ImageView imageView) {
super(imageView);
mImageView = imageView;
}
}
public PhotosAdapter(Context context) {
mContext = context;
calculateImageAspectRatios();
}
#Override
public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
return new PhotoViewHolder(imageView);
}
#Override
public void onBindViewHolder(PhotoViewHolder holder, int position) {
Picasso.with(mContext)
.load(mImageResIds[getLoopedIndex(position)])
.into(holder.mImageView);
}
#Override
public int getItemCount() {
return IMAGE_COUNT;
}
private void calculateImageAspectRatios() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
for (int i = 0; i < mImageResIds.length; i++) {
BitmapFactory.decodeResource(mContext.getResources(), mImageResIds[i], options);
mImageAspectRatios[i] = options.outWidth / (double) options.outHeight;
}
}
// Index gets wrapped around <code>Constants.IMAGES.length</code> so we can loop content.
private int getLoopedIndex(int index) {
return index % Constants.IMAGES.length; // wrap around
}
}
in this demo the image shows properly but in my demo images not show, tha data from source_title arraylist is showing properly but this demo does not work properly, as I use onBindViewHolder method it goes into onPrepareLoad exception called null value of placeHolderDrawable...
Is there any solution to use it or some other method or way to solve this issue?
Sorry for my english and thnx in advance...
//The Path where my images are saving
/storage/emulated/0/Pictures/CameraExample/JPEG_20150107_152640.jpeg
//This is one of the file path.
//I need to sort images like last taken photo as the first one to display //inside the grid view as of now images are displayed, recent photo at the //last.
Below is my code
public class ImageAdapter extends BaseAdapter{
private Context context;
private int imageWidth;
private Activity activity;
ArrayList<String> itemList = new ArrayList<String>();
Bitmap bitmap;
public ImageAdapter(Activity activity,ArrayList<String> itemList,int imageWidth) {
this.activity = activity;
this.itemList = itemList;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.itemList.size();
}
void add(String path) {
itemList.add(path);
}
#Override
public Object getItem(int position) {
return this.itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
}
else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
imageView.setOnClickListener( new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements View.OnClickListener {
int position;
public OnImageClickListener(int position){
this.position = position;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ImageDisplayActivity.class);
intent.putExtra("position", position);
Log.d("ImageAdapter","Intent.putExtra ");
activity.startActivity(intent);
}
}
public Bitmap decodeFile(String path, int reqWidth, int reqHeight) {
try {
File f = new File(path);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = reqWidth;
final int REQUIRED_HEIGHT = reqHeight;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH && o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
// And Finally when I scroll my grid view . Scrolling is not so smooth. Please help me in solving two problems.
// My GridView Activity Class
public class GridViewActivity extends Activity {
private ImageAdapter imageAdapter;
private HelperUtils utils;
private ArrayList<String> itemList = new ArrayList<String>();
private GridView gridView;
private int columnWidth;
private Activity activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, HelperAppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((HelperAppConstant.NUM_OF_COLUMNS + 1) * padding)) / HelperAppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(HelperAppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
Remove the Collections.sort(itemList); from your getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
Log.d("ImageAdapter","Inside the if condition");
imageView = new ImageView(activity);
}
else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
// bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
bitmap = decodeFile(getItem(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
return imageView;
}
Sort the list just before you populate your grid view in your onCreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
Collections.sort(itemList);
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
You could follow the example in this link by creating a list of items that contains the image file path and the image bitmap. This way, you wouldn't have to decode the bitmap everytime getView is called. You could just decode it once before you populate the gridview.
Since the images are sorted in ascending order, you can replace you getItem method with the one below:
#Override
public Object getItem(int position) {
return this.itemList.get(itemList.size() - 1 - position);
}
I updated the getView method. You should use getItem(position) instead of itemList.get(position) to decode the bitmap.
For making your scroll smooth you have to display the images with Picasso library, I had the same issue !
first,sorry for my English.
I'm new in Android,I have a activity to show news,the content is from web server and the content contains images.I used a TextView to display it and I want to the images fit the sreen,so I wrote these codes.
public class CustomImageGetter implements Html.ImageGetter {
private Activity context;
private Picasso picasso;
private TextView textView;
public CustomImageGetter(Activity context, Picasso picasso, TextView textView) {
this.context = context;
this.picasso = picasso;
this.textView = textView;
}
#Override
public Drawable getDrawable(final String source) {
final PlaceHolderBitmapDrawable result = new PlaceHolderBitmapDrawable();
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(Void... params) {
try {
return picasso
.load(Config.WEB_SERVER + source.substring(1))
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
try {
BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
DisplayMetrics metrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = width * bitmap.getHeight() / bitmap.getWidth();
drawable.setBounds(0, 0, width, height);
result.setDrawable(drawable);
result.setBounds(0, 0, width, height);
textView.setText(textView.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}.execute((Void) null);
return result;
}
private static class PlaceHolderBitmapDrawable extends BitmapDrawable {
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
if (drawable != null)
drawable.draw(canvas);
}
public void setDrawable(Drawable drawable) {
this.drawable = drawable;
}
}
}
The image's width is correct but the height is too short in android 4.4 but in android L is normal.
The left picture runs in android 4.4 and the right runs in android L.
How can I fix the problem?
I try to create a gallery with a grid view, now I have a list that load the images in an asynnc way, is so smooth but the problem is that every time a cell is redraw also the image is redraw, I use cache but nothing, this is my code:
public class GalleryFragment extends Fragment {
View view;
GridView gridview;
ImageAdapter myImageAdapter;
Bitmap mPlaceHolderBitmap;
ArrayList<String> arrayPhotos = new ArrayList<String>();
private LruCache<String, Bitmap> mMemoryCache;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.gallery_layout, container, false);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityManager am = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
int memClass = am.getMemoryClass();
final int cacheSize = 1024 * 1024 * memClass / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than number
// of items.
return bitmap.getByteCount();
}
};
}
#Override
public void onStart (){
super.onStart();
gridview = (GridView) view.findViewById(R.id.gridView);
gridview.setAdapter(new ImageAdapter(getActivity()));
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
arrayPhotos.add(file.getAbsolutePath());
}
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return (Bitmap) mMemoryCache.get(key);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return arrayPhotos.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
String imageKey = arrayPhotos.get(position);
Bitmap bm = getBitmapFromMemCache(imageKey);
if (bm == null){
loadBitmap(imageKey, i);
}
else {
i.setImageBitmap(bm);
}
return imageView;
}
}
static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
public void loadBitmap(String resId, ImageView imageView) {
if (cancelPotentialWork(resId, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(resId);
}
}
public static boolean cancelPotentialWork(String data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.path;
// If bitmapData is not yet set or it differs from the new data
if (bitmapData == "" || bitmapData != data) {
// Cancel previous task
bitmapWorkerTask.cancel(true);
}
else {
// The same work is already in progress
return false;
}
}
// No task associated with the ImageView, or an existing task was cancelled
return true;
}
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String path;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
path = params[0];
Bitmap bitmap = decodeSampledBitmapFromResource(path, 300, 300);
addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
return bitmap;
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask && imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public static Bitmap decodeSampledBitmapFromResource(String filePath,int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
where is the mistake?
I am new to android. I am displaying images in gridview by using AsyncTask. But there are some issues like:
1: onScroll AsyncTask tasks gets call again.
2: Images are not displaying correctly ( Once I scroll it shows top image and load the original latter).
here is my code:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListRowHolder listRowHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.ll_sponsor_list_item,
parent, false);
listRowHolder = new ListRowHolder();
listRowHolder.imgSponsor = (ImageView) convertView
.findViewById(R.id.imggrid_item_image);
convertView.setTag(listRowHolder);
} else {
listRowHolder = (ListRowHolder) convertView.getTag();
}
try {
task = new BitmapWorkerTask(listRowHolder.imgSponsor);
task.image_path = ImageName.get(position);
task.execute(1);
} catch (Exception e) {
if (thisLogger != null) {
thisLogger.error(e.toString());
thisLogger.error("\r\n");
}
}
return convertView;
}
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String image_path;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(Integer... params) {
try {
while (running) {
Bitmap picture = BitmapFactory.decodeFile(image_path);
int width = picture.getWidth();
int height = picture.getHeight();
float aspectRatio = (float) width / (float) height;
int newWidth = 98;
int newHeight = (int) (98 / aspectRatio);
Log.v("ImageList", "L");
return picture = Bitmap.createScaledBitmap(picture,
newWidth, newHeight, true);
}
} catch (Exception e) {
if (thisLogger != null) {
thisLogger.error(e.toString());
thisLogger.error("\r\n");
}
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
Please let me know whats wrong here.