无法使用RecyclerAdapter将对象转换为String值

时间:2019-04-24 05:03:26

标签: java android firebase firebase-realtime-database android-recyclerview

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

  

用户对象不能转换为字符串值

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

以下代码包括Fragment类,ViewHolder类,User类,布局xml和应用程序gradle文件。我正在使用SDK 28,并将三星银河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'

2 个答案:

答案 0 :(得分:1)

您的布局为空,因为您还没有通过onCreateView()方法中的片段来扩大布局。

添加此行:-

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

如果您的dataSnapshot引用了您的模态类对象,那么请尝试检索诸如:-

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

 String profileName = post.getName();  

此答案here详细介绍了Firebase引用或如何在Firebase数据库中设置子引用。

答案 1 :(得分:0)

您遇到以下错误:

  

用户对象不能转换为字符串值

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

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

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

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

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

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