Firestore Android中的多个交易

时间:2018-08-21 12:33:45

标签: android google-cloud-firestore

  

我正在尝试从Firestore提取问题的详细信息。必须从different collections获取数据。我有

questionCollection -(questionID,titleOfQuestion,用户ID等);

评论集合-(评论ID,问题ID,用户ID);

questionLikeCollection -((questionID,userID)

QuestionDetailActivity.class

public class QuestionDetailActivity extends AppCompatActivity {

    private static final String TAG = "QuestionDetailActivity";
    private Context mContext;
    private TextView questionTitleTv;
    private RadioGroup radioLL;
    private EditText answerEt;
    private LinearLayout checkboxLL;
    private LinearLayout commentLL;

    private FirebaseFirestore db = null;
    private String questionID;

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

        mContext = QuestionDetailActivity.this;
        db = FirebaseFirestore.getInstance();

        questionTitleTv = findViewById(R.id.tv_question_title);
        radioLL = findViewById(R.id.ll_radio);
        answerEt = findViewById(R.id.et_answer);
        checkboxLL = findViewById(R.id.ll_checkbox);
        commentLL = findViewById(R.id.ll_comments);

        if (getIntent() != null) {
            questionID = getIntent().getExtras().getString("keyQuestionID", "");
        }
        if (!questionID.isEmpty()) {
            getQuestionDetail(questionID);
            showComments(questionID);
            showLike(questionID);
        }
    }

    private void showLike(String questionID) {
        DocumentReference docRef = db.collection("questionLikeCollection").document(questionID);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        // highlight like button...
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    }

    private void showComments(String questionID) {
        db.collection("commentCollection").whereEqualTo("questionID", questionID)
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        if (queryDocumentSnapshots.isEmpty()) {
                            Log.d(TAG, "onSuccess: LIST EMPTY");
                            return;
                        } else {
                            // Convert the whole Query Snapshot to a list
                            // of objects directly! No need to fetch each
                            // document.
                            List<CommentBO> commentList = queryDocumentSnapshots.toObjects(CommentBO.class);

                            if (commentList != null && commentList.size() > 0) {
                                for (int x = 0; x < commentList.size(); x++) {
                                    try {
                                        LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                                LinearLayout.LayoutParams.WRAP_CONTENT);

                                        childParam.setMargins(20, 10, 0, 0);
                                        View commentByView = LayoutInflater.from(mContext).inflate(R.layout.item_comment, null);
                                        TextView tvCommenter = (TextView) commentByView.findViewById(R.id.item_tv_commenter_name);
                                        TextView tvCommenterComment = (TextView) commentByView.findViewById(R.id.item_tv_commenter_comment);
                                        TextView tvCommentDate = (TextView) commentByView.findViewById(R.id.item_tv_comment_date);

                                        tvCommenter.setText(commentList.get(x).getCommentedBy());
                                        tvCommenterComment.setText(commentList.get(x).getComment());

                                        ///tvCommentDate.setText();
                                        commentLL.addView(commentByView, childParam);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                });
    }

    private void getQuestionDetail(String questionID) {
        DocumentReference docRef = db.collection("questionCollection").document(questionID);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Log.d(TAG, "DocumentSnapshot data: " + document.getData());
                        QuestionBO questionBO = document.toObject(QuestionBO.class);
                        updateView(questionBO);
                    } else {
                        Log.d(TAG, "No such document");
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
    }

    private void updateView(QuestionBO mQuestionBO) {
        if (mQuestionBO != null) {
            questionTitleTv.setText(mQuestionBO.getTitle());

            switch (mQuestionBO.getQuestionType()) {
                case CHECKBOX:
                    checkboxLL.setVisibility(View.VISIBLE);
                    if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
                        checkboxLL.removeAllViews();

                        for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {
                            final CheckBox subCheckbox = new CheckBox(mContext);
                            subCheckbox.setText(mQuestionBO.getOptions().get(x));
                            subCheckbox.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            });

                            checkboxLL.addView(subCheckbox, new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        }
                    }
                    break;
                case RADIO:
                    radioLL.setVisibility(View.VISIBLE);
                    if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
                        radioLL.removeAllViews();

                        for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {

                            final RadioButton subRadio = new RadioButton(mContext);
                            subRadio.setText(mQuestionBO.getOptions().get(x));
                            radioLL.addView(subRadio, new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        }
                    }
                    break;
                case DESCRIPTIVE:
                    answerEt.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }
}

activity_question_detail.xml

<?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="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".QuestionDetailActivity">

    <TextView
        android:id="@+id/tv_question_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Hello I am a question"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <LinearLayout
        android:id="@+id/ll_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone" />

    <RadioGroup
        android:id="@+id/ll_radio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone" />

    <EditText
        android:id="@+id/et_answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/like_it"
            android:drawablePadding="8dp"
            android:gravity="center"
            android:src="@drawable/like_it"
            android:text="33"
            android:textSize="18sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:drawableLeft="@drawable/like_it"
            android:drawablePadding="8dp"
            android:gravity="center"
            android:src="@drawable/like_it"
            android:text="33"
            android:textSize="18sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:drawableLeft="@drawable/like_it"
            android:drawablePadding="8dp"
            android:gravity="center"
            android:src="@drawable/like_it"
            android:text="33"
            android:textSize="18sp" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/ll_comments"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"></LinearLayout>
</LinearLayout>

我想显示问题的详细信息,就像stackoverflow 一样。如问题标题,喜欢,收藏,评论,用户名。每个数据都在单独的集合中。我如何在一次交易中称呼它。以及如何减少来自Firestore的读取次数。

0 个答案:

没有答案