Как добавить поисковые фильтры в Android на основе базы данных Firebase в реальном времени? - PullRequest
0 голосов
/ 05 сентября 2018

Я создаю приложение, которое просит пользователя зарегистрировать свое имя, адрес электронной почты, номер телефона и группу крови.

Ниже представлена ​​структура моей базы данных Firebase:

enter image description here

и мой скриншот приложения enter image description here

Как добавить строку поиска или фильтры, отображаемые в соответствии с ключом типа крови, чтобы пользователь мог фильтровать в соответствии с типом крови. Если мне потребуется B отрицательная кровь ... Я буду использовать выпадающее меню для крови, которое мне нужно искать, и при нажатии на кнопку поиска будет отображаться только группа крови, зарегистрированная как отрицательная B в базе данных Firebase, то есть в соответствии с ключом blood_group .

Вот мой код, который я использую для загрузки информации о пользователе:

public class EnquiryActivity extends AppCompatActivity {

    //UI
    Button btnRequest;
    EditText edtName,edtBlood,edtPlace,edtMobile,edtEmail;
    //DB
    DatabaseReference mHelper;
    FirebaseAuth mAuth;
    //progress
    ProgressDialog mProgress;
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enquiry);
        //initialisation
        edtBlood=(EditText)findViewById(R.id.enq_blood);
        edtMobile=(EditText)findViewById(R.id.enq_mobile);
        edtEmail=(EditText)findViewById(R.id.enq_email);
        edtName=(EditText)findViewById(R.id.enq_name);
        edtPlace=(EditText)findViewById(R.id.enq_place);
        btnRequest=(Button)findViewById(R.id.button2);
        //firebase
        mHelper= FirebaseDatabase.getInstance().getReference();
        final String mCurrentUser=FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
        mAuth=FirebaseAuth.getInstance();
        //progress
        mProgress=new ProgressDialog(this);
        mProgress.setTitle("Loading");
        mProgress.setMessage("Please wait..");

        btnRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProgress.show();
                String blood=edtBlood.getText().toString();
                String name=edtName.getText().toString();
                String mobile=edtMobile.getText().toString();
                String email=edtEmail.getText().toString();
                String  place=edtPlace.getText().toString();
                String temp=blood.toUpperCase();
                if(!TextUtils.isEmpty(blood)||!TextUtils.isEmpty(name)||!TextUtils.isEmpty(mobile)||
                        !TextUtils.isEmpty(place)){

                        HashMap<String, String> userMap = new HashMap<>();
                        userMap.put("name", name);
                        userMap.put("blood_group",blood);
                        userMap.put("email", email);
                        userMap.put("mobile", mobile);
                        userMap.put("place","Location:- " + place);

                        mHelper.child("Help").child(mCurrentUser).setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                mProgress.dismiss();
                                Toast.makeText(getApplicationContext(), "Registered Successfully..!", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                        });

            }else{
                    Toast.makeText(getApplicationContext(),"Please enter the details in all fields",Toast.LENGTH_LONG).show();
                }
            }
        });


    }
}

