4

I m currently working on a android apps which fetch data from parse server. I wanted to filter my recyclerView by using searchview. But it shows me nothing while search. It gives me error in this line*for (ParseObject parseObject : mRooms){ * Please help me to edit my code regarding this issues.

roomcardrecyclerviewadapter

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

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 RoomCardRecyclerViewAdapter(Context context, List<ParseObject>arrayList) {
    this();

    this.context = context;
    mRooms = arrayList;
    filterlist = (ArrayList<ParseObject>) arrayList;
}


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")));

   

@Override
public Filter getFilter(){
  return new Filter() {
      @Override
      protected FilterResults performFiltering(CharSequence charSequence) {

String charString = charSequence.toString();
if (charString.isEmpty()){
room = (ParseObject) mRooms;

}else {
List<ParseObject> filteredList = new ArrayList<>();
for (ParseObject parseObject : mRooms){
    if (parseObject.getString("roomSuburb").toLowerCase().contains(charString.toLowerCase())){
        filteredList.add(parseObject);
    }
}
room = (ParseObject) filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = room;

return filterResults;

      }

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

}

mainActivity

mHomeSectionsPagerAdapter = new 
HomeSectionsPagerAdapter(getSupportFragmentManager());
    roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, 
mRooms);
    mRooms = new ArrayList<>();
    // Set up the ViewPager with the sections adapter.
    mViewPager = findViewById(R.id.container);
    mViewPager.setAdapter(mHomeSectionsPagerAdapter);

    
     
    

@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);
   
    MenuItem item = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

    //assumes the current activity is the searchable activity
    

searchView.setSearchableInfo(searchManager.getSearchableInfo
(getComponentName());

    searchView.setSubmitButtonEnabled(true);

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

        @Override
        public boolean onQueryTextChange(String newText) {
            roomCardRecyclerViewAdapter.getFilter().filter(newText);
            return false;
        }
    });

    return true;
}


@Override
public boolean onSearchRequested() {

    //pauseSomeStuff();

    //roomCardRecyclerViewAdapter.getFilter().filter(query);
    return super.onSearchRequested();
}
4
  • can you share the code where u use this RoomCardRecyclerViewAdapter? Commented Oct 3, 2020 at 9:13
  • I shared the file Commented Oct 4, 2020 at 6:14
  • And please, next time try to minimize your code. Delete some parts which you think is unimportant Commented Oct 4, 2020 at 13:44
  • You can use Java Exceptions - Try...Catch block after declaring List. Commented Oct 17, 2022 at 4:58

1 Answer 1

1

I think problem is here:

You haven't shared first lines of MainActivity where you declare your variables. So, I assume that you have some code like this:

List mRooms;

Then I assume that, before assigning value to this mRooms you have passed it to RoomCardRecyclerViewAdapter:

roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);
mRooms = new ArrayList<>();

Then you have assigned value to mRooms. That's why you get NPE. You can solve this problem just like this:

mRooms = new ArrayList<>();
roomCardRecyclerViewAdapter = new RoomCardRecyclerViewAdapter(this, mRooms);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.