如何从Firebase数据库检索数据并将其放入对象中?

时间:2019-01-02 15:07:09

标签: android firebase firebase-realtime-database

我想从Firebase数据库获取数据并将其放在对象中。 我可以看到我正确访问了数据库中的数据,但是无法将其放入我的对象中。

  

FirebaseMethods

package com.example.android.instagramclone.Utils;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.android.instagramclone.R;
import com.example.android.instagramclone.models.User;
import com.example.android.instagramclone.models.UserAccountSettings;
import com.example.android.instagramclone.models.UserSettings;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class FirebaseMethods {

    private static final String TAG = "FirebaseMethods";

    private Context mContext;

    //Firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase database;
    private DatabaseReference reference;

    private String userid;

    /**
     * constructor
     *
     * @param mContext
     */
    public FirebaseMethods(Context mContext) {
        mAuth = FirebaseAuth.getInstance();
        //initialize database.
        database = FirebaseDatabase.getInstance();
        reference = database.getReference();

        this.mContext = mContext;

        if (mAuth.getCurrentUser() != null) {
            //userID is unique to each user.
            userid = mAuth.getCurrentUser().getUid();

        }
    }



    /**
     * add information to the users nodes.
     * add information to the account setting node.
     *
     * @param username
     * @param email
     * @param description
     * @param website
     * @param profile_photo
     */
    public void addNewUser(String username, String email, String description, String website, String profile_photo) {

        //setting up user personal info.
        User user = new User(StringManupulation.condenseUsername(username), 1, email, username);

        //reference a node;
        reference.child(mContext.getString(R.string.dbname_users)).child(userid).setValue(user);

        //setting up userAccountSetting
        UserAccountSettings settings = new UserAccountSettings(
                description,
                username,
                0,
                0,
                0,
                "",
                StringManupulation.condenseUsername(username),
                website
        );

        reference.child(mContext.getString(R.string.dbname_user_account_settings))
                .child(userid)
                .setValue(settings);
    }




    /**
     * setting up FirebaseAuthentificationListener.
     */
    private void updateUI() {

        Log.d(TAG, "updateUI: started.");

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    Log.d(TAG, "onAuthStateChanged: successfully logged in.");
                } else {
                    Log.d(TAG, "onAuthStateChanged: authentification failed.");
                }
            }
        };

    }

    /**
     * retrieve the account settings from Forebase database.
     *
     * @param dataSnapshot
     * @return
     */
    public UserSettings getUserSettings(DataSnapshot dataSnapshot) {
        Log.d(TAG, "getUserAccountSettings: retrieving user acoount settings from firebase.");

        UserAccountSettings settings = new UserAccountSettings();
        User user = new User();

        //Read through all the major nodes.
        for (DataSnapshot ds : dataSnapshot.getChildren()) {

            // If the name of a node is "user_account_setings".
            if (ds.getKey().equals(mContext.getString(R.string.dbname_user_account_settings))) {
                Log.d(TAG, "getUserAccountSettings: datasnapshot: "+ ds);

                try {
                    //Setting display_name.
                    settings.setDisplay_name(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getDisplay_name());

                    Log.d(TAG, "getUserSettings: " + settings.getDisplay_name());

                    //Setting username.
                    settings.setUsername(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getUsername());

                    //Setting website.
                    settings.setWebsite(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getWebsite());

                    //Setting description.
                    settings.setDescription(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getDescription());

                    //Setting profile_photo.
                    settings.setProfile_photo(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getProfile_photo());

                    //Setting posts.
                    settings.setPost(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getPost());

                    //Setting followers.
                    settings.setFollowers(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getFollowers());

                    //Setting Followings.
                    settings.setFollowing(ds.child(userid)
                            .getValue(UserAccountSettings.class)
                            .getFollowing());

                    Log.d(TAG, "getUserAccountSettings: retrieved user_account_settings info.");

                } catch (NullPointerException e) {
                    Log.e(TAG, "getUserAccountSettings: " + e.getMessage());
                }

                //users node
                if (ds.getKey().equals(R.string.dbname_users)) {
                    Log.d(TAG, "getUserAccountSettings: dataSnapShot: " + ds);

                    try {
                        //Setting mail.
                        user.setMail(ds.child(userid)
                                .getValue(User.class)
                                .getMail());

                        //Setting username.
                        user.setUsername(ds.child(userid)
                                .getValue(User.class)
                                .getUsername());

                        //Setting phone_number.
                        user.setPhone_number(ds.child(userid)
                                .getValue(User.class)
                                .getPhone_number());

                        //Setting userID.
                        user.setUserID(ds.child(userid)
                                .getValue(User.class)
                                .getUserID());

                        Log.d(TAG, "getUserAccountSettings: retrieved user info.");


                    } catch (NullPointerException e) {
                        Log.e(TAG, "getUserAccountSettings: " + e.getMessage());
                    }

                }
            }
        }

        return new UserSettings(user, settings);

    }
}
  

