1

I am using parse server for my database. I wanted to get the item while user search on the search function. I search on the google for this but did not found anything suitable.

#MainActivity

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    final ParseQuery<ParseUser> query = ParseUser.getQuery();

    
    //get the search view and set the searchable configuration
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    //searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));


    //assumes the current activity is the searchable activity
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    searchView.setSubmitButtonEnabled(true);
     searchView.setSubmitButtonEnabled(true);
   // searchView.setOnQueryTextListener((SearchView.OnQueryTextListener) this);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
         
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            return true;
        }
    });



    return true;
}


@Override
public boolean onSearchRequested() {

    //pauseSomeStuff();
    return super.onSearchRequested();
}

RoomCardRecyclerViewAdapter

I wanted to get item from this adapter by using search functionality and filter it for the user

private List<ParseObject> mRooms = new ArrayList<>();
private ParseObject room;
private String mSection;

public RoomCardRecyclerViewAdapter(){
    super(DIFF_CALLBACK);
}
public static final DiffUtil.ItemCallback<ParseObject>  DIFF_CALLBACK = new 
DiffUtil.ItemCallback<ParseObject>() {
    @Override
    public boolean areItemsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
        return oldItem.getObjectId() == newItem.getObjectId();
    }

    @Override
    public boolean areContentsTheSame(@NonNull ParseObject oldItem, @NonNull ParseObject newItem) {
        return (oldItem.getUpdatedAt().equals(newItem.getUpdatedAt()) && 
 oldItem.getCreatedAt().equals(newItem.getCreatedAt()));
    }
};


public RoomCardRecyclerViewAdapter(String section) {
  this();
  this.mSection = section;
}
public class RoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    protected ImageView mRoomImage;
    protected TextView mRoomPrice;
    protected TextView mInclusiveOrNot;
    protected TextView mPropertyType;
    protected TextView mNumOfBeds;
    protected TextView mNumOfBaths;
    protected TextView mRoomLocation;

    private Context context;

    public RoomViewHolder(Context context, View itemView) {
        super(itemView);
        mRoomImage = itemView.findViewById(R.id.room_image);
        mRoomPrice = itemView.findViewById(R.id.price_label);
        mInclusiveOrNot = itemView.findViewById(R.id.incl_excl_label);
        mPropertyType = itemView.findViewById(R.id.propertyType_label);
        mNumOfBeds = itemView.findViewById(R.id.num_beds_label);
        mNumOfBaths = itemView.findViewById(R.id.details_num_baths_label);
        mRoomLocation = itemView.findViewById(R.id.location_label);
        this.context = context;
        //set onclick listener
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.i("Click event: ", "My room has been clicked.");
        int pos = getAdapterPosition();
        Intent intent;
        ParseObject room = getCurrentList().get(pos);

        //create the ParseObject proxy
        ParseProxyObject roomProxy = new ParseProxyObject(room);
        Toast.makeText(context, room.getString("roomSuburb"), Toast.LENGTH_LONG).show();
        //fork to corresponding activity
        if(mSection != null) {
            Log.i("mSection text: ", "mSection text is: " + mSection);
            if (mSection.equals("My Rooms")) {
                //start my rooms detail activity
                Log.i("My room: ", "Room selected " + roomProxy.getObjectId());
                intent = new Intent(context, MyRoomDetailActivity.class);
                //add the room to the intent
                intent.putExtra("currentSelectedRoomObject", room);
                Log.i("Selected room", "Put Extra, " + room);
                intent.putExtra("roomObject", roomProxy);
                context.startActivity(intent);
            }
        }else {
            Log.i("My room:", "RoomDetailActivity loaded for MyRoomDetail Activity instead");
            intent = new Intent(context, RoomDetailActivity.class);
            //add the proxy to the intent
            intent.putExtra("roomObject", roomProxy);
            context.startActivity(intent);
        }

    }
}

@Override
public RoomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //inflating the viewholder with the appropriate views
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.room_cardview, parent, false);

    return new RoomViewHolder(parent.getContext(), view);
}

@Override
public void onBindViewHolder(@NonNull RoomViewHolder holder, int position) {
    room = getItem(position);
    holder.mRoomLocation.setText(room.getString("roomSuburb"));
    holder.mRoomPrice.setText(Integer.toString(room.getInt("roomMonthlyRent")));
    holder.mInclusiveOrNot.setText(room.getString("roomRentInclusiveOfBills"));
    holder.mPropertyType.setText(room.getString("roomPropertyType"));
    holder.mNumOfBeds.setText(Integer.toString(room.getInt("roomBedrooms")));
    holder.mNumOfBaths.setText(Integer.toString(room.getInt("roomBathrooms")));

    //get the image
    //check if its roomImage or image1 set
    ParseFile imageFile;
    if (room.getParseFile("roomImage") != null){
        //
        imageFile = room.getParseFile("roomImage");
    }else {
        imageFile = room.getParseFile("roomImage1");
    }

    //if there is no image saved in Parse
    if(imageFile == null){
        //continue to load predefined default image
        int r = R.mipmap.ic_launcher;
        Glide.with(holder.mRoomImage.getContext()).load(r)
                .into(holder.mRoomImage);
    }else {
        Uri fileUri = Uri.parse(imageFile.getUrl());

        //image loader recommended by Google
        Glide.with(holder.mRoomImage.getContext()).load(fileUri.toString())
                .thumbnail(0.6f)
                .centerCrop()
                .crossFade()
                .into(holder.mRoomImage);
    }
}


public void addMoreRooms(List<ParseObject> newRooms){
    mRooms.addAll(newRooms);
    submitList((PagedList<ParseObject>) mRooms);
}

public void addAll(List<ParseObject> latestRooms) {
    mRooms.addAll(0, latestRooms);
    //mRooms.add(i, latestRooms);
    notifyDataSetChanged();
}
@Override
public Filter getFilter(){
  return new Filter() {
      @Override
      protected FilterResults performFiltering(CharSequence charSequence) {
          FilterResults results = new FilterResults();
          List<ParseObject> filteredList = null;
          if (charSequence == null || charSequence.length() == 0) {
              results.count = mRooms.size();
              results.values = mRooms;

              //results = mRooms.size();
          } else {
              filteredList = new ArrayList<>();
              charSequence = charSequence.toString().toLowerCase();
              for (ParseObject item : mRooms) {
                  String mSection = item.getObjectId().toLowerCase();
                  filteredList.add(item);
              }
          }

          results.count = filteredList.size();
          results.values = filteredList;

          return results;
      }

      @Override
      protected void publishResults(CharSequence charSequence, FilterResults results) {
          room = (ParseObject) results.values;
          notifyDataSetChanged();
      }
  };

}

1 Answers1

2

make your adapter implements Filterable and take a look for THIS topic on SO, especially very detailed answer. it's about BaseAdapter, but part resposible for filtering is common for all adapters. the clue is to have custom overriden getFilter() method in your adapter

@Override
public Filter getFilter() {
    return new Filter() {
        // implementation of your Filter
        ...

and pass query from SearchView to it by

@Override
public boolean onSearchRequested() {
    String query - searchView.getText().toString();
    adapter.getFilter().filter(query);
    return true;
}
snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • sir, i updated my code as you said. But its not working. Its not showing me the list while i m searching. – raihan saifullah Sep 16 '20 at 08:10
  • 1
    your `results.values` is always `= filterResults;`. in `publishResults` method you are updating `mSection` and `mRooms` stays untouched, besides that you have there `ClassCastException`, as `results.values` carries array and you are casting to `String`. Also `getFilteredResults` is doing something, but isn't returning any value (should return filtered array imho) – snachmsm Sep 16 '20 at 10:26
  • sir, can you please help me code it. I m getting confused with this program. I need your help. – raihan saifullah Sep 17 '20 at 07:43
  • edit your question and post most current version of your code (adapter and `onCreate` of `Activity`), and also source of `ParseObject` and I will edit my answer with some solution – snachmsm Sep 17 '20 at 08:04
  • I have posted my current version my code and the source of ParseObject. – raihan saifullah Sep 17 '20 at 08:49
  • you've posted `ParseProxyObject` and your adapter is working on `ParseObject` `List`, these aren't same classes... – snachmsm Sep 17 '20 at 08:54
  • I have posted my ParseObject class. But this class is empty. – raihan saifullah Sep 17 '20 at 09:40
  • `ParseObject` isn't empty, it extends `Room` without any purpose, so its unnecessary... just like posted `ParseProxyObject`, which is irrelevant to your problem. Due to your lack of knowledge about programming, extendsing classes, class casting etc. I can't help you, there is so much problems in your code that I would advice you to learn some basics about Java, then start coding – snachmsm Sep 17 '20 at 10:23
  • Thank you sir for your advice. I realized still i have to learn so many things. – raihan saifullah Sep 17 '20 at 10:29