Search code examples
androidfirebaseandroid-recyclerviewandroid-search

Set a search view for a recycler view from firebase database


I am creating a application in which i've used a recyclerview to get the content from the firebase and i want to add a search view. My Main activity page is

public class MainActivity extends AppCompatActivity {

// Creating DatabaseReference.
DatabaseReference databaseReference;

// Creating RecyclerView.
RecyclerView recyclerView;

// Creating RecyclerView.Adapter.
RecyclerView.Adapter adapter ;

// Creating Progress dialog
ProgressDialog progressDialog;

// Creating List of ImageUploadInfo class.
List<ImageUploadInfo> list = new ArrayList<>();


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

    // Assign id to RecyclerView.
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    // Setting RecyclerView size true.
    recyclerView.setHasFixedSize(true);

    // Setting RecyclerView layout as LinearLayout.
    recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

    // Assign activity this to progress dialog.
    progressDialog = new ProgressDialog(MainActivity.this);

    // Setting up message in Progress dialog.
    progressDialog.setMessage("Loading Images From Firebase.");

    // Showing progress dialog.
    progressDialog.show();

    // Setting up Firebase image upload folder path in databaseReference.
    // The path is already defined in MainActivity.
    databaseReference = FirebaseDatabase.getInstance().getReference("Hostel");

    // Adding Add Value Event Listener to databaseReference.
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            List<ImageUploadInfo> list = new ArrayList<>();

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getApplicationContext(), list);

            recyclerView.setAdapter(adapter);

            // Hiding the progress dialog.
            progressDialog.dismiss();
        }




        @Override
        public void onCancelled(DatabaseError databaseError) {

            // Hiding the progress dialog.
            progressDialog.dismiss();

        }
    });

}
}

My recyclerViewAdapter is:

public class RecyclerViewAdapter extends 
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

Context context;
List<ImageUploadInfo> MainImageUploadInfoList;

public RecyclerViewAdapter(Context context, List<ImageUploadInfo> TempList) {

    this.MainImageUploadInfoList = TempList;

    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);

    ViewHolder viewHolder = new ViewHolder(view);





    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    ImageUploadInfo UploadInfo = MainImageUploadInfoList.get(position);

    holder.imageNameTextView.setText(UploadInfo.getName() );
    holder.email.setText(UploadInfo.getEmail());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Context context = view.getContext();
            Intent intent = new Intent(context, Main2Activity.class);
            intent.putExtra("name", holder.imageNameTextView.getText().toString());
            context.startActivity(intent);
        }
    });


    //Loading image from Glide library.
    Glide.with(context).load(UploadInfo.getImageAddress()).into(holder.imageView);
}



@Override
public int getItemCount() {

    return MainImageUploadInfoList.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    public ImageView imageView;
    public TextView imageNameTextView;
    public TextView email;

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

        imageView = (ImageView) itemView.findViewById(R.id.imageView);

        email = (TextView) itemView.findViewById(R.id.Email);

        imageNameTextView = (TextView) 
itemView.findViewById(R.id.ImageNameTextView);
    }
}
}

This is firebase date structure

This is my custom class

public class ShowImages extends AppCompatActivity {

DatabaseReference databaseReference;
String name_global;
ImageView one,two,three,four;

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

    Bundle bundle = getIntent().getExtras();
    final String name = bundle.getString("key").toString();

    databaseReference = FirebaseDatabase.getInstance().getReference("Hostel");

    one = (ImageView) findViewById(R.id.one);
    two = (ImageView) findViewById(R.id.two);
    three = (ImageView) findViewById(R.id.three);
    four = (ImageView) findViewById(R.id.four);



    ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            name_global = dataSnapshot.child(name).child("name").getValue().toString();
            String temp_email = dataSnapshot.child(name).child("email").getValue().toString();


            String photoUrl = dataSnapshot.child(name).child("imageAddress").getValue(String.class);
            Glide.with(ShowImages.this).load(photoUrl).into(one);

            String photoUrl1 = dataSnapshot.child(name).child("image2Address").getValue(String.class);
            Glide.with(ShowImages.this).load(photoUrl1).into(two);

            String photoUrl2 = dataSnapshot.child(name).child("image3Address").getValue(String.class);
            Glide.with(ShowImages.this).load(photoUrl2).into(three);

            String photoUrl3 = dataSnapshot.child(name).child("image4Address").getValue(String.class);
            Glide.with(ShowImages.this).load(photoUrl3).into(four);




        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // Getting Post failed, log a message
        }
    };
    databaseReference.addValueEventListener(postListener);
}
}

I would to have a search button, either in search view or in edit text, but averythin i try one, something goes wrong. If you can help me, I would be very helpfull. Plz answer this question.


Solution

  • I got the output as i desired. In the Main activity, I created the following function. @Override public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.toolbar_menu,menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) menuItem.getActionView();
        searchView.setOnQueryTextListener(this);
        return true;
    }
    

    For the below function, I implemented SearchView

    public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
    

    Thue above code is the starting of Main Activity

    @Override
    public boolean onQueryTextSubmit(String s) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String s) {
    
        String userinput = s.toLowerCase();
        List<ImageUploadInfo> newList = new ArrayList();
        for(ImageUploadInfo name: list1)
        {
            if(name.getName().toLowerCase().contains(userinput)){
                newList.add(name);
            }
    
        }
    
        adapt.updateList(newList);
        recyclerView.setAdapter(adapt);
    
        return true;
    }
    

    Then in Custom Recycler View , The below code is added

    public void updateList(List<ImageUploadInfo> newList)
    {
        MainImageUploadInfoList = new ArrayList<>();
        MainImageUploadInfoList.addAll(newList);
        notifyDataSetChanged();
    }
    

    The Menu xml is:

    <?xml version="1.0" encoding="utf-8"?>
    <menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    
    
    <item
        android:title="Search"
        android:id="@+id/action_search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/> 
    </menu>