首页 > 解决方案 > 无法使用 RecyclerAdapter 将对象转换为字符串值

问题描述

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

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

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

下面的代码包括Fragmentclass、ViewHolderclass、Userclass、Layout xml和app 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'

标签: javaandroidfirebasefirebase-realtime-databaseandroid-recyclerview

解决方案


您的布局是空的,因为您没有在onCreateView()方法中为片段膨胀布局。

添加这一行: -

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

如果您的 dataSnapshot 是指您的模态类对象,请尝试检索您的值,例如:-

 Users post = dataSnapshot.getValue(Users.class);

 String profileName = post.getName();  

这里的这个答案 更详细地描述了 firebase 引用或如何在 firebase 数据库中设置子引用。


推荐阅读