在一个cardView中获取多个Firebase数据库引用的值

时间:2017-03-02 01:10:06

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

我正在开发一个应用程序,它要求我在一个cardview中从两个Firebase数据库引用中获取引用。以下是cardview的模型

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_marginRight="35dp"
    android:layout_marginLeft="35dp"
    android:layout_marginBottom="60dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="75dp"
        >
        <ImageView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="5dp"
            app:srcCompat="@drawable/action_setup"
            android:id="@+id/dPicture"/>
        <TextView
            android:text="Username"
            android:layout_width="0dp"
            android:layout_weight="4"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:id="@+id/posted_username"
            android:paddingLeft="15dp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:elevation="10dp">


        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/posted_image"
            android:scaleType="centerCrop"
            android:adjustViewBounds="true"
            android:src="@color/Orange"
            />

        <TextView
            android:text="Post Title..."
            android:padding="15dp"
            android:textSize="16dp"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/posted_title"/>

        <TextView
            android:text="Summary..."
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingBottom="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLength="300"
            android:maxLines="5"
            android:id="@+id/posted_sharing"/>



    </LinearLayout>

</LinearLayout>
</android.support.v7.widget.CardView>

这就是数据库在Firebase中的样子

{
  "Users" : {
    "1" : {
      "image" : "http://something.com/something",
      "name" : "person 1"
    },
    "2" : {
      "image" : "http://someone.com/someone",
      "name" : "person 2"
    }
  },
  "posts" : {
    "post 1" : {
      "content" : "test content 1",
      "dPicture" : "http://something.com/something",
      "picture" : "http://postimage.com/postimage",
      "title" : "test title 1",
      "uid" : 1,
      "username" : "person 1"
    },
    "post 2" : {
      "content" : "test content 2",
      "dPicture" : "http://someone.com/someone",
      "picture" : "http://postimage2.com/postimage2",
      "title" : "test title 2",
      "uid" : 2,
      "username" : "person 2"
    }
  }
}

活动代码是

public class MainActivity extends AppCompatActivity {

    private RecyclerView mPostedList;
    private LinearLayoutManager mLayoutManager;
    private DatabaseReference mDatabaseSharings;
    private FirebaseAuth mAuth;
    private FirebaseUser mCurrentUser;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference mDatabaseUsers;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mAuth = FirebaseAuth.getInstance();
        mDatabaseSharings = FirebaseDatabase.getInstance().getReference().child("posts");
        mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
        mCurrentUser = mAuth.getCurrentUser();
        mDatabaseSharings.keepSynced(true);

final String uid = mCurrentUser.getUid();


        //bring user to login activity when auth-state is null

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() == null) {
                    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                }
            }
        };




//keep users logged in
        mDatabaseUsers.keepSynced(true);

        mPostedList = (RecyclerView) findViewById(R.id.posted_list);
        mPostedList.setHasFixedSize(true);
        mPostedList.setLayoutManager(new LinearLayoutManager(this));

    }


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


        mAuth.addAuthStateListener(mAuthListener);

        //your adapter
        FirebaseRecyclerAdapter<PostedModel, PostedModelViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<PostedModel, PostedModelViewHolder>(

                PostedModel.class, R.layout.posted_row, PostedModelViewHolder.class, mDatabaseSharings
        ) {
            @Override
            protected void populateViewHolder(PostedModelViewHolder viewHolder, PostedModel model, int position) {


                        viewHolder.setTitle(model.getTitle());
                        viewHolder.setDPicture(getApplicationContext(), model.getDPicture());
                        viewHolder.setSummary(model.getSummary());
                        viewHolder.setImage(getApplicationContext(), model.getImage());
                        viewHolder.setUsername(model.getUsername());


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





                viewHolder.mView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {

                        Intent delete_intent = new Intent(MainActivity.this, DeleteActivity.class);
                        delete_intent.putExtra("blog_id", post_key);
                        startActivity(delete_intent);
                        return false;
                    }
                });
                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent comment_intent = new Intent (MainActivity.this, CommentActivity.class);
                        comment_intent.putExtra("blog_id", post_key);
                        startActivity(comment_intent);
                    }
                });


            }
        };
        mPostedList.setAdapter(firebaseRecyclerAdapter);
        mLayoutManager = new LinearLayoutManager(MainActivity.this);
        mLayoutManager.setReverseLayout(true);
        mLayoutManager.setStackFromEnd(true);
        mPostedList.setLayoutManager(mLayoutManager);


    }

    public static class PostedModelViewHolder extends RecyclerView.ViewHolder{



        View mView;

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





            mView = itemView;
        }

        public void setTitle(String title){


    TextView post_title = (TextView)mView.findViewById(R.id.posted_title);
            post_title.setText(title);
        }
        public void setDPicture(Context ctx, String dPicture){

            ImageView post_dPicture = (ImageView) mView.findViewById(R.id.dPicture);
            Picasso.with(ctx).load(dPicture).into(post_dPicture);
        }


        public void setSummary (String summary){

            TextView post_summary = (TextView)mView.findViewById(R.id.posted_sharing);
            post_summary.setText(summary);
        }
        public void setImage(Context ctx, String image){
           ImageView post_image = (ImageView) mView.findViewById(R.id.posted_image);
            Picasso.with(ctx).load(image).into(post_image);


        }
        public void setUsername (String username){
           TextView post_username = (TextView)mView.findViewById(R.id.posted_username);
            post_username.setText(username);
        }

    }


}

当然有PostedModel.class,它是getters和setters类

public class PostedModel {
    private String title;
    private String summary;
    private String image;
    private String dPicture;


    private String username;

    public PostedModel(){}

    public PostedModel(String title, String summary, String image) {
        this.title = title;
        this.summary = summary;
        this.image = image;
        this.dPicture = dPicture;
        this.username = username;
    }
    public String getDPicture() {
        return dPicture;
    }

    public void setDPicture(String dPicture) {this.dPicture = dPicture;}

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {this.title = title;}

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getUsername() {
        return username;
    }

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

}

现在您可以看到我有一个发布活动,它既传递了用户名,又传递了来自&#34;用户&#34;的图像值。数据库到&#34;帖子&#34;数据库子(dPicture)。但是,当用户更新他/她的用户名时,只有来自&#34;用户&#34;数据库已更改,而不是来自现有的&#34;帖子&#34;

我认为最有效的方法是使用来自两个数据库引用的数据填充视图,使用用户的唯一ID连接两者,这是&#34;用户&#34;数据库和作为孩子(uid)的&#34;帖子&#34;数据库,但我不知道该怎么做...我附上数据库截图的快照,用盒子来说明万一我用我的低级技术语言让人困惑

here

因此,目标是获取红色盒装数据并将其与绿色盒装数据配对。

非常感谢所有人的帮助!

修改 我不知道我是否正确地使用了这个...所以在研究之后,我认为正确的方法是使用valueEventListener为我想要从适配器类中获取数据的数据库。

到目前为止我得到了这个

FirebaseRecyclerAdapter<PostedModel, PostedModelViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<PostedModel, PostedModelViewHolder>(

                PostedModel.class, R.layout.posted_row, PostedModelViewHolder.class, mDatabaseSharings
        ) {
            //calling the value from the Summary.java class
            @Override
            protected void populateViewHolder(final PostedModelViewHolder viewHolder, final PostedModel model, final int position) {
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.getKey().toString() == mDatabaseSharings.child("uid").toString()){
        viewHolder.setUsername(model.getUsername());
        viewHolder.setDPicture(getApplicationContext(), model.getDPicture());
    }

        viewHolder.setTitle(model.getTitle());
        viewHolder.setSummary(model.getSummary());
        viewHolder.setImage(getApplicationContext(), model.getImage());

    }


    @Override
    public void onCancelled(DatabaseError databaseError) {

    }

});

但我得到的是钥匙,而不是通过哈哈的价值

1 个答案:

答案 0 :(得分:0)

尝试创建两个数组列表说ArrayList abc,def。然后,从Users节点获取数据后,写入分配用户名和图像,如abc.username。在此之后,从Posts节点获取数据并对其余数据执行相同的操作。然后在两个函数结束时,写入def.add(abc);我认为这应该可以胜任。