尝试调用虚方法' android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' null对象引用

时间:2016-11-17 17:51:06

标签: java android nullpointerexception parcelable

我正在创建一个应用程序,其中用户可以将图像和视频上传到服务器 它在活动上运作良好,但现在我想在一个片段中使用它。我尝试有效,高效地编码,我在编译期间没有收到任何错误,我的应用程序运行成功但是当我点击片段时它显示"不幸的是应用程序停止了#34;并在log cat中我收到此错误:

  

java.lang.NullPointerException:尝试调用虚拟方法&android; .and.ar。在空对象引用上

并指出这一行:

 public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
   this line  ➦   fileUri = savedInstanceState.getParcelable("file_uri"); 
    }

我不知道什么是错的

我的代码:

public class TabFragment4 extends Fragment implements  View.OnClickListener{

View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();


int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video

private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;


public TabFragment4() {
    // Required empty public constructor
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);

    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {


        AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());

        // Setting Dialog Title
        mAlertDialog.setTitle("Location not available, Open GPS?")
                .setMessage("Activate GPS to use Location Service  ?")
                .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).show();


        // Call your Alert message
    }

    btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
    btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
    gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);

    videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
    location=(ImageButton)parentHolder.findViewById(R.id.location);

    videobtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            video();
        }
    });
    gallerybtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            galleryimage();
        }
    });
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            captureImage();
        }
    });

    /**
     * Capture image button click event
     */

    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });
    /**
     * Record video button click event
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // record video
            recordVideo();
        }
    });

    return parentHolder;
    }



public void video(){
    Intent intent = new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,
            "Select file to upload "), video_code);
}

public void galleryimage(){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,
            "Select file to upload "), req_code);
}

public String getPath(Uri uri) {

    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();

    return cursor.getString(column_index);
}

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri =  getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/**
 * Launching camera app to record video
 */
private void recordVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
    // name

    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    fileUri = savedInstanceState.getParcelable("file_uri");


}




public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image

    if (requestCode == req_code) {
        selectedImageUri = data.getData();

        if (resultCode ==Activity. RESULT_OK) {
            path = getPath(selectedImageUri);
            launchUpload(true);

            System.out.println("selectedPath1 : " + path);
        }
    }

    if (requestCode == video_code) {
        selectedImageUri = data.getData();

        if (resultCode == Activity. RESULT_OK) {
            path = getPath(selectedImageUri);
            launchUpload(false);

            System.out.println("selectedPath1 : " + path);
        }
    }


    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {

            //successfully captured the image
            // launching upload activity
            launchUploadActivity(true);

            //Intent intent = new Intent(this,UploadActivity.class);
            //startActivity(intent);

        } else if (resultCode ==Activity. RESULT_CANCELED) {

            // user cancelled Image capture
            Toast.makeText(getActivity(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to capture image
            Toast.makeText(getActivity(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {

            // video successfully recorded
            // launching upload activity
            launchUploadActivity(false);



        } else if (resultCode == Activity.RESULT_CANCELED) {

            // user cancelled recording
            Toast.makeText(getActivity(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to record video
            Toast.makeText(getActivity(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}


private void launchUploadActivity(boolean isImage) {
    Intent i = new Intent(getActivity(), UploadActivity.class);
    i.putExtra("filePath", fileUri.getPath());
    i.putExtra("isImage", isImage);

    startActivity(i);
}
private void launchUpload(boolean isImage) {
    Intent i = new Intent(getActivity(), UploadActivity.class);
    i.putExtra("filePath", path);
    i.putExtra("isImage", isImage);

    startActivity(i);
}

/**
 * ------------ Helper Methods ----------------------
 * */

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}





@Override
public void onClick(View v) {




}
}

2 个答案:

答案 0 :(得分:2)

Uri imageUri = data.getData();
            Bitmap bitmap= null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }

答案 1 :(得分:1)

似乎savedInstanceState == null所以请使用以下内容:

if (savedInstanceState != null) {
    fileUri = savedInstanceState.getParcelable("file_uri"); 
} else {
    fileUri = ??? - what You want do to in else case;
}