Himanshu Agnihotri Himanshu Agnihotri - 6 days ago 6
Android Question

Getting NullPointerException while picking Picture From Gallery

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);
}
}

/**
* its return true when user provide all the valid details
* else set a error on edittext and return false.
*/
private boolean validateProfile() {
int errorCount = 0;
if (profileName.getText().toString().trim().equals("")) {
profileName.setError("Enter your name");
errorCount = errorCount + 1;
if (errorCount == 1) {
profileName.requestFocus();
}
} else {
profileName.setError(null);
}
if (profileDob.getText().toString().trim().equals("")) {
profileDob.setError("Enter your date of birth");
errorCount = errorCount + 1;
if (errorCount == 1) {
profileDob.requestFocus();
}
} else {
profileDob.setError(null);
}
if (errorCount == 0) {
return true;
} else {
return false;
}
}

/**
* on double Back pressed exit from application.
*/
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Back again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}

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

Answer

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.