и я получаю данные, используя код ниже

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

    private RecyclerView mDonorList;

    private DatabaseReference mFriendsDatabase;
    private DatabaseReference mUsersDatabase;

    private FirebaseAuth mAuth;
    private ProgressDialog mDonorProgress;

    private String mCurrent_user_id;

    private View mMainView;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMainView = inflater.inflate(R.layout.fragment_donor_list, container, false);

        mDonorList = (RecyclerView)mMainView.findViewById(R.id.donor_recyclerview);
        mAuth = FirebaseAuth.getInstance();
        mCurrent_user_id = mAuth.getCurrentUser().getUid();

        mDonorProgress=new ProgressDialog(getContext());

        mDonorProgress.setTitle("Logging In");
        mDonorProgress.setMessage("Please Wait...");
        mDonorProgress.setCanceledOnTouchOutside(false);
        mDonorProgress.show();

        mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
        mUsersDatabase.keepSynced(true);


        mDonorList.setHasFixedSize(true);
        LinearLayoutManager linearVertical = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
       mDonorList.setLayoutManager(linearVertical);

        DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(
                mDonorList.getContext(),
                linearVertical.getOrientation()
        );
        mDonorList.addItemDecoration(mDividerItemDecoration);


        // Inflate the layout for this fragment
        return mMainView;
    }


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

        FirebaseRecyclerAdapter<Donors, DonorsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Donors, DonorsViewHolder>(

                Donors.class,
                R.layout.users_single_layout,
                DonorsViewHolder.class,
                mUsersDatabase


        ) {
            @Override
            protected void populateViewHolder(final DonorsViewHolder donorsViewHolder, Donors donors, int i) {

                donorsViewHolder.setDate(donors.getDate());

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

                mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        final String userName = dataSnapshot.child("name").getValue().toString();
                        String blood=dataSnapshot.child("blood_group").getValue().toString();
                        String phone=dataSnapshot.child("mobile").getValue().toString();
                        final String email=dataSnapshot.child("email").getValue().toString();
                        String address=dataSnapshot.child("place").getValue().toString();
                        mDonorProgress.hide();

                        donorsViewHolder.setName(userName);
                        donorsViewHolder.setBlood(blood);
                        donorsViewHolder.setEmail(email);
                        donorsViewHolder.setAddress(address);
                        donorsViewHolder.setPhone(phone);
                        final String uri=phone;

                        donorsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                                CharSequence options[] = new CharSequence[]{"Email", "Call"};

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

                                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 intent = new Intent(Intent.ACTION_SEND);
                                            intent.setType("plain/text");
                                            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
                                            intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
                                            intent.putExtra(Intent.EXTRA_TEXT, "mail body");
                                            getActivity().startActivity(Intent.createChooser(intent, ""));

                                        }

                                        if(i == 1){
                                          Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+uri));
                                            // callIntent.setData(Uri.parse("tel:"+uri));
                                            callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            getActivity().startActivity(callIntent);

                                        }

                                    }
                                });

                                builder.show();

                            }
                        });


                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }
        };

        mDonorList.setAdapter(friendsRecyclerViewAdapter);


    }

    // viewholder class..

    public static class DonorsViewHolder extends RecyclerView.ViewHolder {
        View mView;
        public DonorsViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }
        public void setBlood(String blood){
            TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_blood);
            userStatusView.setText(blood.toUpperCase());
        }
        public void setName(String name){

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

        public void setEmail(String email){

            TextView userNameView = (TextView) mView.findViewById(R.id.user_single_email);
            userNameView.setText(email);
        }
        public void setPhone(String phone){

            TextView userNameView = (TextView) mView.findViewById(R.id.user_single_phone);
            userNameView.setText(phone);
        }
        public void setAddress(String address) {

            TextView userNameView = (TextView) mView.findViewById(R.id.user_single_address);
            address.toUpperCase();
            userNameView.setText(address.toUpperCase());
        }
        public void setDate(String date){


        }
    }

}

Извините, если я что-то пропустил. Я добавлю, как вам требуется. Любая помощь приветствуется. Заранее спасибо.

1 Ответ

0 голосов
/ 05 сентября 2018

Чтобы достичь желаемого, вам нужно выполнить запрос, который должен выглядеть следующим образом:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query query = usersRef.orderByChild("blood_group").equalTo("Blood Group: " +  newText);

, в котором переменная newText может содержать любое значение, которое вы хотите, B positive, а также B negative.

Таким образом, каждый раз, когда вы создаете поиск, вы должны возвращать новый запрос. Таким образом, в соответствии с этим, каждый раз, когда вы хотите фильтровать новое условие, вам необходимо:

  1. Создание нового запроса на основе нового фильтра:

    Query query = usersRef.orderByChild("blood_group").equalTo("Blood Group: " +  newText);
    
  2. Присоедините слушателя к этому новому созданному запросу.

  3. Создайте новый адаптер с результатами этого нового созданного запроса или обновите существующий, используя метод notifydatasetchanged().

...