我写了一个简单的代码到即时相机图像捕获并将其上传到android firebase 来自Referance Here
尝试将完整代码编写为android studio文档。 但是在logcat中我们可以显示此代码出现错误 uri.getLastPathSegment()。 如何解决这个错误?
错误Logcat:
--------- beginning of crash
05-23 14:52:06.627 12364-12364/com.example.hasib_pc.firebasetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hasib_pc.firebasetest, PID: 12364
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { }} to activity {com.example.hasib_pc.firebasetest/com.example.hasib_pc.firebasetest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4268)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
MainActivity完整代码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final int IMAGE_CAPTURE_CODE = 3;
private Button uploadBtn;
private ImageView showImage;
private StorageReference mStorage;
private ProgressDialog progressDialog;
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
Log.d(TAG, "createImageFile: start.");
String 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
);
mCurrentPhotoPath = image.getAbsolutePath();
Log.d(TAG, "createImageFile: End.");
return image;
}
private void takePictureIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e(TAG, "takePictureIntent: IOException: "+ex.getMessage(),ex);
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, IMAGE_CAPTURE_CODE);
Log.d(TAG, "takePictureIntent: End.");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
uploadBtn = findViewById(R.id.uploadBtnId);
showImage = findViewById(R.id.imageShowId);
progressDialog = new ProgressDialog(this);
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
takePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: Started.");
if(requestCode == IMAGE_CAPTURE_CODE && resultCode == RESULT_OK){
Log.d(TAG, "onActivityResult: start uploading");
progressDialog.setMessage("Uploading...");
progressDialog.show();
Uri uri = data.getData();
Log.d(TAG, "onActivityResult: set filepath");
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
Log.d(TAG, "onActivityResult: try to putFile");
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onSuccess: started.");
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
}
答案 0 :(得分:0)
这是我的错。我找到了解决方案。
创建一个Uri instantce veriable。 private Uri photoURI;
然后用Intent putExtra方法发送这个Uri。
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
并通过StorageReference putFile方法传递uri对象
filepath.putFile(photoURI)
我在 onCreate 方法中调用了Uri photoURI,这个方法是Class实例可靠的,这就是为什么得到NullPointerException。