我正在尝试此代码。它允许图像上传为图库部分,但相机部分出错。
错误是:
java.lang.NullPointerException:尝试调用虚方法 'java.lang.Object android.os.Bundle.get(java.lang.String)'为null 对象参考`
代码:
public class MyProfile extends Fragment implements View.OnClickListener {
//This is the unique id which represents the id has been selected
private static final int RESULT_LOAD_IMAGE = 1;
ImageView profilePic;
Button buttonToUpload;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_profile, container, false);
buttonToUpload = (Button) rootView.findViewById(R.id.upload_button);
profilePic = (ImageView) rootView.findViewById(R.id.profile);
buttonToUpload.setOnClickListener(this);
// Inflate the layout for this fragment
return rootView;
}
@Override
public void onClick(View v) {
CharSequence choice[] = {"Gallery", "Camera"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Choose").
setItems(choice, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//When the user selects a picture the result of which image is selected by the user is given by startActiviytForResult
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}else {
//If User chooses to upload photo through camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, RESULT_LOAD_IMAGE);
}
}
});
alertDialog.show();
}
/**
* Receive the result from a previous call to
* {@link #startActivityForResult(Intent, int)}. This follows the
* related Activity API as described there in
* {@link Activity#onActivityResult(int, int, Intent)}.
*
* @param requestCode The integer request code originally supplied to
* startActivityForResult(), allowing you to identify who this
* result came from.
* @param resultCode The integer result code returned by the child activity
* through its setResult().
* @param data An Intent, which can return result data to the caller
* (various data can be attached to Intent "extras").
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
//Checking that the gallery intent has called this method
if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
//Uniform Resource Indicator: This shows us the image in the form that has been selected
Uri selectedImage = data.getData();
profilePic.setImageURI(selectedImage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}