I am working on a nearyPlaces application that helps users get nearby locations around them. I used retrofit library to fetch response from google api. Everything works perfectly as you can see here. So. I want to parse this results inside a recyclerView just like google maps. The problem is that after consuming the api, it displays as an object instead of an arrayList.
I really need directions on this as it has given me headache for a few weeks.
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());
}
});
}
Nearby Places Class
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;
}
}
Nearby Places Adapter (Updated)
public class PlaceResultAdapter extends RecyclerView.Adapter {
private ArrayList placeModels;
private Context context;
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);
}
}
}
Model Class (Updated)
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;
}
}
}
As you can see, am already retrieving the data inside NearbyPlaces Class which contains the AsyncTask class. So i think what I need to do is find out how to transfer the data from my async task to my adapter so I can show with recyclerView.
create models as per your json response
Main object
public class Response {
#SerializedName("results")
private ArrayList<Result> list;
public ArrayList<Result> getList() {
return list;
}
}
Array inside main object
public class Result {
#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 String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVicinity() {
return vicinity;
}
}
Geometry object
public class Geometry {
#SerializedName("location")
private Location location;
#SerializedName("viewport")
private ViewPort viewPort;
public Location getLocation() {
return location;
}
public ViewPort getViewPort() {
return viewPort;
}
}
Location object
public class Location {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
ViewPort model
public class ViewPort {
#SerializedName("northeast")
private NorthEast northEast;
#SerializedName("southwest")
private SouthWest southWest;
public NorthEast getNorthEast() {
return northEast;
}
public SouthWest getSouthWest() {
return southWest;
}
}
NorthEast model
public class NorthEast {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
SouthWest model
public class SouthWest {
#SerializedName("lat")
private String lat;
#SerializedName("lng")
private String lng;
public String getLat() {
return lat;
}
public String getLng() {
return lng;
}
}
1 Create class for all these models and copy them
2 Modify your interface
interface RequestInterface {
#GET("api/place/nearbysearch/json?sensor=true&key="+Constants.API_KEY)
Call <Response> getPlacesJson(#Query("type") String type, #Query("location") String location, #Query("radius") int radius);
}
3 Modify your apicall function
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<Response> call = requestInteface.getPlacesJson(type, latitude + "," + longitude, proximityRadius);
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(#NonNull Call<Response> call, #NonNull Response<Resonse> response) {
ArrayList<Result> dataList = response.body().getList();
placeResultAdapter=new PlaceResultAdapter(MapActivity.this, dataList);
mRecyclerView.setAdapter(placeResultAdapter);
}
#Override
public void onFailure(Response> call, Throwable t) {
Log.d("error", call.toString() + " " + t.toString());
}
});
}
4 : Now you can fetch api data.
Adapter class
public class PlaceResultAdapter extends RecyclerView.Adapter<PlaceResultAdapter.ViewHolder> {
private ArrayList<NearbyPlaces.Result> placeModels;
private Context context;
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());
viewHolder.place_category.setText(placeModels.get(i).getTypes().get(0));
String image_url = placeModels.get(i).getIcon();
//Picasso.get().load(image_url).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);
}
}
}
Related
I'm new to Retrofit, I have an activity hosting 3 fragments for a weather app. My FirstFragment is where the
current weather data will be displayed using OpenWeatherMap One call API https://openweathermap.org/api/one-call-api. I noticed that retrofit request calls cannot be made on the fragment class, so
I tried using my Activity class and everything worked properly except these following lines:
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(#NonNull Call < WeatherResponse > call, #NonNull Response < WeatherResponse > response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
time_zone.setText(response.body().getTimezone());
time_field.setText(response.body().getCurrent.getDt());
current_temp.setText(response.body().getCurrent().getTemp()+" ℃");
current_output.setText(response.body().getCurrent().getWeather().getDescription);
rise_time.setText(response.body().getCurrent().getSunrise()+" AM");
set_time.setText(response.body().getCurrent().getSunset()+" PM");
temp_out.setText(response.body().getCurrent().getTemp()+" ℃");
Press_out.setText(response.body().getCurrent().getPressure()+" hpa");
Humid_out.setText(response.body().getCurrent().getHumidity()+" %");
Ws_out.setText(response.body().getCurrent).getWind_speed()+" Km/h");
Visi_out.setText(response.body().getCurrent().getVisibility()+" m");
UV_out.setText(response.body().getCurrent().getUvi());
showing error Cannot resolve Symbol "response". What can be done to fix it, please?
My full code:
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
public static String BaseUrl = "http://api.openweathermap.org/";
public static String AppId = "";
public static String lat = "9.0574";
public static String lon = "7.4898";
// User Timezone name, current time, current temperature, current condition, sunrise, sunset, temperature, pressure, humidity, wind_speed, visibility, UV Index
TextView time_zone, time_field, current_temp, current_output, rise_time, set_time, temp_out, Press_out, Humid_out, Ws_out, Visi_out, UV_out;
ConstraintLayout constraintLayout;
public static int count=0;
int[] drawable =new int[]{R.drawable.dubai,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
Timer _t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
time_zone = findViewById(R.id.textView9);
time_field = findViewById(R.id.textView4);
current_temp = findViewById(R.id.textView10);
current_output = findViewById(R.id.textView11);
rise_time = findViewById(R.id.textView25);
set_time = findViewById(R.id.textView26);
temp_out = findViewById(R.id.textView28);
Press_out = findViewById(R.id.textView29);
Humid_out = findViewById(R.id.textView30);
Ws_out = findViewById(R.id.textView33);
Visi_out = findViewById(R.id.textView34);
UV_out = findViewById(R.id.textView35);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
NavController navController = Navigation.findNavController(this, R.id.fragment);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
constraintLayout = findViewById(R.id.layout);
constraintLayout.setBackgroundResource(R.drawable.dubai);
_t = new Timer();
_t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() { // run on ui thread
#Override
public void run() {
if (count < drawable.length) {
constraintLayout.setBackgroundResource(drawable[count]);
count = (count + 1) % drawable.length;
}
}
});
}
}, 5000, 5000);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService service = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(#NonNull Call < WeatherResponse > call, #NonNull Response < WeatherResponse > response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
time_zone.setText(response.body().getTimezone());
time_field.setText(response.body().getCurrent.getDt());
current_temp.setText(response.body().getCurrent().getTemp()+" ℃");
current_output.setText(response.body().getCurrent().getWeather().getDescription);
rise_time.setText(response.body().getCurrent().getSunrise()+" AM");
set_time.setText(response.body().getCurrent().getSunset()+" PM");
temp_out.setText(response.body().getCurrent().getTemp()+" ℃");
Press_out.setText(response.body().getCurrent().getPressure()+" hpa");
Humid_out.setText(response.body().getCurrent().getHumidity()+" %");
Ws_out.setText(response.body().getCurrent).getWind_speed()+" Km/h");
Visi_out.setText(response.body().getCurrent().getVisibility()+" m");
UV_out.setText(response.body().getCurrent().getUvi());
}
}
}
}
WeatherService.java
public interface WeatherService {
#GET("data/2.5/weather?")
Call<WeatherResponse> getCurrentWeatherData(#Query("lat") String lat, #Query("lon") String lon, #Query("APPID") String app_id);
}
JSON Response:
{
"lat":9.08,
"lon":7.4,
"timezone":"Africa/Lagos",
"timezone_offset":3600,
"current":{
"dt":1609157237,
"sunrise":1609134244,
"sunset":1609175993,
"temp":305.15,
"feels_like":304.63,
"pressure":1012,
"humidity":29,
"dew_point":284.9,
"uvi":8.32,
"clouds":82,
"visibility":5000,
"wind_speed":1.5,
"wind_deg":200,
"weather":[
{
"id":721,
"main":"Haze",
"description":"haze",
"icon":"50d"
}
]
}
I converted my JSON to GSON using http://www.jsonschema2pojo.org/
Current.java:
public class Current {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("sunrise")
#Expose
private Integer sunrise;
#SerializedName("sunset")
#Expose
private Integer sunset;
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("feels_like")
#Expose
private Double feelsLike;
#SerializedName("pressure")
#Expose
private Integer pressure;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("dew_point")
#Expose
private Double dewPoint;
#SerializedName("uvi")
#Expose
private Double uvi;
#SerializedName("clouds")
#Expose
private Integer clouds;
#SerializedName("visibility")
#Expose
private Integer visibility;
#SerializedName("wind_speed")
#Expose
private Double windSpeed;
#SerializedName("wind_deg")
#Expose
private Integer windDeg;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Integer getSunrise() {
return sunrise;
}
public void setSunrise(Integer sunrise) {
this.sunrise = sunrise;
}
public Integer getSunset() {
return sunset;
}
public void setSunset(Integer sunset) {
this.sunset = sunset;
}
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getFeelsLike() {
return feelsLike;
}
public void setFeelsLike(Double feelsLike) {
this.feelsLike = feelsLike;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Double getDewPoint() {
return dewPoint;
}
public void setDewPoint(Double dewPoint) {
this.dewPoint = dewPoint;
}
public Double getUvi() {
return uvi;
}
public void setUvi(Double uvi) {
this.uvi = uvi;
}
public Integer getClouds() {
return clouds;
}
public void setClouds(Integer clouds) {
this.clouds = clouds;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Double getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(Double windSpeed) {
this.windSpeed = windSpeed;
}
public Integer getWindDeg() {
return windDeg;
}
public void setWindDeg(Integer windDeg) {
this.windDeg = windDeg;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
}
Weather.java:
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
WeatherResponse.java:
public class WeatherResponse {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("timezone")
#Expose
private String timezone;
#SerializedName("timezone_offset")
#Expose
private Integer timezoneOffset;
#SerializedName("current")
#Expose
private Current current;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public Integer getTimezoneOffset() {
return timezoneOffset;
}
public void setTimezoneOffset(Integer timezoneOffset) {
this.timezoneOffset = timezoneOffset;
}
public Current getCurrent() {
return current;
}
public void setCurrent(Current current) {
this.current = current;
}
}
I also want to make my fragment class make use of the Activity data, how to do that, please?
This piece of code is outside of onCreate
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService service = retrofit.create(WeatherService.class);
Call < WeatherResponse > call = service.getCurrentWeatherData(lat, lon, AppId);
// .... etc.
It needs to be inside a method; onCreate for example.
You can only have declarations and default assignments in the class body. Any other code must be within a method body.
You probably closed the brace of onCreate to early accidentally.
Note: This also explains why you get so many errors. You just have so many lines of code which are, to the compiler, totally out of place and thus marks everything as incorrect.
It might be rather something alike this:
#Override
public void onResponse(#NonNull Call<WeatherResponse> call, #NonNull Response <WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
time_zone.setText(weatherResponse.getTimezone());
time_field.setText(weatherResponse.getCurrent.getDt());
current_temp.setText(weatherResponse.getCurrent().getTemp()+" ℃");
rise_time.setText(weatherResponse.getCurrent().getSunrise()+" AM");
set_time.setText(weatherResponse.getCurrent().getSunset()+" PM");
temp_out.setText(weatherResponse.getCurrent().getTemp()+" ℃");
Press_out.setText(weatherResponse.getCurrent().getPressure()+" hpa");
Humid_out.setText(weatherResponse.getCurrent().getHumidity()+" %");
Ws_out.setText(weatherResponse.getCurrent).getWind_speed()+" Km/h");
Visi_out.setText(weatherResponse.getCurrent().getVisibility()+" m");
UV_out.setText(weatherResponse.getCurrent().getUvi());
}
}
Make sure to have class WeatherResponse and Current properly annotated.
That ? in the URL is useless.
make sure your enqueue() looks like this
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(#NotNull Call<WeatherResponse> call, #NotNull Response<WeatherResponse> response) {
if (response.body() != null) {
//...
}
}
#Override
public void onFailure(#NotNull Call<WeatherResponse> call, #NotNull Throwable t) {
t.printStackTrace();
}
});
Api (Interface)
package com.example.openweathermap;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface Api {
String BASE_URL="https://samples.openweathermap.org/data/2.5/";
#GET("weather/")
Call<WeatherResponse> getWeatherDetails(#Query("api_key")String api_key);
}
My Model Class
Here is my model class which consists of getters and setters
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Weather {
#SerializedName("coord")
private String coord;
#SerializedName("lon")
private String lon;
#SerializedName("lat")
private String lat;
#SerializedName("weather")
private List<Integer> weather = new ArrayList<Integer>();
#SerializedName("description")
private String description;
#SerializedName("base")
private String base;
#SerializedName("main")
private String main;
#SerializedName("temp")
private String temp;
#SerializedName("pressure")
private String pressure;
#SerializedName("humidity")
private Integer humidity;
#SerializedName("temp_min")
private String temp_min;
#SerializedName("temp_max")
private String temp_max;
#SerializedName("visibility")
private String visibility;
#SerializedName("wind")
private String wind;
#SerializedName("speed")
private String speed;
#SerializedName("deg")
private String deg;
#SerializedName("clouds")
private String clouds;
#SerializedName("all")
private String all;
#SerializedName("dt")
private String dt;
#SerializedName("sys")
private String sys;
#SerializedName("type")
private String type;
#SerializedName("id")
private String id;
#SerializedName("message")
private String message;
#SerializedName("country")
private String country;
#SerializedName("sunrise")
private String sunrise;
#SerializedName("sunset")
private String sunset;
public Weather(String description) {
this.description = description;
}
public Weather(String coord, String lon, String lat, List<Integer> weather, String base, String main, String temp, String pressure, Integer humidity, String temp_min, String temp_max, String visibility, String wind, String speed, String deg, String clouds, String all, String dt, String sys, String type, String id, String message, String country, String sunrise, String sunset) {
this.coord = coord;
this.lon = lon;
this.lat = lat;
this.weather = weather;
this.base = base;
this.main = main;
this.temp = temp;
this.pressure = pressure;
this.humidity = humidity;
this.temp_min = temp_min;
this.temp_max = temp_max;
this.visibility = visibility;
this.wind = wind;
this.speed = speed;
this.deg = deg;
this.clouds = clouds;
this.all = all;
this.dt = dt;
this.sys = sys;
this.type = type;
this.id = id;
this.message = message;
this.country = country;
this.sunrise = sunrise;
this.sunset = sunset;
}
public String getCoord() {
return coord;
}
public void setCoord(String coord) {
this.coord = coord;
}
public String getLon() {
return lon;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public List<Integer> getWeather() {
return weather;
}
public void setWeather(List<Integer> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getPressure() {
return pressure;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public String getTemp_min() {
return temp_min;
}
public void setTemp_min(String temp_min) {
this.temp_min = temp_min;
}
public String getTemp_max() {
return temp_max;
}
public void setTemp_max(String temp_max) {
this.temp_max = temp_max;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getClouds() {
return clouds;
}
public void setClouds(String clouds) {
this.clouds = clouds;
}
public String getAll() {
return all;
}
public void setAll(String all) {
this.all = all;
}
public String getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getSys() {
return sys;
}
public void setSys(String sys) {
this.sys = sys;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getSunrise() {
return sunrise;
}
public void setSunrise(String sunrise) {
this.sunrise = sunrise;
}
public String getSunset() {
return sunset;
}
public void setSunset(String sunset) {
this.sunset = sunset;
}
}
MyJSONResponse
I am trying to get this data in adapter which is a RecyclerView Adapter
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class WeatherResponse {
#SerializedName("weather")
private List<Weather> weather;
#SerializedName("id")
private String id;
#SerializedName("main")
private String main;
#SerializedName("description")
private String description;
#SerializedName("temp")
private String temp;
public WeatherResponse(List<Weather> weather) {
this.weather = weather;
}
public WeatherResponse(String weather, String id, String main, String description, String temp) {
this.id = id;
this.main = main;
this.description = description;
this.temp = temp;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
}
----------
**MyAdapter
This is the recyclerview adapter**
----------
package com.example.openweathermap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Weather> weathers;
public Context context;
public MyAdapter(ArrayList<Weather> weathers, Context context) {
this.weathers = weathers;
this.context = context;
}
public MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder holder, int position) {
Weather weather=weathers.get(position);
holder.temp.setText(weather.getTemp());
/*holder.name.setText(weather.getCountry());*/
holder.description.setText(weather.getDescription());
weathers=new ArrayList<>();
}
#Override
public int getItemCount() {
return weathers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView temp;
public TextView name;
public TextView description;
public ViewHolder(#NonNull View itemView) {
super(itemView);
temp=(TextView)itemView.findViewById(R.id.temp);
name=(TextView)itemView.findViewById(R.id.name);
description=(TextView)itemView.findViewById(R.id.description);
}
}
}
Main Activity
package com.example.openweathermap;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<Weather> weathersList;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "ae47e0f7eb5fbbce0c9cfbdf1373a1b3";
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
weathersList=new ArrayList<>();
if (API_KEY.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please obtain your API KEY first ", Toast.LENGTH_LONG).show();
return;
}
getWeather();
}
private void getWeather() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api=retrofit.create(Api.class);
Call<WeatherResponse> call=api.getWeatherDetails(API_KEY);
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
ArrayList<Weather> weathersList = (ArrayList<Weather>) response.body().getWeather();
adapter=new MyAdapter(weathersList,getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
I am getting an error as " Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView Adapter Error" in MyAdapter
I am again trying to use TMBD api. I am using a recyclerview to map the data into a list.But the response I am getting from the retrofit response is null.
Main Activity:
public class MainActivity extends AppCompatActivity {
public final static String BASE_URL="https://api.themoviedb.org";
public final static String apiKey="<ApiKey>";
public final static String language="en-US";
public final static String TAG="tag";
#BindView(R.id.recyclerView)
RecyclerView movieList;
DisplayAdapter adapter;
MovieResponse result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface=retrofit.create(ApiInterface.class);
apiInterface.getMovies(apiKey,language,1)
.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
if(response.isSuccessful())
{
result=response.body();
Log.e(TAG, "onCreate: "+result );
}
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) { }
});
Log.e(TAG, "onCreate: "+result );
adapter=new DisplayAdapter(getApplicationContext(),result);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(getApplicationContext(),1);
movieList.setLayoutManager(layoutManager);
movieList.setAdapter(adapter);
}
}
Response Class:
public class MovieResponse {
private int page;
private int total_results;
private int total_pages;
private List<ResultsBean> results;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public int getTotal_pages() {
return total_pages;
}
public void setTotal_pages(int total_pages) {
this.total_pages = total_pages;
}
public List<ResultsBean> getResults() {
return results;
}
public void setResults(List<ResultsBean> results) {
this.results = results;
}
public static class ResultsBean {
private double popularity;
private int vote_count;
private boolean video;
private String poster_path;
private int id;
private boolean adult;
private String backdrop_path;
private String original_language;
private String original_title;
private String title;
private double vote_average;
private String overview;
private String release_date;
private List<Integer> genre_ids;
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public int getVote_count() {
return vote_count;
}
public void setVote_count(int vote_count) {
this.vote_count = vote_count;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public String getPoster_path() {
return poster_path;
}
public void setPoster_path(String poster_path) {
this.poster_path = poster_path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getBackdrop_path() {
return backdrop_path;
}
public void setBackdrop_path(String backdrop_path) {
this.backdrop_path = backdrop_path;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getOriginal_title() {
return original_title;
}
public void setOriginal_title(String original_title) {
this.original_title = original_title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getVote_average() {
return vote_average;
}
public void setVote_average(double vote_average) {
this.vote_average = vote_average;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public List<Integer> getGenre_ids() {
return genre_ids;
}
public void setGenre_ids(List<Integer> genre_ids) {
this.genre_ids = genre_ids;
}
}
}
The Api Interface:
public interface ApiInterface {
#GET("3/movie/popular")
Call<MovieResponse> getMovies(
#Query("api_key") String apiKey,
#Query("language")String language,
#Query("page")int page
);
}
I am learning the concept of api calling. I dont understand why the response is null. If anybody could explai the reason it will be very helpfull.
This can be several things from what you posted.
It can be that the Java models don't match the JSON. You'd have to double check this.
It can be that you're getting an error, in which case retrofit does not have a response.body(), but rather a response.errorBody(). You can check this by debugging and checking response.erroeBody().string().
Or it could to be a classic example of asynch behaviour being handled like it's synchronous.
adapter=new DisplayAdapter(getApplicationContext(),result);
In this case you're using result, but it's assigned inside the retrofit callback which most likely finished after you create the adapter and hence result is still null.
You can move the creation of the adapter and setting it to the list inside the callback:
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
if(response.isSuccessful())
{
result=response.body();
Log.e(TAG, "onCreate: "+result );
adapter=new DisplayAdapter(getApplicationContext(),result);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(getApplicationContext(),1);
movieList.setLayoutManager(layoutManager);
movieList.setAdapter(adapter);
}
}
These are the only things that come to mind. Hope it helps.
EDIT
After taking a look at the github project, the only thing I found that is crashing the app is inside DisplayAdapter.java line 44:
holder.movieRating.setText((int) listOfMovies.getResults().get(position).getVote_average());
When you call setText that accepts an int you are in fact calling a method that will look in your strings.xml for a string with the id equal to the int you passed in. In this case, you are passing the vote average as an int. I'm guessing that what you want is to display the vote average, so the solution is to convert the double vote average to a string. This can easily be achieved with String.valueOf:
holder.movieRating.setText(String.valueOf(listOfMovies.getResults().get(position).getVote_average()));
Perhaps the most interesting bit is in the log message android.content.res.Resources$NotFoundException: String resource ID #0x7. This is thrown when trying to look for the string that doesn't exist.
API File
METHOD : GET
OUTPUT:
{
"status": true,
"message": "Subjects found.",
"data": {
"subjects": [
{
"subj_id": "2",
"name": "Maths",
"img": "Math.jpg"
},
{
"subj_id": "1",
"name": "Physics",
"img": "physics.png"
}
],
"total": 2
}
}
Model Class
public class SubjectTopics
{
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("message")
#Expose
private String message;
#SerializedName("data")
#Expose
private Data data;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public class Data {
#SerializedName("subjects")
#Expose
private List<Subjects> subjects = null;
#SerializedName("total")
#Expose
private Integer total;
public List<Subjects> getSubjects() {
return subjects;
}
public void setSubjects(List<Subjects> subjects) {
this.subjects = subjects;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Subjects {
#SerializedName("subj_id")
#Expose
private String subjId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("img")
#Expose
private String img;
public String getSubjId() {
return subjId;
}
public void setSubjId(String subjId) {
this.subjId = subjId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
My Adapter
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<Subjects> movies;
private int rowLayout;
private Context context;
public static class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView subjectName;
private TextView ID;
private ImageView ImageV;
private RelativeLayout relativeClick;
public MovieViewHolder(View v) {
super(v);
subjectName = (TextView) itemView.findViewById(R.id.textView);
relativeClick = (RelativeLayout) itemView.findViewById(R.id.relative_click);
ImageV = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public MoviesAdapter(List<Subjects> movies, int rowLayout, Context context) {
this.movies = movies;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public MoviesAdapter.MovieViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new MoviesAdapter.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MoviesAdapter.MovieViewHolder holder, final int position) {
holder.subjectName.setText(movies.get(position).getName());
holder.relativeClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SubjectTopicList.class);
intent.putExtra("subject_id", movies.get(position).getSubjId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Picasso.with(context)
.load(movies.get(position).getImg())
.placeholder(R.drawable.load)
.into(holder.ImageV);
}
#Override
public int getItemCount() {
return movies.size();
}
}
Activity
private void getSubjects() {
progressBar.setVisibility(View.VISIBLE);
Call<SubjectTopics> getProductsModelClassCall = webService.getSubjects();
getProductsModelClassCall.enqueue(new Callback<SubjectTopics>() {
#Override
public void onResponse(Call<SubjectTopics> call, Response<SubjectTopics> response) {
if (response.isSuccessful()) {
List<Subjects> movies = response.body().getData().getSubjects();
MoviesAdapter newAd=new MoviesAdapter(movies, R.layout.unit_test_row, getApplicationContext());
recyclerView.setAdapter(newAd);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(UnitTestSubjects.this, ""+apiError, Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SubjectTopics> call, Throwable t) {
Toast.makeText(UnitTestSubjects.this, "Please Try Again", Toast.LENGTH_SHORT).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
Retrofit Code
public class ServiceGenerator {
private final static String TAG = "ApiCall";
public static Retrofit getRetrofit(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
httpClient.connectTimeout(10, TimeUnit.SECONDS).readTimeout(14, TimeUnit.SECONDS).writeTimeout(16, TimeUnit.SECONDS);
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
return new Retrofit.Builder()
.baseUrl(WebServices.BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static Api getApi(){
return getRetrofit().create(Api.class);
}
}
After calling API's using Retrofit 2.0, Unable to get any response and getting this error:
Failure:
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall#5321
every-time after callback it directly coming out from the method
I have tried all possible ways to solve but not able to find any solution regarding this.
I think this is internal retrofit error or in the pojo class I guess. Please help!
I just want to develop an application that can scan barcode and I also just learned to develop the application. Well the problem dan i'm confusing is, how do the results of the scan barcode send data and match the data then appear like "User Registered".
I use the library from ZXING and RETROFIT,
here is my coding:
public class ScanQRCodeActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qrcode);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
}
#Override
protected void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result rawresult) {
if (rawresult == postData()) {
// i must write what?
}
Log.v("TAG", rawresult.getText());
Log.v("TAG", rawresult.getBarcodeFormat().toString());
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hasil Scan");
builder.setMessage(rawresult.getText());
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.create();
builder.show();
mScannerView.resumeCameraPreview(this);
}
And my model had 2 like this:
public class DataRegisteredIn {
#SerializedName("data")
#Expose
private RegisteredIn data;
#SerializedName("status")
#Expose
private String status;
public RegisteredIn getData() {
return data;
}
public void setData(RegisteredIn data) {
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
and this :
public class RegisteredIn {
#SerializedName("participants_id")
#Expose
private Integer participantsId;
#SerializedName("registration_number")
#Expose
private String registrationNumber;
#SerializedName("title_name")
#Expose
private String titleName;
#SerializedName("call_badge_name")
#Expose
private String callBadgeName;
#SerializedName("family_name")
#Expose
private String familyName;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_title")
#Expose
private String lastTitle;
#SerializedName("event_meals_id")
#Expose
private Integer eventMealsId;
#SerializedName("place")
#Expose
private String place;
#SerializedName("item_name")
#Expose
private String itemName;
public Integer getParticipantsId() {
return participantsId;
}
public void setParticipantsId(Integer participantsId) {
this.participantsId = participantsId;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getTitleName() {
return titleName;
}
public void setTitleName(String titleName) {
this.titleName = titleName;
}
public String getCallBadgeName() {
return callBadgeName;
}
public void setCallBadgeName(String callBadgeName) {
this.callBadgeName = callBadgeName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastTitle() {
return lastTitle;
}
public void setLastTitle(String lastTitle) {
this.lastTitle = lastTitle;
}
public Integer getEventMealsId() {
return eventMealsId;
}
public void setEventMealsId(Integer eventMealsId) {
this.eventMealsId = eventMealsId;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
This is also the first time I ask, so for example there is something I need to add let me clear, please tell me clearly because honestly I am very beginner.
thank you
Updated
this is a little picture what I want to make, in the picture to the left it is my application that can only get the value of the barcode but like the picture is the right one that I want, so like the value of the barcode is translated into a shape like the picture in right.