【问题标题】:Getting values from multiple Firebase database references in one cardView在一个 cardView 中从多个 Firebase 数据库引用中获取值
【发布时间】:2017-03-02 01:10:06
【问题描述】:

我正在开发一个应用程序,该应用程序需要我从一个卡片视图中的两个 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,它是它的 getter 和 setter 类

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;
    }

}

现在你可以看到我有一个发布活动,它将用户名和图像值从“用户”数据库传递到“帖子”数据库子 (dPicture)。但是,当用户更新他/她的用户名时,只会更改“用户”数据库中的值,而不更改现有“帖子”中的值

我认为最有效的方法是使用来自两个数据库引用的数据填充查看器,使用用户的唯一 ID 连接两者,该 ID 是“用户”数据库中的键,并且作为子 (uid) 在“帖子”数据库,但我不知道该怎么做……我附上了带有方框的数据库屏幕截图的快照,以防我用我的技术语言使人们感到困惑

所以目标是获取红框数据并将其与绿框数据配对。

非常感谢您事先提供的所有帮助!

编辑: 我不知道我是否走在正确的轨道上...所以在研究之后我认为正确的方法是使用 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) {

    }

});

但我得到的是密钥而不是传递的值哈哈

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 嗨@Ambuj 感谢您的评论。嗯,我认为我应该使用 valueEventListener,因为这似乎是其他人的做法......我只是不知道如何正确实现它......
    • 我在这里尝试这样做,但它不起作用:stackoverflow.com/questions/55259345/…
    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多