通过从Camera拍照获取onActivityResult中的null [英] Getting null in onActivityResult by taking picture from Camera
问题描述
我在应用程序中创建了一个使用相机拍照的类.
此类将使用相机拍摄照片并将其存储在具有唯一名称的文件夹中.
但是,当我想在onActivityResult
方法中获取图片路径时,我始终会得到data
的null!
I created a class to take picture from camera in my application.
This class will take a picture with camera and store it in a folder with an unique name.
But when I want to get picture path in onActivityResult
method Iget null of data
all the time!
这是我的课堂相机:
public class Camera{
private Activity activity;
private SystemTools systemTools;
public Camera(Context context) {
this.activity = (Activity) context;
systemTools = new SystemTools();
}
/**
* This Method will take a picture with camera for us
*/
public void takePicture() {
boolean cameraAvailable = systemTools.device_isHardwareFeatureAvailable(activity, PackageManager.FEATURE_CAMERA);
if (cameraAvailable &&
systemTools.system_isIntentAvailable(activity, MediaStore.ACTION_IMAGE_CAPTURE)) {
Intent takePicIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//We prepare the intent to store the taken picture
try {
File outputDir = systemTools.storage_getExternalPublicFolder("ReportsAttachments", true);
File outFile = systemTools.storage_createUniqueFileName("cameraPic", ".jpg", outputDir);
takePicIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
} catch (Exception e) {
Toast.makeText(activity, "در دریافت تصویر اشکالی رخ داده است ، لطفا دوباره تلاش کنید.", Toast.LENGTH_SHORT).show();
}
activity.startActivityForResult(takePicIntent, App.REQUEST_IMAGE_CAPTURE);
} else {
if (cameraAvailable) {
Toast.makeText(activity, "برنامه ی دوربین دستگاه خراب است.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "دسترسی به دوربین سیستم امکان پذیر نمی باشد.", Toast.LENGTH_SHORT).show();
}
}
}
}
我使用相机的活动"中的我设置了onActivityResult()
"方法.像这样:
An i Set onActivityResult()
method in Activity that i used camera. like this:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == App.REQUEST_IMAGE_CAPTURE) {
if (resultCode == Activity.RESULT_OK && data != null) {
Log.i("ATTACH", "In Result");
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri selectedImage = getImageUri(this, bmp);
String realPath = getRealPathFromURI(selectedImage);
selectedImage = Uri.parse(realPath);
presenter.onNewAttachmentRequest(selectedImage.getPath());
}
}
} catch (Exception e) {
Log.i("ATTACH", e + " Something went wrong");
}
}
这很好用,并且可以在SD_Card上获取pictre,但是当我想获取图片的路径时,我不能,因为onActivityResult
中的'data'一直为空!
这段代码在哪里出问题?
this works fine and taked pictre is avaliable on SD_Card but when I want to get path of picture I cant't because 'data' in onActivityResult
is null all the time!
Where is the problem with this code?
谢谢.
推荐答案
当我想获取图片的路径时
when I want to get path of picture
您已经具有图片的路径.它是outFile
.将其保存在字段中,并在配置更改时保留它.另外,由于Uri.fromFile()
在Android 7.0+上无法很好地工作,因此请考虑切换到FileProvider
,就像我在
You already have the path of the picture. It is outFile
. Save it in a field and hold onto it across configuration changes. Also, since Uri.fromFile()
will not work on Android 7.0+ especially well, consider switching to FileProvider
, as I do in the following activity from this sample project:
/***
Copyright (c) 2008-2017 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.camcon;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
import java.io.File;
import java.util.List;
public class MainActivity extends Activity {
private static final String EXTRA_FILENAME=
"com.commonsware.android.camcon.EXTRA_FILENAME";
private static final String FILENAME="CameraContentDemo.jpeg";
private static final int CONTENT_REQUEST=1337;
private static final String AUTHORITY=
BuildConfig.APPLICATION_ID+".provider";
private static final String PHOTOS="photos";
private File output=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState==null) {
output=new File(new File(getFilesDir(), PHOTOS), FILENAME);
if (output.exists()) {
output.delete();
}
else {
output.getParentFile().mkdirs();
}
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputUri=FileProvider.getUriForFile(this, AUTHORITY, output);
i.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN) {
ClipData clip=
ClipData.newUri(getContentResolver(), "A photo", outputUri);
i.setClipData(clip);
i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
else {
List<ResolveInfo> resInfoList=
getPackageManager()
.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, outputUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
try {
startActivityForResult(i, CONTENT_REQUEST);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.msg_no_camera, Toast.LENGTH_LONG).show();
finish();
}
}
else {
output=(File)savedInstanceState.getSerializable(EXTRA_FILENAME);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(EXTRA_FILENAME, output);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
Uri outputUri=FileProvider.getUriForFile(this, AUTHORITY, output);
i.setDataAndType(outputUri, "image/jpeg");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(i);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.msg_no_viewer, Toast.LENGTH_LONG).show();
}
finish();
}
}
}
}
这篇关于通过从Camera拍照获取onActivityResult中的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!