开发者社区> 问答> 正文

如何从Firebase云存储检索数据到片段类,它也使用MVVM?

我是新手。尝试了其他资源,但是大多数资源都在回收器视图上进行了讨论,但是对于我的应用程序,我正在使用视图模型。期待获得帮助。我想从Firebase云存储中检索用户个人资料数据。以下是我到目前为止提到的代码。

ProfileViewModel.java

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class ProfileViewModel extends ViewModel {

private MutableLiveData<String> mText;

public ProfileViewModel() {
    mText = new MutableLiveData<>();

    mText.setValue( "Your Profile" );
}

public LiveData<String> getText() {
    return mText;
}

ProfileFragment.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.parkbookingslot.R;

public class ProfileFragment extends Fragment {

private ProfileViewModel profileViewModel;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    profileViewModel =
            ViewModelProviders.of( this ).get( ProfileViewModel.class );
    View root = inflater.inflate( R.layout.fragment_profile, container, false );

    final TextView textView = root.findViewById( R.id.text_profile );

    profileViewModel.getText().observe( getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            textView.setText( s );
        }
    } );

    return root;
}

fragment_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="match_parent"
tools:context=".ui.profile.ProfileFragment">

<TextView
    android:id="@+id/email"
    android:layout_width="84dp"
    android:layout_height="31dp"
    android:layout_marginEnd="164dp"
    android:layout_marginRight="164dp"
    android:layout_marginBottom="182dp"
    android:text="Email"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

<TextView
    android:id="@+id/text_profile"
    android:layout_width="109dp"
    android:layout_height="35dp"
    android:layout_marginEnd="150dp"
    android:layout_marginRight="150dp"
    android:layout_marginBottom="35dp"
    android:text="Your Profile"
    app:layout_constraintBottom_toTopOf="@+id/name"
    app:layout_constraintEnd_toEndOf="parent" />

<TextView
    android:id="@+id/name"
    android:layout_width="84dp"
    android:layout_height="31dp"
    android:layout_marginEnd="164dp"
    android:layout_marginRight="164dp"
    android:layout_marginBottom="34dp"
    android:text="Name"
    app:layout_constraintBottom_toTopOf="@+id/phoneno"
    app:layout_constraintEnd_toEndOf="parent" />

<TextView
    android:id="@+id/phoneno"
    android:layout_width="wrap_content"
    android:layout_height="31dp"
    android:layout_marginEnd="158dp"
    android:layout_marginRight="158dp"
    android:layout_marginBottom="36dp"
    android:text="Phone Number"
    app:layout_constraintBottom_toTopOf="@+id/vehicleno"
    app:layout_constraintEnd_toEndOf="parent" />

<TextView
    android:id="@+id/vehicleno"
    android:layout_width="112dp"
    android:layout_height="35dp"
    android:layout_marginEnd="150dp"
    android:layout_marginRight="150dp"
    android:layout_marginBottom="30dp"
    android:text="Vehicle Number"
    app:layout_constraintBottom_toTopOf="@+id/email"
    app:layout_constraintEnd_toEndOf="parent" />

应用解决方案共享后的编辑代码;

package com.example.parkbookingslot.ui.profile;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.parkbookingslot.R;
import com.example.parkbookingslot.UserProfile;

public class ProfileFragment extends Fragment {

    private ProfileViewModel profileViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle  savedInstanceState) {

    final View root = inflater.inflate( R.layout.fragment_profile, container, false );
    profileViewModel = ViewModelProviders.of( this ).get( ProfileViewModel.class );

    profileViewModel.getUserProfile().observe(getViewLifecycleOwner(), new Observer<UserProfile>() {
        @Override
        public void onChanged(UserProfile userProfile) {
            if (userProfile != null) {
                ((TextView) root.findViewById(R.id.name)).setText(userProfile.getName());
                ((TextView) root.findViewById(R.id.phoneno)).setText(userProfile.getPhoneno());
                ((TextView) root.findViewById(R.id.vehicleno)).setText(userProfile.getVehicleno());
                ((TextView) root.findViewById(R.id.email)).setText(userProfile.getEmail());
            }else {
                Toast toast = Toast.makeText(getActivity().getApplicationContext(), "No user information", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    });
    return root;
}

在编辑代码之前,出现以下屏幕。 更新用户界面后,出现以下屏幕;

我是否错过了fragment_profile.xml中的某个内容,或者它位于ProfileFragment.java中?

编辑了ProfileViewModel.java

package com.example.parkbookingslot.ui.profile;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.parkbookingslot.UserProfile;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class ProfileViewModel extends ViewModel {
    FirebaseAuth fAuth = FirebaseAuth.getInstance();
    String userId = fAuth.getCurrentUser().getUid();

    public LiveData<UserProfile> getUserProfile() {
     final MutableLiveData<UserProfile> userProfileMutableLiveData =    new MutableLiveData<>();
     FirebaseFirestore db = FirebaseFirestore.getInstance();

     DocumentReference docRef =  db.collection("Users").document(userId);
     docRef.get().addOnCompleteListener(new  OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot documentSnapshot = task.getResult();
                if (documentSnapshot != null &&  documentSnapshot.exists()) {
                    UserProfile userProfile =  documentSnapshot.toObject(UserProfile.class);
                    userProfileMutableLiveData.postValue(userProfile);
                }else {
                    userProfileMutableLiveData.postValue(null);
                }
            }else {
                userProfileMutableLiveData.postValue(null);
            }
        }
    });
    return userProfileMutableLiveData;
}

Firebase Cloudstore中的数据

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 09:34:29 1057 0
1 条回答
写回答
取消 提交回答
  • 在ProfileViewModel.java中

    if (task.isSuccessful()) {
        DocumentSnapshot documentSnapshot = task.getResult();
        if (documentSnapshot != null && documentSnapshot.exists()) {
            //start (this lines of code solved the issue)
            String name = documentSnapshot.getString("Name");
            String phoneno = documentSnapshot.getString("Phone number");
            String vehicleno = documentSnapshot.getString("Vehicle Number");
            String email = documentSnapshot.getString("Email");
            UserProfile userProfile = documentSnapshot.toObject(UserProfile.class);
    
            userProfile.setName(name);
            userProfile.setPhoneno(phoneno);
            userProfile.setVehicleno(vehicleno);
            userProfile.setEmail(email);
            //end
            userProfileMutableLiveData.postValue(userProfile);
        }else {
            userProfileMutableLiveData.postValue(null);
        }
    

    回答来源:Stack Overflow

    2020-03-22 09:34:58
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
ui-model,跨框架复用 立即下载
函数计算最佳实践:快速开发一个分布式 Puppeteer 网页截图服务 立即下载
如何使用Tair增强数据结构构建丰富在线实时场景 立即下载