Ali Imtiaz Ali Imtiaz - 23 days ago 27
Android Question

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' null object reference

i am making an app in which a feature that user can upload images and video to server
it was working well on activity but now i want to use it in fragment
i try to code effectively ,efficiently and i am not getting any error during compiling and my app runs successfully but when i click on fragment its shows

"unfortunately app has stopped "
and in log cat i am getting this error

"java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference "
and its points this line

public void onActivityCreated(Bundle savedInstanceState) {

super.onActivityCreated(savedInstanceState);


this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");

}


i don't know whats wrong

my code

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) {




}


}

Answer

Seems savedInstanceState == null so use something like this:

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