Unable to update Firebase Realtime Database in Android

问题: I am trying to make an app in which the user has options to change his name, email, etc. Even though I am getting the correct userID, whenever I try to update the database...

问题:

I am trying to make an app in which the user has options to change his name, email, etc. Even though I am getting the correct userID, whenever I try to update the database the app crashes saying

`Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference`

Here is my code

  public class EditProfile extends AppCompatActivity {

        FirebaseAuth auth;
        DatabaseReference databaseReference;
        private DatabaseReference mFirebaseDatabase;
        private DatabaseReference mFirebaseInstance;
        String name2 , email2 ;
        EditText name , email , bio;
        private SlidrInterface slidr;
        ImageView profilePic;
        final int PICK_IMAGE_REQUEST = 71;
        Uri imageUri;
        Button saveButton;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_edit_profile);

            auth = FirebaseAuth.getInstance();
            databaseReference = FirebaseDatabase.getInstance().getReference();
            final FirebaseUser user = auth.getCurrentUser();
            name = (EditText) findViewById(R.id.name);
            email = (EditText) findViewById(R.id.email);
            bio = (EditText) findViewById(R.id.bio);
            profilePic = (ImageView) findViewById(R.id.profilepic);
            saveButton = (Button) findViewById(R.id.save);
            slidr = Slidr.attach(this);
            mFirebaseInstance = FirebaseDatabase.getInstance().getReference();
            mFirebaseDatabase = FirebaseDatabase.getInstance().getReference();

            final String userID = user.getUid();
            Log.d("TAG" , "USERID = "+userID );

            databaseReference.child("users").child(user.getUid()).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot){
                    name2 = (String) dataSnapshot.child("name").getValue();
                    String gender = (String) dataSnapshot.child("gender").getValue();
                    email2 = (String) dataSnapshot.child("email").getValue();
                    Log.d("TAG", "Name: " +name2);
                    Log.d("TAG", "Email: " +email);
                    Log.d("TAG", "Gender: " +gender);
                    name.setText(name2);
                    email.setText(email2);

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}

            });

            profilePic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

                }
            });

            saveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String nameTest = name.getText().toString();
                    String emailTest = email.getText().toString();
                    String bioTest = bio.getText().toString();

                    Log.d("TAG" , "NAMETEST = "+nameTest);

                    mFirebaseDatabase.child(userID).child("name").setValue(nameTest);
                    //mFirebaseDatabase.child(user).child("bio").setValue(bioTest);
                    mFirebaseDatabase.child(userID).child("email").setValue(emailTest);
                }
            });
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                    && data != null && data.getData() != null )
            {
                imageUri = data.getData();
                //String test = filepath.toString();
                //Log.d("CameraActivity" , " Path is = " +test);
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                    //ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    //bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    //byte[] byteArray = stream.toByteArray();
                    profilePic.setImageURI(imageUri);

                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

            }
        }
     }

I am not able to understand what is the null object refernce here. I have put log statements and checked the individual parmeters.

D/TAG: USERID = 5tI5e4Y2NeOQ7yq8DwefvmYJk713
D/TAG: Name: Darryl Fernandes
Email: fernsdarryl1@gmail.com
Gender: male

Below is an images of my database n An

Please help me figure this out. Thank You

EDIT

As you guys can see I separated the initialization and declaration of mFirebaseDatabase, but still it won't update on firebase even though the error is gone


回答1:

Some changes I can suggest which will make your code more clear and easy to debug.

First use names for your database references which identify node in database so:

FirebaseDatabase db = FirebaseDatabase.getInstance();

DatabaseReference userProfileRef = db.getReference("users").child(userId);

Now use this reference to add single value event instead of value event since you need to read data once to show profile and after profile update you can call single value event again if you need. userProfileRef.addSingleValueEvent(...)

Next instead of setting value you can use update to write all values at once. Create a HashMap<String,Object> (Object if you have different data types for different fields). We will call update with reference to userProfileRef so key will simply be profile fields name

map.add("email",email)
map.add("name",name);
userProfileRef.update(map);

This update call returns a Task on which you can add onCompletionListener and notify user about profile update.


回答2:

Check you declaration and make this changes in it:

private DatabaseReference mFirebaseDatabase;

and assign value to it after you created mFirebaseDatabase

mFirebaseDatabase= FirebaseDatabase.getInstance().getReference();
mFirebaseDatabase.child("/*Pass you're collection name*/").child(userID).child("email").setValue(emailTest);

Check if it's working or not

  • 发表于 2019-07-05 06:27
  • 阅读 ( 231 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除