在Android Java中无法将java.lang.String类型的对象转换为com.hello.writer.postAdapter.PostGeter类型

blmhpbnm  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(123)

我正在尝试从Firebase实时数据库获取数据。

{
  "posts" : {
    "userId" : {
      "10843" : {
        "body" : "fasiaufsuie",
        "title" : "ddddj"
      }
    }
  }
}

它显示此错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.hello.writer, PID: 21625
    com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.hello.writer.postAdapter.PostGeter
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
        at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
        at com.hello.writer.ui.home.HomeFragment$1.onDataChange(HomeFragment.java:61)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:254)
        at android.app.ActivityThread.main(ActivityThread.java:8243)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)

我的家庭碎片码是:

RecyclerView recyclerView = binding.postView;

recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(manager);
ArrayList<PostGeter> list = new ArrayList<>();
postAdapter customAdapter = new postAdapter(getContext(), list);
recyclerView.setAdapter(customAdapter);

database = FirebaseDatabase.getInstance();

reference = database.getReference().child("posts");
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot ds : snapshot.getChildren()){
            for (DataSnapshot data : ds.getChildren()){
                for (DataSnapshot dataSnapshot : data.getChildren()){

                    PostGeter msg = dataSnapshot.getValue(PostGeter.class);
                    list.add( msg);
                }
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});

用于firebase数据管理的ModelView类:

public class PostGeter {
    private String title;
    private String body;
    private String date;
    private String userId;
    private String status;
    private String id;
    private String image;
    private String reaction;

    public PostGeter() {}
    public PostGeter(String title, String body, String date, String userId, String status, String id, String image, String reaction) {
        this.title = title;
        this.body = body;
        this.date = date;
        this.userId = userId;
        this.status = status;
        this.id = id;
        this.image = image;
        this.reaction = reaction;
    }

    public String getTitle() {
        return title;
    }

    public String getBody() {
        return body;
    }

    public String getDate() {
        return date;
    }

    public String getUserId() {
        return userId;
    }

    public String getStatus() {
        return status;
    }

    public String getId() {
        return id;
    }

    public String getImage() {
        return image;
    }

    public String getReaction() {
        return reaction;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public void setReaction(String reaction) {
        this.reaction = reaction;
    }
}

适配器类:

public class postAdapter extends RecyclerView.Adapter<postAdapter.ViewHolder> {
    Context context;
    ArrayList<PostGeter> list;

    public postAdapter(Context context, ArrayList<PostGeter> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public postAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.post_content_view, parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull postAdapter.ViewHolder holder, int position) {
        PostGeter geter = list.get(position);
        holder.title.setText(geter.getTitle());
        holder.content.setText(geter.getBody());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView img; TextView title,content;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.postImageView);
            title = itemView.findViewById(R.id.post_view_title);
            content = itemView.findViewById(R.id.post_view_content);
        }
    }
}

我的数据结构如下:
发布〉用户〉postid〉数据在这里
如果我不使用modelView类它的工作文件显示所有的数据。我使用这段代码看到它显示这些

RecyclerView recyclerView = binding.postView;
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        ArrayList<PostGeter> list = new ArrayList<>();
        postAdapter customAdapter = new postAdapter(getContext(), list);
        recyclerView.setAdapter(customAdapter);

        database = FirebaseDatabase.getInstance();

        reference = database.getReference().child("posts");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot ds : snapshot.getChildren()){
                    for (DataSnapshot data : ds.getChildren()){
                        for (DataSnapshot dataSnapshot : data.getChildren()){
                            System.out.println(dataSnapshot);
                            //PostGeter msg = dataSnapshot.getValue(PostGeter.class);
                            //list.add( msg);
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

这显示这些类型的日志:

I/System.out: DataSnapshot { key = body, value = fasiaufsuie }
I/System.out: DataSnapshot { key = title, value = ddddj }
s3fp2yjn

s3fp2yjn1#

强烈建议以后给你的变量起一个有意义的名字,因为这样做会让问题更容易被发现。
如果我们对你的代码这样做,我们得到:

reference = database.getReference().child("posts");
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot postsSnapshot) {
        for (DataSnapshot userSnapshot: postsSnapshot.getChildren()){ // 👈 key=userId 
            for (DataSnapshot postSnapshot : userSnapshot.getChildren()){ // 👈 key=10843
                for (DataSnapshot bodyTitleSnapshot : postSnapshot.getChildren()){ // 👈 key=body, and then title
                    System.out.println(dataSnapshot);
                    //PostGeter msg = bodyTitleSnapshot.getValue(PostGeter.class);
                    //list.add( msg);
                }
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException(); // 👈 never ignore errors
    }
});

如果查看第三个嵌套循环,即在10843, so the bodyTitleSnapshot的子循环上迭代,则在第一次迭代中指向body,在第二次迭代中指向title。由于这两个循环都不是有效的完整PostGeter对象,因此会出现错误。
实际上只需要两个循环:一个用于JSON中的userId级别,另一个用于post ID(JSON中的10843)。

reference = database.getReference().child("posts");
reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot postsSnapshot) {
        for (DataSnapshot userSnapshot: postsSnapshot.getChildren()){ // userId 
            for (DataSnapshot postSnapshot : userSnapshot.getChildren()){ // e.g. 10843
                PostGeter msg = postSnapshot.getValue(PostGeter.class);
                list.add( msg);
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException(); // 👈 never ignore errors
    }
});

相关问题