我正在尝试使用getter和setter从我的Firebase数据库中检索数据,但收到错误消息说无法转换对象

时间:2019-12-06 06:39:55

标签: java android firebase android-recyclerview

我正在尝试创建一个群组活动,在该活动中可以显示用户连接到的所有群组。我已经创建了分组活动,并在其中插入了回收站视图,并试图从数据库中检索数据,但是不幸的是,当我在Android手机上运行应用程序时出现错误。应用程序崩溃了,并且在logcat中,我收到一条消息,提示无法将java.lang.String类型的对象转换为com.nanb.alpha.modelclass类型。 如果您不介意,请帮助我,以便我完成活动。

下面的代码是用户可以创建组的代码。

      private void groupmethos(final String groupname) {
    DatabaseReference groupref = rootref.child("Group").push();
    final String grouppushid = groupref.getKey();
    Map groupmap = new HashMap<>();
    groupmap.put("GroupprofileName",groupname);
    groupmap.put("Creater",currentUser.getUid());
    groupmap.put("StatusGroup","");
    groupmap.put("profileimage","");
    groupmap.put("id",grouppushid);
    rootref.child("Group").child(grouppushid).updateChildren(groupmap).addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            rootref.child("GroupMessage").child(grouppushid).setValue("").addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()){
                        rootref.child("userconnectedtogroup").child(currentUser.getUid()).child(grouppushid).setValue("Added").addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                Toast.makeText(MainActivity.this,groupname + "group Created successfully",Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }
            });

        }
    });
  }

在上述代码中,

用户请求创建一个组。下面给出的是使用getter和setter从数据库中获取数据的代码。

  package com.nanb.alpha;

public class modelclass {
private String GroupprofileName,StatusGroup,profileimage;

public modelclass() {
}

public modelclass(String groupprofileName, String statusGroup, String profileimage) {
    this.GroupprofileName = groupprofileName;
    this.StatusGroup = statusGroup;
    this.profileimage = profileimage;
}

public String getGroupprofileName() {
    return GroupprofileName;
}

public void setGroupprofileName(String groupprofileName) {
    GroupprofileName = groupprofileName;
}

public String getStatusGroup() {
    return StatusGroup;
}

public void setStatusGroup(String statusGroup) {
    StatusGroup = statusGroup;
}

public String getProfileimage() {
    return profileimage;
}

public void setProfileimage(String profileimage) {
    this.profileimage = profileimage;
}
}

给定代码是recyclerview用来将值设置为给定布局的代码。

     public class group extends AppCompatActivity {

     private RecyclerView recyclerView;
     private DatabaseReference conref,groupref;
     private FirebaseAuth mAuth;
     private String Currentuserid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group);

    intialiation();
    mAuth = FirebaseAuth.getInstance();
    Currentuserid = mAuth.getCurrentUser().getUid();
    conref = FirebaseDatabase.getInstance().getReference().child("userconnectedtogroup").child(Currentuserid);
    groupref = FirebaseDatabase.getInstance().getReference().child("Group");
    }

    private void intialiation() {
    recyclerView = findViewById(R.id.recyclerview);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    }

     @Override
     protected void onStart() {
    super.onStart();
    FirebaseRecyclerOptions option = new FirebaseRecyclerOptions.Builder<modelclass>().setQuery(conref,modelclass.class).build();

    FirebaseRecyclerAdapter<modelclass,group_viewHolder> adapter = new FirebaseRecyclerAdapter<modelclass, group_viewHolder>(option) {
        @Override
        protected void onBindViewHolder(@NonNull final group_viewHolder group_viewHolder, int i, @NonNull modelclass modelclass) {
            String userid = getRef(i).getKey();
            groupref.child(userid).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                  if(dataSnapshot.hasChild("profileimage")){
                      String profileimage = dataSnapshot.child("profileimage").getValue().toString();
                      String groupname = dataSnapshot.child("GroupprofileName").getValue().toString();
                      String groupStatus = dataSnapshot.child("StatusGroup").getValue().toString();

                      group_viewHolder.groupname.setText(groupname);
                      group_viewHolder.groupStatus.setText(groupStatus);
                      Picasso.get().load(profileimage).into(group_viewHolder.profileimage);
                  }else{
                      String groupname = dataSnapshot.child("GroupprofileName").getValue().toString();
                      String groupStatus = dataSnapshot.child("StatusGroup").getValue().toString();

                      group_viewHolder.groupname.setText(groupname);
                      group_viewHolder.groupStatus.setText(groupStatus);
                      Picasso.get().load(R.mipmap.groupicon).into(group_viewHolder.profileimage);
                  }
                }

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

                }
            });
        }

        @NonNull
        @Override
        public group_viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
           View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grouplayout,parent,false);
           group_viewHolder groupholder = new group_viewHolder(view);
            return groupholder;
        }
    };
    recyclerView.setAdapter(adapter);
    adapter.startListening();
    }

    public static class group_viewHolder extends RecyclerView.ViewHolder{
    TextView groupname,groupStatus;
    CircleImageView profileimage;
    public group_viewHolder(@NonNull View itemView) {
        super(itemView);
        groupname = itemView.findViewById(R.id.Group_name);
        groupStatus = itemView.findViewById(R.id.Group_Status);
        profileimage = itemView.findViewById(R.id.group_profile_dp);
    }
    }
    }

