I have a thumbnail gallery. I would like to impose a bitmap over every thumbnail image. The resultant image should be either a bitmap or a drawable. Hence the gallery now consists of these resultant images. When the user scrolls through the gallery, the resultant image will appear.
I am using the following code
public class GalleryVideo extends Activity {
private Integer[] imgId = {R.drawable.followtheleader,
R.drawable.fruitsalad,
R.drawable.gettingstrong,
R.drawable.gulpgulp,
R.drawable.heythereshakyshaky,
R.drawable.its_a_wiggly_circus,
R.drawable.lettucesing,
R.drawable.monkey_dance,
R.drawable.quack_quack,
R.drawable.vegetable_soup,
R.drawable.walk};
public void onCreate(Bundle savedInstanceState) {
....................
selected_photo = (ImageView)findViewById(R.id.selected_photo);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(getApplicationContext()));
th_name = (ImageView)findViewById(R.id.th_name);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
galleryVideoCounter = position;
Intent myIntent = new Intent(getApplicationContext(), StartDance.class);
startActivity(myIntent);
}
});
....................
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
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 imgId.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
try {
if(position > 0)
{
audioPosCount = position;
}
if(audioPosCount == 0 && audioPosCount != audioPosCount1)
{
galleryAudioCounter++;
audioPosCount1 = audioPosCount;
}
if(audioPosCount > 0 && audioPosCount != -1 && audioPosCount != audioPosCount1)
{
galleryAudioCounter++;
audioPosCount = position;
audioPosCount1 = audioPosCount;
}
return position;
} catch (Exception e) {
}
}
public View getView(int position, View convertView, ViewGroup parent) {
audioPosCount = 0;
ImageView imgView = new ImageView(getApplicationContext());
imgView.setImageResource(imgId[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(((int)(width / 1.45)), ((int)(height / 1.6))));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
return imgView;
}
}
}
I need a sample code for this feature.
Related
I want show image in gridview from sdcard directory.i use this code.But when i load image by type : bitmap.getView in gridview adapter need Integer[] array.how i can fix it?
public class LoadPic extends Activity {
Integer[] imageIDs = {
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user
};
int numberOfImages=0;
Bitmap[] m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_pic);
Intent gett = getIntent();
String _area = gett.getStringExtra("area");
String _domain = gett.getStringExtra("domain");
String _block = gett.getStringExtra("block");
String _melk = gett.getStringExtra("melk");
String _build = gett.getStringExtra("build");
String _apar = gett.getStringExtra("apar");
String _senfi = gett.getStringExtra("senfi");
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File img = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
if(img.exists())
{
Bitmap bit = BitmapFactory.decodeFile(img.getAbsolutePath());
}
}
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
//---returns the number of images---
public int getCount() {
return numberOfImages;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(7, 7, 7, 7);
} else {
imageView = (ImageView) convertView;
}
/**/
imageView.setImageResource(imageIDs[position]);
/**/
return imageView;
}
}
}
please help how i can use image in this class(adapter).
If you want to show images from sdcard into your grid view use any imageloader library
Universal Image Loader
https://github.com/nostra13/Android-Universal-Image-Loader
then you need to create a string array or a model class instead of that integer array.
Please refer the below tutorials.
http://wptrafficanalyzer.in/blog/loading-thumbnail-images-in-a-gridview-and-opening-original-images-in-alertdialog-using-media-content-providers/
replace
public int getCount() {
return numberOfImages;
}
with
public int getCount() {
return imageIDs.length();
}
First properly explain what do want to set Drawable or Bitmap?
If Bitmap then this is how you should set bitmap(make a list of bitmaps and then):
imageView.setImageBitmap(bitmaps[position]);
if Drawable then(make list of drawable id's)
imageview.setImageResource(drawables[position]);
This is how make bitmap list:
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File f = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
if(bmp!=null){
bitmaps.add(bmp);
}
}
I have a gridview with an adapter, which also has a checkbox look to be shown when an imageview has been clicked. But something goes wrong. If an image is checked and you scroll to the bottom, one of the images are also checked. If you scroll up again, another image than the one you clicked to begin with, is checked (in most cases).
So here is the code for my adapter. The code in concern is the getView method:
public class ImageAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> files;
private Bitmap mPlaceHolderBitmap;
private File directory;
private int thumbSize;
private GridImageListener gridImageListener;
private LayoutInflater inflater;
private View rootView;
private final int MAX_PICTURE_LIMIT = 5;
private int picturesChosenCount = 0;
public ImageAdapter(Context context, ArrayList<String> files, File directory, int thumbSize, GridImageListener gridImageListener, LayoutInflater inflater, View rootView) {
super();
this.context = context;
this.files = files;
this.directory = directory;
this.thumbSize = thumbSize;
this.gridImageListener = gridImageListener;
this.inflater = inflater;
this.rootView = rootView;
mPlaceHolderBitmap = drawableToBitmap(context.getResources().getDrawable(R.drawable.logo));
}
public Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
#Override
public int getCount() {
return files.size();
}
#Override
public Object getItem(int position) {
return files.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup container) {
final ViewHolder holder;
if (convertView == null) { // if it's not recycled, initialize some attributes
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.component_imageview_checkable, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.checkableImageView);
holder.imageview.getLayoutParams().height = thumbSize;
holder.imageview.getLayoutParams().width = thumbSize;
holder.imageCheckBox = (RelativeLayout) convertView.findViewById(R.id.image_check_view);
loadBitmap(files.get(position), holder.imageview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageCheckBox.setId(position);
holder.imageview.setId(position);
holder.imageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.imageCheckBox.getVisibility() == View.VISIBLE) {
holder.imageCheckBox.setVisibility(View.INVISIBLE);
picturesChosenCount--;
} else {
if (picturesChosenCount < 5) {
holder.imageCheckBox.setVisibility(View.VISIBLE);
picturesChosenCount++;
} else {
Toast.makeText(context, "Max number of pictures has been reached", Toast.LENGTH_SHORT).show();
}
}
gridImageListener.onClickImage(files.get(position));
}
});
holder.id = position;
return convertView;
}
public void loadBitmap(String path, ImageView imageView) {
if (cancelPotentialWork(path, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView, context, path, directory, thumbSize);
final AsyncDrawable asyncDrawable =
new AsyncDrawable(context.getResources(), mPlaceHolderBitmap, task);
imageView.setImageDrawable(asyncDrawable);
task.execute(path);
}
}
public static boolean cancelPotentialWork(String path, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final String bitmapData = bitmapWorkerTask.path;
// If bitmapData is not yet set or it differs from the new data
if (bitmapData.equals("0") || !bitmapData.equals(path)) {
// 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;
}
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();
}
}
}
class ViewHolder {
int id;
ImageView imageview;
RelativeLayout imageCheckBox;
}
I know it has something to do with the recycling of views in the gridview, but I don't know how to avoid/fix it. Each imageview is loaded separately in an asynctask and is reloaded when you scroll to it. If you need to take a look at it, the code is here: http://pastebin.com/2BcBW7PN
And finally, here is my XML for the item of each image:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/checkableImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:id="#+id/image_check_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/checkableImageView"
android:layout_alignTop="#+id/checkableImageView"
android:layout_alignRight="#+id/checkableImageView"
android:layout_alignBottom="#+id/checkableImageView"
android:visibility="invisible">
<com.ivankocijan.magicviews.views.MagicTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#color/white"
android:background="#drawable/blue_border"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<com.ivankocijan.magicviews.views.MagicTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/icon_check"
android:textColor="#color/white"
android:textSize="#dimen/txtsize_standard_smaller_icon"
android:padding="4dp"
app:typeFace="#string/icon_font"
android:background="#color/standard_blue"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</RelativeLayout>
What might be wrong? I have read all the tutorials I could find, but none of them seemed to do any difference.
You can use : Eg: Android – Select multiple photos from Gallery
Or :
Entity -CustomGallery.class
public class CustomGallery {
public String sdcardPath;
public boolean isSeleted = false;
}
Adapter -GalleryAdapterCustom.class
private Context mContext;
private LayoutInflater infalter;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public GalleryAdapterCustom(Context c, ImageLoader imageLoader) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.imageLoader = imageLoader;
// clearCache();
}
#Override
public int getCount() {
return data.size();
}
#Override
public CustomGallery getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
boolean isAllSelected = true;
for (int i = 0; i < data.size(); i++) {
if (!data.get(i).isSeleted) {
isAllSelected = false;
break;
}
}
return isAllSelected;
}
public boolean isAnySelected() {
boolean isAnySelected = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
isAnySelected = true;
break;
}
}
return isAnySelected;
}
public ArrayList<CustomGallery> getSelected() {
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
return dataT;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
} else {
data.get(position).isSeleted = true;
}
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
if (dataT.size() > NewPostActivity.max_image) {
Toast.makeText(mContext, "Bạn chỉ được đăng tối đa 20 ảnh / 1 tin",
Toast.LENGTH_SHORT).show();
data.get(position).isSeleted = false;
}
((ViewHolder) v.getTag()).imgQueueMultiSelected.setSelected(data
.get(position).isSeleted);
// }
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = infalter.inflate(R.layout.gallery_item, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView
.findViewById(R.id.imgQueue);
holder.imgQueueMultiSelected = (ImageView) convertView
.findViewById(R.id.imgQueueMultiSelected);
if (isActionMultiplePick) {
holder.imgQueueMultiSelected.setVisibility(View.VISIBLE);
} else {
holder.imgQueueMultiSelected.setVisibility(View.GONE);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgQueue.setTag(position);
try {
imageLoader.displayImage("file://" + data.get(position).sdcardPath,
holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue
.setImageResource(R.drawable.default_icon2);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgQueueMultiSelected
.setSelected(data.get(position).isSeleted);
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgQueueMultiSelected;
}
public void clearCache() {
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
}
Activity- CustomGalleryActivity.class
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapterCustom adapter;
String count_image;
RelativeLayout layout_select, layout_cancel;
ImageView imgNoMedia;
Button btnGalleryOk;
public static final int REQUEST_CODE_Gallery = 1111;
public static final int REQUEST_CODE_Gallery_OK = 2222;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getStringExtra("action");
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapterCustom(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.layout_select).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.layout_select).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
layout_cancel = (RelativeLayout) findViewById(R.id.layout_cancel);
layout_cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
layout_select = (RelativeLayout) findViewById(R.id.layout_select);
layout_select.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
if (allPath.length == 0) {
Toast.makeText(CustomGalleryActivity.this, "Vui lòng chọn ảnh",
Toast.LENGTH_SHORT).show();
} else {
Intent data = new Intent().putExtra("all_path", allPath);
setResult(REQUEST_CODE_Gallery_OK, data);
finish();
}
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
adapter.changeSelection(v, position);
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(REQUEST_CODE_Gallery_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
Use .
Intent i = new Intent(NewPostActivity.this,
CustomGalleryActivity.class);
i.putExtra("action", Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, REQUEST_CODE_Gallery);
I want to get an image from sd card and place it in gallery view.For that i had converted that image to bitmap but it shows certain errors..
code for conversion of the image.. I am attaching the complete code it showing a null pointer exception
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
System.out.println("Enter the activity");
try{
String filepath = "/sdcard/";
File imagefile = new File(filepath + "abcdoutput.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();
}
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.setImageResource(data[position]);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnLongClickListener(new View.OnLongClickListener() {
#SuppressWarnings("deprecation")
public boolean onLongClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
DisplayImage.this).create();
alertDialog.setTitle("Confirmation");
alertDialog
.setMessage("Do you want to set this image as wallaper?");
alertDialog.setButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Bitmap bitmap = BitmapFactory.decodeResource(
getResources(), data[position]);
try {
DisplayImage.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
});
alertDialog.show();
return true;
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = null;
GalItemBg = typArray.getResourceId(
0, 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);
imgView.setImageResource(data[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
Use this to get the image back from the array and set it:
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
imgView.setImageBitmap(bitmap);
try and simple with one line code
String imagePath=Environment.getExternalStorageDirectory().toString()+"/abcdoutput.jpg";
imgView.setImageDrawable(Drawable.createFromPath("imagePath"));
I am new to android. I have a requirement now. I need to add around 10 images in the res/drawable folder and on running the app i should display this images on a listView.and on selecting any of the image i should display this image in the new activity should be able to zoom in and zoom out. Please help me out to figure out this with the sample code.
Thanks in advance.
this example for create Gallery, select one and set to selectedImageView.
so after that you can do everything with selectedImageView.
public class MyActivity extends Activity{
private int selectedImagePosition = 0;
private ImageView selectedImageView;
private List<Drawable> drawables;
private Gallery gallery;
#Override
public void onCreate(Bundle savedInstanceState) {
selectedImageView = (ImageView) view.findViewById(R.id.selected_imageview);
getDrawablesList();
gallery = (Gallery) view.findViewById(R.id.Gallery);
gallery.setAdapter(new ImageAdapter(getActivity().getApplicationContext()));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
setSelectedImage(selectedImagePosition);
}
});
private void getDrawablesList() {
drawables = new ArrayList<Drawable>();
drawables.add(getResources().getDrawable(R.drawable.res1));
drawables.add(getResources().getDrawable(R.drawable.res2));
drawables.add(getResources().getDrawable(R.drawable.res3));
drawables.add(getResources().getDrawable(R.drawable.res4));
}
private void setSelectedImage(int selectedImagePosition) {
BitmapDrawable bd = (BitmapDrawable) drawables.get(selectedImagePosition);
Bitmap b = Bitmap.createScaledBitmap(bd.getBitmap(), (int) (bd.getIntrinsicHeight() * 0.9), (int) (bd.getIntrinsicWidth() * 0.7), false);
selectedImageView.setImageBitmap(b);
selectedImageView.setScaleType(ScaleType.FIT_XY);
}
You can use a GalleryView
Refer to the link below for more help:
http://mobiforge.com/designing/story/understanding-user-interface-android-part-3-more-views
private ImageView selectedImageView;
private TextView _nameTextView;
private Gallery gallery;
Integer[] imageIDs = { R.drawable.hbath, R.drawable.hfood,
R.drawable.hmedicine, R.drawable.htherapy, R.drawable.htoilet,
R.drawable.hother };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedImageView = (ImageView) findViewById(R.id.imageSwitcher1);
_nameTextView = (TextView) findViewById(R.id.NameTextView);
gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
if (position == 0) {
selectedImageView
.setImageResource(R.drawable.hbathbackground);
_nameTextView.setText("Toilet");
} else if (position == 1) {
selectedImageView
.setImageResource(R.drawable.hfoodbackground);
_nameTextView.setText("Food");
} else if (position == 2) {
selectedImageView
.setImageResource(R.drawable.hmedicinebackground);
_nameTextView.setText("Medicine");
} else if (position == 3) {
selectedImageView
.setImageResource(R.drawable.htherapybackground);
_nameTextView.setText("Therapy");
} else if (position == 4) {
selectedImageView
.setImageResource(R.drawable.htoiletbackground);
_nameTextView.setText("Bath");
} else if (position == 5) {
selectedImageView
.setImageResource(R.drawable.hotherbackground);
_nameTextView.setText("Other");
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
and ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c) {
context = c;
// ---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
// ---returns the number of images---
public int getCount() {
return imageIDs.length;
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setBackgroundColor(0xFF000000);
// imgView.setImageBitmap(bitmap);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(155, 235));
imageView.setBackgroundResource(R.drawable.customborder2);
return imageView;
}
}
I am working on image gallery for which i have made use of ViewPager addon api. I am loading images from a specific folder in sdcard. My goal is to display only 9 images per screen in ViewPager, which i am not able to achieve. The below code is the mainactivity.
public class AndroidSwipeGalleryActivity extends Activity {
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.image_gallery);
File file = new File(Environment.getExternalStorageDirectory()+"/xxxxxxx/images");
if (file.exists()) {
size = file.listFiles().length;
System.out.println("=====File exists====Length is====="+size);
double quo = (double)size/9;
System.out.println("====Dividing by 9====" + quo);
size = (int) Math.ceil(quo);
System.out.println("===Math===== "+size);
} else {
System.out.println("======File does not exists====");
}
MyPagerAdapter adapter = new MyPagerAdapter(this);
adapter.setScrCount(size);
ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
The Pager Adapter and Image adapter are in the below class:
public class MyPagerAdapter extends PagerAdapter {
private TextView tv;
private GridView gv;
private int scrCount;
private int count;
public int imageCount;
private Cursor cursor;
private int columnIndex;
private Activity act;
public MyPagerAdapter(Activity act) {
this.act = act;
}
public int getCount() {
return getScrCount();
}
public Object instantiateItem(View collection, int position) {
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the cursor pointing to the SDCard
String uri = MediaStore.Images.Media.DATA;
String condition = uri + " like '%/beverlyhills/images%'";
cursor = act.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, condition, null, null);
count = cursor.getCount();
System.out.println("Cursor count::::"+count);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
for (int i = 0; i < getScrCount() ; i++) {
if (count > 9) {
if (position == i) {
int num = 0;
num = count - 9;
count = num;
imageCount = 9;
}
} else {
imageCount = count;
}
}
resId = R.layout.number_one;
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
tv = (TextView) collection.findViewById(R.id.swipeTitleTextView);
tv.setText("Swipe Gallery");
gv = (GridView) collection.findViewById(R.id.galleryGridView);
ImageAdapter imageAdapter = new ImageAdapter(collection.getContext(), imageCount);
gv.setAdapter(imageAdapter);
// Set up a click listener
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = act.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
System.out.println("=====Image Path:::::"+imagePath);
}
});
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
public int getScrCount() {
return scrCount;
}
public void setScrCount(int scrCount) {
this.scrCount = scrCount;
}
private class ImageAdapter extends BaseAdapter {
private int count;
public ImageAdapter(Context ctx, int count) {
this.count = count;
}
#Override
public int getCount() {
return count;
}
#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) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(act);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}
The problem is I am able to load the images and display them on screen but not able to display exactly 9 images per screen. Please go through the code, it's not complex.
i have create the other demo example of view pager to manage the page and also load images. follow the steps wise, its perfectly works..
its a Pager adapter and mDataHolder(List of images) and
Set the property of gridview android:numColumns="3"
private int size;
private int start;
private int end;
private int MATRIX = 9;
public int getCount() {
int size = 0;
if (mDataHolder != null)
modular = mDataHolder.get_Listholder().size() % MATRIX;
if (modular != 0)
size++;
return ((mDataHolder.get_Listholder().size()) / MATRIX) + size;
}
#Override
public Object instantiateItem(ViewGroup container, final int pageIndex) {
mRelativeLayoutInflater = (RelativeLayout) mMasterFragmentActivity.getLayoutInflater().inflate(R.layout.member_pager_adapter, container, false);
mGridView = (GridView) mRelativeLayoutInflater.findViewById(R.id.member_gridView_list);
Calculation of pages<
size = MATRIX;
start = pageIndex * MATRIX;
end = 0;
int temp = 0;
if ((start + MATRIX) < mDataHolder.get_Listholder().size()) {
end = start + MATRIX;
} else {
temp = mDataHolder.get_Listholder().size() - start;
end = start + temp;
size = temp;
}
... and then pass the variable to gridview adapter to set other content in pager.
mAdapterMember = new AdapterMember(mContext, start, end, size);
mGridView.setAdapter(mAdapterMember);
((ViewPager) container).addView(mRelativeLayoutInflater);
return mRelativeLayoutInflater;
}
Below Manage pages variables also use the Gridview adapter to set the postion.
when the set page content position to be like (start + position)
private class AdapterMember extends BaseAdapter {
private ViewHolder mViewHolder;
private Context mContext;
private int start;
private int end;
private int size;
private AdapterMember(Context mContext, int start, int end, int size) {
this.mContext = mContext;
this.start = start;
this.end = end;
this.size = size;
}
#Override
public int getCount() {
if (size > 0)
return size;
else
return 0;
}
#Override
public Object getItem(int position) {
if (mMemberListVO.getMember().size() > 0)
return mMemberListVO.getMember().get(position);
else
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.row_member_list, null);
mViewHolder = new ViewHolder();
mViewHolder.mImageViewMemberPhoto = (NetworkImageView) convertView .findViewById(R.id.row_member_list_imageView_person);
mViewHolder.mTextViewMemberName = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_name);
mViewHolder.mTextViewMemberDesignation = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_designation);
mViewHolder.mTextViewMemberAddress = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_address);
mViewHolder.mTextViewMemberNotification = (TextView) convertView .findViewById(R.id.row_member_list_imageview_msg_notification);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mTextViewMemberName.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_First_Name)
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder(). get(start + position).get(DBHelper.mFieldMember_Last_Name));
mViewHolder.mTextViewMemberDesignation.setText(mDataHolder.get_Listholder().get(start + position)
.get(DBHelper.mFieldMember_Occupation));
mViewHolder.mTextViewMemberAddress.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_Block_No)
+ "," + getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_House_No) + ","
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_Home_Address) + ".");
return convertView;
}
private class ViewHolder {
private NetworkImageView mImageViewMemberPhoto;
private TextView mTextViewMemberName, mTextViewMemberDesignation, mTextViewMemberAddress,
mTextViewMemberNotification;
}
}
its perfectly Working with your requirement...
The problem is solve to load the images and display them on screen its display exactly 9 images per screen.