我正在尝试在firebase存储上传图片。按下捕获按钮捕获图片我的应用程序崩溃,我收到此错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,java.lang.String)' / p>
在此行Uri photoURI = FileProvider.getUriForFile(this,
"com.faum.faum_expert.fileprovider",
photoFile);
那是我的代码:
private ImageView ivKitchen1,ivKitchen2,ivKitchen3;
private Button btnCapture1,btnCapture2,btnCapture3;
private TextView tvKitchenSnaps;
private StorageReference snapsStorage;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog mProgress;
private Uri filepath;
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.faum.faum_expert.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kitchen_snaps);
snapsStorage = FirebaseStorage.getInstance().getReference();
ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);
btnCapture1 = (Button)findViewById(R.id.btnCapture1);
mProgress = new ProgressDialog(this);
btnCapture1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);*/
dispatchTakePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
mProgress.setMessage("Uploading...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = snapsStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Kitchen_Snaps.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Kitchen_Snaps.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
宣言文件
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--
-
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.faum.faum_expert.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Social_Connect" />
<activity android:name=".User_sign" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<activity android:name=".Personal_Information" />
<activity android:name=".Contact_Infrormation" />
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps" />
<activity android:name=".Kitchen_Snaps" />
<activity
android:name=".Navigation_Drawer"
android:label="@string/title_activity_navigation__drawer"
android:theme="@style/AppTheme" />
<activity android:name=".New_Deal" />
<activity android:name=".New_Deal_Time" />
<activity android:name=".New_Deal_List" />
<activity android:name=".New_Deal_Confirmation"></activity>
</application>
答案 0 :(得分:0)
我认为,您必须先检查权限 我希望它有所帮助 这是完整的源代码
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kitchen_snaps);
snapsStorage = FirebaseStorage.getInstance().getReference();
ivKitchen1 = (ImageView)findViewById(R.id.ivKitchen1);
btnCapture1 = (Button)findViewById(R.id.btnCapture1);
mProgress = new ProgressDialog(this);
btnCapture1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//startActivityForResult(intent, CAMERA_REQUEST_CODE);*/
//dispatchTakePictureIntent();
if (checkPermission(YourActivity.class))
cameraIntent();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
cameraIntent();
}
break;
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
private void cameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile(SetupProfileActivity.this);
} catch (IOException ex) {
Log.i(TAG, "IOException");
}
//For Android SDk 24+, 7.0
if (photoFile != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mPhotoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, mPhotoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
} else {
mPhotoUri = Uri.fromFile(photoFile);
}
//mPhotoUri = Uri.fromFile(photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}
}
}