1

Hello I'm working on a project that uses GeoJson and it is being stored at a List as a Feature Collection, then use it to a RecyclerView with Item Click for camera positioning and drawing routes on Mapbox, it works well on Initial list, but when I tried Implementing SearchView filtering that's when I got stucked, it definitely filters the list but it seems not to update the card position correctly and it causes trouble over my methods for camera positioning and route drawing on filtered results.

Any help would be greatly appreciated.

Here is the relevant methods used with Search and OnItemClick Implementation on my Main Activity:

List<Feature> featureList = featureCollection.features();

            // Retrieve and update the source designated for showing the store location icons
            GeoJsonSource source = mapboxMap.getStyle().getSourceAs("store-location-source-id");
            if (source != null) {
              source.setGeoJson(FeatureCollection.fromFeatures(featureList));
            }

            if (featureList != null) {

              for (int x = 0; x < featureList.size(); x++) {

                Feature singleLocation = featureList.get(x);

                // Get the single location's String properties to place in its map marker
                String singleLocationName = singleLocation.getStringProperty("name");
                String singleLocationHours = singleLocation.getStringProperty("hours");
                String singleLocationDescription = singleLocation.getStringProperty("description");
                String singleLocationPhoneNum = singleLocation.getStringProperty("phone");


                // Add a boolean property to use for adjusting the icon of the selected store location
                singleLocation.addBooleanProperty(PROPERTY_SELECTED, false);

                // Get the single location's LatLng coordinates
                Point singleLocationPosition = (Point) singleLocation.geometry();

                // Create a new LatLng object with the Position object created above
                LatLng singleLocationLatLng = new LatLng(singleLocationPosition.latitude(),
                  singleLocationPosition.longitude());

                // Add the location to the Arraylist of locations for later use in the recyclerview
                listOfIndividualLocations.add(new IndividualLocation(
                  singleLocationName,
                  singleLocationDescription,
                  singleLocationHours,
                  singleLocationPhoneNum,
                  singleLocationLatLng
                ));

                // Call getInformationFromDirectionsApi() to eventually display the location's
                // distance from mocked device location
                getInformationFromDirectionsApi(singleLocationPosition, false, x);
              }
              // Add the fake device location marker to the map. In a real use case scenario,
              // the Maps SDK's LocationComponent can be used to easily display and customize
              // the device location's puck
              addMockDeviceLocationMarkerToMap();

              setUpRecyclerViewOfLocationCards(chosenTheme);

              mapboxMap.addOnMapClickListener(MapActivity.this);

              Toast.makeText(MapActivity.this, "Click on a card", Toast.LENGTH_SHORT).show();

              // Show 3d buildings if the blue theme is being used
              if (customThemeManager.getNavigationLineColor() == R.color.navigationRouteLine_blue) {
                showBuildingExtrusions();
              }
            }
          }

        });

      }
    });


    @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu,menu);

    MenuItem searchitem = menu.findItem(R.id.searchview);
    SearchView searchView = (SearchView) searchitem.getActionView();

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

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

    private boolean featureSelectStatus(int index) {
    if (featureCollection == null) {
      return false;
    }
    return featureCollection.features().get(index).getBooleanProperty(PROPERTY_SELECTED);
  }

private void setSelected(int index) {
    Feature feature = featureCollection.features().get(index);
    setFeatureSelectState(feature, true);
    refreshSource();
  }
 private void setFeatureSelectState(Feature feature, boolean selectedState) {
    feature.properties().addProperty(PROPERTY_SELECTED, selectedState);
    refreshSource();
  }


private void refreshSource() {
    GeoJsonSource source = mapboxMap.getStyle().getSourceAs("store-location-source-id");
    if (source != null && featureCollection != null) {
      source.setGeoJson(featureCollection);
    }
  }

