问题
I've always used the structure below to identify whether a user has an account in my app.
All of this code is placed in MainActivity
, but Google Architecture Components suggests to separate UI from the back-end logic.
I've followed the example below for integrating the contact list with MVVM structure.
https://github.com/NaarGes/Android-Contact-List
But I don't know how to insert the Firebase Realtime Database validation.
private void getContactList(){
Cursor phones = getContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phone = phone.replace(" ","");
phone = phone.replace("-","");
phone = phone.replace("(","");
phone = phone.replace(")","");
UserObject mContact = new UserObject("",name, phone);
contactList.add(mContact);
getUserDetails(mContact);
}
}
private void getUserDetails(UserObject mContact) {
DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("user");
// Only lists the users that have an account in the app into Firebase
Query query = mUserDB.orderByChild("phone").equalTo(mContact.getPhone());
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String uid, name = "", phone = "", email, image;
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
uid = childSnapshot.getKey().toString();
if (childSnapshot.child("phone").getValue() != null) {
phone = childSnapshot.child("phone").getValue().toString();
}
if (childSnapshot.child("name").getValue() != null) {
name = childSnapshot.child("name").getValue().toString();
}
email = childSnapshot.child("email").getValue().toString();
image = childSnapshot.child("image").getValue().toString();
UserObject mUser = new UserObject(childSnapshot.getKey(), name, phone);
mUser.setImageUrl(image);
if (name.equals(phone)) {
for (UserObject mContactIterator : contactList) {
if (mContactIterator.getPhone().equals(mUser.getPhone())) {
mUser.setName(mContactIterator.getName());
}
}
}
return;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
My question is: How to convert the code above into MVVM (Android Architecture Components
)?
Thanks in advance!
来源:https://stackoverflow.com/questions/57317023/sync-device-contact-list-with-firebase-using-mvvm-android-architecture-componen