gpt4 book ai didi

android - Firebase 数据库无法更新

转载 作者:行者123 更新时间:2023-12-05 00:04:51 25 4
gpt4 key购买 nike

有一个设置选项,您可以在其中设置您的姓名和地址。它应该在当前用户的数据库中更新。每当输入信息并按下“确认”按钮时,应用程序就会崩溃。请帮我调试一下。我附上了一张数据库应该是什么样子的图片。

Here is what the database looks like

下面是logcat

2020-05-09 18:42:26.825 749-749/com.example.macdate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.macdate, PID: 749
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.database.DatabaseReference.updateChildren(java.util.Map)' on a null object reference
at com.example.macdate.SettingsActivity.saveUserInformation(SettingsActivity.java:143)
at com.example.macdate.SettingsActivity.access$000(SettingsActivity.java:38)
at com.example.macdate.SettingsActivity$2.onClick(SettingsActivity.java:86)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

下面是需要注意的代码

package com.example.macdate;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;


public class SettingsActivity extends AppCompatActivity {

private EditText mNameField, mPhoneField;

private Button mBack, mConfirm;

private ImageView mProfileImage;

private FirebaseAuth mAuth;
private DatabaseReference mCustomerDatabase;

private String userId, name, phone, profileImageUrl;

private Uri resultUri;

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

String userSex = getIntent().getExtras().getString("userSex");
mNameField = (EditText) findViewById(R.id.name);
mPhoneField = (EditText) findViewById(R.id.phone);

mProfileImage = (ImageView) findViewById(R.id.profileImage);

mBack = (Button) findViewById(R.id.back);
mConfirm = (Button) findViewById(R.id.confirm);

mAuth = FirebaseAuth.getInstance();
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if(mFirebaseUser != null && userSex != null) {
userId = mFirebaseUser.getUid();
mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userSex).child(userId);
getUserInfo();
}

mProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveUserInformation();
}
});
mBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
return;
}
});
}


private void getUserInfo() {
mCustomerDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("name")!=null){
name = map.get("name").toString();
mNameField.setText(name);
}
if(map.get("phone")!=null){
phone = map.get("phone").toString();
mPhoneField.setText(phone);
}

if(map.get("profileImageUrl")!=null){
profileImageUrl = map.get("profileImageUrl").toString();
switch(profileImageUrl){
case "default":
Glide.with(getApplication()).load(R.mipmap.ic_launcher).into(mProfileImage);
break;
default:
Glide.with(getApplication()).load(profileImageUrl).into(mProfileImage);
break;
}
}
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

}

private void saveUserInformation() {
name = mNameField.getText().toString();
phone = mPhoneField.getText().toString();

Map userInfo = new HashMap();
userInfo.put("name", name);
userInfo.put("phone", phone);
mCustomerDatabase.updateChildren(userInfo);
if(resultUri != null){
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
Bitmap bitmap = null;

try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl();

Map userInfo = new HashMap();
userInfo.put("profileImageUrl", downloadUrl.toString());
mCustomerDatabase.updateChildren(userInfo);

finish();
return;
}
});
}else{
finish();
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mProfileImage.setImageURI(resultUri);
}
}

}*

最佳答案

错误信息:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.database.DatabaseReference.updateChildren(java.util.Map)' on a null object reference

告诉您 mCustomerDatabase 为空。

mCustomerDatabase 为空,因为您在开始使用它之前没有为其分配值。查看执行分配的代码:

        FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if(mFirebaseUser != null && userSex != null) {
userId = mFirebaseUser.getUid();
mCustomerDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userSex).child(userId);
getUserInfo();
}

mCustomerDatabase 在某些情况下不会获得值。您将必须调试您的代码以找出为什么 mFirebaseUseruserSex 为空。

关于android - Firebase 数据库无法更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61704787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com