如何在firebase(android)的homefragment列表视图中显示所有用户图像帖子?

时间:2017-10-15 13:57:16

标签: android firebase firebase-realtime-database firebase-authentication

目前我的listview仅显示来自firebase的当前用户的帖子 我必须更改它以显示来自firebase的所有用户帖子。任何人都可以提供示例代码。

HomeActivit.java
HomeFragment.java
activity_home.xml
fragment_home.xml

2 个答案:

答案 0 :(得分:0)

***HomeActivity***
package tabian.com.instagramclone2.Home;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;


import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.nostra13.universalimageloader.core.ImageLoader;

import tabian.com.instagramclone2.Login.LoginActivity;
import tabian.com.instagramclone2.R;
import tabian.com.instagramclone2.Utils.BottomNavigationViewHelper;
import tabian.com.instagramclone2.Utils.MainfeedListAdapter;
import tabian.com.instagramclone2.Utils.SectionsPagerAdapter;
import tabian.com.instagramclone2.Utils.UniversalImageLoader;
import tabian.com.instagramclone2.Utils.ViewCommentsFragment;

import tabian.com.instagramclone2.models.Photo; import tabian.com.instagramclone2.models.UserAccountSettings;

public class HomeActivity扩展了AppCompatActivity实现         MainfeedListAdapter.OnLoadMoreItemsListener {

@Override
public void onLoadMoreItems() {
    Log.d(TAG, "onLoadMoreItems: displaying more photos");
    HomeFragment fragment = (HomeFragment)getSupportFragmentManager()
            .findFragmentByTag("android:switcher:" + R.id.viewpager_container + ":" + mViewPager.getCurrentItem());
    if(fragment != null){
        fragment.displayMorePhotos();
    }
}

private static final String TAG = "HomeActivity";
private static final int ACTIVITY_NUM = 0;
private static final int HOME_FRAGMENT = 1;

private Context mContext = HomeActivity.this;

//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

//widgets
private ViewPager mViewPager;
private FrameLayout mFrameLayout;
private RelativeLayout mRelativeLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Log.d(TAG, "onCreate: starting.");
    mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
    mFrameLayout = (FrameLayout) findViewById(R.id.container);
    mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayoutParent);

    setupFirebaseAuth();

    initImageLoader();
    setupBottomNavigationView();
    setupViewPager();

}



public void onCommentThreadSelected(Photo photo, String callingActivity){
    Log.d(TAG, "onCommentThreadSelected: selected a coemment thread");

    ViewCommentsFragment fragment  = new ViewCommentsFragment();
    Bundle args = new Bundle();
    args.putParcelable(getString(R.string.photo), photo);
    args.putString(getString(R.string.home_activity), getString(R.string.home_activity));
    fragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, fragment);
    transaction.addToBackStack(getString(R.string.view_comments_fragment));
    transaction.commit();

}

public void hideLayout(){
    Log.d(TAG, "hideLayout: hiding layout");
    mRelativeLayout.setVisibility(View.GONE);
    mFrameLayout.setVisibility(View.VISIBLE);
}


public void showLayout(){
    Log.d(TAG, "hideLayout: showing layout");
    mRelativeLayout.setVisibility(View.VISIBLE);
    mFrameLayout.setVisibility(View.GONE);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if(mFrameLayout.getVisibility() == View.VISIBLE){
        showLayout();
    }
}


private void initImageLoader(){
    UniversalImageLoader universalImageLoader = new UniversalImageLoader(mContext);
    ImageLoader.getInstance().init(universalImageLoader.getConfig());
}

/**
 * Responsible for adding the 3 tabs: Camera, Home, Messages
 */
private void setupViewPager(){
    SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new CameraFragment()); //index 0
    adapter.addFragment(new HomeFragment()); //index 1
    adapter.addFragment(new MessagesFragment()); //index 2
    mViewPager.setAdapter(adapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    tabLayout.getTabAt(0).setIcon(R.drawable.ic_action);
    tabLayout.getTabAt(1).setIcon(R.drawable.ic_action_name);
    tabLayout.getTabAt(2).setIcon(R.drawable.ic_action);
}

/**
 * BottomNavigationView setup
 */
private void setupBottomNavigationView(){
    Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
    BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
    BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
    BottomNavigationViewHelper.enableNavigation(mContext, this,bottomNavigationViewEx);
    Menu menu = bottomNavigationViewEx.getMenu();
    MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
    menuItem.setChecked(true);
}


 /*
------------------------------------ Firebase ---------------------------------------------
        */

/**
 * checks to see if the @param 'user' is logged in
 * @param user
 */
private void checkCurrentUser(FirebaseUser user){
    Log.d(TAG, "checkCurrentUser: checking if user is logged in.");

    if(user == null){
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
    }
}
/**
 * Setup the firebase auth object
 */
private void setupFirebaseAuth(){
    Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");

    mAuth = FirebaseAuth.getInstance();

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

            //check if the user is logged in
            checkCurrentUser(user);

            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
    mViewPager.setCurrentItem(HOME_FRAGMENT);
    checkCurrentUser(mAuth.getCurrentUser());
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

}

答案 1 :(得分:0)

