数据已插入到firebase中但Android中的应用崩溃

时间:2018-05-17 05:38:01

标签: android firebase firebase-realtime-database

好吧,让我更好地解释一下,我已经创建了一个应用程序,它有三个字段作为名称,电子邮件和地址,我想将它存储到实时firebase数据库,我能够存储它,但应用程序崩溃点击按钮后。我不知道导致应用程序崩溃的原因。帮助表示感谢.. 我在这里为用户创建了一个java类:

    public class User {

    public String name;
    public String email;
    public String address;

    public User(String name, String email, String address) {
        this.name = name;
        this.email = email;
        this.address = address;
    }
}

我的mainActivity.java:

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Displaying toolbar icon
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setIcon(R.mipmap.ic_launcher);

            txtDetails  = (TextView) findViewById(R.id.txt_user);
            inputName   = (EditText) findViewById(R.id.name);
            inputEmail  = (EditText) findViewById(R.id.email);
            inputAddr   = (EditText) findViewById(R.id.address);
            btnSave     = (Button) findViewById(R.id.btn_save);

            mFirebaseInstance = FirebaseDatabase.getInstance();

            // get reference to 'users' node
            mFirebaseDatabase = mFirebaseInstance.getReference("users");

            // store app title to 'app_title' node
            mFirebaseInstance.getReference("app_title").setValue("Realtime Database");

            // app_title change listener
            mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Log.e(TAG, "App title updated");

                    String appTitle = dataSnapshot.getValue(String.class);

                    // update toolbar title
                    getSupportActionBar().setTitle(appTitle);
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.e(TAG, "Failed to read app title value.", error.toException());
                }
            });

            // Save / update the user
            btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String name = inputName.getText().toString();
                    String email = inputEmail.getText().toString();
                    String address = inputAddr.getText().toString();

                    // Check for already existed userId
                    if (TextUtils.isEmpty(userId)) {
                        createUser(name, email,address);
                    } else {
                        updateUser(name, email,address);
                    }
                }
            });

            toggleButton();
        }

        // Changing button text
        private void toggleButton() {
            if (TextUtils.isEmpty(userId)) {
                btnSave.setText("Save");
            } else {
                btnSave.setText("Update");
            }
        }

        /**
         * Creating new user node under 'users'
         */
        private void createUser(String name, String email, String address) {
            // TODO
            // In real apps this userId should be fetched
            // by implementing firebase auth
            if (TextUtils.isEmpty(userId)) {
                userId = mFirebaseDatabase.push().getKey();
            }

            User user = new User(name, email, address);

            mFirebaseDatabase.child(userId).setValue(user);

            addUserChangeListener();
        }

        /**
         * User data change listener
         */
        private void addUserChangeListener() {
            // User data change listener
            mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user = dataSnapshot.getValue(User.class);

                    // Check for null
                    if (user == null) {
                        Log.e(TAG, "User data is null!");
                        return;
                    }

                    Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);

                    // Display newly updated name and email
                    txtDetails.setText(user.name + ", " + user.email);

                    // clear edit text
                    Toast.makeText(MainActivity.this, "Data Sent", Toast.LENGTH_SHORT).show();
                    inputEmail.setText("");
                    inputName.setText("");
                    inputAddr.setText("");
                    toggleButton();
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.e(TAG, "Failed to read user", error.toException());
                }
            });
        }

        private void updateUser(String name, String email, String address) {
            // updating the user via child nodes
            if (!TextUtils.isEmpty(name))
                mFirebaseDatabase.child(userId).child("name").setValue(name);

            if (!TextUtils.isEmpty(email))
                mFirebaseDatabase.child(userId).child("email").setValue(email);

            if (!TextUtils.isEmpty(address))
                mFirebaseDatabase.child(userId).child("address").setValue(address);
        }
    }

我的logcat:

com.google.firebase.database.DatabaseException: Class raj.realtime.db.User is missing a constructor with no arguments
        at com.google.android.gms.internal.zzamy$zza.zze(Unknown Source)
        at com.google.android.gms.internal.zzamy$zza.zzce(Unknown Source)
        at com.google.android.gms.internal.zzamy.zze(Unknown Source)
        at com.google.android.gms.internal.zzamy.zzb(Unknown Source)
        at com.google.android.gms.internal.zzamy.zza(Unknown Source)
        at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
        at raj.realtime.db.MainActivity$3.onDataChange(MainActivity.java:127)
        at com.google.android.gms.internal.zzajp.zza(Unknown Source)
        at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source)
        at com.google.android.gms.internal.zzaks$1.run(Unknown Source)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

2 个答案:

答案 0 :(得分:4)

在User.java中添加无参数构造函数:

public class User {

public User(){}

public String name;
public String email;
public String address;

public User(String name, String email, String address) {
    this.name = name;
    this.email = email;
    this.address = address;
   }
}

供参考,请查看以下内容:

setValue

答案 1 :(得分:3)

您只是缺少默认构造函数。

public User() {
}

有理由在模态类中添加Default构造函数。 调用DataSnapshot.getValue(User.class) 所需的默认构造函数。阅读How get value from dataSnapshot?