private void setUpRecyclerViewOfLocationCards(int chosenTheme) {
    // Initialize the recyclerview of location cards and a custom class for automatic card scrolling
    locationsRecyclerView = findViewById(R.id.map_layout_rv);
    locationsRecyclerView.setHasFixedSize(true);
    locationsRecyclerView.setLayoutManager(new LinearLayoutManagerWithSmoothScroller(this));
    styleRvAdapter = new LocationRecyclerViewAdapter(listOfIndividualLocations,
      getApplicationContext(), this, chosenTheme);
    locationsRecyclerView.setAdapter(styleRvAdapter);
    SnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(locationsRecyclerView);
  }



    @Override
  public void onItemClick(int position) {
    // Get the selected individual location via its card's position in the recyclerview of cards
    IndividualLocation selectedLocation = styleRvAdapter.getItem(position);
    // Evaluate each Feature's "select state" to appropriately style the location's icon
    List<Feature> featureList = featureCollection.features();
    assert featureCollection.features() != null;
    Point selectedLocationPoint = (Point) featureCollection.features().get(position).geometry();
    for (int i = 0; i < featureList.size(); i++) {
      if (featureList.get(i).getStringProperty("name").equals(selectedLocation.getName())) {
        if (featureSelectStatus(i)) {
          setFeatureSelectState(featureList.get(i), false);
        } else {
          setSelected(i);
        }
      } else {
        setFeatureSelectState(featureList.get(i), false);
      }
    }

    // Reposition the map camera target to the selected marker
    if (selectedLocation != null) {
      repositionMapCamera(selectedLocationPoint);
    }

    // Check for an internet connection before making the call to Mapbox Directions API
    if (deviceHasInternetConnection()) {
      // Start call to the Mapbox Directions API
      if (selectedLocation != null) {
        getInformationFromDirectionsApi(selectedLocationPoint, true, null);
      }
    } else {
      Toast.makeText(this, R.string.no_internet_message, Toast.LENGTH_LONG).show();
    }
  }

And This is my Adapter:

public class LocationRecyclerViewAdapter extends
  RecyclerView.Adapter<LocationRecyclerViewAdapter.ViewHolder> implements Filterable {

  private ArrayList<IndividualLocation> listOfLocations;
  private ArrayList<IndividualLocation> listOfLocationsFull;

  private Context context;
  private int selectedTheme;
  private static ClickListener clickListener;
  private int upperCardSectionColor = 0;
  private LocationRecyclerViewAdapter styleRv;
  private int locationNameColor = 0;
  private int locationAddressColor = 0;
  private int locationPhoneNumColor = 0;
  private int locationPhoneHeaderColor = 0;
  private int locationHoursColor = 0;
  private int locationHoursHeaderColor = 0;
  private int locationDistanceNumColor = 0;
  private int milesAbbreviationColor = 0;

  public LocationRecyclerViewAdapter(List<IndividualLocation> styles,
                                     Context context, ClickListener cardClickListener, int selectedTheme) {
    this.context = context;
    this.listOfLocations = (ArrayList<IndividualLocation>) styles;
    this.selectedTheme = selectedTheme;
    this.clickListener = cardClickListener;
    listOfLocationsFull = new ArrayList<>(listOfLocations);
  }

  public IndividualLocation getItem(int position){
    return listOfLocationsFull.get(position);
  }

  @Override
  public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    int singleRvCardToUse = R.layout.single_location_map_view_rv_card;
    View itemView = LayoutInflater.from(parent.getContext()).inflate(singleRvCardToUse, parent, false);
    return new ViewHolder(itemView);
  }

  public interface ClickListener {
    void onItemClick(int position);
  }

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

  @Override
  public Filter getFilter(){
    return listOfLocationsFilter;
  }
  private Filter listOfLocationsFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
      List<IndividualLocation> filteredList = new ArrayList<>();
      if(constraint == null || constraint.length() == 0 ){
        filteredList.addAll(listOfLocationsFull);

      }
      else{
        String filterpattern = constraint.toString().toLowerCase().trim();
        for(IndividualLocation item : listOfLocationsFull){
            if(item.getName().toLowerCase().contains(filterpattern)){
              filteredList.add(item);

            }
        }
      }
      FilterResults results = new FilterResults();
      results.values = filteredList;
      return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
      listOfLocations.clear();
      listOfLocations.addAll((List)results.values);
      notifyDataSetChanged();
    }
  };

  @Override
  public void onBindViewHolder(ViewHolder card, int position) {

    IndividualLocation locationCard = listOfLocations.get(position);

    card.nameTextView.setText(locationCard.getName());
    card.addressTextView.setText(locationCard.getAddress());
    card.phoneNumTextView.setText(locationCard.getPhoneNum());
    card.hoursTextView.setText(locationCard.getHours());
    card.distanceNumberTextView.setText(locationCard.getDistance());

    card.constraintUpperColorSection.setBackgroundColor(upperCardSectionColor);
    card.nameTextView.setTextColor(locationNameColor);
    card.phoneNumTextView.setTextColor(locationPhoneNumColor);
    card.hoursTextView.setTextColor(locationHoursColor);
    card.hoursHeaderTextView.setTextColor(locationHoursHeaderColor);
    card.distanceNumberTextView.setTextColor(locationDistanceNumColor);
    card.milesAbbreviationTextView.setTextColor(milesAbbreviationColor);
    card.addressTextView.setTextColor(locationAddressColor);
    card.phoneHeaderTextView.setTextColor(locationPhoneHeaderColor);
  }




  static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView nameTextView;
    TextView addressTextView;
    TextView phoneNumTextView;
    TextView hoursTextView;
    TextView distanceNumberTextView;
    TextView hoursHeaderTextView;
    TextView milesAbbreviationTextView;
    TextView phoneHeaderTextView;
    ConstraintLayout constraintUpperColorSection;
    CardView cardView;
    ImageView backgroundCircleImageView;
    ImageView emojiImageView;
    ViewHolder(final View itemView) {
      super(itemView);
      nameTextView = itemView.findViewById(R.id.location_name_tv);
      addressTextView = itemView.findViewById(R.id.location_description_tv);
      phoneNumTextView = itemView.findViewById(R.id.location_phone_num_tv);
      phoneHeaderTextView = itemView.findViewById(R.id.phone_header_tv);
      hoursTextView = itemView.findViewById(R.id.location_hours_tv);
      backgroundCircleImageView = itemView.findViewById(R.id.background_circle);
      emojiImageView = itemView.findViewById(R.id.emoji);
      constraintUpperColorSection = itemView.findViewById(R.id.constraint_upper_color);
      distanceNumberTextView = itemView.findViewById(R.id.distance_num_tv);
      hoursHeaderTextView = itemView.findViewById(R.id.hours_header_tv);
      milesAbbreviationTextView = itemView.findViewById(R.id.miles_mi_tv);
      cardView = itemView.findViewById(R.id.map_view_location_card);
      cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          clickListener.onItemClick(getAdapterPosition());
        }
      });
    }
      @Override
    public void onClick(View view) {
    }

  }

}

