Android : Bitmap image is not passed to another java activity - android

I have developed an app that allows the following:
1. Load image from gallery and view using ImageView.
2. Save image from ImageView into gallery.
3. An alert dialog box pops out which opens into another layout when clicked 'yes'.
I would like to pass the image bitmap from the first activity to the second activity. I have followed few example but the image is not being passed. My coding are as follows.
LoadImage.java:
public class LoadImage extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
Button buttonSave;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_image);
img = (ImageView)findViewById(R.id.ImageView01);
buttonSave = (Button) findViewById(R.id.button2);
((Button) findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
buttonSave.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
img.setDrawingCacheEnabled(true);
Bitmap bitmap = img.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/PARSE");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Review the Answer?");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to submit answer!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent intent = new Intent(LoadImage.this, TestImage.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
intent.putExtra("byteArray", bs.toByteArray());
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
TestImage.java:
public class TestImage extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_image);
Intent intent = getIntent();
ImageView img = (ImageView) findViewById(R.id.ImageView01);
if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap bitmap = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);
previewThumbnail.setImageBitmap(bitmap);
}
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("byteArray");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
img.setImageBitmap(bmp);
}
}
The 'intent' is the second activity is grey out stating variable 'intent' is never used.
Can someone help me to resolve this issue. Any help is much appreciated. Thank you.
UPDATED!!
LoadImage.java:
buttonSave.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
img.setDrawingCacheEnabled(true);
final Bitmap bitmap = img.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/PARSE");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "Saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Review the Answer?");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to submit answer!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent intent = new Intent(LoadImage.this, TestImage.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
TestImage.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_image);
byte[] bytes = getIntent().getData().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView img = (ImageView) findViewById(R.id.ImageView01);
img.setImageBitmap(bmp);
}
}

Activity
To pass a bitmap between Activites
Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);
And in the Activity class
Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
Fragment
To pass a bitmap between Fragments
SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);
To receive inside the SecondFragment
Bitmap bitmap = getArguments().getParcelable("bitmap");
Transferring large bitmap (Compress bitmap)
If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.
So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this
In the FirstActivity
Intent intent = new Intent(this, SecondActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bitmapbytes",bytes);
And in the SecondActivity
byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

Bitmap implements Parcelable, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

Yes You can send Bitmap through Intent
Intent intent =new Intent(Context ,YourActivity.class);
intent.putExtra("key",bitmap);
To receive the bitmap in YourActivity.class
Intent intent=getIntent();
Bitmap image=intent.getParcelableExtra("key");
This will work fine for Small Size bitmap
When the size of Bitmap is large it will Fail to send through Intent. Beacuse Intent are mean to send small set of data in key value pair.
For this You can send the Uri of the Bitmap through Intent
Intent intent =new Intent(Context ,YourActivity.class);
Uri uri;// Create the Uri From File Or From String.
intent.putExtra("key",uri);
In your YourActivity.class
Intent intent=getIntent();
Uri uri=intent.getParcelableExtra("key");
Create the Bitmap From the Uri.
Hope It will help you.

maybe your bitmap is too large.And you will find FAILED BINDER TRANSACTION in your logcat. So just take a look at FAILED BINDER TRANSACTION while passing Bitmap from one activity to another

Related

Loading a gallery image into an imageview on a dialog

I need to load a picture into an imageview that is on a custom dialog (a class that extends dialog).
A dialog is called within a class, extends dialog and let user choose to load a picture from gallery or take a picture from camera...so far so good!
Then startActivityForResult() is not part of Dialog object!
and for getting the result
onActivityResult() also is not part of Dialog class!
Code:
package ....;
.....
public class AnosLeitura extends Dialog {
...
public void btnImageLogo_OnClick(View v) {
edLogo.setImageResource(R.drawable.no_image);
final String[] option = new String[] { "From camera",
"From gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choice");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) { callCamera(); }
if (which == 1) { callGallery(); }
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
....
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
//This is not possible!
startActivityForResult(Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
// Neither this!
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByte = stream.toByteArray();
edLogo.setImageBitmap(yourImage);
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByte = stream.toByteArray();
edLogo.setImageBitmap(yourImage);
}
break;
}
}
....
}
Does anyone know some solution?
Tks

