Save bitmap when change layout - android

I've a layout to portrait and a layout to landscape. In those layout, there is a ImageView with onClick listener. My ImageView has a default image (a camera icon)
When I push into ImageView, open a dialog and I can open camera and take a picture or open gallery and select a image.
Then, I save a bitmap and put it in the ImageView. This bitmap is a global variable in my class.
But when I turn my app, load my other layout (main_landscape) and if I took a pic, I lose my bitmap and charge default image.
This is my code:
public void takePicture(View view) {
final CharSequence[] options = { "Take a pic", "Gallery","Cancel" };
//Build an AlertDialog object
AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Picture");
//onClickListener method
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int selected) {
if(options[selected].equals("Take a pic")){
//open camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
//this is my global bitmap and I put it null when I push take a picture
resized=null;
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if(options[selected].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else{
dialog.dismiss();
}
//if user doesn't select anything, show default icon
//show picture is my layout ImageView and cameraicon is my default icon
showPicture.setImageResource(R.drawable.cameraicon);
}
});
builder.show();
}
This is my onActivityResult code:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
//if my resultCode is RESULT_OK
if(resultCode == RESULT_OK){
if(requestCode==1){
File f = new File(Environment.getExternalStorageDirectory().toString());
for(File temp: f.listFiles()){
if(temp.getName().equals("temp.jpg")){
f=temp;
break;
}
}
try{
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
newHeight=600;
newWidth=900;
//resized is my global bitmap
resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
//show my new bitmap in my ImageView
showPicture.setImageBitmap(resized);
} catch (Exception e) {
e.printStackTrace();
}
}
//I choose gallery option
else if(requestCode==2){
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage,filePath,null,null,null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
newHeight=600;
newWidth=900;
//my global bitmap
resized = Bitmap.createScaledBitmap(thumbnail, newHeight, newWidth, true);
//show new bitmap in my ImageView
showPicture.setImageBitmap(resized);
}
}
}
When I turn my phone, I loose my bitmap. What I can do, please?
Thanks a lot!!

I think you save the value of your Bitmap by calling onSaveInstaceState(Bundle bundle) and then restore it when the activity is recreated.

You might want to store the filename to your photo file inside the activity:
class MyActivity {
File imageFile = null;
}
Since your activity will get destroyed on rotation, you need to save that image file name in onSaveInstanceState():
public void onSaveInstanceState(Bundle outState)
{
if (imageFile != null) {
outState.putString("IMAGE_FILENAME", imageFile.getAbsolutePath());
}
}
Bitmaps in android are Parcelable, so instead of storing the filename of the image you could also save the Bitmap itself.
The saved state gets passed to onCreate() when your activity gets re-created:
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
if (savedState != null) {
String imagePath = saveState.getString("IMAGE_FILENAME");
if (imagePath != null) {
imageFile = new File(imagePath);
}
}
updateImageView();
}
public void updateImageView()
{
// code from onActivityResult() to load the image
}
Side Notes:
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp: f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
You are writing to the global, external storage directory. Please don't do this, use your application's files' directory. Also, no need to search for a fixed filename in the path, simply check if the file exists.
File imageFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), imageFileName);
if (imageFile.exists()) {
[...]
}

I think better way to do it is using fragment instead activity.
Use method fragment.setRetainInstance(true), and fragment will not be destroyed, when you turn your device.

Related

How to make a "ImageView" field as mandatory in android?

I have a imageview field in my android app, onclick of the same I have given a "open camera" functionality and the user can click the photo from camera and it gets uploaded to ImageView
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_image.getDrawable() == null ){
Toast.makeText(NewCall4.this, "No image uploaded", Toast.LENGTH_SHORT).show();
}
else{
Intent i=new Intent(NewCall4.this,NewCall5.class);
startActivity(i);
}
}
}
);
What I want is, if I am not uploading the image in the imageview then it should give the error/toast message as "Image not uploaded"
You Can check the Drawable if attached to ImageView
Imageview imageView = (ImageView)findViewById(R.id.image);
if(imageView.getDrawable() == null){
//Then Nothing is attached with imageviw
}
It is so simple. When You call Intent for camera open it gives callback in onActivityResult in that just pass the value of the image. And check it is null or not in the click event.
Example :-
=> To Open Camera :-
Intent intent1 = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, camera);
You will get a callback in onActivityResult
=> onActivityResult :- ( I am getting actual Image path here)
if (resultCode == RESULT_OK && requestCode == camera) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
addprofile.setImageBitmap(photo); // set image to imageview
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalfile = new File(getrealpathfromuri(tempUri));
imagepath = finalfile.toString(); // imagepath is a global variable
}
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(),photo,"Title",null);
return Uri.parse(path);
}
private String getrealpathfromuri(Uri tempUri) {
String path = "";
if(getContentResolver() != null){
Cursor cursor = getContentResolver().query(tempUri, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
int idk = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idk);
cursor.close();
}
}
return path;
}
Finally imagepath has an actual path of the image.
=> Check imagepath null or not :- (in event)
if (imagepath == null) {
Toast.makeText(this, "Please Select FileImage", Toast.LENGTH_SHORT).show();
}
Hi you can try something like this
Imageview img = (ImageView)findViewById(R.id.image){
img .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, id);
}
});
And OnResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap photo = (Bitmap) data.getExtras().get(“data”);
img.setImageBitmap(photo);
}

