尝试上传文件时出现NullPointerException

时间:2016-09-23 06:42:44

标签: java android file-upload

我尝试使用多部分表单数据上传文件,但在此行中获得空点异常

int column_index = cursor .getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);

Process: zupportdesk.desk.zupport.chatsystem, PID: 6643
   java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/file/213/ORIGINAL/NONE/1958544359 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F213/ORIGINAL/NONE/1958544359} }} to activity {zupportdesk.desk.zupport.chatsystem/zupportdesk.desk.zupport.chatsystem.Chatting}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
       at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
       at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
       at android.app.ActivityThread.-wrap20(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6077)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
       at zupportdesk.desk.zupport.chatsystem.Chatting.getPath(Chatting.java:276)
       at zupportdesk.desk.zupport.chatsystem.Chatting.uploadMultipart(Chatting.java:290)
       at zupportdesk.desk.zupport.chatsystem.Chatting.onActivityResult(Chatting.java:264)
       at android.app.Activity.dispatchActivityResult(Activity.java:6917)
       at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
       at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
       at android.app.ActivityThread.-wrap20(ActivityThread.java) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:154) 
       at android.app.ActivityThread.main(ActivityThread.java:6077) 
       at java.lang.reflect.Method.invoke(Native Method)

方式

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Chatting.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            Log.d("chatting_imagePath2", filePath);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);

            if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                //FINE
                Uri myUri = Uri.parse(filePath);
                uploadMultipart(myUri);
                //multiPartPost(filePath);
            } else {
                //NOT IN REQUIRED FORMAT
            }
        }
}

public String getPath(Uri uri) {
    String[] projection = {MediaStore.MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();
    String imagePath = cursor.getString(column_index);
    Log.d("chatting_imagePath", imagePath);
    return cursor.getString(column_index);
}


public void uploadMultipart(Uri filePath) {
    //getting name for the image

    //getting the actual path of the image
    String path = getPath(filePath);

    //Uploading code
    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                .addFileToUpload(path, "image") //Adding file
                .addParameter("name", "sathyabaman") //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}


//Requesting permission
private void requestStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }
    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}


//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

摇篮

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile files('libs/gson-2.2.2.jar')
    compile files('libs/signalr-client-sdk-android.jar')
    compile files('libs/signalr-client-sdk.jar')
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
    compile 'br.com.liveo:navigationdrawer-material:2.5.1'
    compile 'org.java-websocket:Java-WebSocket:1.3.0'
    compile 'com.google.android.gms:play-services:7.5.0'
    compile files('libs/httpmime-4.3.1.jar')
    compile 'net.gotev:uploadservice:2.1'
}

0 个答案:

没有答案