1 Answer 1

0

I know it's late but I hope someone gets assisted with my answer.

The android RecyclerView uses an adapter that extends from the RecyclerView.Adapter class which requires a List or ArrayList of data to populate the items in the recyclerview in the onBindViewHolder overridden method.

The position parameter provided by this method is the relative position of items in the RecyclerView at any given time, meaning that when you first load the recyclerview, this position will be in sync with positions in the data ArrayList of your full data that's loaded onto the recyclerview.

When you perform a search on the recyclerview, you pass in a different dataset of the filtered results, say, filteredList, this list will again start it's position(s) from 0 and so on, which means that when you click on an item, the position that gets passed to the onItemClick is the one from the new ArrayList of the filteredResults. This is what causes the confusion as you're getting a position from one list(filteredList) and using it to get data from another list(originalList).

Once you do the search and call the notifyDataSetChanged() with the new list(filteredList), your recyclerView positions will be different and methods to get the clicked item position such as viewHolder.getAdapterPosition() will return you the new position which won't help much as this is a position from the filteredList.

With this understanding, I'll propose a simple but working solution which I've tested on my end.

Challenge: To get the right position for recyclerView item clicks even for search results.

Solution: Have a unique value in your model/dataset which represents the correct index of that data item in the original dataset. This value will never change as it belongs in your model/dataset. In my case, this was the id of the row fetched from a MySQL Database.

In your recyclerView row item in XML, define a TextView which will house this id value. We'll set its android:visibility="gone" as we don't necessarily want the user to see this and it also won't occupy screen space with that setting.

<TextView
        android:id="@+id/tvItemId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"/>

In your Adapter's ViewHolder, initialize this TextView:

tvItemId = temView.findViewById(R.id.tvItemId)

In onBindViewHolder set it's value: holder.tvItemId.setText(itemId)

In your onItemClick, get the view that was clicked as it holds the textview that has the original item id even upon search.

TextView item = view.findViewById(R.id.tvItemId)

Get the value of that textbox, this is the correct item id that will load the correct data for your click event.

int itemId = Integer.parseInt(item.getText().toString());

Use the indexOf() method to get the correct index/position in the ArrayList

int pos = arrayList.indexOf(itemId);

Go ye and do the magic, stay motivated!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.