weberc2
weberc2

Reputation: 7948

Android Camera won't take picture depending on what is after it in code

I have the following code with which I'm trying to take a picture and save some of the photo's information into a database. The database portion has been thoroughly tested and works fine in all other circumstances. Unfortunately, if I uncomment the commented code below, my code times out. For some reason, if there is code following the this.camera.takePicture() method, takePicture() won't call the overridden onPictureTaken method at all (the first thing it's supposed to do is print out a line of text, but it doesn't even do that). If no code follows it, it works fine.

Before installing the latch, I would get an error because ph.getPhoto() was returning null (ph's .photo member variable wasn't yet set by onPictureTaken(), because it hadn't yet been called). After installing the latch, it will wait until timeout (or forever, if no timeout value is specified).

Can someone please tell me what I'm missing?

    public void takePicture(View view) throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Taking Photo!");
        PhotoHandler photoHandler = new PhotoHandler(getApplicationContext(),latch);
        this.camera.takePicture(null, null, photoHandler);

    /* PhotoHandler has an overridden "onPictureTaken()" method which releases the latch as its final
     * action; however, its first instruction is to print a confirmation that it has been accessed.
     * Unfortunately, for some reason, onPictureTaken() is not called if the following code is
     * uncommented; it deadlocks for the five seconds before timing out. However, with out the following,
     * the camera.takePicture method invokes onPictureTaken() and it works just fine. */


//      latch.await(5,TimeUnit.SECONDS);
//      DatabaseHandler db = new DatabaseHandler(this);
//      Photo p = photoHandler.getPhoto();
//      db.addPhoto(p);
//      List<Photo> photos = new ArrayList<Photo>();
//      photos.add(p);
//      this.addPhotosToMap(photos);
}

Upvotes: 1

Views: 1900

Answers (2)

Sparky
Sparky

Reputation: 8477

Put all of your post-processing (i.e., the code you have commented out) into the appropriate callback, not after takePicture. And put slow actions such as file system access into a background thread (e.g., AsyncTask).

Upvotes: 0

zapl
zapl

Reputation: 63955

onPictureTaken() is (afaik) executed on the main / UI thread. If your takePicture method is also exectued there than it must happen simply because a thread cannot wait for itself.

Besides, you must not block the mainthread or your Activity will ANR.

If you move the commented code (minus that latch) to onPictureTaken() then everything should be fine. Those onSomethingHappened callbacks are made exactly for that task

Upvotes: 1

Related Questions