Image captured by camera is not saving

I'm fairly new to android development and I'm trying to create an app that calls implicit intent for the camera by clicking one button. Once the image is captured you can click back button to get to main activity. In the main activity there's second button that when you click it you can see recent files and the captured image should be showing there
I was working through https://developer.android.com/training/camera/photobasics.html#TaskScalePhoto
Used the following code for capturing the image
final TextView textviewcamera = (TextView) findViewById(R.id.TextView1);
final int REQUEST_IMAGE_CAPTURE = 1;
// Set an OnClickListener on this Text View
// Called each time the user clicks the Text View
textviewcamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/*
opens the camera app and we are able to take a photo, photo is not save anywhere, needs to be fixed
code is from android studio, DON'T FORGET to cite
https://developer.android.com/training/camera/photobasics.html
*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if (takePictureIntent.resolveActivity(getPackageManager()) != null)
//{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
//}
}
Then I have another piece of code that shows the recent files
final TextView textviewpicture = (TextView) findViewById(R.id.TextView2);
// Set an OnClickListener on this Text View
// Called each time the user clicks the Text View
textviewpicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
opens the camera app and we are able to take a photo, photo is not save anywhere, needs to be fixed
code is from android studio, DON'T FORGET to cite
https://developer.android.com/training/camera/photobasics.html
*/
Intent viewpicture = new Intent();
viewpicture.setType("image/*");
viewpicture.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(viewpicture, "Select Picture"), 10);
}
});
I'm able to open the camera and take the photo however when I try to view it in my recent files, this part is not working.
Any help would be highly appreciated
Thanks a mill everyone :)
override your onActivityresult there you can preview your image from there save it to external storage
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
if (resultCode != RESULT_CANCELED)
{
if (resultCode == RESULT_OK) {
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
saveImageToExternalStorage(bitmap)
}
} else{
//show error message
}
} }
public static File saveImageToExternalStorage(Bitmap finalBitmap) {
File file;
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/easyGovs");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".png";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 55, out);
out.flush();
out.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
and while passing your intent for camera use this -
private Uri fileUri;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

How to show Picture into a activity after taken and saved from custom camera

In My app I am taking picture and I am successfully saving it in the gallery after compressing it. Now I want to show it into other activity, so that user can share it or view it at least. So How can I do that.
Following is my code which is saving picture and just after saving it, it shows ad , and on the adClosed event I want to send that taken picture to other activity , How Can I do that. My code just goes like this ..
File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "MyAnimals");
storagePath.mkdirs();
String finalName = Long.toString(System.currentTimeMillis());
//this snippet is saving image And I am showing ad after saving picture
File myImage = new File(storagePath, finalName + ".jpg");
String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/" + finalName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
//refreshing gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(myImage));
sendBroadcast(mediaScanIntent);
} catch (IOException e) {
Toast.makeText(this, "Pic not saved", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "Pic saved in: " + photoPath, Toast.LENGTH_SHORT).show();
displayInterstitial();
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
Log.v("Add time");
Intent intent = new Intent(CameraActivity.this,ShowCapturedImage.class);
//Now How to send the saved picture to the image view of other activity?
startActivity(intent);
super.onAdClosed();
}
});
1) put taken image path in intent
2) get path in other activity and set it in imageview
public static final int REQUEST_CODE_FROM_CAMERA = 112;
private Uri fileUri;
String image_path = "";
//Catch image from below function
private void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("FROM CAMERA CLICKED file uri", fileUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_CODE_FROM_CAMERA);
}
//On Activity result store image path
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_FROM_CAMERA
&& resultCode == Activity.RESULT_OK) {
try {
image_path = fileUri.getPath();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
On Click of any button
Intent iSecond=new Intent(FirstActivity.this,SecondActivity.class);
iSecond.putExtra("image_path",image_path);
startActivity(iSecond);
In Second Activity onCreate()
Bundle extras = intent.getExtras();
if(extras != null)
String image_path = extras.getString("image_path");
From this image path , You can get image and set to imageview
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView1);
File imgFile = new File("/storage/emulated/0/1426484497.png");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}
You can do this by adding a ImageView to your Activity.
A simple ImageView should look like this:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView" />
Then you capture it in your Activity class
ImageView imageView = (ImageView) this.findViewById(R.id.imageView);
Now the fun part. We'll capture your image using the image URI and parse it in a bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath()); //Here goes your image path
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap,imageView.getWidth(), imageView.getHeight(), false)); //I scale the bitmap so it show properly. If the image is too big, it wont show on the ImageView
That should do the trick, tell me if it works!

Take a photo, save it in app drawables and display it in an ImageButton

I have an Android app with an ImageButton. When user clicks on it, intent launches to show camera activity. When user capture the image, I'd like to save it in drawable folder of the app and display it in the same ImageButton clicked by the user, replacing the previous drawable image. I used the activity posted here: Capture Image from Camera and Display in Activity
...but when I capture an image, activity doesn't return to activity which contains ImageButton.
Edit code is:
public void manage_shop()
{
static final int CAMERA_REQUEST = 1888;
[...]
ImageView photo = (ImageView)findViewById(R.id.getimg);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST);
}
});
[...]
}
And onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
ImageButton getimage = (ImageButton)findViewById(R.id.getimg);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap getphoto = (Bitmap) data.getExtras().get("data");
getimage.setImageBitmap(getphoto);
}
}
How can I also store the captured image in drawable folder?
once you've saved the image to a file you can use the following snippet to add to gallery.
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, new File(path).toString());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, path);
getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI , values);
to save the file to a directory do the following
private saveFileToDir() {
final InputStream in = Wherever you input stream comes from;
File f = generatePhotoFile();
OutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len;
while ((len=in.read(buffer))>0)
{
out.write(buffer,0,len);
}
in.close();
out.flush();
out.close();
}
private File generatePhotoFile() throws IOException {
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyymmdd_hhmmss");
String newPicFile = "IMG_"+ df.format(date) + ".jpg";
File f = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera/", newPicFile);
if (!f.exists())
{
if(!f.getParentFile().exists())
f.getParentFile().mkdir();
f.createNewFile();
}
return f;
}
How can I also store the captured image in drawable folder?
It's not possible to save an image to the drawable folder dynamically:
See:
android image save to res/drawable folder
and
Write to /res/drawable/ on the fly?

Android save taken image from camera or gallery by using file system

I want to save image uri from taking camera or gallery into SQLite.
And I want to display the image which called uri from SQLite.
If I want to do this, someone said you have to save image uri into SQLite as byte, and
you can set image on imageView.
I understand the theory, but I am still getting stuck with my coding.
If it is true, I want to save formatted image into sdcard or somewhere.
someone said use BitmapFactory and decodeResource.
and call the uri from R.drawable.
However, I don't know how to save image into R.drawable folder.
Could you help me? I will give you some my coding.
I am fighting with saving image into SQLite and how to load it, and how to modify it during two weeks!
Sorry for really long coding. I don't know where I am now.
Thank you.
fridgeDetails.java
populateFields();
private void populateFields()
{
if (mRowId != null)
{
Cursor data = mDbHelper.fetchItem(mRowId);
startManagingCursor(data);
//load image from sqlite
byte[] blob = data.getBlob(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_IMAGE));
mImageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
nameEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
categoryEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
expired_Date_Btn.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
}
else{
expired_Date_Btn.setText(
new StringBuilder()
.append(mDay).append("/")
//month is 0 based. Then add 1
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
}
}
//create dialog for taking image
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
}
}
else
{
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
//image chooser
startActivityForResult(Intent.createChooser(galleryIntent, "Complete action using"), PICK_FROM_GALLERY);
}
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set", Toast.LENGTH_SHORT).show();
saveState();
setResult(RESULT_OK);
finish();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bundle extras = data.getExtras();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 200, false);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
Bitmap bt=Bitmap.createScaledBitmap(bitmap, 200, 200, false);
mImageView.setImageBitmap(bt);
break;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveState();
}
#Override
protected void onPause()
{
super.onPause();
saveState();
}
#Override
protected void onResume()
{
super.onResume();
populateFields();
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date, image);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date, image);
}
}
public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
byte[] imageByteData = imageByteStream.toByteArray();
return imageByteData;
}
The location of your image file can be obtained from data.getData() in OnActivityResult method. You can save the location as a string in Sqlite. Then use
imageView.setImageBitmap(BitmapFactory.decodeFile(filename)
to show the image.
The default location is your app folder. If you want to store elsewhere, pass the location as in the foll code
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
For more info see - http://developer.android.com/guide/topics/media/camera.html
Check this to Get the URI of Captured image
Check this for Inserting image to DB as BLOB and Retrieve it back and display.
It includes download image from Server and insert into DB, just change as it as per your requirement.

Categories

Resources