【问题标题】:Why when photoURI passed on the onActivity() says null?? what am i doing wrong [duplicate]为什么当 onActivity() 上传递的 photoURI 显示为 null 时?我做错了什么[重复]
【发布时间】:2017-09-11 14:34:46
【问题描述】:

这是我的MainActivity,除了buttonUpload,其他功能实际上都可以使用。不幸的是,当我点击按钮上传时,该应用程序停止了。

有什么见解吗?急需。 而且我的 logcat 不能在 android studio 2.3.1 上运行,为什么

 public class MainActivity extends AppCompatActivity {

private TrackGPS gps;
private Button buttonUpload;
private EditText editTextMessage;
double longitude;
double latitude;

private StorageReference storage;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog progressDialog;

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 */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = 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) {
            // Error occurred while creating the File...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.android.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.activity_main);

    buttonUpload = (Button) findViewById(R.id.buttonUpload);
    editTextMessage = (EditText) findViewById(R.id.editTextMessage);
    storage = FirebaseStorage.getInstance().getReference();
    progressDialog = new ProgressDialog(this);


    buttonUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            dispatchTakePictureIntent();

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        Uri uri = data.getData();

        StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                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();
            }
        });
    }
}


public void distressMessage(View view){
    gps = new TrackGPS(MainActivity.this);
    String message = "";

    if(view.getId() == R.id.fab){
        message = editTextMessage.getText().toString();
    }else {
        Button sender = (Button) view;
        message = sender.getText().toString();
    }


    SmsManager smsManager = SmsManager.getDefault();

    if(gps.canGetLocation()){


        longitude = gps.getLongitude();
        latitude = gps.getLatitude();

        smsManager.sendTextMessage("+639972301925", null, message + "\n\nLongitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude), null, null);
        Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
    }
    else
    {

        gps.showSettingsAlert();
    }


} 

}

这是我的 Logcat

                                             java.lang.RuntimeException: Unable to resume activity {com.example.niki.currentlocation/com.example.niki.currentlocation.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.niki.currentlocation/com.example.niki.currentlocation.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
                                                 at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
                                                 at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:135)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                              Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.niki.currentlocation/com.example.niki.currentlocation.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
                                                 at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
                                                 at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2972)
                                                 at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017) 
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:135) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference
                                                 at com.example.niki.currentlocation.MainActivity.onActivityResult(MainActivity.java:101)
                                                 at android.app.Activity.dispatchActivityResult(Activity.java:6192)
                                                 at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
                                                 at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2972) 
                                                 at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017) 
                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
                                                 at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                 at android.os.Looper.loop(Looper.java:135) 
                                                 at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这是问题所在。请帮忙

  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.niki.currentlocation/com.example.niki.currentlocation.MainActivity}: java.lang.NullPointerException: 
 Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference

【问题讨论】:

  • 删除public void onClick(View view) {上方的@Override。您应该首先使用onClick XML 属性。更干净
  • 您可能缺少相机权限,对于 marshmellow 之后您需要请求权限,而对于以下设备,您只需在清单中声明即可。
  • 发布 logcat 错误...
  • @Dinos_12345 谢谢老兄。它工作的问题是当我按下相机上的捕获按钮时它会崩溃。我不知道为什么我的 logcat 什么也没有显示
  • @Est 单击您的 logcat 窗口时,会出现一个下拉菜单。如果我没记错的话,有一个名为“详细”的选项,选择它并再次检查。

标签: android nullpointerexception android-camera-intent


【解决方案1】:

未能交付结果 ResultInfo{who=null, request=1, result=-1, data=null}

您正在尝试getData() 处理不存在的内容。

加入一些问题,然后弄清楚为什么这段代码没有达到你期望的意图

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK 
            && data != null) {

        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        Uri uri = data.getData();

        if (uri != null) {
            StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener

比如你这里一共有三个地方你忽略了一个错误...

if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // #1 Error
        ex.printStackTrace();
    }

    if (photoFile != null) {
        Uri photoURI = FileProvider.getUriForFile(this,
                "com.example.android.fileprovider",
                photoFile);
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
    } else {// No else ... #2 error
        Log.e("Error", "something bad happened");
    }

} else { // No else... #3 error
     Log.e("Error", "something bad happened");
}

【讨论】:

  • 谢谢哥们,它可以工作了,没有更多问题了,但是按钮没有做任何事情,即使在拍照后没有显示进度对话框。我想将其保存到 Firebase 存储中。也许我在这里快点了
  • 就像我说的。这只会阻止应用程序崩溃。它不会让一切都神奇地工作
猜你喜欢
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
相关资源
最近更新 更多