从库中选取图片时获取NullPointerException

Himanshu Agnihotri

嗨,我是Android的新手,我试图将图片保存到服务器上,但是,一旦我单击我的imageview进入图库并选择图片,我的应用程序就会崩溃,它给我这个错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.Object android.os.Bundle.get(java.lang.String)'

我的活动代码:

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

}

我的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)
哈沙德·潘苏里亚(Harshad Pansuriya)

更改此代码:

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

对此

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

bitmap最后添加变量,最后设置值bitmap = BitmapFactory.decodeFile(imagePath);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何从图库中选取图片?

来自分类Dev

从网址获取图片时出错

来自分类Dev

上传图片时获取图片名称

来自分类Dev

上传图片时获取图片名称

来自分类Dev

从图库中选取图片并裁剪尺寸大于500 * 500的图片

来自分类Dev

从相机中获取照片时,imagePickerController崩溃。从图片库工作正常。为什么?

来自分类Dev

从图库中选取图片并在imagae视图中显示

来自分类Dev

获取Facebook图片时芹菜任务错误

来自分类Dev

使用PHAsset获取图片时避免重复

来自分类Dev

NullPointerException在OnDateSet,从Datepicker对话框中选取日期

来自分类Dev

如何修复 NullPointerException:从相机捕获图片时的文件

来自分类Dev

点击图片时如何获取特定记录的ID

来自分类Dev

在Android中获取Facebook个人资料图片时出错

来自分类Dev

上传图片时出错

来自分类Dev

上传图片时出错

来自分类Dev

从向量中选取“随机”元素

来自分类Dev

在图像视图中裁剪后如何获取从图库中选取的图像的宽度和高度

来自分类Dev

上传图片时在数据库中保存完整的URL链接

来自分类Dev

向API请求formData,在上传图片时在axios中获取“网络错误”

来自分类Dev

加载图片时卸载div

来自分类Dev

从图片标题中获取 WordPress 库图片描述

来自分类Dev

从Go Slice中选取随机值

来自分类Dev

Python:从数组中选取某个元素

来自分类Dev

从直线上的点中选取“点差”

来自分类Dev

根据先前的值从数组中选取值

来自分类Dev

从多个数组中选取元素

来自分类Dev

调整从图库中选取的图像的大小

来自分类Dev

相对从数组中选取X个值

来自分类Dev

尝试从 JSON 响应文本中选取数据

Related 相关文章

热门标签

归档