RecyclerView空白页

时间:2018-03-09 20:04:10

标签: java android firebase firebase-realtime-database android-recyclerview

我有两个相同的活动ChatListActivity和FriendsList Activity。

第一个工作正常且相当快,但第二个有时是空白或没有显示个人资料图片(在毕加索的帮助下)。尽管从Firebase正确接收了所有信息。我使用的模型是相同的,基本上Friends.class扩展了Buddies.class。

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
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.Query;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class ChatListActivity extends AppCompatActivity {


    private RecyclerView recyclerView_buddies;
    private FirebaseRecyclerAdapter<Buddies, BuddiesViewHolder> firebaseRecyclerAdapter;
    private DatabaseReference UsersDatabaseReference;
    private DatabaseReference userDatabaseReference;

    private FirebaseUser firebaseUser;
    private FirebaseAuth firebaseAuth;
    private static final String TAG = "Chat List Act:";

    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference messageDatabaseReference;
    private DatabaseReference BuddiesDatabaseReference;
    private String mUserid;
    private String friend_id;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_list);

        recyclerView_buddies = (RecyclerView) findViewById(R.id.RecycleView_chat_list);
        recyclerView_buddies.setHasFixedSize(true);
        recyclerView_buddies.setLayoutManager(new LinearLayoutManager(this));

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        userDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.getUid());
        messageDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Messages");
        UsersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        BuddiesDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Messages").child(firebaseUser.getUid());

        // Presence System
        DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
        connectedRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                boolean connected = snapshot.getValue(Boolean.class);
                if (connected) {
                    System.out.println("connected");
                } else {
                    DatabaseReference userLastOnlineRef = FirebaseDatabase.getInstance().getReference().child("Users")
                            .child(firebaseUser.getUid()).child("online");
                    userLastOnlineRef.onDisconnect().setValue("false");
                    System.out.println("not connected");
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                System.err.println("Listener was cancelled");
            }
        });

        if (firebaseUser == null) {
            //User is not logged in
            Log.w(TAG, "Error. No user is logged in.");
            finish();
            startActivity(new Intent(this, LoginActivity.class));
        }else {
            final Map<String,Object> time_status = new HashMap<>();
            time_status.put("time", ServerValue.TIMESTAMP);
            time_status.put("online", "true");
            userDatabaseReference.updateChildren(time_status);
            Log.w(TAG, "Online status & time updated. edw");
        }

        messageDatabaseReference.keepSynced(true);
        UsersDatabaseReference.keepSynced(true);
        userDatabaseReference.keepSynced(true);

    }

    @Override
    protected void onStart() {
        super.onStart();

        firebaseUser = firebaseAuth.getCurrentUser();
        if (firebaseUser == null) {
            //User is not logged in
            Log.w(TAG, "Error. No user is logged in.");
            finish();
            startActivity(new Intent(this, LoginActivity.class));
        }

        Query conversationQuery = messageDatabaseReference.child("string").orderByChild("time");

        FirebaseRecyclerOptions<Buddies> response = new FirebaseRecyclerOptions.Builder<Buddies>()
                .setQuery(UsersDatabaseReference, Buddies.class)
                .build();

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Buddies, BuddiesViewHolder>(response) {
            @Override
            public BuddiesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                // Create a new instance of the ViewHolder, in this case we are using a custom
                // layout called R.layout.message for each item
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.buddies_layout, parent, false);

                return new BuddiesViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(final BuddiesViewHolder buddiesViewHolder, final int position, Buddies buddies) {
                // Bind the Chat object to the ChatHolder
                // ...
                buddiesViewHolder.textView_Fullname.setText(buddies.getFullname());
                buddiesViewHolder.textView_status.setText(buddies.getStatus());

                if (!buddies.getProfile_pic().isEmpty()) {
                    String path = null;
                    path = buddies.getProfile_pic().toString();

                    Log.d(TAG, "path: " + buddies.getProfile_pic().toString());
                    Picasso.with(getApplicationContext())
                            .load(path)
                            .placeholder(R.mipmap.user_avatar_round)
                            .into(buddiesViewHolder.circleImageView_profile_pic);
                }

                buddiesViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String userid = getRef(position).getKey();

                        Intent intent = new Intent(getApplicationContext(), MessageActivity.class);
                        intent.putExtra("userid", userid);
                        startActivity(intent);
                    }
                });
            }
        };

        firebaseRecyclerAdapter.notifyDataSetChanged();
        recyclerView_buddies.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();

    }

    @Override
    protected void onStop() {
        super.onStop();
        final Map<String,Object> time_status = new HashMap<>();
        time_status.put("time", ServerValue.TIMESTAMP);
        userDatabaseReference.updateChildren(time_status);
        Log.w(TAG, "Online status updated.");
    }

    @Override
    protected void onResume(){
        super.onResume();
        final Map<String, Object> time_status = new HashMap<>();
        time_status.put("time", ServerValue.TIMESTAMP);
        time_status.put("online", "true");
        userDatabaseReference.updateChildren(time_status);
        Log.w(TAG, "Online status updated. anoi3e");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        final Map<String, Object> time_status = new HashMap<>();
        time_status.put("time", ServerValue.TIMESTAMP);
        time_status.put("online", "true");
        userDatabaseReference.updateChildren(time_status);
        Log.w(TAG, "Online status updated.");
    }

    /*
    In future maybe the following function will be in separate file.
     */
    public static class BuddiesViewHolder extends RecyclerView.ViewHolder {

        View mView;
        @BindView(R.id.textViewFullName)
        TextView textView_Fullname;
        @BindView(R.id.buddy_profile_picture)
        CircleImageView circleImageView_profile_pic;
        @BindView(R.id.TextView_User_Desc)
        TextView textView_status;

        public BuddiesViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }
}

