Load Bitmap picture after savedInstanceState Error - android

Threr is what i have done. On my activity. I take 2 picture correctly but if i change the orientation of the phone app crash
public class MyactivityTakePicture extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initialisation
setContentView(R.layout.picture_main_layout);
img1 = (ImageView)findViewById(R.id.photo1);
img2 = (ImageView)findViewById(R.id.photo2);
//creation des dossiers
dir1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g0/";
newdir1 = new File(dir1);
newdir1.mkdirs();
dir2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/g1/";
newdir2 = new File(dir2);
newdir2.mkdirs();
capture1 = (Button) findViewById(R.id.btnCapture1);
capture1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture1();
}
});
capture2 = (Button) findViewById(R.id.btnCapture2);
capture2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
takepicture2();
}
});
if(savedInstanceState != null){
filePath1 = savedInstanceState.getString("chemin1");
filePath2 = savedInstanceState.getString("chemin2");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
//filePath2 = savedInstanceState.getString("chemin1");
Log.w("A", ""+filePath1);
Log.i("F", ""+filePath2);
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
//prise de photo N°1
..................
//prise de photo N°2
protected void takepicture2(){
//nom des photos photo1.jpg, photo2.jpg ...
count++;
file2 = dir2+"photo.jpg";
File newfile2 = new File(file2);
filePath2 = dir2+"photo.jpg";
try {
newfile2.createNewFile();
} catch (IOException e) {
Log.e("Error", e.toString());
}
Uri outputFileUri2 = Uri.fromFile(newfile2);
Intent cameraIntent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent2.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri2);
startActivityForResult(cameraIntent2, TAKE_PHOTO_CODE2);
}
//Enregistrement OK
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE1 && resultCode == RESULT_OK) {
Log.d("CameraDemo1", "Pic saved");
bitmap1 = BitmapFactory.decodeFile(filePath1);
img1.setImageBitmap(bitmap1);
}
if (requestCode == TAKE_PHOTO_CODE2 && resultCode == RESULT_OK){
Log.d("CameraDemo2", "Pic saved");
bitmap2 = BitmapFactory.decodeFile(filePath2);
img2.setImageBitmap(bitmap2);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(newdir1==null){
newdir1 = new File(file1);
}// if
if(newdir2==null){
newdir2 = new File(file2);
}
outState.putString("chemin1", filePath1);
outState.putString("chemin2", filePath2);
}
}
First, Activity lauch correctely, take the two picture.
If i try to change orientation of my phone. She crash.
Please you see?

The problem is that your images aren't getting deallocated from memory.
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
read this articles, would be helpful for you
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
http://androidactivity.wordpress.com/2011/09/24/solution-for-outofmemoryerror-bitmap-size-exceeds-vm-budget/
http://mobi-solutions.blogspot.mx/2010/08/how-to-if-you-want-to-create-and.html
UPDATE:
I have seen your code and i suggest the use of the method onDestroy() to set the bitmap instances to null:
#Override
protected void onDestroy(){
super.onDestroy();
bitmap1 = null;
bitmap2 = null;
}

Related

An error occurs during the operation to place Uri as bitmap in imageView

public class addBoard extends AppCompatActivity {
private final int GET_GALLERY_IMAGE = 200;
Uri image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addboard);
final EditText EDTITLE = findViewById(R.id.editTitle);
final EditText EDTEXT = findViewById(R.id.editText);
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Button addPhoto = findViewById(R.id.photo);
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, GET_GALLERY_IMAGE);
}
});
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), image);
imgView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button backButton = findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Input_Title", EDTITLE.getText().toString());
intent.putExtra("Input_Text", EDTEXT.getText().toString());
intent.putExtra("Input_Image", image);
setResult(RESULT_OK, intent);
finish();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_GALLERY_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectImage = data.getData();
image = selectImage;
}
}
}
If you run this code in another project, there is no error, but if you use it in this project, you will get an error. Why is that?
Error :Caused by: java.lang.NullPointerException: uri
at com.example.toolbar.addBoard.onCreate**(addBoard.java:45)** // blue line
An error occurs during the operation to place Uri as bitmap in imageView.

How to create a GIF from multiple image bitmaps in android

The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}

ImageView - image lost on change in orientation

