简体   繁体   中英

Imageview not displaying image from Camera in Activity

Im hoping one of you could help me solve this questions. I have 2 activities. One with a button that when you click opens up camera, is supposed to save the picture and then display it in imageview in the second activity. I am able to open the app click the button save photo click ok and it goes to second activity but it doesn't display the image. However if I add ic launche icon in the image view src it display the green android logo guy but when i remove that its just a blank page:S

My MainActivity.java file

package com.MYAPP.apk;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends Activity {

private File mFileUri;
private final Context mContext = this;

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

Button btnbutton1 = (Button) findViewById(R.id.button1);
btnbutton1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = new  Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 100);
    }});


// start the image capture Intent
startActivityForResult(getIntent(), 100);

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

mFileUri = getOutputMediaFile(1);

intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);


}  

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent  imageReturnedIntent) {
 super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

if (resultCode == RESULT_OK) {
    if (mFileUri != null) {
        String mFilePath = mFileUri.toString();
        if (mFilePath != null) {
            Intent intent = new Intent(mContext, SecondActivity.class);
            intent.putExtra("filepath", mFilePath);
            startActivity(intent);



      }
    }
  }               
}


// Return image / video
private static File getOutputMediaFile(int type) {

// External sdcard location
File mediaStorageDir = new   File(Environment.getExternalStorageDirectory(),  "DCIM/Camera");

// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
    if (!mediaStorageDir.mkdirs()) {
        return null;
    }
 }

// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",  Locale.getDefault()).format(new Date());
File mediaFile;
if (type == 1) { // image
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"  + timeStamp + ".jpg");
} else if (type == 2) { // video
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else {
    return null;
}

return mediaFile;
}
}

My activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.MYAPP.apk.MainActivity" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Let&apos;s Start Here!" />

</RelativeLayout>

My SecondActivity.java file

package com.MYAPP.apk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.File;

public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Intent intent = getIntent();
String filepath = intent.getStringExtra("filepath");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8; // down sizing image as it throws OutOfMemory    Exception for larger images
filepath = filepath.replace("file://", ""); // remove to avoid   BitmapFactory.decodeFile return null
File imgFile = new File(filepath);
if (imgFile.exists()) {
    ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),  options);
    imageView.setImageBitmap(bitmap);
  }
 }


}

My activity_second.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.MYAPP.apk.SecondActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

</RelativeLayout>

I think you are doing too many things at the same time and not knowing what fails. First try to display the image in the first activity. Once you know how to display the image correctly, you can pass the file path to the second activity. I tried to use your code but it didn't even go the the second activity because mFileUri is always null. Also in your onActivityResult method you should filter the request code not only the resultcode.

I edited your code, remove unused stuff and it works.

MainActivity

public class MainActivity extends Activity {

private String mFileUri;
private final Context mContext = this;

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

    Button btnbutton1 = (Button) findViewById(R.id.button1);
    btnbutton1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Uri uri = createPictureFile();
            mFileUri = uri.getEncodedPath();
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, 100);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100 && resultCode == RESULT_OK) {
        if (mFileUri != null) {
            Intent intent = new Intent(mContext, SecondActivity.class);
            intent.putExtra("filepath", mFileUri);
            startActivity(intent);
        }
    }
}

private static File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "DCIM/Camera");

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == 1) { // image
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if (type == 2) { // video
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

public Uri createPictureFile() {
    String storageState = Environment.getExternalStorageState();
    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        pictureDir = new File(pictureDir, "MyApp");

        // Create the storage directory if it does not exist
        if (!pictureDir.exists()) {
            if (!pictureDir.mkdirs()) {
                Log.d("user", "failed to create directory");
                return null;
            }
        }

        //Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fileName = pictureDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
        File imageFile = new File(fileName);

        // Convert to URI and return
        return Uri.fromFile(imageFile);
    } else {
        Log.d("user", "No media mounted");
        return null;
    }
}
}

SecondActivity

public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    Intent intent = getIntent();
    String filepath = intent.getStringExtra("filepath");

    ImageView imageView = (ImageView) findViewById(R.id.imageView1);

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 6;
    Bitmap bm = BitmapFactory.decodeFile(filepath, opts);
    imageView.setImageBitmap(bm);
}
}

ExifUtil class which you can use to rotate your bitmap

public class ExifUtil {
/**
 * @see http://sylvana.net/jpegcrop/exif_orientation.html
 */
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
    try {
        int orientation = getExifOrientation(src);

        if (orientation == 1) {
            return bitmap;
        }

        Matrix matrix = new Matrix();
        switch (orientation) {
            case 2:
                matrix.setScale(-1, 1);
                break;
            case 3:
                matrix.setRotate(180);
                break;
            case 4:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case 5:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case 6:
                matrix.setRotate(90);
                break;
            case 7:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case 8:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }

        try {
            Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return oriented;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return bitmap;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}

private static int getExifOrientation(String src) throws IOException {
    int orientation = 1;

    try {
        /**
         * if your are targeting only api level >= 5
         * ExifInterface exif = new ExifInterface(src);
         * orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
         */
        if (Build.VERSION.SDK_INT >= 5) {
            Class<?> exifClass = Class.forName("android.media.ExifInterface");
            Constructor<?> exifConstructor = exifClass.getConstructor(new Class[] { String.class });
            Object exifInstance = exifConstructor.newInstance(new Object[] { src });
            Method getAttributeInt = exifClass.getMethod("getAttributeInt", new Class[] { String.class, int.class });
            Field tagOrientationField = exifClass.getField("TAG_ORIENTATION");
            String tagOrientation = (String) tagOrientationField.get(null);
            orientation = (Integer) getAttributeInt.invoke(exifInstance, new Object[] { tagOrientation, 1});
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

    return orientation;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM