0

I am newbie to android, i faced a problem with camera in android. In my class, i have some instance variables(holding some values which i got from Activity1 through intent) and a button and image view. when i click that button the application opens camera and stores in sd card, after that i am doing some operations with instance variables. But the problem is the variables are reinitialized to default values. i have used shared preference or storing(variables data) in another class as static variables then it works fine. My question is why all instance variables are reinitialized.

in my application Activity1--(calling)--->Activity2[this has a button and an imageview], here i am passing some data through intent from Activity1 to Activity2, In Activity2 (in Activity2 i am getting data successfully before calling camera ) if am calling camera,the data which i got from intent are reinitialized to default values.To avoid this i have not passed the data from Activity1(i have stored in SharedPreference or in constant class as static variables it works fine).My question is are these only solutions?

This is camera code in activity2

// camera code

   public void openCamera() {
    if (Helper.checkCameraHardware(this)) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateFileName = sdf.format(new Date()); // generating
                                                            // todays date
                                                            // for folder

            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String curentDateandTime = sdf1.format(new Date()); // generating
                                                                // todays
                                                                // date with
                                                                // min,seconds
                                                                // for image

            // creating an folder in sd card : ed ==> sdCard path/IMG_Folder
            // in helper class / folder with todays date
            File sdImageMainDirectory = new File(Environment
                    .getExternalStorageDirectory().getPath()
                    + "/"
                    + Helper.IMG_FOLDER + "/" + dateFileName);
            if (!sdImageMainDirectory.exists()) { // if folder not exists it
                                                    // created
                sdImageMainDirectory.mkdirs();
            }

            // setting image path to sd card/Img_folder in helper
            // class/todays date folder
            image_PATH = Environment.getExternalStorageDirectory()
                    .getPath()
                    + "/"
                    + Helper.IMG_FOLDER
                    + "/"
                    + dateFileName + "/";
            // creating a new file(jpg) at above image path
            File file = new File(image_PATH, curentDateandTime + ".jpg");

            // re-initilization of image_PATH to new file(jpg)
            image_PATH = image_PATH + curentDateandTime + ".jpg";
            savePreferences();

            // creating an uri for file
            Uri outputFileUri = Uri.fromFile(file);

            Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
            i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            startActivityForResult(i, 1234);

        } catch (Exception e) {
            Helper.AlertBox(this,
                    "Error No: 001\nPlease Contact  Technical Person.\n"
                            + e.toString());
        }
    } else {
        Helper.AlertBox(this, "Camera Not Found.!");
    }
}

private void savePreferences() {
    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    editor.putString("image_PATH", image_PATH);

    // Commit the edits!
    editor.commit();
}

private void restorePreferences() {
    SharedPreferences settings = getPreferences(MODE_PRIVATE);
    image_PATH = settings.getString("image_PATH", "");
}




public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image_PATH = "";
    image_str = "";

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1234) {
        if (resultCode == RESULT_OK) {

            restorePreferences();

            System.out.println("image_PATH :" + image_PATH);

            File file = new File(image_PATH);
            if (file.exists()) {

                Log.e("File exist :", "File exist at " + image_PATH);

                FileInputStream in;
                BufferedInputStream buf;
                try {
                    // in = new FileInputStream(image_PATH);
                    // buf = new BufferedInputStream(in);
                    // bMap = BitmapFactory.decodeStream(buf);

                    // iv_image.setVisibility(View.VISIBLE);
                    // iv_image.setImageBitmap(bMap);
                    // ConstantClass.image_PATH = image_PATH;

                    // if (in != null) {
                    // in.close();
                    // }
                    // if (buf != null) {
                    // buf.close();
                    // }

                    intent = new Intent(TakePhoto.this, PhotoPreview.class);
                    intent.putExtra("index", Helper.index);
                    Log.e("test", "0");
                    Helper.bitMap[Helper.index] = image_PATH;
                    Log.e("test", "1");

                    Helper.btn[Helper.index] = false;
                    Log.e("test", "2");

                    startActivity(intent);
                    Log.e("test", "3");

                    // Helper.AlertBox(this, "Image Captured.");

                } catch (Exception e) {
                    Helper.AlertBox(this,
                            "Error No: 004\nPlease contact  technical person.\n"
                                    + e.toString());
                    Log.e("Error reading file", e.toString());
                }

            } else {
                Helper.AlertBox(this,
                        "Error No: 005\nPlease contact  technical person.");
            }
        } else {
            Toast.makeText(getApplicationContext(), "Cam Not Supported",
                    5000).show();
        }
    }
}

    // camera code end

when i click on image Button,openCamera() will be called.

Thanks in advance

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
LMK
  • 2,882
  • 5
  • 28
  • 52
  • how do you call Activity2 from A1? Is it startActivity(), or startActivityForResult()? Do you by any chance call finish() in A1 at some point? – Alex Cohn Jul 06 '13 at 13:23
  • Activity1--(startActivity())-->Activity2,and Activity2-------(startActivityForResult())------->camera – LMK Jul 08 '13 at 04:10
  • How do you get back to _Activity1_? By pressing **back** button? Do you enter `Activity1.onCreate()` on the way, or `Activity1.onRestart()`? – Alex Cohn Jul 08 '13 at 06:53
  • Activity1--(startActivity())-->Activity2,and Activity2-------(startActivityForResult())------->camera(If i click on save button[in camera preview or back button] it will come to Activity2) – LMK Jul 10 '13 at 04:32
  • The question was how you _return_ to Activty1 – Alex Cohn Jul 10 '13 at 05:12
  • By pressing back button. – LMK Jul 10 '13 at 09:31

1 Answers1

0

Your problem has no relation to the Camera or Shared Preferences. The same can happen to any activity that goes off screen.

After an activity returns from onPaused() callback, the system has no obligations to keep the instance in memory. But, if you call Activity.finish() at some point, the object will be destroyed for sure.

Anyway, the idea to save Activity1 state in Shared Preferences is a viable one. The preferred alternative is to use Activity.onSaveInstanceState(), but it does not make your life much easier, and is not safer.

Community
  • 1
  • 1
Alex Cohn
  • 56,089
  • 9
  • 113
  • 307