[英]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 : 我是Android新手,我正在尝试将图片保存到服务器上,但是当我点击我的imageview并进入图库并选择图片我的应用程序崩溃时它会给我这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.Object android.os.Bundle.get(java.lang.String)'
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 : 我的Logcat是:
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);
最后添加变量
bitmap
并设置值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
如果您仍希望存储到位图成员变量,则在设置了imagepath之后
bitmap = BitmapFactory.decodeFile(imagePath)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.