如何在对象Firebase实时数据库的数据之间执行实时搜索

时间:2020-02-26 19:04:26

标签: android firebase firebase-realtime-database

我想知道如何在对象内部执行实时搜索。

下面有JSON代码。因此,我想这样做:我想在对象-M11-OIIHbKTVqCJ-Swv内部执行实时搜索。如果我在搜索字段中输入以下单词:Abilify数据库将给我结果(我是说它将把数据发送给我)。

JSON代码:

"Places" : {
"-M11-OIIHbKTVqCJ-Swv" : {
  "name" : "Farmacia Pagani Dr. Roberto",
  "others" : {
    "Abilify" : 100,
    "Acetaminophen" : 120,
    "Acyclovir" : 140,
    "Adderall" : 160
  }
},
"-M11-OJJCGAPdJUknLXX" : {
  "name" : "FARMACIA DR. TUMIATTI MARIANO",
  "others" : {
    "Abilify" : 100,
    "Acetaminophen" : 120,
    "Acyclovir" : 140,
    "Adderall" : 160
  }
}

如果我的名字是:Farmacia Pagani Roberto Dr. Roberto,我想检索M11-OIIHbKTVqCJ-Swv“

我写的代码:

    package com.example.ipill;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.FirebaseError;
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.Query;
import com.google.firebase.database.ValueEventListener;


public class FirebaseSearch extends AppCompatActivity {

    private EditText mSearchField;
    private ImageButton mSearchBtn;
    private ImageButton AddToCart;
    private Button Cart;
    private String nameOfThePharmacy;
    private String keyNameOfFarmacy;
    String searchText="";

    private RecyclerView mResultList;
    private DatabaseReference mUserDatabase;





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

        Intent intent = getIntent();
        nameOfThePharmacy = intent.getStringExtra("Name");
        System.out.println("This is the name of the pharmacy that you have clicked on"+nameOfThePharmacy);
        mUserDatabase = FirebaseDatabase.getInstance().getReference("Places");

        mSearchField = findViewById(R.id.search_field);
        mSearchBtn = findViewById(R.id.search_btn);
        mResultList = findViewById(R.id.result_list_cart);
        AddToCart = findViewById(R.id.imageButton2);
        Cart = findViewById(R.id.GoToCart);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));


        Query query = mUserDatabase.orderByChild("name").equalTo(nameOfThePharmacy);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
                                                 @Override
                                                 public void onDataChange(DataSnapshot dataSnapshot) {
                                                     for (DataSnapshot studentSnapshot: dataSnapshot.getChildren()) {
                                                        keyNameOfFarmacy=studentSnapshot.getKey();
                                                     }
                                                     mUserDatabase.child(keyNameOfFarmacy).child("others").addValueEventListener(new ValueEventListener() {
                                                         @Override
                                                         public void onDataChange(DataSnapshot snapshot) {
                                                             try {
                                                                 if (snapshot.getValue() != null) {
                                                                     try {
                                                                         System.out.println("This are the medicines of that specific pharmacy" + snapshot.getValue()); // your name values you will get here
                                                                     } catch (Exception e) {
                                                                         e.printStackTrace();
                                                                     }
                                                                 } else {
                                                                     Log.e("TAG", " it's null.");
                                                                 }
                                                             } catch (Exception e) {
                                                                 e.printStackTrace();
                                                             }
                                                         }

                                                         @Override
                                                         public void onCancelled(@NonNull DatabaseError databaseError) {
                                                             throw databaseError.toException();
                                                         }
                                                     });
                                                 }

                                                 @Override
                                                 public void onCancelled(DatabaseError databaseError) {
                                                     throw databaseError.toException();
                                                 }
                                             });
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchText = mSearchField.getText().toString();
                firebaseUserSearch(searchText);
            }
        });



        Cart.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                Intent itent = new Intent(FirebaseSearch.this, CartActivity.class);
                startActivity(itent);
            }
        });


    }

    private void firebaseUserSearch(String searchText) {
        Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
        Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText).endAt(searchText + "\uf8ff");
        FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                Users.class,
                R.layout.list_layout,
                UsersViewHolder.class,
                firebaseSearchQuery
        ) {
            @Override
            protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {

                viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
                viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
            }
        };
        mResultList.setAdapter(firebaseRecyclerAdapter);
    }


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

    // View Holder Class
    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;
        String Name;
        String Surname;
        Long Price;
        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);

            addToCart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FirebaseDatabase database = FirebaseDatabase.getInstance();
                    DatabaseReference myRef = database.getReference("Cart");
                    myRef.push().setValue(new Users(Name,Surname,Price));

                }
            });
        }

        public void getDetails(String name,String cognome,Long price){
            Name=name;
            Surname=cognome;
            Price=price;
        }


        public void setDetails(String Name, String Surname, Long Price) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
            TextView user_price = (TextView)mView.findViewById(R.id.price);

            user_name.setText(Name);
            user_surname.setText(Surname);
            user_price.setText(Long.toString(Price));

        }
    }




}

问题在于它返回:E / TAG:它为空。

我不了解如何在特定对象内执行实时搜索。我知道如何使用整个数据集执行实时搜索,但暂时没有帮助。

0 个答案:

没有答案