* HomeFragment ***我的HomeFragment.java *

package tabian.com.instagramclone2.Home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.firebase.auth.FirebaseAuth;
 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.Query;
  import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
    import java.util.Map;

 import tabian.com.instagramclone2.R;
  import tabian.com.instagramclone2.Utils.MainfeedListAdapter;
 import tabian.com.instagramclone2.models.Comment;
import tabian.com.instagramclone2.models.Like;
  import tabian.com.instagramclone2.models.Photo;
import tabian.com.instagramclone2.models.UserAccountSettings;

/ **  *由用户于5/28/2017创建。  * /

公共类HomeFragment扩展Fragment {     private static final String TAG =" HomeFragment&#34 ;;

//vars
private ArrayList<Photo> mPhotos;
private ArrayList<Photo> mPaginatedPhotos;
private ArrayList<String> mFollowing;
private ListView mListView;
private MainfeedListAdapter mAdapter;
private int mResults;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup   container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    mListView = (ListView) view.findViewById(R.id.listView);
    mFollowing = new ArrayList<>();
    mPhotos = new ArrayList<>();

    getFollowing();

    return view;
}

private void getFollowing(){
    Log.d(TAG, "getFollowing: searching for following");

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    Query query = reference
            .child(getString(R.string.dbname_following))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                Log.d(TAG, "onDataChange: found user: " +
                singleSnapshot.child(getString(R.string.field_user_id)).getValue());

                mFollowing.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());
            }
            mFollowing.add(FirebaseAuth.getInstance().getCurrentUser().getUid());
            //get the photos
            getPhotos();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void getPhotos(){
    Log.d(TAG, "getPhotos: getting photos");
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    for(int i = 0; i < mFollowing.size(); i++){
        final int count = i;
        Query query = reference
                .child(getString(R.string.dbname_user_photos))
                .child(mFollowing.get(i))
                .orderByChild(getString(R.string.field_user_id))
                .equalTo(mFollowing.get(i));
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                    Photo photo = new Photo();
                    Map<String, Object> objectMap = (HashMap<String, Object>) singleSnapshot.getValue();

                    photo.setCaption(objectMap.get(getString(R.string.field_caption)).toString());
                    photo.setTags(objectMap.get(getString(R.string.field_tags)).toString());
                    photo.setPhoto_id(objectMap.get(getString(R.string.field_photo_id)).toString());
                    photo.setUser_id(objectMap.get(getString(R.string.field_user_id)).toString());
                    photo.setDate_created(objectMap.get(getString(R.string.field_date_created)).toString());
                    photo.setImage_path(objectMap.get(getString(R.string.field_image_path)).toString());

                    ArrayList<Comment> comments = new ArrayList<Comment>();
                    for (DataSnapshot dSnapshot : singleSnapshot
                            .child(getString(R.string.field_comments)).getChildren()){
                        Comment comment = new Comment();
                        comment.setUser_id(dSnapshot.getValue(Comment.class).getUser_id());
                        comment.setComment(dSnapshot.getValue(Comment.class).getComment());
                        comment.setDate_created(dSnapshot.getValue(Comment.class).getDate_created());
                        comments.add(comment);
                    }

                    photo.setComments(comments);
                    mPhotos.add(photo);
                }
                if(count >= mFollowing.size() -1){
                    //display our photos
                    displayPhotos();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

private void displayPhotos(){
    mPaginatedPhotos = new ArrayList<>();
    if(mPhotos != null){
        try{
            Collections.sort(mPhotos, new Comparator<Photo>() {
                @Override
                public int compare(Photo o1, Photo o2) {
                    return o2.getDate_created().compareTo(o1.getDate_created());
                }
            });

            int iterations = mPhotos.size();

            if(iterations > 10){
                iterations = 10;
            }

            mResults = 10;
            for(int i = 0; i < iterations; i++){
                mPaginatedPhotos.add(mPhotos.get(i));
            }

            mAdapter = new MainfeedListAdapter(getActivity(), R.layout.layout_mainfeed_listitem, mPaginatedPhotos);
            mListView.setAdapter(mAdapter);

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

public void displayMorePhotos(){
    Log.d(TAG, "displayMorePhotos: displaying more photos");

    try{

        if(mPhotos.size() > mResults && mPhotos.size() > 0){

            int iterations;
            if(mPhotos.size() > (mResults + 10)){
                Log.d(TAG, "displayMorePhotos: there are greater than 10 more photos");
                iterations = 10;
            }else{
                Log.d(TAG, "displayMorePhotos: there is less than 10 more photos");
                iterations = mPhotos.size() - mResults;
            }

            //add the new photos to the paginated results
            for(int i = mResults; i < mResults + iterations; i++){
                mPaginatedPhotos.add(mPhotos.get(i));
            }
            mResults = mResults + iterations;
            mAdapter.notifyDataSetChanged();
        }
    }catch (NullPointerException e){
        Log.e(TAG, "displayPhotos: NullPointerException: " + e.getMessage() );
    }catch (IndexOutOfBoundsException e){
        Log.e(TAG, "displayPhotos: IndexOutOfBoundsException: " + e.getMessage() );
    }
}

}