Android Share sliding image on whatsapp using intent from viewPager using glide - android

I am working on online gallery app, in a fragment Dialog images from specific displaying as a viewPager.
But the main problem i am unable to share a particular image on whatsapp because I am finding difficulty to get imageViewPreview.
Here is the code for loading image in viewPager
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);
final ImageView imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);
Image image = images.get(position);
Glide.with(getActivity()).load(image.getLarge())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageViewPreview);
container.addView(view);
return view;
}
Now i am trying to get image from imageViewPreview from
whatsappShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG, "Click working");
//shareImage();
// ImageView imageWhatsapp = (ImageView) view.findViewById(R.id.image_preview);
Uri bmpUri = getLocalBitmapUri(imageViewPreview);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
shareIntent.setPackage("com.whatsapp");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
Log.e(TAG, "ERROR" + bmpUri);
}
}
});
My getLocalBitmapUri() methos is as follow:
public Uri getLocalBitmapUri(ImageView imageViewPreview) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageViewPreview.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
Log.e(TAG, "popopo: " + file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
But the problem is I am getting **NULL** from getLocalBitmapUri() method.
please guide me the get imageViewPreview.

i had faced sacreate this method, few time ago i used it and work, i forgot who given this snippet.
public Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
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;
}
at your getLocalBitmapUri()
public Uri getLocalBitmapUri(ImageView imageViewPreview) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageViewPreview.getDrawable();
Bitmap bmp = drawableToBitmap(imageViewPreview);
//...................
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
if(!file.exist()) file.createNewFile();
//..............

Related

i have image view page and i want to add a button to share image from ImageView

i tried the code in ViewPictureActivity.java to share image but i got many errors Below:
public class ViewPictureActivity extends AppCompatActivity {
private static final String KEY_PICTURES = "pics";
private static final String KEY_REQUESTED_POS = "requestedPos";
private ArrayList<Integer> imageIDs;
private int currentPosition = -1;
private ImageView galleryPicture;
Bitmap bitmap;
private File imagePath;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_picture);
initToolbar();
galleryPicture = (ImageView) findViewById(R.id.galleryImage);
imageIDs = (ArrayList<Integer>) getIntent().getSerializableExtra(KEY_PICTURES);
currentPosition = getIntent().getIntExtra(KEY_REQUESTED_POS, 0);
changePicture(currentPosition);
final ImageButton previousItemButton = findViewById(R.id.previous_item_button);
previousItemButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
if (imageIDs != null && imageIDs.size() > 0 && currentPosition > 0) {
changePicture(--currentPosition);
}
}
});
final ImageButton nextItemButton = findViewById(R.id.next_item_button);
nextItemButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
if (imageIDs != null && imageIDs.size() > 0 && imageIDs.size() > currentPosition + 1) {
changePicture(++currentPosition);
} else {
Toast.makeText(getApplicationContext(), "No more pictures", Toast.LENGTH_SHORT).show();
}
}
});
final ImageButton btnshare = findViewById(R.id.btnShare);
btnshare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
OutputStream output;
FrameLayout fm = (FrameLayout) findViewById(R.id.frm2);
Calendar cal = Calendar.getInstance();
Bitmap bitmap = Bitmap.createBitmap(fm.getWidth(),
fm.getHeight(), Config.ARGB_8888);
Canvas b = new Canvas(bitmap);
fm.draw(b);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/D_Envitation/");
dir.mkdir();
String imagename = "image" + cal.getTimeInMillis() + ".png";
// Create a name for the saved image
File file = new File(dir, imagename);
// Show a toast message on successful save
Toast.makeText(ViewPictureActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Uri screenshotUri = Uri.fromFile(file);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(share, "Share With"));
}
});
}
private void initToolbar() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Toolbar displayActToolbar = findViewById(R.id.simple_toolbar);
setSupportActionBar(displayActToolbar);
}
}
private void changePicture(int arrayPosition) {
//galleryPicture.setLayoutParams(new LinearLayout.LayoutParams(500,500));
//galleryPicture.setScaleType(ImageView.ScaleType.CENTER_CROP);
galleryPicture.setImageResource(imageIDs.get(arrayPosition));
}
// starter - to control passing and reading Extra in the same class
public static void start(Context context, ArrayList<Integer> imageIDs, int requestedPos) {
Intent starter = new Intent(context, ViewPictureActivity.class);
starter.putExtra(KEY_PICTURES, imageIDs);
starter.putExtra(KEY_REQUESTED_POS, requestedPos);
context.startActivity(starter);
//Log.d("ViewPictureActivity", "after start");
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hal9000.gridgallery, PID: 23639
android.os.FileUriExposedException: file:///storage/emulated/0/D_Envitation/image1558562487343.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1958)
at android.net.Uri.checkFileUriExposed(Uri.java:2348)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:941)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9735)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9741)
at android.content.Intent.prepareToLeaveProcess(Intent.java:9720)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1609)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
at android.app.Activity.startActivity(Activity.java:4791)
at android.app.Activity.startActivity(Activity.java:4759)
at com.hal9000.gridgallery.ViewPictureActivity$3.onClick(ViewPictureActivity.java:139)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
you can share an image with another app without saved into mobile
public void OnClickShare(View view){
Bitmap bitmap =getBitmapFromView(YourView);
try {
File file = new File(this.getExternalCacheDir(),"logicchip.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
//start share image with intent
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share image via"));
} catch (Exception e) {
e.printStackTrace();
}
}
and this method to get Bitmap from ImageView
// can replace parmeter with ImageView in your state
private Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
//or use #getDrawable with ImageView
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else{
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
return returnedBitmap;
}
I hope this help and don't forget to read the comment in the code to know what you want

Share loaded image with glide from imageview

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}

