0

So i tried implementing a search bar to my app for my listview and it does work but it only takes the first result in a array. I am using a custom array adapter and I am going crazy trying to figure this out.

This is where the listview is called and where i added the editview code. I followed a simple youtube tutorial and I tried looking for solutions for custom array adapter and they are so confusing for me.

package com.example.android.g4_project;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.google.android.libraries.places.api.Places;

import java.util.ArrayList;

public class DisplayRestaurants extends AppCompatActivity {

    private ListView mListView;
    private static final String API_KEY = "my api key";

    public static final String restaurantLat = "Restaurant Latitude";
    public static final String restaurantLong = "Restaurant Longitude";
    public static final String placeName = "Restaurant Name";
    public static final String placeAddress = "Restaurant Address";
    public static final String placeID = "Restaurant PlaceID";
    public static final String currentLat = "Current Latitude";
    public static final String currentLng = "Current Longitude";

    private static ArrayList<Double> latList, lngList;
    private static ArrayList<String> restName;
    private static ArrayList<String> restAddress;
    private static ArrayList<String> restPlaceID;
    private ArrayAdapter adapter;

    private Double devLat;
    private Double devLng;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurants);
        Places.initialize(getApplicationContext(), API_KEY);
        EditText theFilter = (EditText) findViewById(R.id.searchFilter);

        getRestData mm = new getRestData();

        restName = mm.getRestName();
        restAddress = mm.getRestAddress();
        restPlaceID = mm.getRestPlaceID();

        latList = mm.getLatList();
        lngList = mm.getLngList();

        devLat = mm.getDevLat();
        devLng = mm.getDevLng();

        ArrayList<String> list = restName;

        if (list != null) {

            String[] values = list.toArray(new String[list.size()]);
            mListView = findViewById(R.id.listView);
            adapter = new PlaceImageListView(this, values);
            mListView.setAdapter(adapter);


                theFilter.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        DisplayRestaurants.this.adapter.getFilter().filter(s);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }

                });

            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = mListView.getPositionForView(view);
                    if (position == pos) {
                        Intent restInfo = new Intent(DisplayRestaurants.this, restaurantInfo.class);

                        Double lat = latList.get(pos);
                        Double lng = lngList.get(pos);

                        String restAddr = restAddress.get(pos);
                        String restTitle = restName.get(pos);
                        String restID = restPlaceID.get(pos);

                        restInfo.putExtra(restaurantLat, lat);
                        restInfo.putExtra(restaurantLong, lng);
                        restInfo.putExtra(placeAddress, restAddr);
                        restInfo.putExtra(placeName, restTitle);
                        restInfo.putExtra(placeID, restID);
                        restInfo.putExtra(currentLat, devLat);
                        restInfo.putExtra(currentLng, devLng);

                        startActivity(restInfo);
                    }

                }
            });
        }
    }

}

This is my custom array adapter that displays images next to my listview. I had to hardcode it because I have no clue on how to do it more efficiently. There are 60 strings but I only included 2 in the post.

package com.example.android.g4_project;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.common.api.ApiException;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.PhotoMetadata;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.FetchPhotoRequest;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.PlacesClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class PlaceImageListView extends ArrayAdapter<String> implements Filterable {

    public static final String TAG = "YOUR-TAG-NAME";
    private static final String API_KEY = "my api key";

    private final Context context;
    private final String[] values;
    private ListView mListView;
    private static ArrayList<String> restPlaceID;
    private static String address;



    public PlaceImageListView(Context context, String[] values) {
        super(context, R.layout.activity_place_image_list_view, values);
        this.context = context;
        this.values = values;

    }




    @Override
    public View getView(int position, View view, ViewGroup parent) {
        getRestData mm = new getRestData();
        restPlaceID = mm.getRestPlaceID();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.activity_place_image_list_view, parent, false);
        TextView textView = rowView.findViewById(R.id.label);
        //TextView distanceText = rowView.findViewById(R.id.distance); *TO BE DECIDED, CAN'T PUT DISTANCE AS IT LAGS THE SYSTEMS*
        ImageView imageView = rowView.findViewById(R.id.restImg);
        Places.initialize(context, API_KEY);
        PlacesClient placesClient = Places.createClient(context);


        textView.setText(values[position]);
        //distanceText.setText(); *TO BE CHANGED*

 String s = values[position];
        if (s.startsWith("Restoran Oregi")) {

// Specify fields. Requests for photos must always have the PHOTO_METADATAS field.
            final List<Place.Field> fields = Collections.singletonList(Place.Field.PHOTO_METADATAS);

// Get a Place object (this example uses fetchPlace(), but you can also use findCurrentPlace())
            final FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(restPlaceID.get(position), fields);

            placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
                final Place place = response.getPlace();

                // Get the photo metadata.
                final List<PhotoMetadata> metadata = place.getPhotoMetadatas();
                if (metadata == null || metadata.isEmpty()) {
                    Log.w(TAG, "No photo metadata.");
                    return;
                }
                final PhotoMetadata photoMetadata = metadata.get(0);

                // Get the attribution text.
                final String attributions = photoMetadata.getAttributions();

                // Create a FetchPhotoRequest.
                final FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
                        .setMaxWidth(500) // Optional.
                        .setMaxHeight(300) // Optional.
                        .build();
                placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
                    Bitmap bitmap = fetchPhotoResponse.getBitmap();
                    imageView.setImageBitmap(bitmap);
                }).addOnFailureListener((exception) -> {
                    if (exception instanceof ApiException) {
                        final ApiException apiException = (ApiException) exception;
                        Log.e(TAG, "Place not found: " + exception.getMessage());
                        final int statusCode = apiException.getStatusCode();
                        // TODO: Handle error with given status code.
                    }
                });
            });
        }
        if (s.startsWith("Burgertory")){

// Specify fields. Requests for photos must always have the PHOTO_METADATAS field.
            final List<Place.Field> fields = Collections.singletonList(Place.Field.PHOTO_METADATAS);

// Get a Place object (this example uses fetchPlace(), but you can also use findCurrentPlace())
            final FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(restPlaceID.get(position), fields);

            placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
                final Place place = response.getPlace();

                // Get the photo metadata.
                final List<PhotoMetadata> metadata = place.getPhotoMetadatas();
                if (metadata == null || metadata.isEmpty()) {
                    Log.w(TAG, "No photo metadata.");
                    return;
                }
                final PhotoMetadata photoMetadata = metadata.get(0);

                // Get the attribution text.
                final String attributions = photoMetadata.getAttributions();

                // Create a FetchPhotoRequest.
                final FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
                        .setMaxWidth(500) // Optional.
                        .setMaxHeight(300) // Optional.
                        .build();
                placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
                    Bitmap bitmap = fetchPhotoResponse.getBitmap();
                    imageView.setImageBitmap(bitmap);
                }).addOnFailureListener((exception) -> {
                    if (exception instanceof ApiException) {
                        final ApiException apiException = (ApiException) exception;
                        Log.e(TAG, "Place not found: " + exception.getMessage());
                        final int statusCode = apiException.getStatusCode();
                        // TODO: Handle error with given status code.
                    }
                });
            });
        }
  return rowView;
    }

}
Shazali
  • 1
  • 1

0 Answers0