Android images gridview - android

The code to display the images from sd card and whatsapp in the app but when I run the code the pictures are displayed but there are random whitespaces between photos and the photos are not of the same size. How do I resize the image ? Heres the code for the main activity:
import java.io.File;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ImageAdapter imageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
imageAdapter = new ImageAdapter(this);
gridview.setAdapter(imageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
File f=new File(Environment.getExternalStorageDirectory()+"/WhatsApp");
if(f.exists()){
String path=Environment.getExternalStorageDirectory()+"/WhatsApp/Media/WhatsApp Images";
File t=new File(path);
File[] fo=t.listFiles();
for(File fil : fo){
imageAdapter.add(fil.getAbsolutePath());
}
}
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
imageAdapter.add(file.getAbsolutePath());
}
}
Heres the code for image adapter:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context context;
ArrayList<String> imageList = new ArrayList<String>();
public ImageAdapter(Context c) {
context = c;
}
void add(String path){
imageList.add(path);
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100,100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(imageList.get(position), 100,100);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
As I said before, the code runs but the sizee of the image is not uniform and there are whitespaces. Please help me solve it.

try to set the scale type fit_xy
imageView.setScaleType(ImageView.ScaleType.FIT_XY);

Related

Grid view scrolling and image loading very slow

I am using the below code to populate a grid view with images, the image loading in the grid view is slow ,The Grid view scrolling is quite slow and stuck at some point. I am not sure what am i doing wrong.
No error messages are written in the logcat
package com.dbprox.tagpic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import java.io.File;
import java.util.ArrayList;
public class imagegallery extends AppCompatActivity {
private class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path){
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 185, 185);
if(bm!=null){
imageView.setImageBitmap(bm);
}
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public 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) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagegallery);
GridView gridview = (GridView) findViewById(R.id.imagegridview);
gridview.setFastScrollEnabled(true);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath =Environment.getExternalStorageDirectory().toString()+"/Pictures"; //ExternalStorageDirectoryPath + "/Pictures";
// Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
try {
myImageAdapter.add(file.getAbsolutePath());
}catch(Exception e) {
Log.d("TAG", "Error is " + e);}
}
}
}
All the image related operations you are performing are being done on the main thread which blocks the UI. You need to push all this work to a worker thread.
Alternatively use libraries like Glide or Picasso to do all the heavy lifting for you.
I had the same issue. Load your images using Picasso - Square and the application will run smoother than ever. Works for both images fetched from servers as well as drawable resources.

I want to set images into into gridview from SD card?

Below is my AppConstant.java
package com.domore.gridviewtutorial.helper;
import java.util.Arrays;
import java.util.List;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class AppContant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "MyPhotos";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
in this class i set the file extension which i load in my app
Here, is my utils class
package com.domore.gridviewtutorial.helper;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class Utils {
private Context context;
public Utils(Context context){
this.context=context;
}
public ArrayList<String> getFilePaths(){
ArrayList<String> filePaths=new ArrayList<String>();
File directory=new File(android.os.Environment.getExternalStorageDirectory()+File.separator+AppContant.PHOTO_ALBUM);
if(directory.isDirectory()){
File[] listFiles=directory.listFiles();
if(listFiles.length > 0 ){
for(int i=0;i<listFiles.length;i++){
String filePath=listFiles[i].getAbsolutePath();
if(IsSupportedFile(filePath)){
filePaths.add(filePath);
}
}
}
else{
Toast.makeText(
context,
AppContant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
}
else{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Error!");
alert.setMessage(AppContant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppContant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Here is my grid_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000">
</GridView>
i have Adapter class to load images
package com.domore.gridviewtutorial.adapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.view.View.OnClickListener;
/**
* Created by MY WORLD on 11/28/2015.
*/
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> _filePaths=new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity,ArrayList<String> _filePaths,int imageWidth){
this.activity=activity;
this._filePaths=_filePaths;
this.imageWidth=imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.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(this.activity);
}
else{
imageView=(ImageView)convertView;
}
Bitmap image=decodeFile(this._filePaths.get(position),imageWidth,imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
// Intent i = new Intent(activity, FullScreenViewActivity.class);
// i.putExtra("position", _postion);
// activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
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;
}
}
Here is my MainActivity.java
package com.domore.gridviewtutorial;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import com.domore.gridviewtutorial.adapter.GridViewImageAdapter;
import com.domore.gridviewtutorial.helper.AppContant;
import com.domore.gridviewtutorial.helper.Utils;
import java.util.ArrayList;
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.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);
}
}
I got error in mainActivity.java
here is my error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setNumColumns(int)' on a null object reference
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)
at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)
can anyone who help me to solve out this error i cannot able to understand.
Your gridView variable is null because you are recreating the a new variable gridView in your onCreate() method and your's activity's instance gridView variable is never get Initialized.
public class AndroidGridLayoutActivity extends AppCompatActivity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// initiated the gridView variable
gridView=(GridView)findViewById(R.id.grid_view);
utils=new Utils(this);
InitilizeGridLayout();
imagePaths=utils.getFilePaths();
adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppContant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppContant.NUM_OF_COLUMNS + 1) * padding)) / AppContant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppContant.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);
}
}

