获得空指针异常。知道错误的位置,但不知道如何解决这个问题

时间:2018-03-24 21:41:19

标签: android android-intent nullpointerexception google-cloud-firestore

    package com.lukaut.android.fragments;


    import android.Manifest;
    import android.app.ProgressDialog;
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.content.ContextCompat;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.webkit.MimeTypeMap;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.Toast;

    import com.bumptech.glide.Glide;
    import com.google.android.gms.tasks.OnFailureListener;
    import com.google.android.gms.tasks.OnSuccessListener;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.firestore.DocumentSnapshot;
    import com.google.firebase.firestore.FirebaseFirestore;
    import com.google.firebase.firestore.SetOptions;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.OnProgressListener;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;
    import com.lukaut.android.Model.UserModel;
    import com.lukaut.android.R;
    import com.squareup.picasso.Picasso;

    import java.io.IOException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.OnClick;

    import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class EditProfileFragment extends Fragment {

    private static final int STORAGE_PERMISSION_CODE = 23;
    private FirebaseAuth mAuth;
    UploadTask uploadTask;
    public static final int PICK_IMAGE = 1;
    ProgressBar progressBar;

    FirebaseFirestore firestore;
    private static final String TAG = "Editprofile";
    @BindView(R.id.edit_fullname)EditText edit_user_fullname;
    @BindView(R.id.edit_email)EditText edit_user_email;
    @BindView(R.id.edit_mobile)EditText edit_user_phoneno;
    @BindView(R.id.edit_age)EditText edit_user_age;
    @BindView(R.id.edit_e_fullname_1)EditText edit_e_fullname_1;
    @BindView(R.id.edit_e_fullname_2)EditText edit_e_fullname_2;
    @BindView(R.id.edit_e_fullname_3)EditText edit_e_fullname_3;
    @BindView(R.id.edit_e_number_1)EditText edit_e_number_1;
    @BindView(R.id.edit_e_number_2)EditText edit_e_number_2;
    @BindView(R.id.edit_e_number_3)EditText edit_e_number_3;

    private static final int GALLERY_INTENT = 2;

    private StorageReference storageReference,imageRef;
    ProgressDialog progressDialog;
    Uri selectedImage;
    @BindView(R.id.img_user_profile_pic)
    ImageView img_user_profile_pic;

    public EditProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_edit_profile, container, false);
        ButterKnife.bind(this,v);
        getActivity().setTitle("Edit your profile");
        firestore = FirebaseFirestore.getInstance();

        mAuth = FirebaseAuth.getInstance();
        storageReference = FirebaseStorage.getInstance().getReference();
        getUserDetails(mAuth.getUid());

        return  v;
    }

    private void getUserDetails(String uid) {

        firestore.collection("Users").document(mAuth.getUid()).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                try {
                    UserModel userModel = documentSnapshot.toObject(UserModel.class);
                    //if (!userModel.getUserEmail().isEmpty() || !userModel.getUserEmail().equals("")) {
                     //   loadHomeFragment();
                    //} else {
                        edit_user_fullname.setText(userModel.getUserFullName());
                        edit_user_email.setText(userModel.getUserEmail());
                        edit_user_age.setText(userModel.getUserAge());
                        edit_user_phoneno.setText(userModel.getUserPhoneNo());
                        edit_e_fullname_1.setText(userModel.getEmergency_UserFullName_1());
                        edit_e_fullname_2.setText(userModel.getEmergency_UserFullName_2());
                        edit_e_fullname_3.setText(userModel.getEmergency_UserFullName_3());
                        edit_e_number_1.setText(userModel.getEmergency_UserPhoneNo_1());
                        edit_e_number_2.setText(userModel.getEmergency_UserPhoneNo_2());
                        edit_e_number_3.setText(userModel.getEmergency_UserPhoneNo_3());
                        if (!userModel.getUserProfilePic().equals("") ||!userModel.getUserProfilePic().isEmpty()){
//                            Glide.with(getActivity()).load(userModel.getUserProfilePic()).into(img_user_profile_pic);

面对下面的错误

 Picasso.with(getActivity()).load(userModel.getUserProfilePic()).placeholde r(R.drawable.placeholder).into(img_user_profile_pic);
                        }
                    //}
                        }catch(Exception e){
                            e.printStackTrace();
                            Log.d(TAG, "user details " + e.getMessage());

                    }

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    e.printStackTrace();

                }
            });
        }
        @OnClick(R.id.button_save_details)public void saveDetails() {

            final String userFullNameText = edit_user_fullname.getText().toString();
            final String userEmailText = edit_user_email.getText().toString();
            final String userPhoneNoText = edit_user_phoneno.getText().toString();
            final String userAgeText = edit_user_age.getText().toString();
            final String euserFullName_1 = edit_e_fullname_1.getText().toString();
            final String euserFullName_2 = edit_e_fullname_2.getText().toString();
            final String euserFullName_3 = edit_e_fullname_3.getText().toString();
            final String euserPhoneno_1 = edit_e_number_1.getText().toString();
            final String euserPhoneno_2 = edit_e_number_2.getText().toString();
            final String euserPhoneno_3 = edit_e_number_3.getText().toString();
            String regx = "^[\\p{L} .'-]+$";
            CharSequence inputStr = edit_user_fullname.getText().toString();
            Pattern pattern = Pattern.compile(regx);
            Matcher matcher = pattern.matcher(inputStr);
            if (!matcher.matches()) {
                Toast.makeText(getActivity(), "Plz enter valid full name", Toast.LENGTH_SHORT).show();
                return;
            }

            if (selectedImage != null) {
                imageRef = storageReference.child("profile/" + System.currentTimeMillis() + "." + GetFileExtension(selectedImage));
                progressDialog = new ProgressDialog(getActivity());
                progressDialog.setMax(100);
                progressDialog.setMessage("Uploading...");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
                progressDialog.setCancelable(false);
                //starting upload
                uploadTask = imageRef.putFile(selectedImage);
                // Observe state change events such as progress, pause, and resume
                uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                        //sets and increments value of progressbar
                        progressDialog.incrementProgressBy((int) progress);
                    }
                });
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getActivity(), "Error in uploading!", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        Log.d(TAG, "image uploaded at :" + downloadUrl);
                        final UserModel userModel = new UserModel(mAuth.getUid(), userFullNameText, userEmailText, userPhoneNoText, userAgeText, euserFullName_1, euserFullName_2, euserFullName_3, euserPhoneno_1, euserPhoneno_2, euserPhoneno_3,downloadUrl.toString());
                        firestore.collection("Users").document(mAuth.getUid()).set(userModel, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d(TAG, "DocumentSnapshot successfully written!" + userModel.toString());
                                Toast.makeText(getActivity(), "Successfully Saved", Toast.LENGTH_SHORT).show();
                               // loadHomeFragment();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Error writing document", e);
                            }
                        });
                        Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        //showing the uploaded image in ImageView using the download url
                        //Picasso.with(UploadActivity.this).load(downloadUrl).into(img_user_profile_pic);
                    }
                });
            } else {
                final UserModel userModel = new UserModel(mAuth.getUid(), userFullNameText, userEmailText, userPhoneNoText, userAgeText, euserFullName_1, euserFullName_2, euserFullName_3, euserPhoneno_1, euserPhoneno_2, euserPhoneno_3);
                firestore.collection("Users").document(mAuth.getUid()).set(userModel, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        Log.d(TAG, "DocumentSnapshot successfully written!" + userModel.toString());
                        Toast.makeText(getActivity(), "Successfully Saved", Toast.LENGTH_SHORT).show();
    //                    loadHomeFragment();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "Error writing document", e);
                    }
                });
            }
        }
        public String GetFileExtension(Uri uri) {

            ContentResolver contentResolver = getActivity().getContentResolver();

            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

            // Returning the file Extension.
            return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

        }
        private void loadHomeFragment() {
            Fragment homef = new MapsFragment();
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.setCustomAnimations(R.anim.fragment_slide_left_enter, R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter, R.anim.fragment_slide_right_exit);
            ft.replace(R.id.container, homef);
            ft.commit();
        }

        @OnClick(R.id.img_user_profile_pic)
        public void uploadImage(){
            if (isReadStorageAllowed()){
    //            Intent i = new Intent(Intent.ACTION_PICK);
    //            i.setType("image/*");
    //            startActivityForResult(i,GALLERY_INTENT);
                Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
                getIntent.setType("image/*");

                Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                pickIntent.setType("image/*");

                Intent chooserIntent = Intent.createChooser(getIntent, "Select image to upload");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
                startActivityForResult(chooserIntent,GALLERY_INTENT);

            }else {
                requestStoragePermission();
            }
        }

    //    private void pickImage(){
    //        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
    //        getIntent.setType("image/*");
    //
    //        Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    //        pickIntent.setType("image/*");
    //
    //        Intent chooserIntent = Intent.createChooser(getIntent, "Select image to upload");
    //        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
    //
    //        startActivityForResult(chooserIntent, PICK_IMAGE);
    //    }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == GALLERY_INTENT && resultCode== RESULT_OK ){
                Uri uri = data.getData();

    //            selectedImage = storageReference.child("profile").child(uri.getd);
                selectedImage = uri;

                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),uri);
                    img_user_profile_pic.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        private boolean isReadStorageAllowed() {
            //Getting the permission status
            int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);

            //If permission is granted returning true
            if (result == PackageManager.PERMISSION_GRANTED)
                return true;

            //If permission is not granted returning false
            return false;
        }
        private void requestStoragePermission(){

            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_EXTERNAL_STORAGE)){
                //If the user has denied the permission previously your code will come to this block
                //Here you can explain why you need this permission
                //Explain here why you need this permission
            }

            //And finally ask for the permission
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

            //Checking the request code of our request
            if(requestCode == STORAGE_PERMISSION_CODE){

                //If permission is granted
                if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

                    //Displaying a toast
                    //Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
                }else{
                    //Displaying another toast if permission is not granted
                    //CustomDialogClass.showAlert(CreateActivity.this,"Oops you just denied the permission\n Allow permission to upload pics");
                    Toast.makeText(getActivity(), "Allow storage permission to upload image", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

below image of database

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at com.lukaut.android.fragments.EditProfileFragment$2.onSuccess(EditProfileFragment.java:132)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at com.lukaut.android.fragments.EditProfileFragment$2.onSuccess(EditProfileFragment.java:114)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at com.google.android.gms.tasks.zzj.run(Unknown Source)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at android.os.Looper.loop(Looper.java:154)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6123)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-25 03:06:50.762 10269-10269/com.lukaut.android W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

1 个答案:

答案 0 :(得分:2)

从堆栈跟踪看起来你的错误就是抛出:

if (!userModel.getUserProfilePic().equals("") ||!userModel.getUserProfilePic().isEmpty()){

在第一个代码片段中。

我猜你的userModel不是从同一代码片段

中的上一行创建的
UserModel userModel = documentSnapshot.toObject(UserModel.class);

您可能想要调查为什么会发生这种情况,但与此同时,您可以通过添加空指针检查来防止崩溃:

if ( userModel != null && (!userModel.getUserProfilePic().equals("") ||!userModel.getUserProfilePic().isEmpty())) {

额外的“userModel!= null”将确保usermodel不为null,使用“&amp;&amp;”然后,如果它为null,则会阻止评估以下条件。

这有时被称为“快捷布尔评估”。一旦知道布尔表达式的结果,执行程序(在这种情况下为Java虚拟机)将不会打扰评估表达式的任何其他部分。

因为任何带有false的“anded”只能是false(userModel!= null,当userModel为null时将返回false),将不会执行附加检查(!userModel.getUserProfilePic().equals("") ||!userModel.getUserProfilePic().isEmpty()),因此不会出现空指针异常。 / p>

对于长时间的解释感到抱歉,但是一些新的程序员可能会觉得它很有趣。

希望这会有所帮助。 CJ