I am new to coding and never worked with it before! We are working with Android and Java eclipse, it's a school project. Now I am working with a band application were I am supposed to create the gallery. This I managed, but to create a function were the user can set an image to a wallpaper, I couldn't. I need some help with this! I believe I found good code, but I don't know how to implement it in my work.
Does anyone know how I should connect these to each other? Really thankful for help,
Sandra
My Gallery code:
package com.Lavin;
import com.Lavin.R;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.WallpaperManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
public class Lavin extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.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.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.lavin_thumb_0, R.drawable.lavin_thumb_1,
R.drawable.lavin_thumb_2, R.drawable.lavin_thumb_3,
R.drawable.lavin_thumb_4, R.drawable.lavin_thumb_5,
R.drawable.lavin_thumb_6, R.drawable.lavin_thumb_7,
R.drawable.lavin_thumb_8, R.drawable.lavin_thumb_9,
R.drawable.lavin_thumb_10, R.drawable.lavin_thumb_11,
R.drawable.lavin_thumb_12};
private Integer[] mImageIds = {
R.drawable.lavin_0, R.drawable.lavin_1, R.drawable.lavin_2,
R.drawable.lavin_3, R.drawable.lavin_4, R.drawable.lavin_5,
R.drawable.lavin_6, R.drawable.lavin_7, R.drawable.lavin_8,
R.drawable.lavin_9, R.drawable.lavin_10,
R.drawable.lavin_11, R.drawable.lavin_12};
}
My Wallpaper code:
package com.Lavin;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Wallpaper extends Activity {
final static private int[] mColors =
{Color.BLUE, Color.GREEN, Color.RED, Color.LTGRAY, Color.MAGENTA, Color.CYAN,
Color.YELLOW, Color.WHITE};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
final Drawable wallpaperDrawable = wallpaperManager.getDrawable();
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setDrawingCacheEnabled(true);
imageView.setImageDrawable(wallpaperDrawable);
Button randomize = (Button) findViewById(R.id.randomize);
randomize.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
int mColor = (int) Math.floor(Math.random() * mColors.length);
wallpaperDrawable.setColorFilter(mColors[mColor], PorterDuff.Mode.MULTIPLY);
imageView.setImageDrawable(wallpaperDrawable);
imageView.invalidate();
}
});
Button setWallpaper = (Button) findViewById(R.id.setwallpaper);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
try {
wallpaperManager.setBitmap(imageView.getDrawingCache());
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
public class LoadImagesFromSDCardActivity extends Activity implements
OnItemClickListener {
/**
* Grid view holding the images.
*/
private GridView sdcardImages;
/**
* Image adapter for the grid view.
*/
private ImageAdapter imageAdapter;
/**
* Display used for getting the width of the screen.
*/
private Display display;
/**
* Creates the content view, sets up the grid, the adapter, and the click listener.
*
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Request progress bar
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.sdcard);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
/**
* Free up bitmap related resources.
*/
protected void onDestroy() {
super.onDestroy();
final GridView grid = sdcardImages;
final int count = grid.getChildCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
}
/**
* Setup the grid view.
*/
private void setupViews() {
sdcardImages = (GridView) findViewById(R.id.sdcard);
sdcardImages.setNumColumns(display.getWidth()/95);
sdcardImages.setClipToPadding(false);
sdcardImages.setOnItemClickListener(LoadImagesFromSDCardActivity.this);
imageAdapter = new ImageAdapter(getApplicationContext());
sdcardImages.setAdapter(imageAdapter);
}
/**
* Load images.
*/
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if (data == null) {
new LoadImagesFromSDCard().execute();
} else {
final LoadedImage[] photos = (LoadedImage[]) data;
if (photos.length == 0) {
new LoadImagesFromSDCard().execute();
}
for (LoadedImage photo : photos) {
addImage(photo);
}
}
}
/**
* Add image(s) to the grid view adapter.
*
* #param value Array of LoadedImages references
*/
private void addImage(LoadedImage... value) {
for (LoadedImage image : value) {
imageAdapter.addPhoto(image);
imageAdapter.notifyDataSetChanged();
}
}
/**
* Save bitmap images into a list and return that list.
*
* #see android.app.Activity#onRetainNonConfigurationInstance()
*/
#Override
public Object onRetainNonConfigurationInstance() {
final GridView grid = sdcardImages;
final int count = grid.getChildCount();
final LoadedImage[] list = new LoadedImage[count];
for (int i = 0; i < count; i++) {
final ImageView v = (ImageView) grid.getChildAt(i);
list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
}
return list;
}
/**
* Async task for loading the images from the SD card.
*
* #author Mihai Fonoage
*
*/
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
/**
* Load images from SD Card in the background, and display each image on the screen.
*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Object doInBackground(Object... params) {
//setProgressBarIndeterminateVisibility(true);
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
//No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
//Error fetching image, try to recover
}
}
cursor.close();
return null;
}
/**
* Add a new LoadedImage in the images grid.
*
* #param value The image.
*/
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
/**
* Set the visibility of the progress bar to false.
*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Adapter for our image files.
*
* #author Mihai Fonoage
*
*/
class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
public ImageAdapter(Context context) {
mContext = context;
}
public void addPhoto(LoadedImage photo) {
photos.add(photo);
}
public int getCount() {
return photos.size();
}
public Object getItem(int position) {
return photos.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageBitmap(photos.get(position).getBitmap());
return imageView;
}
}
/**
* A LoadedImage contains the Bitmap loaded for the image.
*/
private static class LoadedImage {
Bitmap mBitmap;
LoadedImage(Bitmap bitmap) {
mBitmap = bitmap;
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/**
* When an image is clicked, load that image as a puzzle.
*/
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int columnIndex = 0;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null);
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
String imagePath = cursor.getString(columnIndex);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap, parent.getWidth(), parent.getHeight(), true);
bitmap.recycle();
//Display bitmap (useThisBitmap)
}
catch (Exception e) {
//Try to recover
}
finally {
try {
if (bis != null) {
bis.close();
}
if (is != null) {
is.close();
}
cursor.close();
projection = null;
} catch (Exception e) {
}
}
}
}
}
The sdcard.xml file:
<GridView
android:id="#+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />
Related
Well, I'm developing a Gallery App for android. However, when I scroll down, the images still take a while to load. Why is that? I'm already loading a scaled down version of the images and using ViewHolder as well. Below is the code for the MainActivity.java. Any help would be highly appreciated. Thanks.
PS: Should I use libraries like Universal Image Loader? Will that make any difference to the problem that I'm facing currently?
package com.example.om.imageviewer3;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
String[]imgLoc;
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
File targetDirector;
ImageAdapter myTaskAdapter;
public AsyncTaskLoadFiles(ImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera/";
targetDirector = new File(targetPath);
myTaskAdapter.clear();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
int i=0;
for(File file:files){
i++;
}
int len=i;
imgLoc=new String[len];
i=0;
for(File file:files){
imgLoc[i]=file.getAbsolutePath();
i++;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
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);
}
void clear() {
itemList.clear();
}
void remove(int index){
itemList.remove(index);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//getView load bitmap ui thread
/*
#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;
}
*/
//getView load bitmap in AsyncTask
#Override
public View getView(final 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(500,250));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(20,0,20,0);
ViewHolder dataHolder=new ViewHolder();
dataHolder.image=imageView;
imageView.setTag(dataHolder);
convertView = imageView;
}
ViewHolder holder=(ViewHolder)convertView.getTag();
holder.image.setImageBitmap(null);
holder.position=position;
//imageView = (ImageView) convertView;
//Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 500, 250);
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//Not work for me!
if (v.position == position) {
// If this item hasn't been recycled already,
// show the image
v.image.setImageBitmap(result);
}
//v.image.setImageBitmap(result);
}
}.execute(holder);
//imageView.setImageBitmap(bm);
//return imageView;
return convertView;
}
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;
}
class ViewHolder {
ImageView image;
int position;
}
}
ImageAdapter myImageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
//grid.seto
/*
* Move to asyncTaskLoadFiles 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()); }
*/
myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
myAsyncTaskLoadFiles.execute();
//gridview.setOnItemClickListener(myOnItemClickListener);
/*Button buttonReload = (Button)findViewById(R.id.reload);
buttonReload.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Cancel the previous running task, if exist.
myAsyncTaskLoadFiles.cancel(true);
//new another ImageAdapter, to prevent the adapter have
//mixed files
myImageAdapter = new ImageAdapter(MainActivity.this);
gridview.setAdapter(myImageAdapter);
myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
myAsyncTaskLoadFiles.execute();
}});*/
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
seeImage(view,position);
}
});
}
public void seeImage(View v, int position){
Intent intent=new Intent(this.getApplicationContext(), SeeImage.class);
intent.putExtra("getimgloc",""+imgLoc[position]);
startActivity(intent);
}
}
Edit: Ok, so here's the code after the update(As helped by #Raiv)
package com.example.om.imageviewer3;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
String[]imgLoc;
private LruCache<String,Bitmap> mMemoryCache;
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
File targetDirector;
ImageAdapter myTaskAdapter;
public AsyncTaskLoadFiles(ImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera/";
targetDirector = new File(targetPath);
myTaskAdapter.clear();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
int i=0;
for(File file:files){
i++;
}
int len=i;
imgLoc=new String[len];
i=0;
for(File file:files){
imgLoc[i]=file.getAbsolutePath();
i++;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
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);
}
void clear() {
itemList.clear();
}
void remove(int index){
itemList.remove(index);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//getView load bitmap ui thread
/*
#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;
}
*/
//getView load bitmap in AsyncTask
#Override
public View getView(final 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.FIT_CENTER);
imageView.setPadding(20,0,20,0);
ViewHolder dataHolder=new ViewHolder();
dataHolder.image=imageView;
imageView.setTag(dataHolder);
convertView = imageView;
}
ViewHolder holder=(ViewHolder)convertView.getTag();
holder.image.setImageBitmap(null);
holder.position=position;
//imageView = (ImageView) convertView;
//Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
//String a=itemList.
String hash= getMD5Hash(itemList.get(position))+".jpg";
Bitmap bm=null;
synchronized (mMemoryCache){
bm=mMemoryCache.get(hash);
}
if(bm==null){
File cacheFile=new File(Environment.getDownloadCacheDirectory(),hash);
if(cacheFile.exists()){
bm=BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
if(bm!=null){
synchronized (mMemoryCache){
bm=mMemoryCache.put(hash,bm);
}
return bm;
}
}
}else{
return bm;
}
if(bm==null){
bm=decodeSampledBitmapFromUri(itemList.get(position),220,250);
FileOutputStream out = null;
try {
out = new FileOutputStream(Environment.getDownloadCacheDirectory());
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bm;
}
public String getMD5Hash(String a){//throws NoSuchAlgorithmException{
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(a.getBytes());
return new BigInteger(1, m.digest()).toString(16);
}catch(NoSuchAlgorithmException e){}
return "Error";
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//Not work for me!
if (v.position == position) {
// If this item hasn't been recycled already,
// show the image
v.image.setImageBitmap(result);
}
//v.image.setImageBitmap(result);
}
}.execute(holder);
//imageView.setImageBitmap(bm);
//return imageView;
return convertView;
}
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;
}
class ViewHolder {
ImageView image;
int position;
}
}
ImageAdapter myImageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
//grid.seto
/*
* Move to asyncTaskLoadFiles 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()); }
*/
myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
myAsyncTaskLoadFiles.execute();
//gridview.setOnItemClickListener(myOnItemClickListener);
/*Button buttonReload = (Button)findViewById(R.id.reload);
buttonReload.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Cancel the previous running task, if exist.
myAsyncTaskLoadFiles.cancel(true);
//new another ImageAdapter, to prevent the adapter have
//mixed files
myImageAdapter = new ImageAdapter(MainActivity.this);
gridview.setAdapter(myImageAdapter);
myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
myAsyncTaskLoadFiles.execute();
}});*/
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
seeImage(view,position);
}
});
final int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
final int cacheSize=maxMemory/8;
mMemoryCache=new LruCache<String, Bitmap>(cacheSize){
#Override
protected int sizeOf(String key,Bitmap bitmap){
return bitmap.getByteCount()/1024;
}
};
}
public void seeImage(View v, int position){
Intent intent=new Intent(this.getApplicationContext(), SeeImage.class);
intent.putExtra("getimgloc",""+imgLoc[position]);
startActivity(intent);
}
}
You should use some image caching for that.
First - don't reload your images every time, save them on disk once loaded. for example: a) create hash for every link you use, and save images by hash in cache folder. b) on loading, check by hash for file existance and if it exists use cached file.Also you may add in-memory caching for further speed-up.
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
String hash = Utils.getMD5Hash(itemList.get(position))+".jpg"// implement hash yourself
Bitmap bm = null;
synchronized (mMemoryCache) {
bm = mMemoryCache.get(hash);
return bm;
}
File cacheFile = new File( Environment.getDownloadCacheDirectory(),hash);
if(bm==null)
{
if(cacheFile.exists()){
bm = /*try to load from cache dir*/
if(bm!=null){
synchronized (mMemoryCache) {
bm = mMemoryCache.put(hash,bm);
}
return bm;
}
}
}else
{
return bm;
}
if(bm==null)
{
bm =decodeSampledBitmapFromUri(itemList.get(position), 500, 250);
/*save on disk*/
/*save in mem cache*/
return bm;
}
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//Not work for me!
if (v.position == position) {
// If this item hasn't been recycled already,
// show the image
v.image.setImageBitmap(result);
}
//v.image.setImageBitmap(result);
}
}.execute(holder);
in-memory cache implementation below, look for docs
here
private LruCache<String, Bitmap> mMemoryCache;
...
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
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) {
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
md5 hash implementation:
String getMD5(String data){
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(data.getBytes());
return new BigInteger(1, m.digest()).toString(16);
}
load bitmap
bm = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
save bitmap here
In grid view I’ve selected two images(Checkbox) and I’ve scrolled down the view to the bottom and somehow these selections are displayed on completely different images.
This is my Code.Please help me on this
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class GridViewImageAdapter extends BaseAdapter {
private static final float ASPECT_RATIO = 10/16f; //To show grid view items as rectangles instead of squares
private Activity mActivity;
private ArrayList<File> mFiles = new ArrayList<File>();
private ArrayList<File> mSelectedFiles = new ArrayList<File>();
private int mImageWidth;
private File mCurrentFolder;
private PresentationUtils mUtils;
public GridViewImageAdapter gridViewAdpter = this;
Resources resources;
public GridViewImageAdapter(Activity activity, File folderToScan,
int imageWidth) {
this.mActivity = activity;
this.mCurrentFolder = folderToScan;
this.mImageWidth = imageWidth;
this.mFiles = new PresentationUtils(mActivity).getFiles(folderToScan.getAbsolutePath(), true);
mUtils = new PresentationUtils(mActivity);
}
#Override
public int getCount() {
return this.mFiles.size();
}
#Override
public Object getItem(int position) {
return this.mFiles.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
final CheckBox gViewItemSelBt;
TextView label;
View v;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view_item, null);
} else {
v = convertView;
}
imageView = (ImageView) v.findViewById(R.id.image);
label = (TextView) v.findViewById(R.id.label);
gViewItemSelBt = (CheckBox) v.findViewById(R.id.imageSelector);
// get screen dimensions
Bitmap image = null;
if(!mFiles.get(position).isDirectory()){
image = decodeFile(mFiles.get(position).getAbsolutePath(), mImageWidth,
mImageWidth);
final int pos = position;
gViewItemSelBt.setVisibility(View.VISIBLE);
gViewItemSelBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(gViewItemSelBt.isChecked()){
mSelectedFiles.add(mFiles.get(pos));
}else{
mSelectedFiles.remove(mFiles.get(pos));
};
}
});
} else {
image = BitmapFactory.decodeResource(mActivity.getResources(),
R.drawable.ic_folder);
/*File latestFile = mFiles.get(mFiles.size() -1);
image = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_folder );
image = decodeFile(latestFile.getAbsolutePath(), mImageWidth,
mImageWidth);*/
gViewItemSelBt.setVisibility(View.GONE);
}
int height = (int) (mImageWidth*ASPECT_RATIO);
imageView.setImageBitmap(image);
imageView.setLayoutParams(new RelativeLayout.LayoutParams(mImageWidth, height));
imageView.setOnClickListener(new OnImageClickListener(position));
if(mUtils.getSharedValue(mActivity, mFiles.get(position).getName()).length() > 0 ){
mActivity.getActionBar().setTitle(mCurrentFolder.getName());
label.setText(mUtils.getSharedValue(mActivity, mFiles.get(position).getName()));
}
else{
label.setText(mFiles.get(position).getName());
mActivity.getActionBar().setTitle("Albums");
}
return v;
}
class OnImageClickListener implements OnClickListener {
int mPostion;
// constructor
public OnImageClickListener(int position) {
this.mPostion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
if(mFiles.get(mPostion).isDirectory()){
//We just need to go one level deeper and load images from there
mCurrentFolder = new File(mFiles.get(mPostion).getAbsolutePath());
loadFiles();
mActivity.invalidateOptionsMenu();
}else{
//An image has been clicked, open in full screen view
Intent i = new Intent(mActivity, FullScreenViewActivity.class);
i.putExtra(AppConstant.INTENT_DATA_POSITION, mPostion);
i.putExtra(AppConstant.INTENT_DATA_FOLDER, mCurrentFolder.getAbsolutePath());
i.putExtra(AppConstant.INTENT_DATA_IMAGENAME, mFiles.get(mPostion).getName());
mActivity.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;
if(!f.isDirectory())
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;
if(!f.isDirectory()){
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}else{
return null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public void goBackOneLevel() {
mCurrentFolder = mCurrentFolder.getParentFile();
mActivity.getActionBar().setTitle("Albums");
loadFiles();
}
public boolean isAtRootFolder() {
File rootImageFolder = new File(mActivity.getFilesDir().getPath()
+ File.separator + AppConstant.PHOTO_GALLERY_ROOT_FOLDER);
if(mCurrentFolder.compareTo(rootImageFolder) == 0){
return true;
}
return false;
}
public void loadFiles() {
mFiles = mUtils.getFiles(mCurrentFolder.getAbsolutePath(), true);
notifyDataSetChanged();
}
public void createAlbum(String albumName){
mUtils.moveFiles(this.mSelectedFiles, albumName);
}
public void deleteFile(){
mUtils.deleteFile(this.mSelectedFiles);
}
public boolean isFileSelected(){
notifyDataSetChanged();
if(this.mSelectedFiles.isEmpty()){
return false;
}else{
return true;
}
}
}
See These Links,
1:- http://www.thaicreate.com/mobile/android-gridview-checkbox.html
2:- http://yan-note.blogspot.in/2012/11/android-gridview-checkbox.html
3:- http://nepstare.blogspot.in/2013/12/custom-gridview-with-checkbox-in-android.html
4:- http://vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/
if you still not able to resolve, let me know.
In my app i want to get the Images from SD card to a specific position and i need to display in gallery,
The code i used is attaching
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
try{
String filepath = "/sdcard/data/Crak/";
File imagefile = new File(filepath +"abcd.jpg" );
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
System.out.println("cnvrtn");
}
catch(Exception e) {
e.printStackTrace();
}
final Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
position = 0;
imgView = (ImageView) findViewById(R.id.ImageView01);
imgView.setImageBitmap(bitmapimage);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
imgView.setImageBitmap(bitmapimage);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View paramView) {
// TODO Auto-generated method stub
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
#SuppressWarnings("null")
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return data.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 imgView = new ImageView(cont);
final Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
imgView.setImageBitmap(bitmapimage);;
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
The problems are
1)How can i get all image in the specific folder in SD card
2) GalleryView is indefiniite or a long one without end
here is the UPDATED code to get images from specific path...
package com.example.gall;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.example.gall.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class gall extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this, ReadSDCard()));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
}
});
}
private List<String> ReadSDCard()
{
List<String> tFileList = new ArrayList<String>();
//It have to be matched with the directory in SDCard
File f = new File("/android/sdcard2/");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
tFileList.add(file.getPath());
}
return tFileList;
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private List<String> FileList;
public ImageAdapter(Context c, List<String> fList) {
mContext = c;
FileList = fList;
TypedArray a = obtainStyledAttributes(R.styleable.gall);
mGalleryItemBackground = a.getResourceId(
R.styleable.gall_android_galleryItemBackground,0);
a.recycle();
}
public int getCount() {
return FileList.size();
}
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);
Bitmap bm = BitmapFactory.decodeFile(
FileList.get(position).toString());
i.setImageBitmap(bm);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
public TypedArray obtainStyledAttributes(int theme) {
// TODO Auto-generated method stub
return null;
}
}
Getting all the images will cause a memory overflow the best way is to keep a list of paths in string form and supply that to the gallery. If you are making a custom gallery you will have to create bitmaps and garbage collect them.
This is a good way to access sd-card:
String path = Environment.getExternalStorageDirectory().getPath()+ "/yourFolder/"
This is how to get the list
File directory = new File(path);
if(directory.isDirectory)
{
if(directory.list().length > 0 /*&& check if its an img etc*/)
{
for(String s: directory.list())
{
Log.d(TAG, "adding " + s);
fileNames.add(s);
}
}
}
you should make sure to check sd-card is loaded
//YOUR CODE HERE...
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA, // add DATA column
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.TITLE,
};
// Get the base URI for the People table in the Contacts content provider.
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Log.i("URI", images.toString());
// Make the query.
Cursor cur = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
MediaStore.Images.Thumbnails.IMAGE_ID // Ordering
);
Log.i("ListingImages"," query count="+cur.getCount());
if (cur.moveToFirst()) {
String bucket;
String date;
String name;
int bucketColumn = cur.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(
MediaStore.Images.Media.DATE_TAKEN);
int nameColumn = cur.getColumnIndex(
MediaStore.Images.Media.TITLE);
// Get the field values
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
name = cur.getString(nameColumn);
int columnIndex = cur.getColumnIndex(MediaStore.Images.Media.DATA);
String picPath = cur.getString(columnIndex);
imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));
// Do something with the values.
Log.i("ListingImages", " bucket=" + bucket
+ " name_taken=" + name);
}
}
Hi I have images in grid view. when i click my grid view images, it's display in full screen. if i want view another image go back in grid view then select another image view in full screen. i feel it's hard one.. so i am trying to view images full screen view using to swipe....no idea how to create this method please guide me and give some nice codes also...
This is my working app screen shot:
source code: 1. ImageViewExample.java
public class ImageViewExample extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""+ id));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setLayoutParams(new GridView.LayoutParams(92, 92));
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}
ViewImage.java
public class ViewImage extends Activity {
private String filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
filename = extras.getString("filename");
ImageView iv = new ImageView(getApplicationContext());
Bitmap bm = BitmapFactory.decodeFile(filename, bfo);
iv.setImageBitmap(bm);
setContentView(iv);
}
}
After getting id of selected image, implement this..
// this Class For Grid view images
package com.thumbnailview;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class Activity_ThumbView extends Activity
{
GridView gridview;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(Activity_ThumbView.this, "" + position, 2).show();
id=parent.getPositionForView(v);
Intent i=new Intent(Activity_ThumbView.this,Activity_ImageView.class);
i.putExtra("position", position);
startActivity(i);
finish();
}
});
}
public class ImageAdapter extends BaseAdapter
{
Context context;
public ImageAdapter(Context c )
{
context = c ;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return mThumbIds[position];
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(75, 75));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
}
public static Integer[] mThumbIds = {
R.drawable.a,R.drawable.icon,
R.drawable.b, R.drawable.s,
R.drawable.c, R.drawable.r,
R.drawable.d, R.drawable.q,
R.drawable.e, R.drawable.p,
R.drawable.f, R.drawable.o,
R.drawable.g, R.drawable.n,
R.drawable.h, R.drawable.m,
R.drawable.i, R.drawable.l,
R.drawable.j, R.drawable.k,
R.drawable.t,R.drawable.y,
R.drawable.u,R.drawable.x,
R.drawable.v,R.drawable.s,
R.drawable.cd,R.drawable.z,
R.drawable.bc,R.drawable.ab
};
}
// This Flip image Class
package com.thumbnailview;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class Activity_ImageView extends Activity
{
ImageView thumb_imgview;
ViewFlipper viewFlipper;
Button b_wall;
Button b_home;
// Animation a,b;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
int j;
WallpaperManager myWall;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
j=getIntent().getExtras().getInt("position");
myWall = WallpaperManager.getInstance(getApplicationContext());
b_wall=(Button) findViewById(R.id.button3);
b_home=(Button) findViewById(R.id.button1);
thumb_imgview=(ImageView) findViewById(R.id.thumb_txt_image);
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
gestureDetector = new GestureDetector(new MyGestureDetector());
b_wall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
myWall.setResource(Activity_ThumbView.mThumbIds[j]);
} catch (IOException e) {
e.printStackTrace();
}
}
});
b_home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(Activity_ImageView.this,Activity_ThumbView.class);
startActivity(i);
finish();
}
});
}
public class MyGestureDetector extends SimpleOnGestureListener implements OnGestureListener
{
public boolean onFling(MotionEvent m1, MotionEvent m2, float velocityX, float velocityY)
{
try
{
if (Math.abs(m1.getY() - m2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
if(m1.getX() - m2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if(Activity_ThumbView.mThumbIds.length>j)
{
j++;
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
}
}
else if (m2.getX() - m1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if(j>0)
{
j--;
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
}
}
}
catch (Exception e)
{
}
return false;
}
}
public boolean onTouchEvent(MotionEvent event)
{
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}
}
Implement OnGestureListener in ViewImage activity and capture swipe from user.
For displaying previous or next image, use cursor.
Store all image filenames in array when you are populating into Gridview and then pass that array to another view from that array you can get all images instead of go back to gridview for selecting images..
The easiest way to do this is indeed like RajaReddy P said: create an array with the filenames/urls pass it to the ViewImage activity...
For the ViewImage activity I really would use the ViewPager! Really easy to implement and the swiping is handled for you!
More about viewpager:
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
good day, i am having a bit of a problem here. i am using and async task to display images from external or internal storage.Now it works but the problem is, it is very slow and slightly jerky in scrolling. I have no idea why? please any solution or an idea how to do this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Wallpaper extends Activity implements OnItemClickListener{
/*Instance variables*/
private GridView grid;
private ImageAdapter imageAdapter;
private Display display;
Cursor cursor;
boolean inInternalStorage = false;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.wallpaper_images);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
#Override
protected void onStop(){
super.onStop();
}
/*methods called from AsyncTask as appropriate when its querying and processing the images from the MediaStore*/
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if(data == null){
new LoadImagesFromSDCard().execute();
}else {
final LoadedImage[] photos = (LoadedImage[])data;
if(photos.length == 0){
new LoadImagesFromSDCard().execute();
}
for(LoadedImage photo:photos){
addImage(photo);
}
}
}
private void addImage(LoadedImage... value) {
for(LoadedImage photo: value){
imageAdapter.addPhotos(photo);
imageAdapter.notifyDataSetChanged();
}
}
private void setupViews() {
grid = (GridView)findViewById(R.id.gridview);
grid.setNumColumns(display.getWidth()/95);
grid.setClipToPadding(false);
imageAdapter = new ImageAdapter(getApplicationContext());
grid.setAdapter(imageAdapter);
grid.setOnItemClickListener(this);
}
protected void onDestroy() {
super.onDestroy();
final GridView gridview = grid;
final int count = grid.getChildCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
unbindDrawables(findViewById(R.id.gridview));
System.gc();
}
/*public Object onRetainNonConfigurationInstance(){
final GridView gridview = grid;
final int count = grid.getChildCount();
final LoadedImage[] list = new LoadedImage[count];
for(int i = 0; i < count; i++){
final ImageView v = (ImageView)grid.getChildAt(i);
list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
}
return list;
}*/
/*utility method called that prevents screen from crashing when screen orientation changes*/
private void unbindDrawables(View view){
if(view.getBackground() != null){
view.getBackground().setCallback(null);
}
if(view instanceof ViewGroup){
for(int i = 0; i < ((ViewGroup) view).getChildCount(); i++){
unbindDrawables(((ViewGroup)view).getChildAt(i));
}
try{
((ViewGroup)view).removeAllViews();
}catch(Exception e){
e.printStackTrace();
}
}
}
/*AsyncTask thats queries the MediaStore for images and creates thumbnail images from bitmaps*/
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Cursor cursor;
Bitmap bitmap = null;
Bitmap newbitmap = null;
Uri uri = null;
String [] img = {MediaStore.Images.Media._ID};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img,
MediaStore.Images.Media.DATA + " like ? " , new String[]{ "%dcim%"}, null);
} else {
cursor = getContentResolver().query(MediaStore.Images.Media.INTERNAL_CONTENT_URI, img, null, null, null);
inInternalStorage = true;
}
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
if(size == 0){
Toast.makeText(getApplicationContext(), "There are no Images on the sdcard", Toast.LENGTH_SHORT).show();
}else {
}
for(int i = 0; i < size; i++){
cursor.moveToPosition(i);
int ImageId = cursor.getInt(column_index);
if(inInternalStorage == true){
uri = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "" + ImageId);
}else {
uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + ImageId);
}
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=4;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
if(bitmap != null){
newbitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
bitmap.recycle();
}
if(newbitmap != null){
publishProgress(new LoadedImage(newbitmap));
}
}catch(IOException e){
}
}
cursor.close();
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value){
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class LoadedImage {
Bitmap mBitmap;
LoadedImage(Bitmap bitmap) {
mBitmap = bitmap;
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/*Image Adapter to populate grid view of images*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
public ImageAdapter(Context context){
this.mContext = context;
}
public void addPhotos(LoadedImage photo){
photos.add(photo);
}
#Override
public int getCount() {
return photos.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) {
System.gc();
ImageView image;
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.image_list,null);
holder = new ViewHolder();
holder.image = (ImageView)convertView.findViewById(R.id.image_list_id);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
holder.image.setLayoutParams(new GridView.LayoutParams(100, 100));
holder.image.setImageBitmap(photos.get(position).getBitmap());
return convertView;
}
}
static class ViewHolder {
ImageView image;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = null;
int image_column_index = 0;
String[] proj = {MediaStore.Images.Media.DATA};
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,proj, MediaStore.Images.Media.DATA + " like ? ", new String[]{"%dcim%"},null);
}else{
cursor = managedQuery(MediaStore.Images.Media.INTERNAL_CONTENT_URI,proj,null, null,null);
}
cursor.moveToPosition(position);
image_column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String info = cursor.getString(image_column_index);
Intent imageviewer = new Intent(getApplicationContext(), ViewImage.class);
imageviewer.putExtra("pic_name", info);
startActivity(imageviewer);
}
}
i think what i am after is a way to allow doBackground() to run for a while before i call publishProgress(). just like how the gallery app in android does.
Any ideas on why this could be slow or how to solve this problem will be greatly appreciated as i have been stuck on how to improve the perfomance for a while now.
The biggest bottleneck will be accessing the images from the device (internal or external). Therefore, you'll want to have as many images in memory as possible (within reason of course). You can do this in a number of ways:
Load perhaps 18 images first (as you said, prebuffer before displaying). Check to make sure the number of images doesn't exceed whatever number you choose though.
Create a 'thumbs.db' type file which will store 100x100 px thumbnails of the bitmaps. This will allow much faster reading since you'd only need to read in one file then extract each bitmap. If the user clicks an image, then request it from the storage. This method requires more work, but will be able to load the thumbnails really fast. You'd probably have to design your own simple file headers, such as:
<file header (size of file, number of images)>
<image header (img id, size in bytes)>
<image bitmap data>
<image header (img id, size in bytes)>
<image bitmap data>
<image header (img id, size in bytes)>
<image bitmap data>
...