无法将java.lang.String类型的对象转换为com.psb.farmersmarket.Model.User类型。如何解决此错误?

时间:2020-06-06 10:55:49

标签: java android firebase firebase-realtime-database

我想获取所有用户,但UsersFragment中的当前登录用户除外。但是我正面临下面给出的错误。以及Java文件和Firebase数据库。


错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.psb.farmersmarket, PID: 13713
    com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.psb.farmersmarket.Model.User
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.3.0:435)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.3.0:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.3.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.3.0:203)
        at com.psb.farmersmarket.Fragments.UsersFragment$1.onDataChange(UsersFragment.java:107)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.3.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.3.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.3.0:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6806)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

UserFragment.java

public class UsersFragment extends Fragment {

    private RecyclerView recyclerView;
    private UserAdapter adapter;
    private List<User> userList;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_users,container,false);

        recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        userList = new ArrayList<>();

        readUsers();
        return view;
    }

    private void readUsers() {
        final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        assert firebaseUser != null;
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                userList.clear();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                    User user = snapshot.getValue(User.class);
                    assert user != null;
                    if(!user.getUserID().equals(firebaseUser.getUid())){
                        userList.add(user);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getActivity(), databaseError.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

在此userfragment.java文件中,此给定的行生成错误。

User user = snapshot.getValue(User.class);

错误是

Can't convert object of type java.lang.String to type com.psb.farmersmarket.Model.User

User.java

public class User {
    private String UserName;
    private String UserPhone;
    private String UserDesc;
    private String UserEmail;
    private String UserID;
    private String imageURL;
    private String search;

    public User(String userName,String userPhone,String userDesc,String userEmail, String userID, String imageURL, String search) {
        this.UserName = userName;
        this.UserPhone = userPhone;
        this.UserDesc = userDesc;
        this.UserEmail = userEmail;
        this.UserID = userID;
        this.imageURL = imageURL;
    }

    public User() {
    }

    @PropertyName("name")
    public String getUserName() {
        return UserName;
    }

    @PropertyName("name")
    public void setUserName(String userName) {
        UserName = userName;
    }

    @PropertyName("Phone No")
    public String getUserPhone() {
        return UserPhone;
    }

    @PropertyName("Phone No")
    public void setUserPhone(String userPhone) {
        UserPhone = userPhone;
    }

    @PropertyName("Description")
    public String getUserDesc() {
        return UserDesc;
    }

    @PropertyName("Description")
    public void setUserDesc(String userDesc) {
        UserDesc = userDesc;
    }

    @PropertyName("email")
    public String getUserEmail() {
        return UserEmail;
    }

    @PropertyName("email")
    public void setUserEmail(String userEmail) {
        UserEmail = userEmail;
    }

    @Exclude
    public String getUserID() {
        return UserID;
    }

    @Exclude
    public void setUserID(String userID) {
        UserID = userID;
    }

    @PropertyName("imageURL")
    public String getImageURL() {
        return imageURL;
    }

    @PropertyName("imageURL")
    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }
}

数据库文件

{
  "Users" : {
    "77EOhwNHgPbDwSEz1mbHOclUy0o1" : {
      "Description" : "student",
      "Phone No" : "9876543210",
      "email" : "pratikbharad@xyz.com",
      "imageURL" : "default",
      "name" : "Pratik Bharad",
      "search" : "pratik bharad",
      "status" : "offline",
      "user id" : "77EOhwNHgPbDwSEz1mbHOclUy0o1"
    },
    "vjDg7Q9QtgQO0DGM83Dwynk5Caa2" : {
      "Description" : "student",
      "Phone No" : "9876543210",
      "email" : "pratikbharad213@xyz.com",
      "imageURL" : "default",
      "name" : "Pratik",
      "search" : "pratik",
      "status" : "offline",
      "user id" : "vjDg7Q9QtgQO0DGM83Dwynk5Caa2"
    }
  },
}

我非常想解决此错误,但该错误仍然相同 请帮助我解决此错误。

2 个答案:

答案 0 :(得分:1)

您的代码将一个侦听器附加到/Users/aSpecificUid。因此,在您的onDataChange中,dataSnapshot将包含单个用户的数据。但是您的代码然后在dataSnapshot.getChildren()上循环,这意味着该循环中的每个snapshot都包含该用户的单个属性(DescriptionPhone No等)的数据。然后,当您调用snapshot.getValue(User.class)时,您试图将一个简单的字符串/数字值转换为一个完整的User对象,这将无法正常工作。

解决方案是从您的getChildren()中删除onDataChange上的循环:

    final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    assert firebaseUser != null;
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            userList.clear();
            User user = dataSnapshot.getValue(User.class);
            assert user != null;
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(getActivity(), databaseError.toString(), Toast.LENGTH_SHORT).show();
        }
    });

另外:给定您在附加侦听器的位置,不需要if(!user.getUserID().equals(firebaseUser.getUid())){检查,因此我将其删除。

展望未来,请始终考虑DataSnapshot是包含单个节点还是可以包含多个节点。如果它可以包含多个节点,则需要遍历getChildren()


更新:要显示“除当前登录的用户以外的所有用户”,您需要读取所有用户的数据,然后在循环中跳过当前登录的用户。 / p>

由于您已经在循环中检查了UID,因此应该将侦听器附加到正确的节点/Users

final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        userList.clear();
        for(DataSnapshot snapshot: dataSnapshot.getChildren()){
            User user = snapshot.getValue(User.class);
            assert user != null;
            if(!user.getUserID().equals(firebaseUser.getUid())){
                userList.add(user);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(getActivity(), databaseError.toString(), Toast.LENGTH_SHORT).show();
    }
});

答案 1 :(得分:0)

您可以像这样从数据快照读取数据

 @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
       String description= dataSnapshot.child("Description").getValue(String.class);
       // also pick the other and then create yours object
}

我认为userId可能是造成问题的原因。环绕

 User user = snapshot.getValue(User.class);

使用try catch,因此寻找产生问题的字段。还有一点是,最好在变量名之间没有空格,例如 Phone Number,所以应该像phoneNumber