尝试从图库上传图像并从相机图像捕获图像到Web服务器。画廊中的图像成功上传,但捕获的图像未成功上传。有错误:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {my-pack-name/my-pack-name.my-activity-name}: java.lang.NullPointerException: uriString
清单:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus"
android:required="false" />
提供者:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="my-pack-name.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
文件路径:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--<external-path name="images" path="."/>-->
<external-path name="my_images" path="Android/data/my-pack-name/files/Pictures" />
</paths>
活动方法:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
photoFile = null;
try {
photoFile = createImageFile();
displayMessage(getBaseContext(),photoFile.getAbsolutePath());
Log.i("May",photoFile.getAbsolutePath());
} catch (IOException ex) {
Toast.makeText(this,"error",Toast.LENGTH_LONG).show();
}
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,"my-pack-name.fileprovider",photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case REQUEST_PERMISSION:
{
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"permissions granted", LENGTH_LONG).show();
else Toast.makeText(this,"permissions denied", LENGTH_LONG).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
iView.setImageBitmap(myBitmap);
/* Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");*/
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
selectedFileURI = data.getData();
result = new File(selectedFileURI.getPath());
}
else{
selectedFileURI = getImageUri(getApplicationContext(), myBitmap);
result = new File(getRealPathFromURI(selectedFileURI));}
}
if (resultCode == RESULT_OK && requestCode == REQUEST_GALLERY) {
//some code
}
}
private Uri getImageUri(Context applicationContext, Bitmap imageBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), imageBitmap, "Title", null);
return Uri.parse(path);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
}
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
currentPhotoPath = image.getAbsolutePath();
return image;
}
public String getRealPathFromURI(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private void uploadFile() {
// selectedFileURI = Uri.parse("file:///sdcard/img.png");
// if(selectedFileURI !=null){
if(result !=null){
dialog=new ProgressDialog(ChooseSecondPhotoActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading...");
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setCancelable(false);
dialog.show();
// File file=FileUtils.getFile(this,selectedFileURI);
// File file = new File(selectedFileURI.toString());
//String filePath=PathUtil.getPath(this,selectedFileURI);
// File file= new File(filePath);
// ProgressRequestBody requestFile=new ProgressRequestBody(file,this);
//final MultipartBody.Part body=MultipartBody.Part.createFormData("uploaded_file", file.getName(),requestFile);
ProgressRequestBody requestFile=new ProgressRequestBody(result,this);
final MultipartBody.Part body=MultipartBody.Part.createFormData("uploaded_file", result.getName(),requestFile);
new Thread(new Runnable() {
@Override
public void run() {
mService.uploadFile(body)
.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
Toast.makeText(ChooseSecondPhotoActivity.this,"Uploaded!", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
Toast.makeText(ChooseSecondPhotoActivity.this,t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}).start();
}
}