get imageview from viewpager to save and share from button - android

I have a list of images from picasa. I put it in grid view and then on click have the fullscreen image that is done by viewpager. I tried many ways to get bitmap or get imageview from view pager adapter but it is giving null. Please help me, I'm new, this is my first app and I'm confused.
This is my code :
package com.example.soha.livingroom;
public class fullimafepager extends Activity implements OnClickListener {
// TouchImageView imgflag;
// BitmapDrawable btmpDr;
private static final String STATE_POSITION = "STATE_POSITION";
// #InjectView(R.id.pager)
LruBitmapCache lreucach;
private PrefManager prefmanger;
private List<String> images = new ArrayList<String>();
private String imageuri;
// Picasa JSON response node keys
// Declare Variables
private ViewPager viewPager;
private ImageAdapter adapter;
private int npostion;
// private Bitmap[] image2;
private int position;
// private im selectedPhoto;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
private View view;
private Bitmap bitmap;
private ImageView fullImageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from viewpager_main.xml
prefmanger = new PrefManager(getApplicationContext());
setContentView(R.layout.viewpager_main);
if (getIntent().getExtras() != null) {
this.images = getIntent().getExtras().getStringArrayList("list");
position = getIntent().getIntExtra("postion", 0);
;
// fullImageView= images.get(position);
Log.d("=======", "Data " + images.get(1));
Toast.makeText(this, "the" + images.get(1) + position, Toast.LENGTH_LONG).show();
// Intent i = getIntent();
// image selectedPhoto = (image) getIntent().getSerializableExtra(TAG_SEL_IMAGE);
// System.out.println(images);
}
prefmanger = new PrefManager(getApplicationContext());
// Generate sample data
// flag = new int[] { R.drawable.ico_loader, R.drawable.ico_loader, R.drawable.ico_loader, R.drawable.ico_loader};
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.pager);
// Pass results to ViewPagerAdapter Class
adapter = new ImageAdapter(fullimafepager.this, images);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
// viewPager.setCurrentItem(0);
viewPager.setCurrentItem(position);
Log.d("test", "Current Page:"+viewPager.getCurrentItem());
// fullImageView= (ImageView) viewPager.getChildAt(position);
npostion= viewPager.getCurrentItem();
// fullImageView= (TouchImageView) viewPager.findViewById(R.id.imgFullscreen);
fullImageView= (TouchImageView) viewPager.findViewWithTag("pos" + viewPager.getCurrentItem());
Log.d("test", "Current uri:" + fullImageView);
// Log.d("test", "Current Page:"+npostion);
// view = fullimafepager.viewPager.getChildAt(fullimafepager.viewPager.getCurrentItem()).getRootView();
// fullImageView = (ImageView)fullimafepager.viewPager.findViewWithTag("myview" + fullimafepager.viewPager.getCurrentItem());
// Log.d("=======", "Data " + fullImageView);
//addition
// imageUri = images.get(npostion);
// uri = Uri.parse(imageUri);
// imageuri=images.get(npostion);
// bitmap=lreucach.getBitmap(imageuri);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
// fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
// getActionBar().hide();
// utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
}
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
// Bitmap bitmap = ((BitmapDrawable) imgflag.getBitmap();
/* Bitmap bitmap1= null;
try {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(imageuri));
} catch (IOException e) {
e.printStackTrace();
}*/
Log.d("test", "Current uri:" + bitmap);
switch (v.getId()) {
case R.id.llDownloadWallpaper:
// utils.saveImageToSDCard(bitmap);
{ File myDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
prefmanger.getGalleryName());
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Wallpaper-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(
fullimafepager.this,
fullimafepager.this.getString(R.string.toast_saved).replace("#",
"\"" + prefmanger.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
// Log.d(this, "Wallpaper saved to: " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(fullimafepager.this,
fullimafepager.this.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();}}
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
// utils.shareIt(bitmap);
{ /*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
// share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));*/
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (Exception e) {
System.err.println(e.toString());
}
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
}
break;
default:
break;
}
}
/**
* #author Terry E-mail: yaoxinghuo at 126 dot com
* #version create: 2010-10-21 ??01:40:03
*/
}
and this is my adapter
public class ImageAdapter extends PagerAdapter {
private Activity _activity;
// Declare Variables
Context context;
Utils utiles;
TouchImageView imgflag;
LruBitmapCache lreucach;
private List<String> image2;
private LayoutInflater inflater;
private Bitmap bitmap;
//new
private image selectedPhoto;
public ImageAdapter(Activity activity,
List<String> flag) {
this._activity = activity;
this.image2 = flag;
}
#Override
public int getCount() {
return this.image2.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int postion) {
// Declare Variables
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.activity_fullscreen_image, container,
false);
imgflag = (TouchImageView) itemView.findViewById(R.id.imgFullscreen);
// fullImageView.setOnTouchListener(this);
// Capture position and set to the ImageView
Picasso.with(_activity).load(image2.get(postion)).into(imgflag);
imgflag.setTag("pos" + postion);
// imgflag.setImageURI(Uri.parse("http:/i.dailymail.co.uk/i/pix/2014/0‌​9/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG"));
/* Uri imgUri = Uri.parse(image2.get(postion));
imgflag.setImageURI(null);
imgflag.setImageURI(imgUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(image2.get(postion), options);
imgflag.setImageBitmap(bitmap);*/
// bitmap = ((BitmapDrawable) imgflag.getDrawable()).getBitmap();;
// Bitmap bitmap;
// OutputStream output;
// utiles.setBitmap();
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(imgflag);
// lreucach.putBitmap(image2.get(postion),bitmap);
Log.d("test", "Adapter creating item:" + postion);
return imgflag;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((TouchImageView) object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
public Bitmap getBtmap(){
BitmapDrawable btmpDr = (BitmapDrawable) imgflag.getDrawable();
bitmap = btmpDr.getBitmap();
return bitmap;
}

Related

java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2 in viewpager

In my application am using two languages using same adapter, first if user select first language, the data populate in ViewPager, if we swipe two,three pages after that if we change another language data populate in ViewPager, but if we click any button in pager ,it show this
error java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2,
can anyone give solution for this error , thanks in advance.
public class MyCustomAdapter extends PagerAdapter {
Context context1;
LayoutInflater inflater = null;
String title;
public static LinearLayout full_link, containers, language;
public static Uri bmpUri = null;
TextView txtfullstory;
int pStatus = 0;
private Handler handler = new Handler();
public static Bitmap bitmap;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
String user_type_id;
public MyCustomAdapter(Context context1,
ArrayList<String> NewsidArray,
ArrayList<String> NewsdescArray,
ArrayList<String> NewstitleArray,
ArrayList<String> NewsimageArray,
ArrayList<String> NewsdateArray,
ArrayList<String> NewsauthorArray,
ArrayList<String> NewsurlArray) {
this.context1 = context1;
newsidArray = NewsidArray;
newsdescArray = NewsdescArray;
newstitleArray = NewstitleArray;
newsimageArray = NewsimageArray;
newsdateArray = NewsdateArray;
newsauthorArray = NewsauthorArray;
newsurlArray = NewsurlArray;
}
#Override
public int getCount() {
if (newstitleArray == null) {
return 0;
}
return newstitleArray.size();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public Object instantiateItem(ViewGroup container, final int position) {
final int delPosition = position;
final Holder holder = new Holder();
inflater = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View itemView = inflater.inflate(R.layout.fragment_layout, container, false);
holder.date = (TextView) itemView.findViewById(R.id.txtdate);
holder.txttitle = (TextView) itemView.findViewById(R.id.txttitle);
holder.txtdesc = (TextView) itemView.findViewById(R.id.txtdesc);
holder.txtauthor = (TextView) itemView.findViewById(R.id.txtauthor);
holder.imageview = (ImageView) itemView.findViewById(R.id.imageview);
holder.share = (ImageView) itemView.findViewById(R.id.share);
holder.url = (TextView) itemView.findViewById(R.id.url);
holder.reverse = (ImageView) itemView.findViewById(R.id.reverse);
holder.progress = (ProgressBar) itemView.findViewById(R.id.progress);
full_link = (LinearLayout)itemView.findViewById(R.id.line_above);
containers = (LinearLayout)itemView.findViewById(R.id.containers);
language = (LinearLayout)itemView.findViewById(R.id.language);
txtfullstory = (TextView) itemView.findViewById(R.id.txtfullstory);
String date = newsdateArray.get(position).toString();
String image = newsimageArray.get(position).toString();
holder.txtdesc.setText(Html.fromHtml(newsdescArray.get(position).toString()));
holder.txttitle.setText(Html.fromHtml(newstitleArray.get(position).toString()));
holder.txtauthor.setText(Html.fromHtml(newsauthorArray.get(position).toString()));
holder.url.setText(newsurlArray.get(position).toString());
Typeface font = Typeface.createFromAsset(context1.getAssets(), "fonts/Seravek.ttc");
holder.txtdesc.setTypeface(font);
holder.txttitle.setTypeface(font, Typeface.BOLD);
holder.txtauthor.setTypeface(font);
title = newstitleArray.get(position);
pref = context1.getSharedPreferences("MyPref", 0);
editor = pref.edit();
user_type_id = pref.getString("langid", null);
if(user_type_id != null && user_type_id.equals("2")){
txtfullstory.setText(Html.fromHtml("पर पूरी कहानी"));
}else {
txtfullstory.setText(Html.fromHtml("Full story on"));
}
try {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
Date parsedDate = dateFormat1.parse(date);
long times = parsedDate.getTime();
new Timestamp(times);
String result = (String) DateUtils.getRelativeTimeSpanString(times, System.currentTimeMillis() + 5 * 60 * 1000, 0);
holder.date.setText(result);
} catch (ParseException e) {
Log.d("Error", e.getMessage());
}
if(!(!image.equalsIgnoreCase("") && !image.equalsIgnoreCase(null))) {
holder.imageview.setVisibility(View.INVISIBLE);
}
else{
holder.progress.setVisibility(View.VISIBLE);
holder.imageview.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (pStatus <= 100) {
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
holder.progress.setProgress(pStatus);
holder.progress.setSecondaryProgress(pStatus + 5);
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
Picasso.with(context1).load(WebService.WS_ImageOnlineURL + image).fit().centerCrop()
.error(R.drawable.image_loading).transform(new RoundedTransformation(4, 0)).into(holder.imageview, new Callback()
{
#Override
public void onSuccess()
{
holder.progress.setVisibility(View.INVISIBLE);
holder.imageview.setVisibility(View.VISIBLE);
}
#Override
public void onError()
{
}
});
}
itemView.setDrawingCacheEnabled(true);
itemView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
itemView.layout(0, 0, 300, 400);
itemView.buildDrawingCache(true);
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(), itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
sendIntent.putExtra(Intent.EXTRA_TEXT, newstitleArray.get(myCustomPosition) + "\r\n" + "Get odd news only on Oddcast" + "\r\n" + "https://goo.gl/8jeJga");
sendIntent.setType("image/*");
context1.startActivity(sendIntent);
}catch(Exception e) {
e.printStackTrace();
}
}
});
holder.txttitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
full_link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
language.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("newstitleArray", String.valueOf(newstitleArray.size()));
Intent language = new Intent(context1, UserPreferedLanguage.class);
context1.startActivity(language);
Activity activity = (Activity) context1;
activity.overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
});
container.addView(itemView);
return itemView;
}
public class Holder {
TextView date,txtauthor,txttitle,txtdesc,url; //Initialize TextView variable
ImageView imageview,share,reverse;
ProgressBar progress;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((LinearLayout) object).removeView(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Execeptions
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
java.util.ArrayList.get(ArrayList.java:308)
oddcast.jetlabs.com.oddcast.adapter.MyCustomAdapter$3.onClick(MyCustomAdapter.java:267)
android.view.View.performClick(View.java:4761)
android.view.View$PerformClick.run(View.java:19767)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:135)
android.app.ActivityThread.main(ActivityThread.java:5312)
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke(Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

Android - Take a picture from the Camera and save it to the internal storage

I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!

OnClick goto new Activity in GridView Android

I take a photo from the camera and store them in a GridView, now when i view them there is no OnClick function to Enlarge or Goto new Activity to Enlarge the selected image, Here's the code:
Where to implement the OnClick method to take the selected image to a new Activity and enlarge it
package com.example.veeresh.myphotogallery;
public class Photo_1 extends AppCompatActivity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
private String path;
private String pathMusic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
int pos = 0;
path = " ";
pathMusic = getIntent().getStringExtra("Store to Music");
if(pathMusic != null)
{
path = pathMusic;
}
captureBtn = (Button) findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = (GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {
try {
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
Toast.makeText(this, "Launching Camera", Toast.LENGTH_SHORT).show();
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if (requestCode == CAMERA_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(path);
imageDirectory.mkdirs();
String _path = path + imgcurTime + ".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if (listOfImagesPath != null) {
grid.setAdapter(new ImageListAdapter(this, listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(path);
if (f.exists()) {
File[] files = f.listFiles();
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
public class ImageListAdapter extends BaseAdapter {
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic) {
context = c;
imgPic = thePic;
}
public int getCount() {
if (imgPic != null)
return imgPic.size();
else
return 0;
}
//---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;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; //Disable Dithering mode
bfOptions.inPurgeable = true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if (fs != null) {
bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(300, 600));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}
Use setOnItemClickListener of girdview.
grid = (GridView) findViewById(R.id.gridviewimg);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "you clicked at : " + position, Toast.LENGTH_LONG).show();
// put your intent here to open activity
}
});
put this code inside your onCreate(...) method.
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do your stuff.
}
});

Download/save viewing picture from application resource

How do I set my application to download/save to phone the image I am previewing?
I Tried with the code below but it's not working, it gives me error and I can't figure out where is that error. So what am I supposed to replace and with what?
public class FullImageActivity extends Activity {
Bitmap bm;
boolean isSDAvail=false, isSDWriteable = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.full_image);
//AdView ad = (AdView) findViewById(R.id.adView);
//ad.loadAd(new AdRequest());
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ImageAdapter imageAdapter = new ImageAdapter(this);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
checkSDstuff();
}
private void checkSDstuff() {
// TODO Auto-generated method stub
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
//write
isSDAvail = true;
isSDWriteable =true;
}else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
//read only
isSDAvail =true;
isSDWriteable = false;
}else{
//uh oh
isSDAvail = false;
isSDWriteable =false;
}
Button buttonSave = (Button)findViewById(R.id.download);
buttonSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isSDAvail && isSDWriteable){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String name = filename.getText().toString(); //how to set name from postion
File file = new File(path, name + ".jpeg");
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.pic); //here to set (imageAdapter.mThumbIds[position]) from position of ImageView
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
}
}
});
}
Here is code to create a bitmap from an ImageView:
public Bitmap getBitmapFromImageView(ImageView imageView) {
int viewWidth = imageView.getWidth();
int viewHeight = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
imageView.layout(0, 0, viewWidth, viewHeight);
imageView.draw(canvas);
return bitmap;
}
Then to save the Bitmap:
try {
Bitmap bmp = getBitmapFromImageView(imageView);
FileOutputStream out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Check when onClick is checked only?

I have a checkbox, that when checked, makes a bitmap and then saves that bitmap to internal storage. Then, in a gridView adapter, I have it check for the bitmap from internal storage with FileInputstream.
The issue is that the checkbox's onClick method is also in a class that extends baseadapter.
With the way it is now, when I start my app, it automatically checks for the bitmap and then returns a FileNotFound exception and then the onClick of the checkbox doesn't do anything.
I thought about this and realized that the reason it checks for it is that it is creating the gridView when I first open my app (which it is supposed to). In other words, it checks for the file because it is in the getView() method of my gridView adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
Is there a way that I can make it check internal storage ONLY IF the checkbox is checked?
Please note that the onClick method of the checkbox is in one class while I am getting the bitmap in another.
Here are my two full classes:
AppInfoAdapter (the one with the onClick method---I will only post the needed coding here):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class AppInfoAdapter extends BaseAdapter {
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private List<ResolveInfo> originalListAppInfo;
private Filter filter;
private String fname;
public AppInfoAdapter(Context c, List<ResolveInfo> listApp,
PackageManager pm) {
mContext = c;
this.originalListAppInfo = this.mListAppInfo = listApp;
mPackManager = pm;
Log.d("AppInfoAdapter", "top");
}
#Override
public int getCount() {
Log.d("AppInfoAdapter", "getCount()");
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
Log.d("AppInfoAdapter", "getItem");
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
Log.d("AppInfoAdapter", "getItemId");
return position;
}
public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {
final float densityMultiplier = c.getResources().getDisplayMetrics().density;
int h= (int) (100*densityMultiplier);
int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));
default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
// TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return default_b;
}
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
// FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.activityInfo.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
Drawable icon = null;
try {
icon = pm
.getApplicationIcon(entry.activityInfo.packageName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable default_icon = pm.getDefaultActivityIcon();
if (icon instanceof BitmapDrawable
&& default_icon instanceof BitmapDrawable) {
BitmapDrawable icon_bd = (BitmapDrawable) icon;
Bitmap icon_b = icon_bd.getBitmap();
BitmapDrawable default_bd = (BitmapDrawable) pm
.getDefaultActivityIcon();
Bitmap default_b = default_bd.getBitmap();
if (icon_b == default_b) {
// It's the default icon
scaleDownBitmap(default_b, 100, v.getContext());
Log.d("AppInfoAdapter", "Scale Bitmap Chosen");
SaveImage(default_b);
Log.d("AppInfoAdapter", "Scaled BM saved to External Storage");
Intent intent = new Intent(v.getContext(), GridViewAdapter.class);
// intent.hasExtra("bitmapA");
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
GridViewAdapter:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GridViewAdapter extends BaseAdapter {
private Context Context;
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
// Constructor
public GridViewAdapter(Context c){
Context = c;
Log.d("GridViewAdapter", "Constructor is set");
drawables.add(R.drawable.pattern1);
Log.d("GridViewAdapter", "pattern1 added");
drawables.add(R.drawable.pattern2);
Log.d("GridViewAdapter", "pattern2 added");
drawables.add(R.drawable.trashcan);
Log.d("GridViewAdapter", "trashcan added");
drawables.add(R.drawable.ic_launcher);
Log.d("GridViewAdapter", "ic_launcher added");
Bitmap default_b = BitmapFactory.decodeFile("picture");
}
#Override
// How many items are in the data set represented by this Adapter
public int getCount() {
return drawables.size();
}
#Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
return drawables.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
}
FURTHER UPDATED CODING:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked = true){
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}}
PLUS I ADDED THIS METHOD:
public void setCheckBox(CheckBox checkbox){
mCheckBox=checkbox;
}
AND THIS VARIABLE:
CheckBox mCheckBox=null;
You dont need to listen to the onClick event in the adapter.
Instead, you can read the checkbox status.
for this, in your adapter, you add a field and a setter:
CheckBox mCheckBox=null;
public void setCheckBox( CheckBox checkbox){
mCheckBox=checkbox;
}
and then, in the getView(), you add thiss line at the begining;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
UPDATE
then in your activity, i suppose you have something like
GridViewAdapter mGridViewAdapter= new GridViewAdapter(this);
so, below you have to add:
CheckBox mCheckBox = findViewById(R,id.YOURCHECKBOXID);
mGridViewAdapter.setCheckBox(mCheckBox);
And that's it!

Categories

Resources