How to save an image attached to the image view?

I am using a Glide library for loading remote URLs into ImageView's.
I want to save the image from this ImageView to gallery. (I don't want to make another network call again to download the same image).
How we can achieve this?
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//set bitmap to imageview and save
}
};
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
String fileName = "image.jpeg";
File file = new File("your_directory_path/"
+ fileName);
try {
file.createNewFile();
// write the bytes in file
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
// remember close the FileOutput stream
fileOutputStream.close();
ToastHelper.show(getString(R.string.qr_code_save));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ToastHelper.show("Error");
}
Note : If your drawble is not always an instanceof BitmapDrawable
Bitmap bitmap;
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Try this
I haven't try this way. But i think this match your problem. Put this code on onBindViewHolder of your RecyclerView adapter.
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//Set bitmap to your ImageView
imageView.setImageBitmap(bitmap);
viewHolder.saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Save bitmap to gallery
saveToGallery(bitmap);
}
});
}
};
This might help you
public void saveBitmap(ImageView imageView) {
Bitmap bitmap = ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/My Images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + 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();
} catch (Exception ex) {
//ignore
}
}

How to share external image in custom listview?

I have created a custom listview that is handled by a custom adapter. Each item in this list displays an image and a share button. The images are loaded from external sources with ion. This works fine.
Now I want to share the image when the user clicks on the button. While I'm able to share text, etc. I'm not able to share these external images, even after implementing this code: Sharing Remote Images
Two things:
I'm new to android so I might be using the setTag/getTag completely wrong
if (drawable instanceof BitmapDrawable) is false, but I don't know why or how to fix this
Any help or suggestion is greatly appreciated!
This is the code from my adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
//brand new
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.contentImageView = (ImageView) convertView.findViewById(R.id.contentImageView);
holder.contentLabel = (TextView) convertView.findViewById(R.id.contentLabel);
holder.contentShareButton = (Button) convertView.findViewById(R.id.contentShareButton);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Content content = mContents[position];
Ion.with(mContext)
.load(content.getSrc()) //the external image url
.intoImageView(holder.contentImageView);
holder.contentLabel.setText(content.getTitle());
holder.contentShareButton.setTag(holder.contentImageView);
holder.contentShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView ivImage = (ImageView) v.getTag();
//ImageView ivImage = (ImageView) findViewById(R.id.ivResult);
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(ivImage);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
mContext.startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
Log.i("test", "Sharing failed, handler error.");
}
}
});
return convertView;
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
Log.i("test", "is null");
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
Adding these four lines to the getLocalBitmapUri-function got it working for me:
bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
And here is the complete function with the updated code:
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

setting up byte array in gridView from intent

I have an onClick listener of a checkbox set up here:
#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");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
default_b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Log.d("AppInfoAdapter", "Scale Bitmap to Array");
Intent intent = new Intent(v.getContext(), Drag_and_Drop_App.class);
intent.putExtra("picture", byteArray);
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
and am trying to get the Intent sent here (that contains the bitmap) to my gridView here (this is the gridView adapter):
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
// Constructor
public GridViewAdapter(Context c){
mContextGV = 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");
}
But since I don't have anything to get in my adapter, I would have to get the bitmap here: (where my gridView is actually set up):
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// GridView
Log.d("D&D", "onCreate called");
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap default_b = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
android.widget.GridView gridView = (android.widget.GridView) findViewById(R.id.GRIDVIEW1);
// Instance of Adapter Class
gridView.setAdapter(new GridViewAdapter(this));
But then I am unable to add that bitmap default_b to my gridView.
How can I do this?
UPDATED CODING:
#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);
Intent intent = new Intent(v.getContext(),Drag_and_Drop_App.class);
intent.putExtra("picture", fname);
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
and here is the class:
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 +".jpg";
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You shouldn't be passing a byte array into an intent. Intent bundles have a maximum size when being sent between activities, and furthermore may bog down your application as they are serialized and deserialized.
See also this issue describing your exact problem, and note that the issue was closed with "working as intended". In the words of Romain Guy:
It is very costly to pass large amount of data via Intents. You should NOT be using
Intents as a transport mechanism for bitmaps. Instead, pass around URIs or any other
location mechanism (file path, etc.)
I would urge you to write the image to the cache directory and read it asynchronously from the other activity.

Categories

Resources