I have an application where I take a picture and set it as the image on image button. On change in orientation, the image vanishes. Please help.
I click a picture and set it as the image on the ImageItem
public void onImageButtonClicked(View view)
{
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent, TAKE_PHOTO);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PHOTO && resultCode == Activity.RESULT_OK)
try {
InputStream stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
stream.close();
ImageButton imageButton = (ImageButton) findViewById(R.id.itemImage);
int mDstWidth = getResources().getDimensionPixelSize(R.dimen.destination_width);
int mDstHeight = getResources().getDimensionPixelSize(R.dimen.destination_height);
scaledBmp = Bitmap.createScaledBitmap(bitmap, mDstWidth, mDstHeight, true);
imageButton.setImageBitmap(scaledBmp);
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
When the orientation is changed, image disappears.
I saved the image in
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (scaledBmp != null) {
savedInstanceState.putByteArray("image", getBitmapAsByteArray(scaledBmp));
}
}
and retrieved in
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
byte[] savedImage;
savedImage = savedInstanceState.getByteArray("image");
if (savedImage != null) {
scaledBmp = BitmapFactory.decodeByteArray(savedImage, 0, savedImage.length -1);
}
}
Should I set the image on the button manually now? Is there something I am missing?
I was missing onResume()
protected void onResume()
{
super.onResume();
if (scaledBmp != null)
{
ImageButton ib = (ImageButton) findViewById(R.id.itemImage);
if (ib != null)
ib.setImageBitmap(scaledBmp);
}
}
With this change, things started working. I am getting the image in landscape as well as portrait mode.
Asthme's comment helped me, thanks.

Is there anything wrong with the code of saving camera image to file?

I thought it was simple to capture camera image to a file, since there are many examples. But after tying a lot of them, I still not get it work.
My code is:
public class MyActivity extends Activity {
private Button btn;
private ImageView imageView;
private static final File photoPath = new File(Environment.getExternalStorageState(), "camera.jpg");
private static final int CAMERA = 1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setListeners();
}
private void setListeners() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoPath));
startActivityForResult(intent, CAMERA);
}
});
}
private void findViews() {
btn = (Button) findViewById(R.id.btn);
imageView = (ImageView) findViewById(R.id.imageView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA) {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = getCameraBitmap(data);
if (bitmap == null) {
Toast.makeText(MyActivity.this, "Can't get bitmap from camera", Toast.LENGTH_LONG).show();
} else {
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
Toast.makeText(MyActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getCameraBitmap(Intent data) throws IOException {
if (data == null) {
// try solution 1
try {
return MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(photoPath));
} catch (FileNotFoundException e) {
return BitmapFactory.decodeFile(photoPath.getAbsolutePath());
}
} else {
Uri image = data.getData();
if (image != null) {
// try solution 3
InputStream inputStream = getContentResolver().openInputStream(image);
return BitmapFactory.decodeStream(inputStream);
} else {
// try solution 4
return (Bitmap) data.getExtras().get("data");
}
}
}
}
But it still get "Can't get bitmap from camera" shown. I don't known where is wrong.
I also created a working demo: https://github.com/freewind/AndroidCameraTest, you can see the full code there, and you may clone it and have a try on your own android device :)
Update
This code is working fine on android emulators, but not on my android pad.
I have seen this problem too; I removed intent.putExtra(MediaStore.EXTRA_OUTPUT,...), and it worked using the method:
stream = getContentResolver().openInputStream(data.getData());
image = BitmapFactory.decodeStream(stream);

How can I store the imagePath of the image that I took using the camera activity into the database and retrieving the path?

how to store the imagePath of the image that I had captured using the camera activity to database. I also need to retrieve that imagePath and display on another activity?
Can someone help me please?
Update:
public class Image_secondPage extends Activity
{
public static final int CAMERA_RESULT = 1;
Button btn1;
ImageView imageView1;
private final String tag = getClass().getName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.image_secondpage);
imageView1 = (ImageView)findViewById(R.id.imageView1);
Button btnNext = (Button)findViewById(R.id.buttonNext);
btnNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Image_secondPage.this, ImagesPage.class);
startActivity(intent);
}
});
PackageManager pm = getPackageManager();
if(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
}
else
{
Toast.makeText(getBaseContext(), "Camera is not available", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.i(tag, "Receive the camera result");
if(resultCode == RESULT_OK && requestCode == CAMERA_RESULT)
{
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists())
{
Toast.makeText(getBaseContext(), "Error while capturing image", Toast.LENGTH_LONG).show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
imageView1 = null;
}
I am supposed to get the imagePath that I have captured and show the image on the imageView that I had on the next class but I don't know how. Can someone help me?
try use this
bitmap = (Bitmap) data.getExtras().get("data");
this will give you bitmap image, then you can save it to database or anything you want.
let me know if this not solve your problem.

Categories

Resources