how to put image in Android using Insert Into query in SQLite Android?

I'm a newbie in Android,
I just wondering how to store an image to SQLite database in Android, well i have database look like this.
Photo
id (int) | image (BLOB)
Then i have a class to get an image from gallery..
LogoSQLiDemoActivity
public class LogoSQLiteDemoActivity extends Activity implements OnClickListener{
ContactImageAdapter imageAdapter;
Validation valid;
DBDataSource db;
private ArrayList<image> imageArry = new ArrayList<image>();
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
int imageId;
byte[] imageName;
String nama_foto;
String nama;
Bitmap theImage;
byte imageInByte[];
private Long id;
//widget
private EditText edNama_foto;
Button addImage;
Button cancel;
ListView dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_data_photo2);
/*** create DatabaseHandler object*/
db = new DBDataSource(this);
//error in here
db.open();
dataList = (ListView) findViewById(R.id.list);
cancel = (Button)findViewById(R.id.btnCancel);
addImage = (Button) findViewById(R.id.btnAdd);
cancel.setOnClickListener(this);
Sma sekolah = db.getLastSma();
id = sekolah.getId();
/**
* Reading and getting all records from database
*/
List<image> img = db.getAllImage_Logo(id);
for (image cn : img)
{
// add contacts data in arrayList
imageArry.add(cn);
/** Set Data base Item into listview}*/
imageAdapter = new ContactImageAdapter(this, R.layout.screen_list, imageArry);
dataList.setAdapter(imageAdapter);
}
/**
* go to next activity for detail image
*/
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
imageName = imageArry.get(position).getLokasi_foto();
imageId = imageArry.get(position).get_id_sma();
Log.d("Before Send:****", imageName + "-" + imageId);
// convert byte to bitmap
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageName);
theImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(LogoSQLiteDemoActivity.this,
DisplayImageActivity2.class);
intent.putExtra("imagename", theImage);
intent.putExtra("imageid", imageId);
startActivity(intent);
}
});
/**
* open dialog for choose camera/gallery
*/
final String[] option = new String[] { "Ambil dari Kamera",
"Pilih dari Album" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pilihan");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Pilihan", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
/**
* On activity result
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap yourImage = extras.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this, LogoSQLiteDemoActivity.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null)
{
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addImage3(new image(imageInByte));
Intent i = new Intent(LogoSQLiteDemoActivity.this,
LogoSQLiteDemoActivity.class);
startActivity(i);
finish();
}
}
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 150);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnCancel:
Intent intent = new Intent(getApplicationContext(), MenuAdmin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
and this a method i use to store picture in sqlite
public void addImage3(image img) {
open(); //it's mean to open the connection from database
//THE Question is right here, how i can put a byte array into database
//without using this method, a.k.a INSERT INTO, cause i have tried to search any
//solution in google, but i can't solve my problem
ContentValues values = new ContentValues();
values.put(image, img._lokasi_foto);
// Inserting Row
database.insert(Photo, null, values);
close(); // Closing database connection
}
and here's my image class
public class image {
public byte[] _lokasi_foto;
//this is getter
public byte[] getLokasi_foto() {
return _lokasi_foto;
}
//this is setter
public void setLokasi_foto(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
and this the constructor
public image(byte[] lokasi_foto) {
this._lokasi_foto = lokasi_foto;
}
}
Can someone help me with this problem, cause i have been search in google, but i can't still solve my problem, Please Help...
Save the image in a local folder with the same name as your id. So now whenever you want to retrieve the image, just open id.jpg / id.png
private void saveToDB() {
SQLiteDatabase myDb;
String MySQL;
byte[] byteImage1 = null;
byte[] byteImage2 = null;
MySQL = "create table emp1(_id INTEGER primary key autoincrement, sample TEXT not null, audio BLOB);";
myDb = openOrCreateDatabase("Blob List", Context.MODE_PRIVATE, null);
myDb.execSQL(MySQL);
String s = myDb.getPath();
textView.append("\r\n" + s + "\r\n");
myDb.execSQL("delete from emp1");
ContentValues newValues = new ContentValues();
newValues.put("sample", "HI Hello");
try {
InputStream is = new FileInputStream("YOUR IMAGE PATH");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
textView.append("\r\n" + bytes.length + "\r\n");
newValues.put("audio", bytes);
long ret = myDb.insert("emp1", null, newValues);
if (ret < 0)
textView.append("\r\n!!! Error add blob failed!!!\r\n");
} catch (IOException e) {
textView.append("\r\n!!! Error: " + e + "!!!\r\n");
}
Cursor cur = myDb.query("emp1", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
textView.append("\r\n" + cur.getString(1) + "\r\n");
cur.moveToNext();
}
// /////Read data from blob field////////////////////
cur.moveToFirst();
byteImage2 = cur.getBlob(cur.getColumnIndex("audio"));
// bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
// byteImage2.length));
textView.append("\r\n" + byteImage2.length + "\r\n");
cur.close();
myDb.close();
}

Where to save an Image - android

I am developing Android application where users choose an icon image from a gallery. I need to save that image (bitmap), so I can use it when application is restarted.
Any simple example would be greatly appreciated.
Thanks.
Make use of the code below to save an image:
void saveImage() {
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Save");
alertDialog.setMessage("Your drawing had been saved:)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
And to retrive image from sdcard:
Supose you retrieves the image from sdcard in your Import.java Acitivty like that:
File file = new File(getExternalFilesDir(null), "MyFile.jpg");
So, once you have your image in a File object, you just need to put its path on a Intent that will be used to be a result data, which will be sent back to the "caller" activity. In some point of your "called" acitivity you should do that:
Intent resultData = new Intent();
resultData.putExtra("imagePath", file.getAbsolutePath());
setResult(RESULT_OK,returnIntent);
finish();
Your method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_OK)
{
String path = data.getStringExtra("imagePath");
}
}
That's it!
Hope it helps :)
http://developer.android.com/guide/topics/data/data-storage.html
I would suggest using external storage
Use SharedPreferences to store image in Base64 String representation.
Bitmap imageBitmap = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );
byte[] byte = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(byte , Base64.DEFAULT);
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences .edit();
sharedPreferencesEditor.putString("image_data", encodedImage).commit();
While retrieving, convert Base64 representation back to Bitmap.
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
String encodedImage = sharedPreferences.getString("image_data", "");
if( !encodedImage.equals("") ){
byte[] byte = Base64.decode(encodedImage , Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(byte, 0, byte.length);
imageView.setImageBitmap(bitmap);
}

Need to have image from Gallery to show up in IMageView at ALL TIME. Whenever the app starts

I am somewhat frustrated trying to get this to work. Can someone please help me with this. I am new to this and all i want is to get an image from Gallery/Image_capture to show on an ImageView at ALL TIME. I have been back and forth with so many ppl and have got diff answer.
This is the Activity that has a ImageView called editpic. Once user clicks on it,it opens a Dialog asking to choose from Gallery or Camera.
public int GET_CAM_IMG=2;
public int GET_GAL_IMG=1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
profile();
private void profile() {
editpic = (ImageView)findViewById(R.id.editpic);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
CharSequence[] names = { "From Gallery", "From Camera" };
new AlertDialog.Builder(context)
.setTitle("Select an option for updating your Profile Picture")
.setItems(names, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int pos) {
// TODO Auto-generated method stub
if (pos == 0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, GET_GAL_IMG);
} else {
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, GET_CAM_IMG);
}
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
}
}).create().show();
}});
ONCE USER CLICKS IT GOES THROUGH CASE AND SWITCH
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case 2://Camera
if (resultCode == -1) {
String encodedImageString = null;
Uri selectedImage = intent.getData();
String selectedImagepath = getPath(selectedImage);
editpic.setImageURI(selectedImage);
Bitmap bmp_image = BitmapFactory.decodeFile(filePath);
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
byte[] image = baos.toByteArray();
encodedImageString = Base64.encodeToString(image,
Base64.DEFAULT);
} else {
System.out.println("Compreesion returned false");
Log.d("Compress", "Compreesion returned false");
}
break;
case 3://Selecting from Gallery
if (resultCode == -1) {
String encodedImageString = null;
Bitmap bmp_image = null;
Bundle extras = intent.getExtras();
bmp_image = (Bitmap) extras.get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bmp_image.compress(Bitmap.CompressFormat.JPEG, 50, baos)) {
byte[] image = baos.toByteArray();
encodedImageString = Base64.encodeToString(image,
Base64.DEFAULT);
} else {
System.out.println("Compression returned false");
Log.d("Compress", "Compression returned false");
}
}
break;
}
}
TRIED CREATING A METHOD SO I CAN GET THE IMAGE PATH AND THEN USE THAT BUT COULDN'T GET IT TO WORK
SharedPreferences userprofile = getSharedPreferences(filename,0);
SharedPreferences.Editor editor = userprofile.edit();
editor.putString("Imagepath",selectedImagepath);
editor.commit();
AFTER TAKING THE PIC, images comes on Imageview but disappears. I want it to be there as this is a profile pic. It is suppose to be something the contact pic in phonebook.

Capture Screen Programmatically not working

I have following method to Capture Screen on Action Item Click. Its working on Android <2.3 but not on 4+. What is wrong with this way of screen capture.
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capturedImage", capturedBitmap);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
The ScreenCaputureAlertActivity.java >>>
public class ScreenCapturedAlertActivity extends SherlockActivity {
private ImageView capturedImage;
private Bitmap capturedBitmap;
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_screencaptured_alert);
capturedBitmap = (Bitmap) getIntent().getParcelableExtra("capturedImage");
name = getIntent().getStringExtra("name");
capturedImage = (ImageView) findViewById(R.id.ivCapturedImage);
capturedImage.setImageBitmap(capturedBitmap);
}
private void saveAndShare(boolean share) {
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/capture/");
if(!dir.exists())
dir.mkdirs();
FileOutputStream outStream = null;
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
File file = new File(dir, "Capture "+n+".jpg");
if(file.exists()) {
file.delete();
}
try {
outStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}
if(share) {
Uri screenshotUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Location of " + name);
intent.putExtra(Intent.EXTRA_TITLE, getText(R.string.screen_share_message));
intent.putExtra(Intent.EXTRA_TEXT, getText(R.string.screen_share_message));
intent.setType("image/*");
startActivity(Intent.createChooser(intent, "Share with"));
finish();
} else {
Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStorageDirectory())));
finish();
}
}
public void saveCapture(View view) {
saveAndShare(false);
}
public void shareCapture(View view) {
saveAndShare(true);
}
}
Thanks to #KumarBibek guidance.
The error I was getting was
!!! FAILED BINDER TRANSACTION !!!
So as from the selected answer from the link
Send Bitmap as Byte Array
I did like this in first activity:
private void captureScreen() {
View v = mapView.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap capturedBitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
capturedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
if(capturedBitmap != null) {
Intent intent = new Intent(this, ScreenCapturedAlertActivity.class);
intent.putExtra("capture", byteArray);
intent.putExtra("name", location.getName());
startActivity(intent);
} else {
Toast.makeText(this, "Screen Capture Failed", Toast.LENGTH_SHORT).show();
}
}
And in ScreenCapturedAlertActivity :
byte[] byteArray = getIntent().getByteArrayExtra("capture");
capturedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
It is working WELL now. Thanks again to #KumarBibek
Instead of passing the whole bitmap, try passing the file saved file's path to the next activity. Bitmap is a large object, and it's not supposed to be passed around like that.
Since you already checked the the image is being saved fine, if you deal with paths instead of bitmaps, I think it would solve your problem.

Categories

Resources