Skip to content
Related Articles

Related Articles

Improve Article
Implementing Search for a Specific Blog On Home Page and Logout Functionality in Social Media Android App
  • Last Updated : 09 Apr, 2021

This is the Part 7 of “Build a Social Media App in Android Studio” tutorial, and we are going to cover the following functionalities in this article:

  • We are going to Search For a Blog on Home Page.
  • If there are few blogs in our app then it is easy to search for a blog manually. But what happens when we have 1000 blogs then search for a particular blog became a very complicated and time taking task.
  • That’s why we are implementing this feature to search for a blog using the title or description provided.
  • Also, we have implemented the Logout functionality in this article.

Step By Step Implementation

Step 1: Create a Logout and Search Button in the menu folder

Go to the app > res > menu > right-click > New > Menu Resource File and name the file as main_menu. Below is the code for the main_menu.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
  
    <item
        android:id="@+id/logout"
        android:title="Logout">
    </item>
  
    <item
        android:id="@+id/search"
        android:icon="@drawable/ic_search"
        android:title="Search"
        app:actionViewClass="android.widget.SearchView"
        app:showAsAction="always">
    </item>
  
</menu>

Step 2: Working with the HomeFragment.java file



We are searching for a blog in Node “Posts” using title and description value. If any key-value matches then it will all those blogs whose value contains our search content

if(modelPost.getTitle().toLowerCase().contains(search.toLowerCase())||
      modelPost.getDescription().toLowerCase().contains(search.toLowerCase())) {
      posts.add(modelPost);
  }

Below is the code for the Logout functionality

@Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.logout) {
            firebaseAuth.signOut();
            startActivity(new Intent(getContext(), SpalshScreen.class));
            getActivity().finish();
        }

        return super.onOptionsItemSelected(item);
 }

Go to the HomeFragment.java file and refer to the following code. Below is the complete and updated code for the HomeFragment.java file.

Java




package com.example.socialmediaapp;
  
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
import com.google.firebase.auth.FirebaseAuth;
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 java.util.ArrayList;
import java.util.List;
  
/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {
  
    FirebaseAuth firebaseAuth;
    String myuid;
    RecyclerView recyclerView;
    List<ModelPost> posts;
    AdapterPosts adapterPosts;
  
    public HomeFragment() {
        // Required empty public constructor
    }
  
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        firebaseAuth = FirebaseAuth.getInstance();
        recyclerView = view.findViewById(R.id.postrecyclerview);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        posts = new ArrayList<>();
        loadPosts();
        return view;
    }
  
    private void loadPosts() {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                posts.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    ModelPost modelPost = dataSnapshot1.getValue(ModelPost.class);
                    posts.add(modelPost);
                    adapterPosts = new AdapterPosts(getActivity(), posts);
                    recyclerView.setAdapter(adapterPosts);
                }
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
  
    // Search post code
    private void searchPosts(final String search) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                posts.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    ModelPost modelPost = dataSnapshot1.getValue(ModelPost.class);
                    if (modelPost.getTitle().toLowerCase().contains(search.toLowerCase()) ||
                            modelPost.getDescription().toLowerCase().contains(search.toLowerCase())) {
                        posts.add(modelPost);
                    }
                    adapterPosts = new AdapterPosts(getActivity(), posts);
                    recyclerView.setAdapter(adapterPosts);
  
                }
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
  
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }
  
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_menu, menu);
        MenuItem item = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!TextUtils.isEmpty(query)) {
                    searchPosts(query);
                } else {
                    loadPosts();
                }
                return false;
            }
  
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)) {
                    searchPosts(newText);
                } else {
                    loadPosts();
                }
                return false;
            }
        });
  
        super.onCreateOptionsMenu(menu, inflater);
    }
  
    // Logout functionality
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
  
        if (item.getItemId() == R.id.logout) {
            firebaseAuth.signOut();
            startActivity(new Intent(getContext(), SpalshScreen.class));
            getActivity().finish();
        }
  
        return super.onOptionsItemSelected(item);
    }
  
}

Output:

For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing

Below is the file structure after performing these operations:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :