How to Implement Search for a Registered User Functionality in Social Media Android App?


Enabling registered users to search for others within a social media Android app involves implementing a search functionality. This allows for effective queries of the user database using an efficient search algorithm. Furthermore, by displaying relevant search results based on user input, the feature facilitates connections and promotes networking within the app's user community.

Search in Android

The search functionality in Android encompasses a feature that empowers users to effortlessly find specific content within an Android application. This capability allows users to enter their desired search queries through a designated search bar and promptly receive relevant results based on their input. The implementation of this functionality involves incorporating a compre-hensive search algorithm that efficiently processes the queries and retrieves matching data from the application's database.

The search results are presented to the user in either a list or grid format, providing a convenient and efficient way to locate desired information or resources within an Android app. Moreover, additional options may be available, allowing users to refine their search results through filtering and sorting functionalities. This enhances the overall user experience by offering effective tools for navigation and exploration.

Approaches

There are different approaches that can be used to implement a search facility in a social media android app. Let’s look at the same here:

  • Local Search within the App

  • Firebase Realtime Database User Search

Method 1: Local Search within the App

In this particular approach, the app's local database conveniently stores both user profiles and relevant information. When a user initiates a search, the local database can be effortlessly queried to locate matching profiles. Here is an implementation guide:

  • The application stores user profiles and their associated information in a local database, such as SQLite.

  • It incorporates a search bar that allows users to input search queries.

  • Upon receiving user input, the application executes a query on the local database to retrieve matching user profiles based on criteria like name, username, interests, and more.

  • Finally, it displays the search results to the user.

Example

// activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/
android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <EditText
      android:id="@+id/searchEditText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="Search user profiles"/>

   <ListView
      android:id="@+id/resultsListView"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"/>

</LinearLayout>

// MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

   private DatabaseReference usersRef;

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

      // Initialize Firebase
      FirebaseDatabase database = FirebaseDatabase.getInstance();
      usersRef = database.getReference("users");

      // Bind views
      Button addUserButton = findViewById(R.id.addUserButton);

      // Handle add user button click
      addUserButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // Create a new user
            User user = new User();
            user.setName("John Doe");
            user.setUsername("johndoe");
            user.setInterests(Arrays.asList("Sports", "Music"));

            // Generate a unique key for the new user
            String userId = usersRef.push().getKey();

            // Save the new user profile to the database
            usersRef.child(userId).setValue(user)
                  .addOnSuccessListener(new OnSuccessListener<Void>() {
                     @Override
                     public void onSuccess(Void aVoid) {
                        Toast.makeText(MainActivity.this, "User profile added successfully", Toast.LENGTH_SHORT).show();
                     }
                  })
                  .addOnFailureListener(new OnFailureListener() {
                     @Override
                     public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, "Failed to add user profile: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                     }
                  });
               }
         });
    }
}
// User.java
public class User {
   private String name;
   private String username;
   private List<String> interests;

   public User() {
      // Default constructor required for Firebase
   }

   public User(String name, String username, List<String> interests) {
      this.name = name;
      this.username = username;
      this.interests = interests;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }

   public List<String> getInterests() {
      return interests;
   }

   public void setInterests(List<String> interests) {
      this.interests = interests;
   }

   @Override
   public String toString() {
      return name + " (" + username + ")";
   }
}

Output

Method 2: Firebase Realtime Database User Search

The User Search method in Firebase Realtime Database allows Android Studio developers to integrate user search functionality seamlessly. This feature utilizes Firebase Authentication for user management and the Realtime Database for storing user profiles.

By utilizing Firebase Authentication, users can effortlessly register and log into the app. This se-amless process ensures that their profiles are securely stored within the Realtime Database. Additionally, a search feature has been thoughtfully implemented to enhance user experience. Users have the capability to input their specific search queries, which are then utilized to retrieve matching user profiles from the database. The results of this search query are seamlessly displayed on the app's user interface, optimizing its functionality as a social media application.

Example

// User.java
public class User {
   private String userID;
   private String username;

   public User() {
      // Empty constructor for Firebase
   }

   public User(String userID, String username) {
      this.userID = userID;
      this.username = username;
   }

   // Getters and setters
   public String getUserID() {
      return userID;
   }

   public void setUserID(String userID) {
      this.userID = userID;
   }

   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }
}

// UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
   private List<User> userList;

   public UserAdapter(List<User> userList) {
      this.userList = userList;
   }

   @NonNull
   @Override
   public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
      // Inflate your user item layout and create the ViewHolder
      // Return the created ViewHolder
   }

   @Override
   public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
      User user = userList.get(position);
      // Bind the user data to the ViewHolder's views
   }

   @Override
   public int getItemCount() {
      return userList.size();
   }

   public static class UserViewHolder extends RecyclerView.ViewHolder {
      // Declare your user item views here

      public UserViewHolder(@NonNull View itemView) {
         super(itemView);
         // Initialize your user item views here
      }
   }
}

// SearchActivity.java
public class SearchActivity extends AppCompatActivity {
   private EditText searchEditText;
   private RecyclerView userRecyclerView;
   private UserAdapter userAdapter;
   private List<User> userList;
   private DatabaseReference usersRef;

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

      searchEditText = findViewById(R.id.searchEditText);
      userRecyclerView = findViewById(R.id.userRecyclerView);
      userList = new ArrayList<>();
      userAdapter = new UserAdapter(userList);
      userRecyclerView.setAdapter(userAdapter);
      
      // Get the Firebase database reference
      usersRef = FirebaseDatabase.getInstance().getReference().child("users");

      searchEditText.addTextChangedListener(new TextWatcher() {
         @Override
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Do nothing
         }

         @Override
         public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Call the search function whenever the search query changes
            onSearchTextChanged(s.toString());
         }

         @Override
         public void afterTextChanged(Editable s) {
            // Do nothing
         }
      });
   }

   private void onSearchTextChanged(String searchQuery) {
      Query query = usersRef.orderByChild("username").startAt(searchQuery).endAt(searchQuery + "\uf8ff");
      query.addValueEventListener(new ValueEventListener() {
         @Override
         public void onDataChange(@NonNull DataSnapshot snapshot) {
            userList.clear();
            for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
               User user = dataSnapshot.getValue(User.class);
               userList.add(user);
            }
            userAdapter.notifyDataSetChanged();
         }

         @Override
         public void onCancelled(@NonNull DatabaseError error) {
            // Handle database error
         }
      });
   }
}

Output

Conclusion

In the implementation of search functionality for registered users in a social media Android app, a two-fold approach can be adopted. Firstly, incorporating a local search feature within the app proves beneficial. This involves creating a user-friendly search bar where individuals can enter their queries. The app subsequently retrieves a list of registered users from the local database and filters it based on the entered text, ultimately displaying relevant results.

Furthermore, leveraging the Firebase Realtime Database allows users to easily search for information. By establishing a database and storing user details, it becomes feasible to incorporate a searchable interface. As individuals input their queries into the search bar, the application promptly accesses the database and retrieves corresponding profiles in real-time, ensuring live updates with instant display of matched results.

By combining these different approaches, a comprehensive and efficient search functionality can be offered to registered users within your social media Android app. This enhancement aims to elevate the overall user experience.

Lailly
Lailly

e

Updated on: 27-Jul-2023

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements