Я работаю над приложением nearyPlaces
, которое помогает пользователям находить близлежащие места вокруг них. Я использовал библиотеку retrofit
для получения ответа от Google API. Все работает отлично, как вы можете видеть здесь . Так. Я хочу проанализировать эти результаты внутри recyclerView
, как карты Google. Проблема в том, что после consuming
API, он отображается как object
вместо arrayList
.
Мне действительно нужны указания по этому вопросу, так как это дало мне головную боль на несколько недель.
RequestInterface
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
interface RequestInterface {
@GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
Call <NearbyPlaces.Result> getPlacesJson(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}
MapActivity. java
private void getPlacesResponse(String type) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface requestInteface = retrofit.create(RequestInterface.class);
Call<NearbyPlaces.Result> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);
call.enqueue(new Callback<NearbyPlaces.Result>() {
@Override
public void onResponse(@NonNull Call<NearbyPlaces.Result> call, @NonNull Response<NearbyPlaces.Result> response) {
Log.d("error", response.toString());
placeResultAdapter=new PlaceResultAdapter(MapActivity.this, placeResultAdapter);
//here I need to set an arrayList to my adapter but I can't because the retrofit's data comes as an object instead of arrayList.
// mRecyclerView.setAdapter(placeResultAdapter);
}
@Override
public void onFailure(Call<NearbyPlaces.Result> call, Throwable t) {
Log.d("error", call.toString() + " " + t.toString());
}
});
}
Класс ближайших мест
public class GetNearbyPlaces extends AsyncTask<Object, String,String> {
private String googlePlaceData;
private GoogleMap mMap;
private Context mContext;
private Bitmap bitmap;
public GetNearbyPlaces (Context context){
mContext = context;
}
@Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap) objects[0];
String url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try {
googlePlaceData = downloadUrl.ReadTheURL(url);
} catch (IOException e) {
e.printStackTrace();
}
return googlePlaceData;
}
@Override
protected void onPostExecute(String s) {
List<HashMap<String, String>> nearbyPlacesList;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
Log.d("nearby", nearbyPlacesList.toString());
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList){
for (int i = 0; i<nearbyPlacesList.size(); i++){
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
String nameOfPlace = googleNearbyPlace.get("place_name");
String iconLink = googleNearbyPlace.get("icon");
String vicinity = googleNearbyPlace.get("vicinity");
double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(nameOfPlace);
//load image icon from url;
Glide.with(mContext)
.asBitmap()
.apply(RequestOptions.centerCropTransform())
.load(iconLink)
.listener(new RequestListener<Bitmap>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap bitmap, Transition<? super Bitmap> transition) {
Bitmap locator = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.locator_red);
Bitmap scaledLocator =Bitmap.createScaledBitmap(locator, 100, 100, true);
Bitmap iconBitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
Bitmap mergedImages = createSingleImageFromMultipleImages(scaledLocator, tintImage(iconBitmap, Color.WHITE));
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(mergedImages));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
});
}
}
private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(firstImage, 0f, 0f, null);
canvas.drawBitmap(secondImage, 35, 10, null);
return result;
}
public static Bitmap tintImage(Bitmap bitmap, int color) {
Paint paint = new Paint();
paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
Bitmap bitmapResult = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapResult);
canvas.drawBitmap(bitmap, 0, 0, paint);
return bitmapResult;
}
}
Адаптер ближайших мест (обновлен)
publi c Класс PlaceResultAdapter расширяет RecyclerView.Adapter {private ArrayList placeModels; контекст частного контекста;
public PlaceResultAdapter(Context context, ArrayList<NearbyPlaces.Result> placeModels) {
this.placeModels=placeModels;
this.context=context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.place_result_item,viewGroup,false);
return new PlaceResultAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull PlaceResultAdapter.ViewHolder viewHolder, int i) {
viewHolder.place_name.setText(placeModels.get(i).getName());
//Picasso.get().load(placeModels.get(i).getUrl()).into(viewHolder.car_image);
}
@Override
public int getItemCount() {
return placeModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView place_image;
private TextView place_name,place_category;
public ViewHolder(@NonNull View itemView) {
super(itemView);
place_image= itemView.findViewById(R.id.image_view);
place_name= itemView.findViewById(R.id.title);
place_category= itemView.findViewById(R.id.category_text);
}
}
}
Модель класса (обновлено)
public abstract class NearbyPlaces {
public class Result {
@Expose
@SerializedName("photos")
private List<Photos> photos;
@SerializedName("geometry")
private Geometry getGeometry;
@SerializedName("icon")
private String icon;
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("vicinity")
private String vicinity;
public Geometry getGetGeometry() {
return getGeometry;
}
public List<Photos> getPhotos() {
return photos;
}
public void setPhotos(List<Photos> photos) {
this.photos = photos;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVicinity() {
return vicinity;
}
}
public static class Photos {
@Expose
@SerializedName("width")
private int width;
@Expose
@SerializedName("photo_reference")
private String photoReference;
@Expose
@SerializedName("html_attributions")
private List<String> htmlAttributions;
@Expose
@SerializedName("height")
private int height;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String getPhotoReference() {
return photoReference;
}
public void setPhotoReference(String photoReference) {
this.photoReference = photoReference;
}
public List<String> getHtmlAttributions() {
return htmlAttributions;
}
public void setHtmlAttributions(List<String> htmlAttributions) {
this.htmlAttributions = htmlAttributions;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
public static class Reviews {
@Expose
@SerializedName("time")
private int time;
@Expose
@SerializedName("text")
private String text;
@Expose
@SerializedName("relative_time_description")
private String relativeTimeDescription;
@Expose
@SerializedName("rating")
private int rating;
@Expose
@SerializedName("profile_photo_url")
private String profilePhotoUrl;
@Expose
@SerializedName("language")
private String language;
@Expose
@SerializedName("author_url")
private String authorUrl;
@Expose
@SerializedName("author_name")
private String authorName;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRelativeTimeDescription() {
return relativeTimeDescription;
}
public void setRelativeTimeDescription(String relativeTimeDescription) {
this.relativeTimeDescription = relativeTimeDescription;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getProfilePhotoUrl() {
return profilePhotoUrl;
}
public void setProfilePhotoUrl(String profilePhotoUrl) {
this.profilePhotoUrl = profilePhotoUrl;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getAuthorUrl() {
return authorUrl;
}
public void setAuthorUrl(String authorUrl) {
this.authorUrl = authorUrl;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
public static class Geometry {
@Expose
@SerializedName("viewport")
private Viewport viewport;
@Expose
@SerializedName("location")
private Location location;
public Viewport getViewport() {
return viewport;
}
public void setViewport(Viewport viewport) {
this.viewport = viewport;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
public static class Viewport {
@Expose
@SerializedName("southwest")
private Southwest southwest;
@Expose
@SerializedName("northeast")
private Northeast northeast;
public Southwest getSouthwest() {
return southwest;
}
public void setSouthwest(Southwest southwest) {
this.southwest = southwest;
}
public Northeast getNortheast() {
return northeast;
}
public void setNortheast(Northeast northeast) {
this.northeast = northeast;
}
}
public static class Southwest {
@Expose
@SerializedName("lng")
private double lng;
@Expose
@SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class Northeast {
@Expose
@SerializedName("lng")
private double lng;
@Expose
@SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class Location {
@Expose
@SerializedName("lng")
private double lng;
@Expose
@SerializedName("lat")
private double lat;
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class AddressComponents {
@Expose
@SerializedName("types")
private List<String> types;
@Expose
@SerializedName("short_name")
private String shortName;
@Expose
@SerializedName("long_name")
private String longName;
public List<String> getTypes() {
return types;
}
public void setTypes(List<String> types) {
this.types = types;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getLongName() {
return longName;
}
public void setLongName(String longName) {
this.longName = longName;
}
}
} Как видите, я уже получаю данные внутри NearbyPlaces
Класс, который содержит класс AsyncTask
. Поэтому я думаю, что мне нужно сделать, это выяснить, как перенести данные из моей асиновой задачи c в мою adapter
, чтобы я мог показать с помощью recyclerView
.