How to retrieve data from firebase cloud store to a fragment class for example ProfileFragment.class which also uses MVVM?

huangapple go评论63阅读模式
英文:

How to retrieve data from firebase cloud store to a fragment class for example ProfileFragment.class which also uses MVVM?

问题

以下是翻译好的代码部分:

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/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" />

    <!-- ... 省略其他部分 ... -->

</androidx.constraintlayout.widget.ConstraintLayout>

ProfileFragment.java (编辑后的部分):

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;
    }
}

ProfileViewModel.java (编辑后的部分):

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;
    }
}

请注意,此翻译只包含您提供的代码部分,其他内容已被省略。

英文:

I am a newbie. Tried other resources but most of them have discussed on recycler view but for my app I am using view model. Looking forward for help. I want to retrieve the user profile data from firebase cloud store. Following is the code I referred so far.

ProfileViewModel.java

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class ProfileViewModel extends ViewModel {
private MutableLiveData&lt;String&gt; mText;
public ProfileViewModel() {
mText = new MutableLiveData&lt;&gt;();
mText.setValue( &quot;Your Profile&quot; );
}
public LiveData&lt;String&gt; 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&lt;String&gt;() {
@Override
public void onChanged(@Nullable String s) {
textView.setText( s );
}
} );
return root;
}

}

fragment_profile.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.ui.profile.ProfileFragment&quot;&gt;
&lt;TextView
android:id=&quot;@+id/email&quot;
android:layout_width=&quot;84dp&quot;
android:layout_height=&quot;31dp&quot;
android:layout_marginEnd=&quot;164dp&quot;
android:layout_marginRight=&quot;164dp&quot;
android:layout_marginBottom=&quot;182dp&quot;
android:text=&quot;Email&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/text_profile&quot;
android:layout_width=&quot;109dp&quot;
android:layout_height=&quot;35dp&quot;
android:layout_marginEnd=&quot;150dp&quot;
android:layout_marginRight=&quot;150dp&quot;
android:layout_marginBottom=&quot;35dp&quot;
android:text=&quot;Your Profile&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/name&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/name&quot;
android:layout_width=&quot;84dp&quot;
android:layout_height=&quot;31dp&quot;
android:layout_marginEnd=&quot;164dp&quot;
android:layout_marginRight=&quot;164dp&quot;
android:layout_marginBottom=&quot;34dp&quot;
android:text=&quot;Name&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/phoneno&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/phoneno&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;31dp&quot;
android:layout_marginEnd=&quot;158dp&quot;
android:layout_marginRight=&quot;158dp&quot;
android:layout_marginBottom=&quot;36dp&quot;
android:text=&quot;Phone Number&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/vehicleno&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/vehicleno&quot;
android:layout_width=&quot;112dp&quot;
android:layout_height=&quot;35dp&quot;
android:layout_marginEnd=&quot;150dp&quot;
android:layout_marginRight=&quot;150dp&quot;
android:layout_marginBottom=&quot;30dp&quot;
android:text=&quot;Vehicle Number&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/email&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;

</androidx.constraintlayout.widget.ConstraintLayout>

Edited Code after applying the solution shared;

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&lt;UserProfile&gt;() {
@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(), &quot;No user information&quot;, Toast.LENGTH_SHORT);
toast.show();
}
}
});
return root;
}

}

Before the edited code, I get the following screen.
After updating the UI, I get the following screen;

Did I miss something in fragment_profile.xml or it's in ProfileFragment.java?

Edited 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&lt;UserProfile&gt; getUserProfile() {
final MutableLiveData&lt;UserProfile&gt; userProfileMutableLiveData =    new MutableLiveData&lt;&gt;();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef =  db.collection(&quot;Users&quot;).document(userId);
docRef.get().addOnCompleteListener(new  OnCompleteListener&lt;DocumentSnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;DocumentSnapshot&gt; task) {
if (task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if (documentSnapshot != null &amp;&amp;  documentSnapshot.exists()) {
UserProfile userProfile =  documentSnapshot.toObject(UserProfile.class);
userProfileMutableLiveData.postValue(userProfile);
}else {
userProfileMutableLiveData.postValue(null);
}
}else {
userProfileMutableLiveData.postValue(null);
}
}
});
return userProfileMutableLiveData;
}

}

