我想在android中捕获图像并将其显示在imageview中。访问相机并拍照没有问题,但是每当我要拍照时都会出现空指针错误。以下是我的代码
public class New3Fragment extends Fragment implements OnClickListener,
DialogClickListener {
EditText name_EditText, phonenumber_EditText, email_EditText;
ImageView photo1_ImageView, photo2_ImageView, photo3_ImageView;
String choice;
private Uri fileUri; // file url to store image/video
public static final int DIALOG_FRAGMENT = 1;
private int photo_number;
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static int RESULT_LOAD_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Safirisha";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new3, container,
false);
name_EditText = (EditText) rootView
.findViewById(R.id.new3_editText_name);
phonenumber_EditText = (EditText) rootView
.findViewById(R.id.new3_editText_phonenumber);
email_EditText = (EditText) rootView
.findViewById(R.id.new3_editText_email);
photo1_ImageView = (ImageView) rootView
.findViewById(R.id.new3_imageView_photo1);
photo2_ImageView = (ImageView) rootView
.findViewById(R.id.new3_imageView_photo2);
photo3_ImageView = (ImageView) rootView
.findViewById(R.id.new3_imageView_photo3);
photo_number = 0;
photo1_ImageView.setOnClickListener(this);
photo2_ImageView.setOnClickListener(this);
photo3_ImageView.setOnClickListener(this);
return rootView;
}
/**
* Select image from gallery
*/
private void selectFromGallery() {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
/**
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
fileUri = savedInstanceState.getParcelable("file_uri");
}
}
/**
* Receiving activity result method will be called after closing the camera
* */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity().getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == RESULT_LOAD_IMAGE
&& resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
previewFromGallery(picturePath);
} else if (requestCode == DIALOG_FRAGMENT) {
if (resultCode == Activity.RESULT_OK) {
}
// After Ok code.
else if (resultCode == Activity.RESULT_CANCELED) {
// After Cancel code.
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
if (photo_number == 1) {
photo1_ImageView.setImageBitmap(bitmap);
} else if (photo_number == 2) {
photo2_ImageView.setImageBitmap(bitmap);
} else if (photo_number == 3) {
photo3_ImageView.setImageBitmap(bitmap);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void previewFromGallery(String picturePath) {
photo1_ImageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Error creating "
+ IMAGE_DIRECTORY_NAME + " directory.");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.new3_imageView_photo1:
photo_number = 1;
UploadPhotoDialog uploadPhotoDialog = new UploadPhotoDialog()
.newInstance(123);
uploadPhotoDialog.setTargetFragment(this, DIALOG_FRAGMENT);
uploadPhotoDialog.show(getFragmentManager().beginTransaction(),
"dialog");
break;
case R.id.new3_imageView_photo2:
photo_number = 2;
UploadPhotoDialog uploadPhotoDialog2 = new UploadPhotoDialog()
.newInstance(123);
uploadPhotoDialog2.setTargetFragment(this, DIALOG_FRAGMENT);
uploadPhotoDialog2.show(getFragmentManager().beginTransaction(),
"dialog");
break;
case R.id.new3_imageView_photo3:
photo_number = 3;
UploadPhotoDialog uploadPhotoDialog3 = new UploadPhotoDialog()
.newInstance(123);
uploadPhotoDialog3.setTargetFragment(this, DIALOG_FRAGMENT);
uploadPhotoDialog3.show(getFragmentManager().beginTransaction(),
"dialog");
break;
}
}
@Override
public void onCameraClick() {
Toast.makeText(getActivity(), "Camera", Toast.LENGTH_SHORT).show();
captureImage();
}
@Override
public void onGalleryClick() {
selectFromGallery();
}
和logcat输出
07-07 14:05:23.225: E/AndroidRuntime(28851): FATAL EXCEPTION: main
07-07 14:05:23.225: E/AndroidRuntime(28851): java.lang.NullPointerException: file
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.net.Uri.fromFile(Uri.java:446)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.koncious.safirisha.New3Fragment.getOutputMediaFileUri(New3Fragment.java:213)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.koncious.safirisha.New3Fragment.captureImage(New3Fragment.java:95)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.koncious.safirisha.New3Fragment.onCameraClick(New3Fragment.java:289)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.koncious.safirisha.UploadPhotoDialog.onClick(UploadPhotoDialog.java:67)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.view.View.performClick(View.java:3511)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.view.View$PerformClick.run(View.java:14105)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.os.Handler.handleCallback(Handler.java:605)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.os.Handler.dispatchMessage(Handler.java:92)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.os.Looper.loop(Looper.java:137)
07-07 14:05:23.225: E/AndroidRuntime(28851): at android.app.ActivityThread.main(ActivityThread.java:4440)
07-07 14:05:23.225: E/AndroidRuntime(28851): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 14:05:23.225: E/AndroidRuntime(28851): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
07-07 14:05:23.225: E/AndroidRuntime(28851): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
07-07 14:05:23.225: E/AndroidRuntime(28851): at dalvik.system.NativeStart.main(Native Method)
213行是
return Uri.fromFile(getOutputMediaFile(type));
如果有人可以指出哪里出了问题,我将不胜感激。
您需要先运行媒体扫描仪(ACTION_MEDIA_SCANNER_SCAN_FILE),然后才能访问图像
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(fileUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
这实际上是将您的图像添加到图库数据库。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句