在Android 7.1中从相机获取图像时将结果传递给活动失败

时间:2017-11-02 11:15:39

标签: android android-camera-intent

在Android 7.1中从相机获取图像时将结果ResultInfo {who = null,request = 3,result = -1,data = null}发送到活动失败

我正试图从我的相机意图中获取并成像,但在尝试从我的Uri获取路径时遇到错误,因为我需要将文件上传到我的服务器的路径。

这是我的代码

  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);
    }

public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            String document_id = cursor.getString(0);
            document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
            cursor.close();

            cursor = getContentResolver().query(
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
            cursor.moveToFirst();
            path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            cursor.close();
        }


        return path;
    }



  public void startCamera() {
        Intent callCameraApplicationIntent = new Intent();
        callCameraApplicationIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

        File photoFile = null;
        try {
            photoFile = createImageFile();

        } catch (IOException e) {
            e.printStackTrace();
        }

        String authorities = getApplicationContext().getPackageName() + ".provider";
        currentImageUri = FileProvider.getUriForFile(this, authorities, photoFile);
        callCameraApplicationIntent.putExtra(MediaStore.EXTRA_OUTPUT, currentImageUri);
        callCameraApplicationIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        callCameraApplicationIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(callCameraApplicationIntent, CAMERA_REQUEST);

    }



protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            try {
                filePath = data.getData();
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
                String format = simpleDateFormat.format(new Date());
                storedImagePath = tempFileImage(this, bitmap, "name" + format);
                uploadMultipart();

            } catch (IOException e) {
                e.printStackTrace();
            }

        } else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            filePath = currentImageUri;
            uploadMultipart();


        }
}

最后uoloading到服务器

   public void uploadMultipart() {
        //getting name for the image
        String path = "";

        String name = messageET.getText().toString().trim();
        //getting the actual path of the image


        if (currentImageUri != null) {
//            path = getPath(currentImageUri);
            path = getRealPathFromURI(currentImageUri);
        }
        if (filePath != null) {
            path = getPath(filePath);
        }


        try {
            String uploadId = UUID.randomUUID().toString();
            String uploadUrl = "https://app.aer.media/v2/message_router/_sendMessage";

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, uploadUrl)
                    .addFileToUpload(path, "mediaFile") //Adding file
                    .addParameter("data[message]", name) //Adding text parameter to the request
                    .addParameter("data[user_data]", k) //Adding text parameter to the request
                    //                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload
//            getConvoData(k, "", "", false);
//            rv_convo.getAdapter().notifyItemInserted(convobeans.size() - 1);

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);

            ConvoResponseModel.DataBean.ConversationBean.MediaFileBean mf = new ConvoResponseModel.DataBean.ConversationBean.MediaFileBean();

            mf.setImage(null);
            mf.setThumb(null);
            mf.setBitmap(bitmap);
            long time = new Date().getTime() / 1000;


            ConvoResponseModel.DataBean.ConversationBean conversationBean = new ConvoResponseModel.DataBean.ConversationBean();
            conversationBean.setMessage("");
            conversationBean.setIs_me(1);
            conversationBean.setTime(String.valueOf(time));
            conversationBean.setMediaFile(mf);

            adapter.addItem(conversationBean);
//            adapter.notifyItemInserted(convobeans.size - 1);


        } catch (Exception exc) {
        }
    }

我能够以完全相同的路径查看从我的文件保存的图像,但是当我尝试将图像上传到服务器并调用其getpath()时,它会抛出错误

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: media.aer.influencer, PID: 24847
                                                                      java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=null} to activity {media.aer.influencer/media.aer.influencer.Activity.ChatDetailsActivity}: android.database.CursorIndexOutOfBoundsException: Requested column: -1, # of columns: 2
                                                                          at android.app.ActivityThread.deliverResults(ActivityThread.java:4257)
                                                                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:4300)
                                                                          at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1588)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6321)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                       Caused by: android.database.CursorIndexOutOfBoundsException: Requested column: -1, # of columns: 2
                                                                          at android.database.MatrixCursor.get(MatrixCursor.java:66)
                                                                          at android.database.MatrixCursor.getString(MatrixCursor.java:254)
                                                                          at android.database.CursorWrapper.getString(CursorWrapper.java:137)
                                                                          at media.aer.influencer.Activity.ChatDetailsActivity.getRealPathFromURI(ChatDetailsActivity.java:2787)
                                                                          at media.aer.influencer.Activity.ChatDetailsActivity.uploadMultipart(ChatDetailsActivity.java:2640)
                                                                          at media.aer.influencer.Activity.ChatDetailsActivity.onActivityResult(ChatDetailsActivity.java:2735)
                                                                          at android.app.Activity.dispatchActivityResult(Activity.java:7022)
                                                                          at android.app.ActivityThread.deliverResults(ActivityThread.java:4253)
                                                                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:4300) 
                                                                          at android.app.ActivityThread.-wrap20(ActivityThread.java) 
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1588) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                          at android.os.Looper.loop(Looper.java:154) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6321) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

1 个答案:

答案 0 :(得分:0)

ACTION_IMAGE_CAPTURE未返回Uri,而您的getPath() / getRealPath()代码仍无效。

您知道文件的位置。您已将其添加到EXTRA_OUTPUT中。它被称为photoFile。保持此值(包括将其保存在已保存的实例状态Bundle中)并使用它。

This sample app显示如何将FileProviderACTION_IMAGE_CAPTURE结合使用。