FriendsListActivity

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
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.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class FriendsListActivity extends AppCompatActivity {

    private RecyclerView recyclerView_buddies;
    private FirebaseRecyclerAdapter<Friends, FriendsViewHolder> firebaseRecyclerAdapter;
    private DatabaseReference FriendsDatabaseReference;
    private DatabaseReference userDatabaseReference;
    private DatabaseReference usersDatabaseReference;
    private DatabaseReference mUsersDatabase;

    private FirebaseUser firebaseUser;
    private FirebaseAuth firebaseAuth;
    private static final String TAG ="Friends Act:";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_list);

        recyclerView_buddies = (RecyclerView) findViewById(R.id.RecycleView_friends_list);
        recyclerView_buddies.setHasFixedSize(true);
        recyclerView_buddies.setLayoutManager(new LinearLayoutManager(this));

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        FriendsDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friends");
        mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(firebaseUser.getUid());
        usersDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        userDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseUser.getUid());
        userDatabaseReference.keepSynced(true);
        usersDatabaseReference.keepSynced(true);
        FriendsDatabaseReference.keepSynced(true);
        mUsersDatabase.keepSynced(true);

    }

    @Override
    protected void onStart(){
        super.onStart();

        firebaseUser = firebaseAuth.getCurrentUser();
        if( firebaseUser == null){
            //User is not logged in
            Log.w(TAG, "Error. No user is logged in.");
            finish();
            startActivity(new Intent(this, LoginActivity.class));
        }
        else {
            final Map<String,Object> time_status = new HashMap<>();
            time_status.put("time", ServerValue.TIMESTAMP);
            userDatabaseReference.updateChildren(time_status);
            Log.w(TAG, "Online status updated.");
        }

        // Presence System
        DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
        connectedRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                boolean connected = snapshot.getValue(Boolean.class);
                if (connected) {
                    System.out.println("connected");
                } else {
                    DatabaseReference userLastOnlineRef = FirebaseDatabase.getInstance().getReference().child("Users")
                            .child(firebaseUser.getUid()).child("online");
                    userLastOnlineRef.onDisconnect().setValue("false");
                    System.out.println("not connected");
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                System.err.println("Listener was cancelled");
            }
        });

        FirebaseRecyclerOptions<Friends> response = new FirebaseRecyclerOptions.Builder<Friends>()
                .setQuery( mUsersDatabase , Friends.class)
                .build();

        firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(response) {
            @Override
            public FriendsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                // Create a new instance of the ViewHolder, in this case we are using a custom
                // layout called R.layout.message for each item
                View view = LayoutInflater.from(getApplicationContext())
                        .inflate(R.layout.buddies_layout, parent, false);

                return new FriendsViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(final FriendsViewHolder friendsViewHolder, final int position, final Friends friends) {
                // Bind the Chat object to the ChatHolder
                // ...

                // Next feature display since when they are friends
                //friendsViewHolder.setDate(friends.getDate());

                final String list_user_id = getRef(position).getKey();

                usersDatabaseReference.child(list_user_id).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        if(dataSnapshot.hasChild("online")) {

                            String userOnline = dataSnapshot.child("online").getValue().toString();
                            friendsViewHolder.setUserOnline(userOnline);

                            Log.d(TAG, "User availability status: " + dataSnapshot.child("online").getValue().toString());

                        }
                        if(dataSnapshot.hasChild("profile_pic")) {
                            final String path = dataSnapshot.child("profile_pic").getValue().toString();

                            Log.d(TAG, "path: " + path);

                            friendsViewHolder.setUserImage(path, getApplicationContext());

                        }
                        if(dataSnapshot.hasChild("fullname")) {

                            //friendsViewHolder.textView_Fullname.setText(dataSnapshot.child("fullname").getValue().toString());

                            Log.w(TAG, "Friends name: "+ dataSnapshot.child("fullname").getValue().toString());

                            friendsViewHolder.setName(dataSnapshot.child("fullname").getValue().toString());

                        }
                        if(dataSnapshot.hasChild("status")) {

                            //friendsViewHolder.textView_status.setText(dataSnapshot.child("status").getValue().toString());

                            Log.w(TAG, "Friends status desc: "+ dataSnapshot.child("status").getValue().toString());

                            friendsViewHolder.setStatus(dataSnapshot.child("status").getValue().toString());

                        }

                        friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(getApplicationContext(), ViewFriendActivity.class);
                                intent.putExtra("userid", list_user_id);
                                startActivity(intent);
                            }
                        });

                        friendsViewHolder.mView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View view) {
                                CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};

                                final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

                                builder.setTitle("Select Options");
                                builder.setItems(options, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                        //Click Event for each item.
                                        if(i == 0){

                                            Intent profileIntent = new Intent(getApplicationContext(), ViewFriendActivity.class);
                                            profileIntent.putExtra("user_id", list_user_id);
                                            startActivity(profileIntent);

                                        }

                                        if(i == 1){

                                            Intent chatIntent = new Intent(getApplicationContext(), MessageActivity.class);
                                            chatIntent.putExtra("user_id", list_user_id);
                                            startActivity(chatIntent);

                                        }

                                    }
                                });
                                //builder.show();

                                return false;
                            }

                        });


                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
            }
        };

        firebaseRecyclerAdapter.notifyDataSetChanged();
        recyclerView_buddies.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();

    }





    @Override
    protected void onStop() {
        super.onStop();
        firebaseRecyclerAdapter.stopListening();
        final Map<String,Object> time_status = new HashMap<>();
        time_status.put("time", ServerValue.TIMESTAMP);
        userDatabaseReference.updateChildren(time_status);
        Log.w(TAG, "Activity Stopped. Online status updated.");
    }

    /*
    In future maybe the following function will be in separate file.
     */
    public static class BuddiesViewHolder extends RecyclerView.ViewHolder {

        View mView;
        @BindView(R.id.textViewFullName)
        TextView textView_Fullname;
        @BindView(R.id.buddy_profile_picture)
        CircleImageView circleImageView_profile_pic;
        @BindView(R.id.TextView_User_Desc)
        TextView textView_status;

        public BuddiesViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    public static class FriendsViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public FriendsViewHolder(View itemView) {
            super(itemView);

            mView = itemView;


        }

        public void setDate(String date){

            TextView userStatusView = (TextView) mView.findViewById(R.id.TextView_User_Desc);
            userStatusView.setText(date);

        }

        public void setName(String name){

            TextView userNameView = (TextView) mView.findViewById(R.id.textViewFullName);
            userNameView.setText(name);

        }

        public void setStatus(String status){

            TextView textView_status = (TextView) mView.findViewById(R.id.TextView_User_Desc);
            textView_status.setText(status);

        }

        public void setUserImage(String thumb_image, Context ctx){

            CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.buddy_profile_picture);
            Picasso.with(ctx).load(thumb_image).placeholder(R.mipmap.user_avatar_round).into(userImageView);

        }

        public void setUserOnline(String online_status) {

            ImageView userOnlineView = (ImageView) mView.findViewById(R.id.buddy_profile_picture);

            if(online_status.equals("true")){

                userOnlineView.setVisibility(View.VISIBLE);

            } else {

                userOnlineView.setVisibility(View.INVISIBLE);

            }

        }


    }
}

活动xml布局(它们是相同的。它们只包含RecyclerView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    tools:context="com.forthnet.dalva.bestbud.FriendsListActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecycleView_friends_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</LinearLayout>

ChatListActivity xml布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.forthnet.dalva.bestbud.ChatListActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecycleView_chat_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>
  

更新问题   我检查了每个参数,发现这行代码是   ChatListActivity xml上的错误:

android:layout_height="wrap_content"
     

所以,我把它设置为match_parent,最后我不是黑色的   没有解决加载每个人的个人资料图片的问题   用户。

1 个答案:

答案 0 :(得分:0)

我检查了每个参数,发现这行代码是ChatListActivity xml上的错误:

onTitleClick

所以,我把它设置为AppBar,最后它不是黑色的,虽然我没有解决加载每个用户的个人资料图片的问题。

我也发现我没有把这一行写成评论......

android:layout_height="wrap_content"

这就是为什么所有的图像都是看不见的!