个人资料片段

package com.example.android.instagramclone.Profile;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.android.instagramclone.R;
import com.example.android.instagramclone.Utils.BottomNavigationViewHelper;
import com.example.android.instagramclone.Utils.FirebaseMethods;
import com.example.android.instagramclone.Utils.GridImageAdapter;
import com.example.android.instagramclone.Utils.UniversalImageLoader;
import com.example.android.instagramclone.models.User;
import com.example.android.instagramclone.models.UserAccountSettings;
import com.example.android.instagramclone.models.UserSettings;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.ValueEventListener;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

public class ProfileFragment extends Fragment {

    private static final String TAG = "ProfileFragment";
    private Context mContext;

    private TextView mPosts;
    private TextView mFollowers;
    private TextView mFollowings;
    private TextView mDisplayName;
    private TextView mUserName;
    private TextView mWebsite;
    private TextView mDescription;
    private ProgressBar mProgressBar;
    private CircleImageView mProfilePhoto;
    private GridView gridView;
    private ImageView profileMenu;
    private android.support.v7.widget.Toolbar toolbar;
    private BottomNavigationView bottomNavigationView;

    //For bottomNavigationView icons.
    private static final int ACTIVITY_NUM = 4;

    //The number of columns of gridView for pics uploaded.
    private static final int NUM_GRID_COLUMNS = 3;

    //Firebase things.
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase database;
    private DatabaseReference myRef;
    private FirebaseMethods mFirebaseMethods;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        Log.d(TAG, "onCreateView: started.");

        //Setting up each widgets.
        mDisplayName = (TextView) view.findViewById(R.id.display_name);
        mUserName = (TextView) view.findViewById(R.id.username);
        mPosts = (TextView) view.findViewById(R.id.tv_posts);
        mFollowings = (TextView) view.findViewById(R.id.tvFollowing);
        mFollowers = (TextView) view.findViewById(R.id.tvFollowers);
        mWebsite = (TextView) view.findViewById(R.id.display_website);
        mDescription = (TextView) view.findViewById(R.id.display_description);
        mProfilePhoto = (CircleImageView) view.findViewById(R.id.profile_image);
        mProgressBar = (ProgressBar) view.findViewById(R.id.profileProgressBar);
        gridView = (GridView) view.findViewById(R.id.gridview);
        toolbar = (android.support.v7.widget.Toolbar) view.findViewById(R.id.profileToolBar);
        profileMenu = (ImageView) view.findViewById(R.id.profile_menu);
        bottomNavigationView = (BottomNavigationView) view.findViewById(R.id.bottomNavViewBar);
        mContext = getActivity();
        mFirebaseMethods = new FirebaseMethods(getActivity());

        //setting up progress bar
        mProgressBar.setVisibility(View.GONE);


        setupBottomNavigationView();
        setupToolbar();

        setUpFirebaseAuth();

        return view;
    }

    /**
     * Setting up information retrieving from FIrebaseDatabase.
     * @param userSettings
     */
    private void setProfileWidgets(UserSettings userSettings){


        //Create instances.
        User user = userSettings.getUser();
        UserAccountSettings accountSettings = userSettings.getSettings();

        Log.d(TAG, "setProfileWidgets: Setting Widgets with data retrieving from firebaseDatabase: " + accountSettings.toString());

        //Set values to each views.
        UniversalImageLoader.setImage(accountSettings.getProfile_photo(), mProfilePhoto, null, "");
        mDisplayName.setText(accountSettings.getDisplay_name());
        mUserName.setText(accountSettings.getUsername());
        mWebsite.setText(accountSettings.getWebsite());
        mDescription.setText(accountSettings.getDescription());
        mPosts.setText(String.valueOf(accountSettings.getPost()));
        mFollowers.setText(String.valueOf(accountSettings.getFollowers()));
        mFollowings.setText(String.valueOf(accountSettings.getFollowing()));
    }


    /**
     * setting up the toolBar on the top.
     */
    private void setupToolbar() {
        //アクションバーとしてtoolbarを使う
        ((ProfileActivity) getActivity()).setSupportActionBar(toolbar);

        // When the toolbar button is tapped, navigate to Account setting page.
        profileMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: navigating to account settings.");
                Intent intent = new Intent(mContext, AccountSettingActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * set up bottomNavigationView
     */
    private void setupBottomNavigationView() {
        Log.d(TAG, "setBottomNavigationView: setting up bottomNavigationView");

        BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationView);
        Menu menu = bottomNavigationView.getMenu();
        MenuItem menuItem = menu.getItem(ACTIVITY_NUM);

        menuItem.setChecked(false);
    }

    /**
     * -----------------Firebase section starts------------------------*
     */

    /**
     * Setting up FirebaseAuth for Authentification of user
     */
    private void setUpFirebaseAuth() {
        Log.d(TAG, "setUpFirebaseAuth: started.");

        mAuth = FirebaseAuth.getInstance();

        //Preparing to get info from FirebaseDatabase.
        database = FirebaseDatabase.getInstance();
        myRef = database.getReference();


        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (user != null) {
                    Log.d(TAG, "onAuthStateChanged: User logged in.");
                } else if (user == null) {
                    Log.d(TAG, "onAuthStateChanged: User not logged in.");
                }
            }
        };

        //Allow us to get data snapshot and read, write data.
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                //retrieve user info from database.
                setProfileWidgets(mFirebaseMethods.getUserSettings(dataSnapshot));

                //retrieve images for the user in question.

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: started.");

        //user Authentification and update UI accordingly.
        setUpFirebaseAuth();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: started.");

        if(mAuthListener != null ){
            mAuth.removeAuthStateListener(mAuthListener);
        }

    }

    /**
     * -----------------Firebase section ends ------------------------*
     */
}
FirebaseMethods中的

log.d正确显示了“ ds”的内容,这意味着我可以正确访问数据。但是,当我在对象“ accountSettings”中放入数据后看到每个值时,它显示String为null,长值(初始化值)为0。 您能告诉我为什么会发生这种情况以及如何解决这个问题吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

我不知道这是否有用,但这是我从Firebase设置数据的方式。

private DatabaseReference mUsernameDatabase;

//

    mUsernameDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);


mUsernameDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


                    String about = Objects.requireNonNull(dataSnapshot.child("about").getValue()).toString();
                    editAbout.setText(about);

                    String address = Objects.requireNonNull(dataSnapshot.child("address").getValue()).toString();
                    editAddress.setText(address);
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                 Toast.makeText(Profile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                }
            });

答案 1 :(得分:0)

谢谢,我解决了这个问题。 那是因为我已经删除了登录帐户。 不是因为我的代码。 但是我从您的答案中学到了很多。 再次感谢。