Grid view scrolling and image loading very slow - android

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.

Related

Android images gridview

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

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.

Loading images from assets

i have been working on wallpaper app for a while and it's almost done but the size of app is pretty big cause i use .png extension so currently i'm trying to load jpg via assets instead of png in res
i tried to implement this answer
Images from Assets folder in a GridView
i get an error while loading the imageadapter
02-21 23:13:05.883: E/AndroidRuntime(17634): FATAL EXCEPTION: main
02-21 23:13:05.883: E/AndroidRuntime(17634): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.imagieview05/com.example.imagieview05.MainActivity}: java.lang.NullPointerException
here is my code
public class MainActivity extends Activity {
private GridView mGridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView) findViewById(R.id.GridView1);
Bitmap[] mBitArray = new Bitmap[4];
try {
mBitArray[0] = getBitmapFromAssets("g1p2.jpg");
mBitArray[1] = getBitmapFromAssets("g1p1.jpg");
mBitArray[2] = getBitmapFromAssets("g1p3.jpg");
mBitArray[3] = getBitmapFromAssets("g1p4.jpg");
} catch (Exception e) {
e.printStackTrace();
}
mGridView.setAdapter(new ImageAdapter(this ,mBitArray));
}
public Bitmap getBitmapFromAssets (String filename) throws IOException{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(filename);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private Bitmap[] mImageArray;
public GallaryAdapter(Context c, Bitmap[] mBitArray) {
c = mContext;
mBitArray = mImageArray;
}
public int getCount() {
return mImageArray.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mImageArray[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(mContext);
imgView.setImageBitmap(mImageArray[position]);
//put black borders around the image
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setLayoutParams(new GridView.LayoutParams(120, 120));
return imgView;
}
here is the original working code without Assets reference
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.GridView1);
gridView.setAdapter(new ImageAdapter(this));
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
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) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.g1p1, R.drawable.g1p2,
R.drawable.g1p3, R.drawable.g1p4,
R.drawable.g1p5, R.drawable.g1p6,
R.drawable.g1p22, R.drawable.g1p33,
R.drawable.g1p44, R.drawable.g1p55,
R.drawable.g1p5, R.drawable.g1p6,
R.drawable.g1p22, R.drawable.g1p33,
R.drawable.g1p44, R.drawable.g1p55
};
};
thanks for help in advance
mBitArray = mImageArray; its pointing mBitArray toward mImageArray witch is nothing, maybe?
i dont think it really matters if you use jpeg or png memory wise anyway, in the program its going to completely uncompress the jpeg anyway
I wrote the code loader images from assets folder following the example code
private Bitmap decodeStreamFromAssets(String path, int reqWidth, int reqHeight) {
InputStream ims = null;
try {
ims = getAssets().open(path);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(ims, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(ims, null, options);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (ims != null) {
try {
ims.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private 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;
}
Load *.jpg work, but *.png not work for ex.
IMG // work
Bitmap bitmap = decodeStreamFromAssets("test.jpg", 64, 64);
if(bitmap1 != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Log.e("ERROR", "error");
}
PNG // not work ( is error )
Bitmap bitmap = decodeStreamFromAssets("test.png", 64, 64);
if(bitmap1 != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Log.e("ERROR", "error");
}

How can I show the full size of Image?

I'm new here and new in programming Android. I found this example (below is the example) on a site in internet, It's a great tutorial! What do I want to achieve is when once I clicked a picture on the GridView I want to show the full size of the Image.
public class MainActivity extends Activity {
public 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(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220,
220);
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_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG)
.show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
myImageAdapter.add(file.getAbsolutePath());
}
}
}
Pass the image to the other activity to show it in full view.
To pass the image from Your main Activity. USe following code:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
ImageView img = ia.getView(position, v, parent);
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
Intent intent = new Intent(HelloGridView.this,
Imageviewer.class);
Bundle bundle = new Bundle();
//bundle.putParcelable("image", bmap);
String par=myimageadpter.getpath(position);
bundle.putParcelable("imagepath", par);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
});
In other activity use this code to show the passed image:
Bundle bundle = this.getIntent().getExtras();
bmp=bundle.getParcelable("image");
ImageView img=(ImageView) findViewById(R.id.imageView1);
d =new BitmapDrawable(bmp);
img.setImageBitmap(bmp);
If you pass path. the second activity look like this:
Bundle bundle = this.getIntent().getExtras();
String s=bundle.getParcelable("imagepath");
Bitmap Imagefrompath = BitmapFactory.decodeFile(s);
ImageView img=(ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(Imagefrompath );

Categories

Resources