如何在firebase数据库中保存对象?

时间:2016-06-26 07:18:36

标签: android firebase firebase-realtime-database

我无法将对象添加到firebase实时数据库。我尝试了以下代码。但是当这段代码执行 userRef.child(“Users”)。child(Integer.toString(random.nextInt(100)))。setValue(newUser); 我的应用程序崩溃了。

    public class MainActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;
    private DatabaseReference userRef;
    EditText nameEditText;
    EditText passEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameEditText = (EditText) findViewById(R.id.nameEditText);
        passEditText = (EditText) findViewById(R.id.passEditText);

        mAuth = FirebaseAuth.getInstance();
        //        signInAnonymously();
                mAuth.signInAnonymously().addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                    }

                    public void onFailure(Throwable throwable) {
                        throw new RuntimeException(throwable);
                    }
                });
    }
    public void createUser(View view){

        Random random = new Random();



        userRef = FirebaseDatabase.getInstance().getReference();



        String userN = String.valueOf(nameEditText.getText());
        String pass = String.valueOf(passEditText.getText());


        UserDetails newUser = new UserDetails(userN,pass);

        userRef.child("Users").child(Integer.toString(random.nextInt(100))).setValue(newUser);


    }
@IgnoreExtraProperties
public class UserDetails{

    public String userName;
    public String password;

    public UserDetails(){

    }

    public UserDetails(String userName, String userPass){

        this.userName = userName;
        this.password = userPass;
        Log.i("Check", this.userName);

    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }
}
}

这是logcat错误消息。

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.crossappfactory.username, PID: 20144
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19884)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
                   Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4785) 
at android.view.View$PerformClick.run(View.java:19884) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5343) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700) 
                   Caused by: com.google.firebase.database.DatabaseException: Invalid key: this$0. Keys must not contain '/', '.', '#', '$', '[', or ']'
at com.google.android.gms.internal.zzaiw.zziv(Unknown Source)
at com.google.android.gms.internal.zzaiw.zzau(Unknown Source)
at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
at com.crossappfactory.username.MainActivity.createUser(MainActivity.java:63)
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4785) 
at android.view.View$PerformClick.run(View.java:19884) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5343) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

2 个答案:

答案 0 :(得分:8)

解决方案很简单,将UserDetails类标记为静态,因此编译器不会生成额外字段:

public static class UserDetails {

如果您有兴趣,请说明为什么需要这样做。

错误消息显示错误,但在这种情况下解析起来有点困难:"无效密钥:此$ 0。密钥不得包含' /','。','#',' $',' [& #39;,或']'"

它显示this$0,它是对UserDetails对象的引用。 $0表示它是MainActivity的内部类。当你创建一个内部类时,该类的实例会获得一个引用其包含对象的额外隐藏字段,以便您可以在this.MainActivity的代码中说出UserDetails。但Firebase SDK无法处理这个额外的隐藏字段,因此会引发异常。

答案 1 :(得分:0)

尝试使用 push()而不是生成随机数而不是在哪里调用createUser方法?并且您可以在应用程序崩溃时添加logcat详细信息,这样可以更轻松地找到问题。