android-在实时数据库中读取和写入

时间:2018-04-19 12:59:49

标签: android firebase firebase-realtime-database

我有一个用户类,它有一个联系人列表(朋友)。我想添加添加朋友的可能性。

我的数据库 database

在我的代码中,我有addFriend方法,该方法调用checkUser方法。在这里,我检查用户是否存在,以便我可以将他添加到好友列表中。我在实现它时遇到了困难,比如如何从匿名类中检索变量?

这是我的代码。

package com.android.pfe.other;

import android.support.annotation.Keep;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.IgnoreExtraProperties;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by SADA INFO on 13/04/2018.
 */
@IgnoreExtraProperties
@Keep
public class User implements Serializable {
    private static final String TAG ="UserClass" ;
    public String username;
    public String email;
    public Hashtable contact;
    public String Uid;
    public List article;
    public DatabaseReference mDatabase;
    public List<User> UserList;
    public User uti;
    public User() {
        // Default constructor required for calls to DataSnapshot.getValue(com.android.pfe.other.User.class)
    }

    public User(String username, String email,String uid) {
        this.username = username;
        this.email = email;
        this.contact=new Hashtable<String,Boolean>();
        this.Uid=Uid;


    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void addUser(String UserId, String name, String email) {
        mDatabase = FirebaseDatabase.getInstance().getReference("User");
        User user = new User(name, email,UserId);
        mDatabase.child(UserId).setValue(user);

    }
    public void addFriend(String UserId, final String email)
    {
        mDatabase = FirebaseDatabase.getInstance().getReference("User");
        DatabaseReference user = mDatabase.child(UserId);
        final DatabaseReference friendlist = user.child("contact");

        if(checkUser(email)==true)
        friendlist.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Hashtable list = dataSnapshot.getValue(Hashtable.class);
                if(list.isEmpty())
                {
                    friendlist.setValue(email);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }
    public boolean checkUser(String email){
        Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("email").equalTo(email);
        query.addListenerForSingleValueEvent(mValueEventListener);
       if(uti==null)
       {
           return false;
       }
        return true;
    }

    ValueEventListener mValueEventListener=new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists())
        {
            uti=dataSnapshot.getValue(User.class);

        }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
        }
    };

} 

1 个答案:

答案 0 :(得分:1)

我建议您使用onSuccess(DataSnapshot dataSnapshot)和onError(Exception e)方法定义一个名为'ICheckUserListener'的接口。

public void checkUser(String email, ICheckUserListener listener) 
//Since this method is independent of a specific User instance, it can be static which would require minor adjustments to prevent a memory-leak
{
    ValueEventListener mValueEventListener = new ValueEventListener() 
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) 
        {
            listener.success(dataSnapshot.exists() ? dataSnapshot : null);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) 
        {
            Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
            listener.onError(databaseError.toException());
        }
    };

    FirebaseDatabase
       .getInstance()
       .getReference("User")
       .orderByChild("email") //This is redundant if email ids are unique
       .equalTo(email)
       .addListenerForSingleValueEvent(mValueEventListener);

}

然后,您可以在'addFriend'方法中实现'ICheckUserListener'来处理结果。