Lalinda Sampath Lalinda Sampath - 1 month ago 6
Android Question

Camera does not open until I click back button - android

In my android application, when I clicked on the button first it should open the camera and once I capture an image it should redirects to a new activity.

But what happens is, when I click on the button first it redirects to new activity and once I clicked the back button it opens the camera.

I can't understand what's the problem in my code, seems like it's in well order.Any Help?

public void onCameraButtonClicked()
{

camera_btn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {

final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
makingDirectory(dir);

storePicture(dir);
}
}
);
}

public void makingDirectory(String dir)
{
File newdir = new File(dir);
newdir.mkdirs();
}

public void storePicture(String dir)
{
boolean flag_storePicture = false;
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try
{
newfile.createNewFile();
Uri outputFileUri = Uri.fromFile(newfile);

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
flag_storePicture = true;
Log.d("myApp", "Hiiiiii from inside");
}
catch (IOException e)
{

}
finally {
Log.d("myApp", "Hiiiiii");
Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
startActivity(camera_intent);
}
}


In my logcat I'm getting this message.

Skipped 62 frames! The application may be doing too much work on its main thread.

Answer

as it clear to you as well , the issue is flow of control ,

inside try block , the camera app has been opened for you

 startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);

then right after that finally gets executed

finally {
            Log.d("myApp", "Hiiiiii");
            Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
            startActivity(camera_intent);
        }

and now you have your googlemap1.Camera activity over your camera app so hence if you press back you will find your camera app.

Solution : as per your requirements move your finally block code into onActivityResult along with an if condition to verify the image capture task completion. like

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK){ // image captured successfully 
            //..code to start your other activity 
        Intent camera_intent = new Intent("com.example.lalinda.googlemap1.Camera");
        startActivity(camera_intent);
        }else{
           // ..  image capture failure , user pressed cancel etc
           }
    }