Firebase Database: Getting “No-Argument Constructor” Error Despite Having It

北城余情 提交于 2020-05-15 11:26:13

问题


I am trying to writing data in an activity and then reading it in another activity. My writing part is working. For my reading part, I am trying to use getValue with parameter of a class I wrote. But I keep getting this error:

com.google.firebase.database.DatabaseException: Class ozhan.climb.MainActivity$User does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.

My class that used in getValue():

class User {
    public String  Server,
            NeededRole,
            Role,
            SummonerName;

    User() {}

    public String get_Server() {
        return Server;
    }

    public String get_NeededRole() {
        return NeededRole;
    }

    public String get_Role() {
        return Role;
    }

    public String get_SummonerName() {
        return SummonerName;
    }
}

and here is the code that should get data:

public void getUserData(){
    final TextView tv_sumName = findViewById(R.id.tv_sumName),
             tv_neededRole = findViewById(R.id.tv_neededrole),
             tv_userRole = findViewById(R.id.tv_userrole),
             tv_server = findViewById(R.id.tv_server);
    final String uid = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();

    DatabaseReference usersDataRef = databaseRef.child("Users").child(uid);
    usersDataRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            User u = dataSnapshot.getValue(User.class);
            if (u != null) {
                tv_server.setText(u.Server);
                tv_neededRole.setText(u.NeededRole);
                tv_userRole.setText(u.Role);
                tv_sumName.setText(u.SummonerName);
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

回答1:


The exception says your class is ozhan.climb.MainActivity$User - i.e., it is an inner class of MainActivity.

Inner classes require an instance of their outer class to construct. This won't work with Firebase Database, although the error message could definitely be improved.

Your User class should be a static class, which does not have the same requirement to exist only within the instance of a containing class:

static class User {
  ...
}


来源:https://stackoverflow.com/questions/52807892/firebase-database-getting-no-argument-constructor-error-despite-having-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!