0

I, I'm starting to explore Android and I am kind of stuck with my first issue. My ImageView is returning 0 on width and height after rotating the screen. It works fine the first time when I upload a photo, but once I flip the screen it returns 0. I've tried to obtain it in the onResume and onRestoresavedInstance methods, but I've failed. Does anyone have an idea how to solve the problem?

Thank you in advance. :)

Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
    android:id="@+id/text_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/email" />

<EditText
    android:id="@+id/text_nickname"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/nickname" />

<Button
    android:id="@+id/button_take_photo"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="takePhoto"
    android:text="@string/photo_button" />

<ImageView
    android:id="@+id/image_viewer"
    android:layout_width="match_parent"
    android:contentDescription="@string/photo_taken" 
    android:background="@android:color/black" 
    android:layout_height="0dip"
    android:layout_weight="1"
    android:gravity="top"
    android:adjustViewBounds="true" />

</LinearLayout> 

Code

public class MainActivity extends Activity {

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private String fileUri;
private ImageView mImageView;
private EditText nickTextView;
private EditText mailTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initUI();
}

@Override
public void onResume() {
    super.onResume();
    try {
        if (this.fileUri != null) {
            setPic();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

    // Save UI state changes to the savedInstanceState.
    // This bundle will be passed to onCreate if the process is
    // killed and restarted.

    savedInstanceState.putString("fileUri", this.fileUri);
    savedInstanceState.putString("nick", this.nickTextView.getText()
            .toString());
    savedInstanceState.putString("email", this.mailTextView.getText()
            .toString());
    super.onSaveInstanceState(savedInstanceState);
}

// onRestoreInstanceState
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    this.fileUri = savedInstanceState.getString("fileUri");
    this.nickTextView.setText(savedInstanceState.getString("nick"));
    this.mailTextView.setText(savedInstanceState.getString("email"));
}

public void takePhoto(View view) {
    if (checkCameraHardware(this)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        this.fileUri = getOutputMediaFilePath();
        File temp = new File(fileUri);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp));
        startActivityForResult(intent,
                MainActivity.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    } else {
        System.out
                .println("This hardware does not support camera features!!!");
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // galleryAddPic();
            try {
                setPic();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (resultCode == RESULT_CANCELED) {
            System.out.println("User cancelled the image capture");
        } else {
            System.out.println("Image capture failed, advise user");
        }
    }
}

private void initUI() {
    // Get the image view
    mImageView = (ImageView) findViewById(R.id.image_viewer);

    // Get the text views
    nickTextView = (EditText) findViewById(R.id.text_nickname);
    mailTextView = (EditText) findViewById(R.id.text_email);
}

private String getOutputMediaFilePath() {
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
            .format(new Date());
    String imageFileName = "liftoff_" + timeStamp + ".jpg";
    File image = new File(storageDir, imageFileName);
    return image.getAbsolutePath();
}

private boolean checkCameraHardware(Context context) {
    if (context.getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(fileUri);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

private void setPic() throws Exception {

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(fileUri, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Get the dimensions of the View
    int targetH = mImageView.getHeight();
    int targetW = mImageView.getWidth();

    // Put correct orientation
    Matrix matrix = new Matrix();
    ExifInterface exif = new ExifInterface(this.fileUri);
    String orientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
    if (orientation.equals(ExifInterface.ORIENTATION_NORMAL)) {
        // Do nothing. The original image is fine.
    } else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_90 + "")) {
        photoW = bmOptions.outHeight;
        photoH = bmOptions.outWidth;
        matrix.postRotate(90);
    } else if (orientation
            .equals(ExifInterface.ORIENTATION_ROTATE_180 + "")) {
        matrix.postRotate(180);
    } else if (orientation
            .equals(ExifInterface.ORIENTATION_ROTATE_270 + "")) {
        matrix.postRotate(270);
        photoW = bmOptions.outHeight;
        photoH = bmOptions.outWidth;
    }

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(fileUri, bmOptions);

    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
            bitmap.getWidth(), bitmap.getHeight(), matrix, true);

    mImageView.setImageBitmap(resizedBitmap);
}
user1819741
  • 13
  • 1
  • 3
  • Hi,welcome to android :). We will need some code or layouts to try to help you. Just to get it started, where do you have your layout file? Do you have layouts for both orientations ( portrait and landscape ) – Robert Estivill Nov 16 '12 at 03:29

1 Answers1

0

Make sure that the View has finished its layout process. Give this a try.

Community
  • 1
  • 1
zienkikk
  • 2,404
  • 1
  • 21
  • 28
  • Hi, thanks! Basically the code above is just an experiment, so it might not make sense. It's to experiment the camera features. As a result I only have one layout, the thing is that I want my picture to scale to the correct size when I rotate the screen. I've edited the question with the code. – user1819741 Nov 16 '12 at 11:10