fredrick cyril
fredrick cyril

Reputation: 83

How to save object in firebase Database?

I Couldn't add an object to firebase realtime database. I tried the following code. But when this code executes userRef.child("Users").child(Integer.toString(random.nextInt(100))).setValue(newUser); my app crashes.

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

This is the logcat error message.

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)

 

Upvotes: 2

Views: 7276

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The solution is simple, mark the UserDetails class as static, so the compiler doesn't generate the extra field:

public static class UserDetails {

Explanation of why this is needed, in case you're interested.

The error message says what's wrong, but it's a bit hard to parse in this case: "Invalid key: this$0. Keys must not contain '/', '.', '#', '$', '[', or ']'"

It says this$0, which is a reference to your UserDetails object. The $0 indicates that its an inner class of the MainActivity. When you make an inner class, instances of that class get an extra hidden field referring to their containing object, so that you can say this.MainActivity from within the code of UserDetails. But the Firebase SDK cannot handle this extra, hidden field, so it raises an exception.

Upvotes: 8

Siddhesh Dighe
Siddhesh Dighe

Reputation: 2954

Instead of generating a random number, try using push() also Where are you calling your createUser method ? and can you add the logcat details when your app crashes, that would make it easier to find the problem.

Upvotes: 1

Related Questions