Data in firebase cloudstore

答案1

得分: 0

ViewModel

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

public class ProfileViewModel extends ViewModel {

    public LiveData<UserProfile> getUserProfile() {
        final MutableLiveData<UserProfile> userProfileMutableLiveData = new MutableLiveData<>();
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        DocumentReference docRef = db.collection("users").document("android.dev@gmail.com");
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null && document.exists()) {
                        UserProfile userProfile = document.toObject(UserProfile.class);
                        userProfileMutableLiveData.postValue(userProfile);
                    } else {
                        userProfileMutableLiveData.postValue(null);
                    }
                } else {
                    userProfileMutableLiveData.postValue(null);
                }
            }
        });

        return userProfileMutableLiveData;
    }
}

Fragment

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) {

        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) {
                    // UPDATE YOUR UI HERE
                } else {
                    // SHOW ERROR MESSAGE
                }
            }
        });

        return root;
    }
}

User Profile Model

public class UserProfile {
    String fullName, address, gender, phone;

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

Firestore View
How to retrieve data from firebase cloud store to a fragment class for example ProfileFragment.class which also uses MVVM?

英文:

ViewModel

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class ProfileViewModel extends ViewModel {
public LiveData&lt;UserProfile&gt; getUserProfile(){
final MutableLiveData&lt;UserProfile&gt; userProfileMutableLiveData = new MutableLiveData&lt;&gt;();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection(&quot;users&quot;).document(&quot;android.dev@gmail.com&quot;);
docRef.get().addOnCompleteListener(new OnCompleteListener&lt;DocumentSnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;DocumentSnapshot&gt; task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null &amp;&amp; document.exists()) {
UserProfile userProfile = document.toObject(UserProfile.class);
userProfileMutableLiveData.postValue(userProfile);
} else {
userProfileMutableLiveData.postValue(null);
}
} else {
userProfileMutableLiveData.postValue(null);
}
}
});
return userProfileMutableLiveData;
}
}

Fragment

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) {
View root = inflater.inflate( R.layout.fragment_profile, container, false );
profileViewModel =  ViewModelProviders.of(this).get(ProfileViewModel.class);
profileViewModel.getUserProfile().observe(getViewLifecycleOwner(),new Observer&lt;UserProfile&gt;(){
@Override
public void onChanged(UserProfile userProfile) {
if(userProfile != null){
//UPDATE YOUR UI HERE
} else {
//SHOW ERROR MESSAGE
}
}
});
return root;
}

User Profile Model

public class UserProfile {
String fullName, address, gender, phone;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}

Firestore View

How to retrieve data from firebase cloud store to a fragment class for example ProfileFragment.class which also uses MVVM?

答案2

得分: 0

在ProfileViewModel.java文件中:

if (task.isSuccessful()) {
    DocumentSnapshot documentSnapshot = task.getResult();
    if (documentSnapshot != null && documentSnapshot.exists()) {
        //start (这段代码解决了问题)
        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);
    }
}
英文:

In ProfileViewModel.java:

if (task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if (documentSnapshot != null &amp;&amp; documentSnapshot.exists()) {
//start (this lines of code solved the issue)
String name = documentSnapshot.getString(&quot;Name&quot;);
String phoneno = documentSnapshot.getString(&quot;Phone number&quot;);
String vehicleno = documentSnapshot.getString(&quot;Vehicle Number&quot;);
String email = documentSnapshot.getString(&quot;Email&quot;);
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);
}

huangapple
  • 本文由 发表于 2020年3月17日 02:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60711278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定