Android:使用.getStringExtra

时间:2015-11-13 06:53:32

标签: java android nullpointerexception bundle

我会直接解决问题。在UploadNotesActivity.java ....

首先,我使用意图

选择一个.pdf文件
chooseNotesBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create intent to Open Image applications like Gallery, Google Photos
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            // Start the Intent
            startActivityForResult(intent, RESULT_LOAD_FILE);
        }
    });

然后,在`onActivityResult中,我保存了所选文件的filePath。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_FILE && resultCode == RESULT_OK && data != null) {
        data.putExtra("filePath", data.getData().getPath());
        choosenFile.setText(data.getStringExtra("filePath"));
    } else {
        Toast.makeText(this, "Error in choosing file",
                Toast.LENGTH_LONG).show();
    }
}

点击Upload按钮开始上传文件

 uploadNotesBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onUploadButtonClick();
        }
    });

onUploadButtonClick()

private void onUploadButtonClick() {
    final String serverUrlString = "http://XXXX/uploadNotes.php";
    if (getIntent().getStringExtra("filePath").isEmpty()) {
        Log.d(TAG, "filePath is null");
    } else {
        Log.d(TAG, getIntent().getStringExtra("filePath"));
    }
    final String fileToUploadPath = getIntent().getStringExtra("filePath");
    final String paramNameString = "uploaded_file";

    String fileName[] = fileToUploadPath.split("/");

    final MultipartUploadRequest request =
            new MultipartUploadRequest(this, UUID.randomUUID().toString(), serverUrlString);

    request.addFileToUpload(fileToUploadPath, paramNameString,
            fileName[fileName.length-1]+".pdf", ContentType.APPLICATION_OCTET_STREAM);

    request.setNotificationConfig(R.drawable.ic_launcher,
            getString(R.string.app_name),
            getString(R.string.uploading),
            getString(R.string.upload_success),
            getString(R.string.upload_error),
            false);

    // if you comment the following line, the system default user-agent will be used
    request.setCustomUserAgent("UploadServiceDemo/1.0");

    // set the intent to perform when the user taps on the upload notification.
    // currently tested only with intents that launches an activity
    // if you comment this line, no action will be performed when the user taps
    // on the notification
    // request.setNotificationClickIntent(new Intent(this, MainActivity.class));

    // set the maximum number of automatic upload retries on error
    request.setMaxRetries(2);

    try {
        request.startUpload();
    } catch (Exception exc) {
        Toast toast = Toast.makeText(getApplicationContext(), "Malformed upload request. " + exc.getLocalizedMessage(), Toast.LENGTH_LONG);
        toast.show();
    }
}

但问题是,它会抛出空指针异常,我不太明白这一点。

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.onUploadButtonClick(UploadNotesActivity.java:73)
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity.access$100(UploadNotesActivity.java:19)
        at com.fyp.mycyberlaw.Lecturer.UploadNotesActivity$2.onClick(UploadNotesActivity.java:53)

第73行:if (getIntent().getStringExtra("filePath").isEmpty())

第19行:public class UploadNotesActivity extends Activity

第53行:onUploadButtonClick();

似乎第73行中的filePath是空的,我将filePath保存到bundle(?)的方式不正确。如何从onActivityResult获取filePath?这是.java类,以防万一。先感谢您。真的需要你的帮助。

1 个答案:

答案 0 :(得分:1)

Intent对象用于在活动之间传递参数。如果您收到文件路径,则必须将其保留在活动中。

在您的活动中创建一个filePath变量,将其设置在onActivityResult上并在onUploadButtonClick上阅读。

请注意,必须在onSaveInstanceState回调期间保存变量值,并在onCreate中将其恢复,因为每次关闭手机时,活动都会被销毁并重新创建。请查看此信息以获取更多信息:Recreating an Activity