GridView bitmap images double upon refresh

I was following this Android tutorial to fix an "out of memory" error I kept getting when using Bitmap images in my GridView. The tutorial fixed this problem, but now when I click on other tabs in my activity, then return to my photo tab, the photos that are there, double. So for example, when I first load the tab, it pulls 3 photos from my SD card, and fills the rest with placeholder images. But then when I browse other tabs (4 altogether), I come back to find 6 images in my photo tab GridView, and the rest are placeholders.
Background info: each time my tab is visible, it loads images from the SD card, changes them into bitmaps, then my adapter puts those into each ImageView inside the GridView. Before I had the memory problem, it loaded fine, and did not double the images when I browsed other tabs then came back to the photo tab. It did however eventually crash with the memory problem, so I had to fix that.
How can I not load double upon a refresh to tab? Thanks for your help.
PhotoTab.java
package org.azurespot.cutecollection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import org.azurespot.R;
import java.io.File;
import java.util.ArrayList;
/**
* Created by mizu on 2/8/15.
*/
public class PhotoTab extends Fragment {
private GridView gridView;
File[] files;
ArrayList<PhotoGridItem> photoList = new ArrayList<>();
ArrayAdapter<PhotoGridItem> adapter;
Bitmap bitmap;
public PhotoTab() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.photo_tab, container, false);
// with fragments, make sure you include the rootView when finding id
gridView = (GridView) v.findViewById(R.id.photo_grid);
adapter = new GridViewPhotoAdapter(getActivity(), R.layout.photo_grid_item);
// Set the Adapter to GridView
gridView.setAdapter(adapter);
adapter.addAll(loadSDCard());
// add the default icons remaining, to GridView, if less than 24 files on SD card
for (int i = 0; i < (24 - photoList.size()); i++) {
adapter.add(new PhotoGridItem(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_photo_placeholder)));
}
adapter.notifyDataSetChanged();
return v;
}
private ArrayList<PhotoGridItem> loadSDCard() {
try {
// gets directory CutePhotos from sd card
File cutePhotosDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES), "CutePhotos");
// lists all files in CutePhotos, loads in Files[] array
files = cutePhotosDir.listFiles();
for (File singleFile : files) {
String filePath = singleFile.getAbsolutePath();
bitmap = decodeSampledBitmap(filePath, 270, 270);
photoList.add(new PhotoGridItem(bitmap));
}
} catch (Exception e) {
e.printStackTrace();
}
return photoList;
}
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;
}
public static Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
GridViewPhotoAdapter
package org.azurespot.cutecollection;
/**
* Created by mizu on 2/5/15.
*/
// package org.azurespot.cutecollection;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.azurespot.R;
/**
* Created by mizu on 2/5/15.
*/
public class GridViewPhotoAdapter extends ArrayAdapter<PhotoGridItem> {
public Context context;
private int resourceId;
Bitmap bm;
public GridViewPhotoAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
this.context = context;
this.resourceId = layoutResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.imageView = (ImageView) row.findViewById(R.id.photo_grid_view);
// stores holder with view
row.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
PhotoGridItem photoGridItem = getItem(position);
if (photoGridItem != null) {
bm = photoGridItem.getImage();
holder.imageView.setImageBitmap(bm);
// positioning the image in the GridView slot
holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.imageView.setLayoutParams(new LinearLayout.LayoutParams
(270, 270));
}
return row;
}
public class ViewHolder{
ImageView imageView;
}
}
Try this:
adap = null;
if (adap == null) {
adap = new Grid_View_Adatper(activity, arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();

android caching image from sdcard

i want to get image from sdcard in listview item i am able to show image but i want to cache that image so that i have smooth scroll can anyone please tell me how to cache image from sdcard i got the code but it show image from drawable but i want from sdcard
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
public class ListAdapter extends BaseAdapter {
Context context;
ArrayList<String> items;
private LruCache<String, Bitmap> mMemoryCache;
public ListAdapter(Context context, ArrayList<String> items) {
this.context = context;
this.items = items;
// Get memory class of this device, exceeding this amount will throw an
// OutOfMemory exception.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 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 int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
ImageView img = null;
if (convertView == null) {
img = new ImageView(context);
img.setScaleType(ImageView.ScaleType.CENTER_CROP);
img.setLayoutParams(new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
} else {
img = (ImageView) convertView;
}
int resId = context.getResources().getIdentifier(items.get(arg0),
"drawable", context.getPackageName());
loadBitmap(resId, img);
return img;
}
public void loadBitmap(int resId, ImageView imageView) {
if (cancelPotentialWork(resId, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
imageView.setBackgroundResource(R.drawable.empty_photo);
task.execute(resId);
}
}
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 static boolean cancelPotentialWork(int data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final int bitmapData = bitmapWorkerTask.data;
if (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;
}
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);
}
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
public int data = 0;
private final WeakReference<ImageView> imageViewReference;
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(Integer... params) {
data = params[0];
final Bitmap bitmap = decodeSampledBitmapFromResource(
context.getResources(), data, 100, 100);
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 (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, 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) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
}
I think you have to use AQuery. Download AQuery jar file from here. Add it into your Build path and then where you want to show your image, just display it like below:
AQuery aQuery=new AQuery(this);
File file = new File(YOUR IMAGE PATH);
aq.id(R.id.avatar).image(file, true,true); // that both true means you caching your images.

how to intergrate decode method to slideshow android

Im having problem integrating method for scaling images thru method on animate slide show. My goal is i have 10 large images that i will us for slide show, when i try to test 2 images its working perfectly, but when i try to use all the images it gives me error java.lang.OutOfMemoryError: bitmap size exceeds VM budget, i search on the internet, i came up to scale the images or use bitmap, several codes i got, but my problem is that how can i integrate the bitmap/decode codes that i got from the net to my slideshow script.
below is the script:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SliderActivity extends Activity {
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingImage;
private int[] IMAGE_IDS = {
R.drawable.pic1edited, R.drawable.pic2edited, R.drawable.pic3edited,
R.drawable.pic4edited, R.drawable.pic5edited
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set fullscreen and no title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_slider);
Bitmap image = BitmapFactory.decodeResource(getResources(), getResources().getIdentifier( "imagename" , "drawable", getPackageName()));
final Handler mhandler = new Handler();
//Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
#Override
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; //delay for 1 sec
int period = 8000; //repeat every 4 sec
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
mhandler.post(mUpdateResults);
}
}, delay, period);
}
//Helper method to start the animation on the splash screen
private void AnimateandSlideShow() {
slidingImage = (ImageView)findViewById(R.id.imageView1);
slidingImage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
slidingImage.setAnimation(rotateimage);
Log.d(getClass().getName(), "value = " + currentimageindex);
}
private Drawable resize(Drawable image) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 50, 50, false);
return new BitmapDrawable(bitmapResized);
}
private Bitmap decodeFile(File f){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_SIZE=70;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//override some buttons
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Log.d("button", new Integer(keyCode).toString());
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_CALL)) {
return false;
}
else if ((keyCode == KeyEvent.KEYCODE_MENU)) {
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}

Categories

Resources