对象不能使用回收器适配器转换为字符串值



我正在尝试在我的Android应用程序中显示Firebase实时数据库中的所有用户,Fragment名为RequestFragment。但是该应用程序没有显示任何内容,我在日志中看到的错误是:

用户对象无法转换为字符串值

有人可以查看下面的代码并让我知道可能存在的问题吗?

下面的代码包括Fragment类、ViewHolder类、User类、布局 xml 和应用程序 gradle 文件。我正在使用SDK 28并使用我的三星Galaxy A6(2017(手机作为设备。

public class RequestsFragment extends Fragment {
    private View UsersView;
    private RecyclerView myUsersList;
    //private DatabaseReference UsersRef;
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private String currentUserID;
    private FirebaseDatabase database;
    public RequestsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
        String uid = current_user.getUid();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).push();
    UsersView = inflater.inflate(R.layout.fragment_requests, container, false);
    myUsersList = UsersView.findViewById(R.id.users_list);
    myUsersList.setLayoutManager(new LinearLayoutManager(getContext()));
    return UsersView;
    }
    @Override
    public void onStart() {
        super.onStart();
        FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Users>()
                .setQuery(mDatabase, Users.class)
                .build();
        FirebaseRecyclerAdapter<Users, UserViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UserViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull final UserViewHolder holder, int position, @NonNull Users model) {

                mDatabase.addValueEventListener(new ValueEventListener() {
                 @Override
                 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                     if (dataSnapshot.hasChild("image"))
                     {
                         String userImage = dataSnapshot.child("image").getValue().toString();
                         String profileName = dataSnapshot.child("name").getValue().toString();
                         String profileStatus = dataSnapshot.child("status").getValue().toString();

                         holder.userName.setText(profileName);
                         holder.userStatus.setText(profileStatus);
                         Picasso.with(getContext()).load(userImage).placeholder(R.drawable.default_avatar).into(holder.profileImage);
                     }
                     else{
                         String profileName = dataSnapshot.child("name").getValue().toString();
                         String profileStatus = dataSnapshot.child("status").getValue().toString();

                         holder.userName.setText(profileName);
                         holder.userStatus.setText(profileStatus);
                     }
                 }
                 @Override
                 public void onCancelled(@NonNull DatabaseError databaseError) {
                 }
             });
            }
            @NonNull
            @Override
            public UserViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_single_layout, viewGroup,false);
                UserViewHolder viewHolder = new UserViewHolder(view);
                return viewHolder;
            }
        };
        myUsersList.setAdapter(adapter);
        adapter.startListening();
    }

    public static class UserViewHolder extends RecyclerView.ViewHolder
    {
        TextView userName, userStatus;
        CircleImageView profileImage;
        public UserViewHolder(@NonNull View itemView){
            super(itemView);
            userName = itemView.findViewById(R.id.user_single_name);
            userStatus = itemView.findViewById(R.id.user_single_status);
            profileImage = itemView.findViewById(R.id.user_single_image);
        }
    }
}

用户类

公共类用户 {

public String name;
public String image;
public String status;
public String thumb_image;

public Users(){
}
public Users(String name, String image, String status, String thumb_image) {
    this.name = name;
    this.image = image;
    this.status = status;
    this.thumb_image = thumb_image;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}
public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public String getThumb_image() {
    return thumb_image;
}
public void setThumb_image(String thumb_image) {
    this.thumb_image = thumb_image;
}

}

//users_single_layout.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/usersingle"
    android:background="?android:selectableItemBackground">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/user_single_image"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:src="@drawable/default_avatar" />

    <TextView
        android:id="@+id/user_single_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/user_single_image"
        android:layout_marginStart="20dp"
        android:layout_toEndOf="@+id/user_single_image"
        android:text="Display Name"
        android:textColor="@android:color/black"
        android:textSize="18sp" />
    <TextView
        android:id="@+id/user_single_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/user_single_name"
        android:layout_below="@+id/user_single_name"
        android:layout_marginTop="10dp"
        android:text="User default Status" />
    <ImageView
        android:id="@+id/user_single_online_icon"
        android:layout_width="8dp"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/user_single_name"
        android:layout_marginLeft="10dp"
        android:layout_toEndOf="@+id/user_single_name"
        android:visibility="invisible"
        app:srcCompat="@drawable/online_icon" />
</RelativeLayout>


//Gradle app file
apply plugin: 'com.android.application'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.xyx"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.google.firebase:firebase-storage:16.1.0'
    implementation 'com.google.firebase:firebase-auth:16.2.1'
    implementation 'com.firebase:firebase-client-android:2.4.0'
    implementation 'com.google.firebase:firebase-database:16.1.0'
    //For Gallery Images
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'de.hdodenhof:circleimageview:2.1.0'
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    implementation 'id.zelory:compressor:2.0.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp:okhttp:2.5.0'

    //https://github.com/firebase/FirebaseUI-Android
    // FirebaseUI for Firebase Realtime Database
    implementation 'com.firebaseui:firebase-ui-database:4.3.2'
    // FirebaseUI for Cloud Firestore
    implementation 'com.firebaseui:firebase-ui-firestore:4.3.2'
    // FirebaseUI for Firebase Auth
    implementation 'com.firebaseui:firebase-ui-auth:4.3.2'
    // FirebaseUI for Firebase Auth (GitHub provider)
    implementation 'com.firebaseui:firebase-ui-auth-github:4.3.2'
    // FirebaseUI for Cloud Storage
    implementation 'com.firebaseui:firebase-ui-storage:4.3.2'
    //implementation 'com.google.firebase:firebase-analytics:16.4.0'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    //implementation 'com.google.android.gms:play-services-basement:jar:12.0.1'
    //implementation 'com.google.android.gms:play-services:12.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.6.0'
}
apply plugin: 'com.google.gms.google-services'

您的布局为空,因为您尚未在 onCreateView() 方法中对片段进行布局膨胀。

添加此行:-

UsersView = inflater.inflate(R.layout.fragment_layout,container,false);

您的数据快照引用的是模态类对象,因此请尝试检索您的值,例如:-

 Users post = dataSnapshot.getValue(Users.class);
 String profileName = post.getName();  

此答案在此处详细介绍了有关 Firebase 引用或如何在 Firebase 数据库中设置子引用的信息。

您收到以下错误:

用户对象无法转换为字符串值

因为您的mDatabase指向字符串,而不是指向包含User对象的节点:

mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).push();

另请注意,每次调用 push() 方法时,都会生成一个新的随机键,并且该引用不能绝对传递给您的 FirebaseRecyclerOptions 对象。

要解决此问题,您需要传递一个可以返回User对象而不是字符串的查询。需要传递的查询应为:

mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");

因为在Users节点下只存在用户对象。

最新更新