I'm trying to send an image from a activity to another, i was reading similar questions but none solved my problem.
The code I am using to send this picture is
public void aceptar (View view) {
ImageView iv = (ImageView) findViewById(R.id.foto);
iv.setImageBitmap(BitmapFactory.decodeFile(foto));
File file = new File(foto);
Intent intent = new Intent(this, XMPPClient.class);
ImageView img_view = (ImageView) findViewById(R.id.foto);
img_view.setBackgroundResource(intent.getIntExtra("foto",1));
startActivity(intent);
}
and to receive the image
Bundle extras = getIntent().getExtras();
if (extras == null)
{
return;
}
int res = extras.getInt("resourseInt");
ImageView foto = (ImageView) findViewById(R.id.foto);
view.setBackgroundResource(res);
the error is this
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
This has been asked before,
Passing image from one activity another activity
There are 3 Solutions to solve this issue.
"1) First Convert Image into Byte Array and then pass into Intent and in next activity get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView.
Convert Bitmap to Byte Array:-
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray();
Pass byte array into intent:-
Intent intent = new Intent(this, NextActivity.class); intent.putExtra("picture", byteArray); startActivity(intent);
Get Byte Array from Bundle and Convert into Bitmap Image:-
Bundle extras = getIntent().getExtras(); byte[] byteArray = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); ImageView image = (ImageView) findViewById(R.id.imageView1); image.setImageBitmap(bmp);
2) First Save image into SDCard and in next activity set this image into ImageView.
3) Pass Bitmap into Intent and get bitmap in next activity from bundle, but the problem is if your Bitmap/Image size is big at that time the image is not load in next activity."
This has been asked before but it's possible. Are you trying to pass an Image or ImageView?
Both are possible
ImageView: Pass ImageView from one activity to another - Intent - Android
Integer.parseInt() only works for strings like "1" or "123" that really contain just the string representation of an Integer.
What you need is find a drawable resource by its name.
This can be done using reflection:
String name = "image_0";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);
Or using Resources.getIdentifier():
String name = "image_0";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
Related
I have an activity with an ImageView and I want to send this ImageView in an other activity, how can I do this?
You can't actually pass the ImageView itself. You can however, pass it's value and re-load that in your other Activity in it's own new ImageView.
You can pass data between Activitys in the intent.
This goes per example like this;
Intent intent = new Intent(this, MyNewActivity.class);
intent.putExtra("EXTRA_IMAGEVIEW_URL", myImageViewData);
startActivity(intent)
Then in the started (MyNewActivity) you can fetch that data again;
String imageview_url = getIntent().getStringExtra("EXTRA_IMAGEVIEW_URL");
Use whatever method is appropriate for your type of data.
edit note:
This solution is assuming that you send a simple pointer to the image, not the image itself. You either send the URL or URI from where you load it, your drawable ID or the image path in your file system. Indeed, do not try to send the whole image itself as a base64, binary or whatever you come up with.
You cannot pass imageviews between activties.
Assuming you need to pass the image from one activity to another.
You can pass bitmap by converting it to bytearray as below
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Pass byte array into intent:-
Intent intent = new Intent(FirstActivity.this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
In NextActivity Get Byte Array from Bundle and Convert into Bitmap Image:-
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
Update : 5-9-2019
Note: It is better to store the image in some place on the disk and then pass only the path to the image to next activity. The above might not work if the image is huge.
you can either subclass imageview and implement serializable interface and pass it with this way or you can pass resource id(int) of imageview to another activity then load that activity's imageview with this resource id or you make imageview static and then at the other acitvity you simply call it via FirstClass.imageView
Passing bitmap by converting it to bytearray works fine with me
I have a list view which displays a image, name, price.
What m trying to do is on click on that list I should send the image the name and price to next activity.
Intent in = new Intent(getApplicationContext(), DescActivity.class);
ImageView img=(ImageView)view.findViewById(R.id.list_image);
String name=((TextView) view.findViewById(R.id.name)).getText().toString();
String price=((TextView) view.findViewById(R.id.price)).getText().toString();
Bitmap bitmap = img.getDrawingCache();
in.putExtra("IMAGE", bitmap);
in.putExtra("NAME",name );
in.putExtra("PRICE", price);
startActivity(in);
But the above code is not working. please help me. m stuck with this for 3 days :'(
Did you try this,
Intent i = new Intent(this, SecondActivity.class);
Bitmap b = img.getDrawingCache();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("myImage", bs.toByteArray());
startActivity(i);
Then in your next Activity use
if(getIntent().hasExtra("myImage")) {
ImageView image = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("myImage"),0,getIntent().getByteArrayExtra("myImage").length);
image.setImageBitmap(b);
}
try this-
make bitmap static in first activity. i.e.
static Bitmap bitmap = img.getDrawingCache();
and in second activity-
Bitmap _mBitmap=FirstAcitivity.bitmap;
you can also use this-
in first activity-
Drawable drbl=_imageView.getDrawable();
Bitmap bit = ((BitmapDrawable)drbl).getBitmap();
intent.putExtra("Bitmap",bit);
In second acivity-
Bitmap _mBitmap=intent.getParcelableExtra("Bitmap");
Drawable _mDrawable=new BitmapDrawable(getResources(),_mBitmap);
I'm developing a simple android game divided into levels. I want a check icon (ImageView) to appear next to a level button (on level select menu) when that level is completed.
A level is completed after pressing a button, as follows (InsideLevelActivity):
final EditText level1editText=(EditText)findViewById(R.id.level1editText);
Button level1completeButton=(Button)findViewById(R.id.level1completeButton);
level1completeButton.setOnClickListener(new View.OnClickListener()
public void onClick(View v)
{
final String edittext=level1editText.getText().toString();
if(edittext.trim().equals("Complete level"))
{
{
Intent visible1 = new Intent();
visible1.putExtra("iconvisible",0);
startActivity(visible1);
{
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_level1completed,
(ViewGroup) findViewById(R.id.img11_toast));
Toast toast = new Toast(Level1Activity.this);
toast.setView(view);
toast.show();
{ onBackPressed(); {
return;
}
}
}
else
{
Toast.makeText(Level1Activity.this,
"Type Complete level.", Toast.LENGTH_LONG).show();
}
And then returns to level select menu activity. I'm trying to retrieve data this way (LevelMenuActivity):
ImageView logocheckicon1=(ImageView)findViewById(R.id.logocheckicon1);
logocheckicon1.setVisibility(View.GONE);
Intent visible1 = getIntent();
int state = Integer.parseInt(visible1.getExtras().get("iconvisible").toString());
complete1.setVisibility(iconvisible);
I've tried many approaches for the last couple of days, including this one (how to pass data between two activities). I've even tried to make the check icon (ImageView) invisible, and making it visible again this way.
Also, the same check icon will appear next to every completed level. Is it possible to acomplish this with only one ImageView (without creating 10 different IDs of the same drawable)?
Thank you in advance.
EDIT:
I apologize if i wasn't clear enough. I tought there was some way to change the visibility of an image located, for instance, on MainActivity with an intent inside the button on another activity.
Thank you for your answers.
EDIT2: Added the code of another unsuccessful try.
To Pass image from one activity to another activity. At First convert image into Bitmap then base64 then convert string then pass it via intent or save share-preference.
public boolean saveImage(Context context, Bitmap realImage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
}
Then take this image in another activity via intent or get from share-preference
public Bitmap getFacebookImageBitmap(Context context)
{
Bitmap bitmap = null;
String saveimage=from intent or share-preference string.
if( !saveimage.equalsIgnoreCase("") ){
byte[] b = Base64.decode(saveimage, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
}
return bitmap;
}
Thanks
You can pass the image through intents. First convert your image to a byte array and send it with the intent.
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picture", b);
startActivity(intent);
then you can retrieve this image from the next avtivity.
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
Hope this will help you.
I want to pass the Background Image that I have set to Button in PutExtra() with intent object into another Class.
Can anybody know how to do that ?
Thanks
davidbrown
Sender Activity:
Bitmap bitmap = BitmapFactory.decodeResource
(getResources(), R.drawable.sticky_notes); // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
Reciever Activity:
if(getIntent().hasExtra("byteArray")) {
ImageView imv= new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
imv.setImageBitmap(bitmap);
}
Intent can keep only 40 kbytes. If you can zip your images less then 40 kbytes - you can put it into extras
intent.putExtra("imageData", bitmap)
better approach is to create a link instead of passing directly bitmap.
intent.putExtra("image_url",R.drawable.image);
try this...
first get image in bitmap.
Bitmap tileImage = BitmapFactory.decodeResource(getResources(), R.drawable.floore);
Conver it in byte array.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bundle b = new Bundle();
b.putByteArray("camara",byteArray);
Intent intent3 = new Intent(this,Second.class);
intent3.putExtras(b);
startActivity(intent3);
You can pass Bitmap (since it's implementing Parcelable) if you're sure that it won't be deleted from memory (in other words - don't store Bitmaps like that).
Bitmap itself is just a small Java wrapper of native resources, so it won't take a lot of space.
Be careful when passing files that can be very large, such as a photo or gallery file. Even if you compress it, the size may exceed putExtra's acceptable limit. I suggest sending the image link or file path for a file from the gallery. In my app I always compress my files as max as I can, but there was always one that crashs the app.
Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
intent.putExtra("url", url);
//OR file path
intent.putExtra("path", path);
startActivityForResult(intent,PHOTO_VIEW_REQUEST);
In that case on PhotoViewActivity
String url = getIntent().getStringExtra("url");
String path = getIntent().getStringExtra("path");
if(url != null && !url.isEmpty()){
//Get using Picasso or other framework
}else if(path != null && !path.isEmpty()){
//In my case I transform in Bitmap
//see this link for more detail : https://stackoverflow.com/questions/16804404/create-a-bitmap-drawable-from-file-path
}else{
//Throw exception and close activity
}
How transform path in Bitmap:
Create a Bitmap/Drawable from file path
How can I pass an image, drawable type between activities?
I try this:
private Drawable imagen;
Bundle bundle = new Bundle();
bundle.putSerializable("imagen", (Serializable) unaReceta.getImagen());
Intent myIntent = new Intent(v.getContext(), Receta.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
But it reports me an execption:
java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable
1) Passing in intent as extras
In the Activity A you decode your image and send it via intent:
Using this method (extras) image is passed in 162 milliseconds time interval
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picture", b);
startActivity(intent);
In Activity B you receive intent with byte array (decoded picture) and apply it as source to ImageView:
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
2) Saving image file and passing its reference to another activity
WHY to do so? - taken from http://groups.google.com/group/android-developers/browse_frm/thread/9309931b3f060284#
"The size limit is: keep it as small as possible. Definitely don't put
a bitmap in there unless it is no larger than an icon (32x32 or
whatever).
In *Activity A* save the file (Internal Storage)
String fileName = "SomeName.png";
try {
FileOutputStream fileOutStream = openFileOutput(fileName, MODE_PRIVATE);
fileOutStream.write(b); //b is byte array
//(used if you have your picture downloaded
// from the *Web* or got it from the *devices camera*)
//otherwise this technique is useless
fileOutStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Pass location as String to Activity B
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picname", fileName);
In *Activity B* retrieve the file
Bundle extras = getIntent().getExtras();
String fileName = extras.getString("picname");
Make *drawable* out of the picture
File filePath = getFileStreamPath(fileName);
Drawable d = Drawable.createFromPath(filePath.toString());
Apply it to the ImageView resource
someImageView.setBackgroundDrawable(d);
You can tag each image (in the xml, or programmaticlly) with the image resource name (like "img1.png"),
then retrieve the image name using the getTag();
Then use getResources().getIdentifier(image name,"drawable", .getPackageName()) to get the drawable resource id.
And just pass the resource id through the intent -
intent.putExtra("img 1",resource id);
Lastly the result Activity can create the image from the resource using:
getResources().getDrawable(intent.getIntExtra("img 1",-1));
Drawable objects are not inherently serializable, so they cannot be passed directly in Intent extras. You must find another way to serialize or persist the image data and retrieve it in the new Activity.
For example, if you are working with BitmapDrawable instances, the underlying Bitmap could be written out to a file and read back, or serialized into a byte array (if its small enough) and the byte array could be passed via extras of an Intent.
HTH
Much much much better not to pass (or serialize) Drawables around among Activities. Very likely your are getting the drawable out of a resource. Hence there's a resource ID. Pass that around instead, that's just an int. And re-hydrate the Drawable in the other Activity.
If the Drawable is not coming from a resource, but it's built at runtime in memory ... well let's speak about it. #Devunwired has a nice suggestion in that case.
You can simply use a native buildDrawingCache method:
ImageView imageView = imageLayout.findViewById (R.id.img_thumb);
imageView.buildDrawingCache ();
Bundle extras = new Bundle ();
extras.putParcelable ("image", imageView.getDrawingCache ());
Intent intent = new Intent (this, ImageActivity.class);
intent.putExtras (extras);
startActivity (intent);
then get it at your ImageActivity:
Bundle bundle = getIntent ().getExtras ();
if (bundle != null) {
ImageView imageView = findViewById (R.id.img_full);
Bitmap image = bundle.getParcelable ("image");
imageView.setImageBitmap (image);
}
In case you pull those images from web and load them again and again, caching them would be really good option since you'll decrease network traffic and increase loading speed. I suggest using WebImageView from Droid-Fu. Really good solution, used it on some projects and I'm very satisfied with it.
I don't know if this is the case, but if the reason why you are trying to pass a drawable is because you are using an Imageview, just put the resource id in the imageview's tag, pass the tag as an Integer instead of the drawable in the intent's extra and use the following line in the receiving activity:
imageView.setImageDrawable(getResources().getDrawable(getIntent().getIntExtra("image_id",0)));
Hope it will help someone.