以下是我的Firebase数据库的图像。其中显示了与小组活动有关的所有结构。 Group contains all the information related to the Group like admin id, group name, etc.in the Group message section will contain the message that will be shared inside that group. Userconnectedtogroup contains the group's id to which the user is connected or added.

下面是在应用程序崩溃后显示的logcat消息。

  

com.google.firebase.database.DatabaseException:无法将java.lang.String类型的对象转换为com.nanb.alpha.modelclass类型           在com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database @@ 19.1.0:418)           com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database @@ 19.1.0:214)           com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database @@ 19.1.0:79)           com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database @@ 19.1.0:203)           在com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)           在com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:15)           在com.firebase.ui.common.BaseCachingSnapshotParser.parseSnapshot(BaseCachingSnapshotParser.java:35)           在com.firebase.ui.common.BaseObservableSnapshotArray.get(BaseObservableSnapshotArray.java:52)           在com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:106)           在com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:122)           在androidx.recyclerview.widget.RecyclerView $ Adapter.onBindViewHolder(RecyclerView.java:6781)           在androidx.recyclerview.widget.RecyclerView $ Adapter.bindViewHolder(RecyclerView.java:6823)           在androidx.recyclerview.widget.RecyclerView $ Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)           在androidx.recyclerview.widget.RecyclerView $ Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)           在androidx.recyclerview.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5858)           在androidx.recyclerview.widget.RecyclerView $ Recycler.getViewForPosition(RecyclerView.java:5854)           在androidx.recyclerview.widget.LinearLayoutManager $ LayoutState.next(LinearLayoutManager.java:2230)           在androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)           在androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)           在androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)           在androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)           在androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)           在androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)           在android.widget.FrameLayout.onLayout(FrameLayout.java:514)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)           在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)           在android.widget.LinearLayout.onLayout(LinearLayout.java:1466)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)           在android.widget.FrameLayout.onLayout(FrameLayout.java:514)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)           在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)           在android.widget.LinearLayout.onLayout(LinearLayout.java:1466)           在android.view.View.layout(View.java:15689)           在android.view.ViewGroup.layout(ViewGroup.java:5048)           在android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)           在android.widget.FrameLayout.onLayout(FrameLayout.java:514)           在android

2 个答案:

答案 0 :(得分:0)

您在数据库中的userconnectedtogroup不包含模型,它包含诸如 Added 之类的字符串。如下更新您的query

FirebaseRecyclerOptions option = new FirebaseRecyclerOptions.Builder<String>().setQuery(conref,String.class).build();
FirebaseRecyclerAdapter<String,group_viewHolder> adapter = new FirebaseRecyclerAdapter<String, group_viewHolder>(option) {
    @Override
    protected void onBindViewHolder(@NonNull final group_viewHolder group_viewHolder, int i, @NonNull modelclass modelclass) {
        String groupId = getRef(i).getKey();
        groupref.child(groupId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                if(dataSnapshot.hasChild("profileimage")){
                    String profileimage = dataSnapshot.child("profileimage").getValue().toString();
                    String groupname = dataSnapshot.child("GroupprofileName").getValue().toString();
                    String groupStatus = dataSnapshot.child("StatusGroup").getValue().toString();

                    group_viewHolder.groupname.setText(groupname);
                    group_viewHolder.groupStatus.setText(groupStatus);
                    Picasso.get().load(profileimage).into(group_viewHolder.profileimage);
                }else{
                    String groupname = dataSnapshot.child("GroupprofileName").getValue().toString();
                    String groupStatus = dataSnapshot.child("StatusGroup").getValue().toString();

                    group_viewHolder.groupname.setText(groupname);
                    group_viewHolder.groupStatus.setText(groupStatus);
                    Picasso.get().load(R.mipmap.groupicon).into(group_viewHolder.profileimage);
                }
            }

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

            }
        });
    }

    @NonNull
    @Override
    public group_viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grouplayout,parent,false);
        group_viewHolder groupholder = new group_viewHolder(view);
        return groupholder;
    }
};

您还可以在onDataChange内部使用模型,如下所示:

@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

    modelclass modelClass = dataSnapshot.getValue(modelclass.class);

    if(!TextUtils.isEmpty(modelClass.getProfileimage())) {
        group_viewHolder.groupname.setText(modelClass.getGroupprofileName());
        group_viewHolder.groupStatus.setText(modelClass.getStatusGroup());
        Picasso.get().load(modelClass.getProfileimage()).into(group_viewHolder.profileimage);
    } else {
        group_viewHolder.groupname.setText(modelClass.getGroupprofileName());
        group_viewHolder.groupStatus.setText(modelClass.getStatusGroup());
        Picasso.get().load(R.mipmap.groupicon).into(group_viewHolder.profileimage);
    }
}

答案 1 :(得分:0)

在选项对象中使用groupref而不是conref