简体   繁体   中英

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

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

The exception says your class is ozhan.climb.MainActivity$User - ie, 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 {
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM