HI i am new to Android and i am trying to save a picture onto a server but as soon as i click on my imageview and get into the gallery and select the picture my App gets crashed and it gives me this Error :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
My Activity Code :
public class ProfileActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private static int LOAD_IMAGE = 1;
public RadioGroup profileRadioGroup;
String imagePath;
private EditText profileName, profileDob;
private CircleImageView profileImageView;
private Button profileSave;
private RadioButton genderMale, genderFemale;
private String profileGender;
private boolean doubleBackToExitPressedOnce = false;
private TelephonyManager telephoneManager;
private NetworkUtil networkUtil;
private Bitmap bitmap;
private SharePrefUtil prefUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().hide();
networkUtil = new NetworkUtil(getApplicationContext());
telephoneManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
prefUtil = new SharePrefUtil(getApplicationContext());
initScreen();
fillLayout();
}
private void initScreen() {
profileImageView = (CircleImageView) findViewById(R.id.displayprofileimage);
profileImageView.setOnClickListener(new ButtonClick());
profileName = (EditText) findViewById(R.id.fed_profilename);
InputFilter[] FilterArray1 = new InputFilter[1];
FilterArray1[0] = new InputFilter.LengthFilter(30);
profileName.setFilters(FilterArray1);
profileDob = (EditText) findViewById(R.id.fed_profileDob);
profileDob.setFocusable(false);
profileDob.setOnClickListener(new ButtonClick());
profileRadioGroup = (RadioGroup) findViewById(R.id.radioSex);
genderMale = (RadioButton) findViewById(R.id.gender_male);
genderFemale = (RadioButton) findViewById(R.id.gender_female);
profileSave = (Button) findViewById(R.id.btn_profilesave);
profileSave.setOnClickListener(new ButtonClick());
}
private void fillLayout(){
Log.d("jagteraho","profileImage: "+prefUtil.getValueFromSharePref("profileImage"));
if(!prefUtil.getValueFromSharePref("profileImage").equalsIgnoreCase("")
&&!prefUtil.getValueFromSharePref("profileImage").equalsIgnoreCase("null"))
{
byte[] encodeByte = Base64.decode(prefUtil.getValueFromSharePref("profileImage"), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
profileImageView.setImageBitmap(bitmap);
}
else{
profileImageView.setImageResource(R.drawable.profile2);
}
if (!prefUtil.getValueFromSharePref("profileName").equalsIgnoreCase("null")) {
profileName.setText(prefUtil.getValueFromSharePref("profileName"));
}
if (!prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("null")) {
if (prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("male"))
genderMale.setChecked(true);
else if (prefUtil.getValueFromSharePref("profileGender").equalsIgnoreCase("female")) {
genderFemale.setChecked(true);
}
}
if (!prefUtil.getValueFromSharePref("profileDob").equalsIgnoreCase("null")) {
profileDob.setText(prefUtil.getValueFromSharePref("profileDob"));
}
}
/**
* used for display profile picture from the gallery.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
bitmap = (Bitmap) data.getExtras().get("data"); //I am Getting Error At This LIne
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(index);
cursor.close();
profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
}
/**
* save the user profile using the active android database library.
*/
private void saveProfile() {
prefUtil.setValueInSharePref("profileName",profileName.getText().toString());
prefUtil.setValueInSharePref("profileDob", profileDob.getText().toString());
if (genderFemale.isChecked()) {
prefUtil.setValueInSharePref("profileGender", "Female");
} else if (genderMale.isChecked()) {
prefUtil.setValueInSharePref("profileGender", "Male");
}
if(imagePath!=null) {
prefUtil.setValueInSharePref("profileImage", imagePath);
}
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "" + year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
profileDob.setText(date);
}
/**
* used to call gallery, onclick to profile imageView.
*/
class ButtonClick implements View.OnClickListener {
public void onClick(View v) {
switch(v.getId())
{
case R.id.displayprofileimage:
displayProfileImageClicked();
break;
case R.id.btn_profilesave:
btnProfileSaveClicked();
break;
case R.id.fed_profileDob:
btnProfileDOBClicked();
break;
default:
break;
}
}
}
private void displayProfileImageClicked(){
Intent a = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(a, LOAD_IMAGE);
}
private void btnProfileDOBClicked() {
Calendar cal = Calendar.getInstance();
cal.set(2005, 12, 31);
DatePickerDialog dpd = DatePickerDialog.newInstance(
ProfileActivity.this,
2005, 12, 31
);
dpd.setMaxDate(cal);
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void btnProfileSaveClicked(){
if (validateProfile()) {
try {
if(genderFemale.isChecked())
profileGender = genderFemale.getText().toString();
else
profileGender = genderMale.getText().toString();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Please select a gender", Toast.LENGTH_SHORT).show();
}
if (profileGender == null) {
Toast.makeText(this, "Please select a gender", Toast.LENGTH_SHORT).show();
} else {
if (networkUtil.isConnected()) {
profileService();
} else {
android.app.AlertDialog.Builder alertbox = new android.app.AlertDialog.Builder(ProfileActivity.this);
alertbox.setMessage("No network connection, Please try after some time");
alertbox.create();
alertbox.setCancelable(false);
alertbox.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertbox.show();
}
}
}
}
/**
* class provide all the information of user to server and
* getting a authentication key as response.
*/
private void profileService(){
OkHttpClient client = new OkHttpClient();
String requestURL = String.format(getResources().getString(R.string.service_profileCreate));
String proImg = null;
if(imagePath!=null) {
try {
File f = new File(imagePath);
FileInputStream fin = new FileInputStream(f);
byte[] data = new byte[fin.available()];
fin.read(data);
fin.close();
proImg = Base64.encodeToString(data, Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
}
JSONObject jsonRequest = new JSONObject();
try {
jsonRequest.accumulate("empAuthKey", prefUtil.getValueFromSharePref("authKey"));
jsonRequest.accumulate("profileImg", proImg);
jsonRequest.accumulate("name", profileName.getText().toString().trim());
jsonRequest.accumulate("strDOB", profileDob.getText().toString().trim());
jsonRequest.accumulate("gender", profileGender);
jsonRequest.accumulate("mobileNo", prefUtil.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("imei", telephoneManager.getDeviceId());
}catch(Exception e)
{
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest.toString());
Request request = new Request.Builder()
.url(requestURL)
.post(body).build();
final SweetAlertDialog pDialog = new SweetAlertDialog(ProfileActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Saving Please wait ...");
pDialog.setCancelable(false);
pDialog.show();
client.newCall(request).enqueue(new Callback() {
String status, message;
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == 1) {
Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
} else if (msg.what == 0) {
Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
} else if (msg.what == -1) {
Toast.makeText(ProfileActivity.this, "" + message, Toast.LENGTH_LONG).show();
} else if (msg.what == 2) {
Toast.makeText(ProfileActivity.this, "System Error Please try again...", Toast.LENGTH_LONG).show();
}
return false;
}
});
@Override
public void onFailure(Call call, IOException e) {
if (pDialog.isShowing()) pDialog.dismiss();
handler.sendEmptyMessage(2);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseString = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(responseString);
status = jsonResponse.getString("status");
message = jsonResponse.getString("message");
Log.d("jagteraho", "status: " + status + " message: " + message);
if (status.equals("success")) {
if (pDialog.isShowing()) pDialog.dismiss();
saveProfile();
handler.sendEmptyMessage(1);
Intent login = new Intent(ProfileActivity.this, LoginActivity.class);
startActivity(login);
finish();
} else if (status.equalsIgnoreCase("failure")) {
if (pDialog.isShowing()) pDialog.dismiss();
handler.sendEmptyMessage(0);
Intent profile = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(profile);
finish();
} else if (status.equalsIgnoreCase("error")) {
if (pDialog.isShowing()) pDialog.dismiss();
handler.sendEmptyMessage(-1);
Intent alarm = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(alarm);
finish();
}
} catch (Exception e) {
if (pDialog.isShowing()) pDialog.dismiss();
handler.sendEmptyMessage(2);
e.printStackTrace();
}
}
}
});
}
}
My Logcat are :
E/CustomActivityOnCrash: App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler
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/107745/ORIGINAL/NONE/2008282015 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Ffile%2F107745/ORIGINAL/NONE/2008282015} }} to activity {com.aspeage.jagteraho/com.aspeage.jagteraho.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
at com.aspeage.jagteraho.ProfileActivity.onActivityResult(ProfileActivity.java:143)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Try this
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
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);
}
/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Change this code :
if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
bitmap = (Bitmap) data.getExtras().get("data"); //I am Getting Error At This LIne
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(index);
cursor.close();
profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
to this
if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(index);
cursor.close();
profileImageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
bitmap = BitmapFactory.decodeFile(imagePath);
}
Add your variable bitmap
at last and set value bitmap = BitmapFactory.decodeFile(imagePath);
at the end.
Even though you are trying to set the bitmap object at that point, you are not anyways using it anywhere. I think you could remove that line. You are using the image path from the content resolver anyways to get the image. If you still want to store to the bitmap member variable, after you have set the imagepath
bitmap = BitmapFactory.decodeFile(imagePath)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.