在RecyclerView中选择项目从Firebase获取唯一键

时间:2017-10-01 08:14:02

标签: java android firebase android-recyclerview

我想知道如何在自定义RecyclerView中选择项目时从Firebase获取Key。这是我的情景。

  • MainActivity(包含片段)显示自定义RecyclerView(1图像+3文本)。
  • 点击一个项目后,在活动中显示详细信息(在可编辑模式下:表示用户想要编辑或删除此项目)。我在一个位置读取数据并通过捆绑发送。
  • 问题是我不知道如何获取该订单项的uniqueKey,因为我需要将其更新回firebase数据库,或者在用户决定时将其删除。

Firebase Image Here

enter image description here

我的代码如下:

    package com.abc.personalexpensestracker;

   import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    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.ValueEventListener;
    import com.squareup.picasso.Picasso;

    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.LinkedHashSet;

    import de.hdodenhof.circleimageview.CircleImageView;
    import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;
    import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
    import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection;


    /**
     * A simple {@link Fragment} subclass.
     */
    public class CurrentmonthFragment extends Fragment {

        private SectionedRecyclerViewAdapter mSectionAdapter; 

        private FloatingActionButton mCurrMonthAddFab;

        private RecyclerView mTransactionsList;
        private DatabaseReference mUsersTransactionsDatabase;

        private FirebaseAuth mAuth;
        private FirebaseUser mCurrUser;

        private ArrayList<TransactionsData transactionsListViewValuesArr =null;

        private int mYear, mMonth, mDay;


        public CurrentmonthFragment() {
            // Required empty public constructor
        }

        @Override
        public void onResume() {
            super.onResume();


            mTransactionsList.setLayoutManager(new LinearLayoutManager(getContext()));
            //mTransactionsList.setHasFixedSize(true);
            mSectionAdapter = new SectionedRecyclerViewAdapter(); 

            //// Set data in arraylist
            transactionsListViewValuesArr = new ArrayList<TransactionsData();
            setTransactionsListData();

            mUsersTransactionsDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    //check if there are categories with current user ID
                    if(dataSnapshot.exists()){

                        LinkedHashSet<String uniqueSetDate = new LinkedHashSet<String();

                        //first get unique Date from database
                        for (DataSnapshot data : dataSnapshot.getChildren()) {

                            uniqueSetDate.add(data.child("datetime").getValue().toString());

                        }

                        //Bind recyclerView by Section, group by date
                        for(String sDate : uniqueSetDate) {
                            String sDatetime =sDate;
                            ArrayList<TransactionsData transactionsPerDay = getTransactionsPerDay(sDate, transactionsListViewValuesArr);
                            if (transactionsPerDay.size()  0) {
                                mSectionAdapter.addSection(new TransactionsSection(String.valueOf(sDatetime), transactionsPerDay));
                            }
                            mTransactionsList.setAdapter(mSectionAdapter);
                        }

                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_currentmonth, container, false);


            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            mAuth = FirebaseAuth.getInstance();
            mCurrUser = mAuth.getCurrentUser();
            mUsersTransactionsDatabase = FirebaseDatabase.getInstance().getReference().child("users_transactions").child(mCurrUser.getUid()).child("by_year").child(String.valueOf(mYear)).child(String.valueOf(mMonth));


            mCurrMonthAddFab = (FloatingActionButton) view.findViewById(R.id.current_month_add_fab);
            mCurrMonthAddFab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent newTransactionIntent = new Intent(getActivity(),AddNewTransaction.class);
                    startActivity(newTransactionIntent);

                }
            });


            mTransactionsList= (RecyclerView)view.findViewById(R.id.ListView_Curr_Transactions);


            return view;

        }


        public static class TransactionsViewHolder extends RecyclerView.ViewHolder{

            View mView;

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

                mView = itemView;
            }

            public  void setTransactCat(String name){
                TextView categoryName = (TextView) mView.findViewById(R.id.txt_TransSingle_CatName);
                categoryName.setText(name);
            }

            public void setTransactCatImage(String image, Context ctx){
                CircleImageView catImageView= (CircleImageView) mView.findViewById(R.id.img_TransSingle_Cat);
                Picasso.with(ctx).load(image).placeholder(R.mipmap.question_circular_button).into(catImageView);

            }
            public  void setTransactDate(String transactDate){
                TextView categoryName = (TextView) mView.findViewById(R.id.txt_TransSingle_Date);
                categoryName.setText(transactDate);
            }

            public  void setTransactAmount(Double transactAmount){
                TextView categoryName = (TextView) mView.findViewById(R.id.txt_TransSingle_Amt);
                if (!Double.isNaN(transactAmount)){
                    categoryName.setText(transactAmount.toString());
                }
            }

        }


        private ArrayList<TransactionsData getTransactionsPerDay(String date, ArrayList<TransactionsData transactionsList) {
            ArrayList<TransactionsData transactions = new ArrayList<TransactionsData();

            for(int i = 0; i < transactionsList.size(); i++) {
                //System.out.println(transactionsListViewValuesArr.get(i)); //prints element i
                TransactionsData transaction = transactionsList.get(i);
                if (transaction.getDatetime().equals(date)) {
                    transactions.add(transaction);
                }
            }

            return transactions;
        }



        private class TransactionsSection extends StatelessSection {

            String title;
            ArrayList<TransactionsData alist;

            TransactionsSection(String title, ArrayList<TransactionsData list) {
                super(new SectionParameters.Builder(R.layout.transactions_single_layout)
                        .headerResourceId(R.layout.transactions_section_header)
                        .build());

                this.title = title;
                this.alist = list;
            }

            @Override
            public int getContentItemsTotal() {
                return alist.size();
            }

            @Override
            public RecyclerView.ViewHolder getItemViewHolder(View view) {
                return new TransactionsViewHolder(view);
            }

            @Override
            public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
                final TransactionsViewHolder itemHolder = (TransactionsViewHolder) holder;


                final TransactionsData tData = alist.get(position);

                itemHolder.setTransactDate(tData.getDatetime());
                itemHolder.setTransactCat(tData.getCategory());
                itemHolder.setTransactAmount(tData.getAmount());


                itemHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(), String.format("Clicked on position #%s of Section %s", mSectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show();

                        Intent editTransactionIntent = new Intent(getActivity(),EditExistingTransaction.class);
                        Bundle transactionBundle = new Bundle();
                        transactionBundle.putDouble("selected_amount",tData.getAmount());
                        transactionBundle.putString("selected_catType",tData.getCategory_type());
                        transactionBundle.putString("selected_catName",tData.getCategory());
                        transactionBundle.putString("selected_date",tData.getDatetime());
                        transactionBundle.putString("selected_note",tData.getNotes());
                        editTransactionIntent.putExtras(transactionBundle);
                        startActivity(editTransactionIntent);
                    }
                });
            }

            @Override
            public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
                return new HeaderViewHolder(view);
            }

            @Override
            public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
                HeaderViewHolder headerHolder = (HeaderViewHolder) holder;

                headerHolder.tvTitle.setText(title);
            }
        }


        private class HeaderViewHolder extends RecyclerView.ViewHolder {

            private final TextView tvTitle;

            HeaderViewHolder(View view) {
                super(view);

                tvTitle = (TextView) view.findViewById(R.id.txt_transaction_header_date);
            }
        }


        /****** Function to set data in ArrayList *************/
        public void setTransactionsListData()
        {

            //transactionsListViewValuesArr.add(new TransactionsData(5.5,"default","default","default","default"));

            mUsersTransactionsDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    for(DataSnapshot categorySnapshot: dataSnapshot.getChildren()){
                        String transactionCat = categorySnapshot.child("category").getValue(String.class);
                        String transactionDate = categorySnapshot.child("datetime").getValue(String.class);
                        Double transactionAmt = categorySnapshot.child("amount").getValue(Double.class);
                        String transactionCatType = categorySnapshot.child("category_type").getValue(String.class);
                        String transactionNote = categorySnapshot.child("notes").getValue(String.class);

                        final TransactionsData transactionsData = new TransactionsData();
                        /******* Firstly take data in model object ******/
                        transactionsData.setCategory(transactionCat);
                        transactionsData.setDatetime(transactionDate);
                        transactionsData.setAmount(transactionAmt);
                        transactionsData.setCategory_type(transactionCatType);
                        transactionsData.setNotes(transactionNote);


                        /******** Take Model Object in ArrayList **********/
                        transactionsListViewValuesArr.add(transactionsData);
                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }

            });

        }

    }

1 个答案:

答案 0 :(得分:0)

使用代码在dataSnapshot

中存储ArrayList中的所有键
HashMap<String, Object> allData = (HashMap<String, Object>) dataSnapshot.getValue();
String[] allKey = allData.keySet().toArray(new String[0]);

您还可以在循环运行时获取密钥

for (DataSnapshot data : dataSnapshot.getChildren()) {

                        String key = data.getKey();

                    }