Android: Draw direction in google map java - java

how to find the best route for multiple locations in google maps api in android? I have some locations as LatLng but I dont know how specify a optimal route

ArrayList<LatLng> directionPoint = latLongList;
PolylineOptions rectLine = new PolylineOptions().width(8).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
Try this , pass your list of latlongs in latLongList

Using Google maps direction api you can acheive it, follow the documentation about using waypoints -
https://developers.google.com/maps/documentation/directions/intro#Waypoints
Now a fully functional api looks like this -
https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY
Here origin = starting point, destination = Ending point, waypoints = points that you want to cover, optimize:true = the route through the given waypoints will be optimized(i.e following Traveling Salesman Problem) and key = your map api key.
Now in order to save the api response here is the model class -
public class DirectionApiResponse {
private ArrayList<Geocoded_waypoints> geocoded_waypoints;
private String status;
private ArrayList<Routes> routes;
public ArrayList<Geocoded_waypoints> getGeocoded_waypoints ()
{
return geocoded_waypoints;
}
public void setGeocoded_waypoints (ArrayList<Geocoded_waypoints> geocoded_waypoints)
{
this.geocoded_waypoints = geocoded_waypoints;
}
public String getStatus ()
{
return status;
}
public void setStatus (String status)
{
this.status = status;
}
public ArrayList<Routes> getRoutes ()
{
return routes;
}
public void setRoutes (ArrayList<Routes> routes)
{
this.routes = routes;
}
#Override
public String toString()
{
return "ClassPojo [geocoded_waypoints = "+geocoded_waypoints+", status = "+status+", routes = "+routes+"]";
}
public class Geocoded_waypoints
{
private String place_id;
private String geocoder_status;
private ArrayList<String> types;
public String getPlace_id ()
{
return place_id;
}
public void setPlace_id (String place_id)
{
this.place_id = place_id;
}
public String getGeocoder_status ()
{
return geocoder_status;
}
public void setGeocoder_status (String geocoder_status)
{
this.geocoder_status = geocoder_status;
}
public ArrayList<String> getTypes ()
{
return types;
}
public void setTypes (ArrayList<String> types)
{
this.types = types;
}
#Override
public String toString()
{
return "ClassPojo [place_id = "+place_id+", geocoder_status = "+geocoder_status+", types = "+types+"]";
}
}
public class Routes {
private String summary;
private Bounds bounds;
private String copyrights;
private ArrayList<String> waypoint_order;
private ArrayList<Legs> legs;
private ArrayList<String> warnings;
private Overview_polyline overview_polyline;
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Bounds getBounds() {
return bounds;
}
public void setBounds(Bounds bounds) {
this.bounds = bounds;
}
public String getCopyrights() {
return copyrights;
}
public void setCopyrights(String copyrights) {
this.copyrights = copyrights;
}
public ArrayList<String> getWaypoint_order() {
return waypoint_order;
}
public void setWaypoint_order(ArrayList<String> waypoint_order) {
this.waypoint_order = waypoint_order;
}
public ArrayList<Legs> getLegs() {
return legs;
}
public void setLegs(ArrayList<Legs> legs) {
this.legs = legs;
}
public ArrayList<String> getWarnings() {
return warnings;
}
public void setWarnings(ArrayList<String> warnings) {
this.warnings = warnings;
}
public Overview_polyline getOverview_polyline() {
return overview_polyline;
}
public void setOverview_polyline(Overview_polyline overview_polyline) {
this.overview_polyline = overview_polyline;
}
#Override
public String toString() {
return "ClassPojo [summary = " + summary + ", bounds = " + bounds + ", copyrights = " + copyrights + ", waypoint_order = " + waypoint_order + ", legs = " + legs + ", warnings = " + warnings + ", overview_polyline = " + overview_polyline + "]";
}
public class Bounds
{
private Southwest southwest;
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;
}
#Override
public String toString()
{
return "ClassPojo [southwest = "+southwest+", northeast = "+northeast+"]";
}
public class Southwest
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class Northeast
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
}
public class Overview_polyline {
private String points;
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
#Override
public String toString() {
return "ClassPojo [points = " + points + "]";
}
}
public class Legs {
private Duration duration;
private Distance distance;
private End_location end_location;
private String start_address;
private String end_address;
private Start_location start_location;
private ArrayList<String> traffic_speed_entry;
private ArrayList<String> via_waypoint;
private ArrayList<Steps> steps;
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public End_location getEnd_location() {
return end_location;
}
public void setEnd_location(End_location end_location) {
this.end_location = end_location;
}
public String getStart_address() {
return start_address;
}
public void setStart_address(String start_address) {
this.start_address = start_address;
}
public String getEnd_address() {
return end_address;
}
public void setEnd_address(String end_address) {
this.end_address = end_address;
}
public Start_location getStart_location() {
return start_location;
}
public void setStart_location(Start_location start_location) {
this.start_location = start_location;
}
public ArrayList<String> getTraffic_speed_entry() {
return traffic_speed_entry;
}
public void setTraffic_speed_entry(ArrayList<String> traffic_speed_entry) {
this.traffic_speed_entry = traffic_speed_entry;
}
public ArrayList<String> getVia_waypoint() {
return via_waypoint;
}
public void setVia_waypoint(ArrayList<String> via_waypoint) {
this.via_waypoint = via_waypoint;
}
public ArrayList<Steps> getSteps() {
return steps;
}
public void setSteps(ArrayList<Steps> steps) {
this.steps = steps;
}
#Override
public String toString() {
return "ClassPojo [duration = " + duration + ", distance = " + distance + ", end_location = " + end_location + ", start_address = " + start_address + ", end_address = " + end_address + ", start_location = " + start_location + ", traffic_speed_entry = " + traffic_speed_entry + ", via_waypoint = " + via_waypoint + ", steps = " + steps + "]";
}
public class Duration {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Start_location
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class End_location {
private String lng;
private String lat;
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
#Override
public String toString() {
return "ClassPojo [lng = " + lng + ", lat = " + lat + "]";
}
}
public class Distance {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Steps
{
private String html_instructions;
private Duration duration;
private Distance distance;
private End_location end_location;
private Polyline polyline;
private Start_location start_location;
private String travel_mode;
public String getHtml_instructions ()
{
return html_instructions;
}
public void setHtml_instructions (String html_instructions)
{
this.html_instructions = html_instructions;
}
public Duration getDuration ()
{
return duration;
}
public void setDuration (Duration duration)
{
this.duration = duration;
}
public Distance getDistance ()
{
return distance;
}
public void setDistance (Distance distance)
{
this.distance = distance;
}
public End_location getEnd_location ()
{
return end_location;
}
public void setEnd_location (End_location end_location)
{
this.end_location = end_location;
}
public Polyline getPolyline ()
{
return polyline;
}
public void setPolyline (Polyline polyline)
{
this.polyline = polyline;
}
public Start_location getStart_location ()
{
return start_location;
}
public void setStart_location (Start_location start_location)
{
this.start_location = start_location;
}
public String getTravel_mode ()
{
return travel_mode;
}
public void setTravel_mode (String travel_mode)
{
this.travel_mode = travel_mode;
}
#Override
public String toString()
{
return "ClassPojo [html_instructions = "+html_instructions+", duration = "+duration+", distance = "+distance+", end_location = "+end_location+", polyline = "+polyline+", start_location = "+start_location+", travel_mode = "+travel_mode+"]";
}
public class Polyline
{
private String points;
public String getPoints ()
{
return points;
}
public void setPoints (String points)
{
this.points = points;
}
#Override
public String toString()
{
return "ClassPojo [points = "+points+"]";
}
}
}
}
}
}
Now to draw the route in between way-points you can use the below method -
private void setRoutePath(DirectionApiResponse directionObj){
gMap.clear();
addMarkers(localLeedsArrayList);
int count = 0;
ArrayList<LatLng> points = null;
DirectionApiResponse.Routes route = directionObj.getRoutes().get(0);
// Traversing through all the routes
for(DirectionApiResponse.Routes.Legs leg : route.getLegs()){
PolylineOptions lineOptions = new PolylineOptions();
points = new ArrayList<LatLng>();
Log.e("Route", leg.getStart_address()+" "+leg.getEnd_address());
// Fetching all the points in i-th route
//for(DirectionApiResponse.Routes.Legs.Steps step : leg.getSteps()){
for(int j=0;j<leg.getSteps().size();j++){
DirectionApiResponse.Routes.Legs.Steps step = leg.getSteps().get(j);
points.addAll(PolyUtil.decode(step.getPolyline().getPoints()));
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(20);
lineOptions.color(colors[count]);
Polyline polylineFinal = gMap.addPolyline(lineOptions);
count++;
}
Log.e("SouthWest",directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng());
Log.e("northeast",directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getNortheast().getLng());
/*LatLng lSouth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng()));
LatLng lNorth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLng()));
LatLngBounds latLngBounds = new LatLngBounds(lNorth,lSouth);
gMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,14));*/
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()),15));
}
Here gMap is the google map object..
******* UPDATE Api Calling********
In order to call the api Create interface IApiMethods and put the code below -
#GET("json?origin=35.693391,51.424261&destination=35.692032,51.432715&waypoints=35.691997,51.432758")
Call<DirectionApiResponse> getDirectionWalking(#Query("key")String key);
you can change the co-ordinates accordingly
Now call the method below to call the api and get the DirectionApiResponse object
private void getDirection(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/api/directions/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IApiMethods service = retrofit.create(IApiMethods.class);
Call<DirectionApiResponse> directionApiResponseCall = service.getDirectionWalking("YOUR API KEY");
directionApiResponseCall.enqueue(new Callback<DirectionApiResponse>() {
#Override
public void onResponse(Call<DirectionApiResponse> call, Response<DirectionApiResponse> response) {
setRoutePath(response.body());
}
#Override
public void onFailure(Call<DirectionApiResponse> call, Throwable t) {
}
});
}
Finally add the following dependencies to the app's build.gradle file -
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

How to get the route
You might want to look at the Distance Matrix service: https://developers.google.com/maps/documentation/javascript/distancematrix
It gives you distances between a set of origins and destinations, and might help you with narrowing down options.
2. To Find the best route :
If using the web service, ensure you set optimize:true before listing your waypoints, and check the waypoint_order array.
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
If use the JS API, set optimizeWaypoints:true in your request.
3. To draw polyline with the latlongs you have
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);

Related

Can't get all data from my model class using Retrofit

I need a little help, I'd already run out of ideas, tried to run this program out for two days, but I'm literally out of any ideas. So, I want from program to:
Display actual currency exchange
In another activity, the program should have a possibility to calculate currencies (let's say, we have a String with value "CZK" so the program should get from Model class currency value, to get that possibility to calculate the currencies, and here's the problem, I can't get those values. Actually, I can display it, but I want to call methods like getCZK(); because there are the actual values of those currencies. To be more accurate, ill try to explain it in other way: Let's say, the base currency is EUR, user selected option, that he want converse EUR to CZK, so program should have a String based of user choice (in this case it's String with value "CZK") now, program should search in switch case for value such as CZK, when it will find it, it should pass method like getCZK(); to suitable variable, to make conversion possible. I hope I explained it well to you guys.
Model class
public class Model {
#SerializedName("base")
private String base;
#SerializedName("rates")
private Map<String, Double> rates;
public void setRates(Map<String, Double> rates) {
this.rates = rates;
}
public void setBase(String base) {
this.base = base;
}
public String getBase() {
return base;
}
public Map<String, Double> getRates() {
return rates;
}
class Rates {
#SerializedName("BGN")
private Double bGN;
#SerializedName("NZD")
private Double nZD;
#SerializedName("ILS")
private Double iLS;
#SerializedName("RUB")
private Double rUB;
#SerializedName("CAD")
private Double cAD;
#SerializedName("USD")
private Double uSD;
#SerializedName("PHP")
private Double pHP;
#SerializedName("CHF")
private Double cHF;
#SerializedName("ZAR")
private Double zAR;
#SerializedName("AUD")
private Double aUD;
#SerializedName("JPY")
private Double jPY;
#SerializedName("TRY")
private Double tRY;
#SerializedName("HKD")
private Double hKD;
#SerializedName("MYR")
private Double mYR;
#SerializedName("THB")
private Double tHB;
#SerializedName("HRK")
private Double hRK;
#SerializedName("NOK")
private Double nOK;
#SerializedName("IDR")
private Double iDR;
#SerializedName("DKK")
private Double dKK;
#SerializedName("CZK")
private Double cZK;
#SerializedName("HUF")
private Double hUF;
#SerializedName("GBP")
private Double gBP;
#SerializedName("MXN")
private Double mXN;
#SerializedName("KRW")
private Double kRW;
#SerializedName("ISK")
private Double iSK;
#SerializedName("SGD")
private Double sGD;
#SerializedName("BRL")
private Double bRL;
#SerializedName("PLN")
private Double pLN;
#SerializedName("INR")
private Double iNR;
#SerializedName("RON")
private Double rON;
#SerializedName("CNY")
private Double cNY;
#SerializedName("SEK")
private Double sEK;
public Double getBGN() {
return bGN;
}
public void setBGN(Double value) {
this.bGN = value;
}
public Double getNZD() {
return nZD;
}
public void setNZD(Double value) {
this.nZD = value;
}
public Double getILS() {
return iLS;
}
public void setILS(Double value) {
this.iLS = value;
}
public Double getRUB() {
return rUB;
}
public void setRUB(Double value) {
this.rUB = value;
}
public Double getCAD() {
return cAD;
}
public void setCAD(Double value) {
this.cAD = value;
}
public Double getUSD() {
return uSD;
}
public void setUSD(Double value) {
this.uSD = value;
}
public Double getPHP() {
return pHP;
}
public void setPHP(Double value) {
this.pHP = value;
}
public Double getCHF() {
return cHF;
}
public void setCHF(Double value) {
this.cHF = value;
}
public Double getZAR() {
return zAR;
}
public void setZAR(Double value) {
this.zAR = value;
}
public Double getAUD() {
return aUD;
}
public void setAUD(Double value) {
this.aUD = value;
}
public Double getJPY() {
return jPY;
}
public void setJPY(Double value) {
this.jPY = value;
}
public Double getTRY() {
return tRY;
}
public void setTRY(Double value) {
this.tRY = value;
}
public Double getHKD() {
return hKD;
}
public void setHKD(Double value) {
this.hKD = value;
}
public Double getMYR() {
return mYR;
}
public void setMYR(Double value) {
this.mYR = value;
}
public Double getTHB() {
return tHB;
}
public void setTHB(Double value) {
this.tHB = value;
}
public Double getHRK() {
return hRK;
}
public void setHRK(Double value) {
this.hRK = value;
}
public Double getNOK() {
return nOK;
}
public void setNOK(Double value) {
this.nOK = value;
}
public Double getIDR() {
return iDR;
}
public void setIDR(Double value) {
this.iDR = value;
}
public Double getDKK() {
return dKK;
}
public void setDKK(Double value) {
this.dKK = value;
}
public Double getCZK() {
return cZK;
}
public void setCZK(Double value) {
this.cZK = value;
}
public Double getHUF() {
return hUF;
}
public void setHUF(Double value) {
this.hUF = value;
}
public Double getGBP() {
return gBP;
}
public void setGBP(Double value) {
this.gBP = value;
}
public Double getMXN() {
return mXN;
}
public void setMXN(Double value) {
this.mXN = value;
}
public Double getKRW() {
return kRW;
}
public void setKRW(Double value) {
this.kRW = value;
}
public Double getISK() {
return iSK;
}
public void setISK(Double value) {
this.iSK = value;
}
public Double getSGD() {
return sGD;
}
public void setSGD(Double value) {
this.sGD = value;
}
public Double getBRL() {
return bRL;
}
public void setBRL(Double value) {
this.bRL = value;
}
public Double getPLN() {
return pLN;
}
public void setPLN(Double value) {
this.pLN = value;
}
public Double getINR() {
return iNR;
}
public void setINR(Double value) {
this.iNR = value;
}
public Double getRON() {
return rON;
}
public void setRON(Double value) {
this.rON = value;
}
public Double getCNY() {
return cNY;
}
public void setCNY(Double value) {
this.cNY = value;
}
public Double getSEK() {
return sEK;
}
public void setSEK(Double value) {
this.sEK = value;
}
}
Api
public interface Api {
#GET("latest")
Call<Model> getRates();
#GET("latest")
Call<Model> getRatesByGivenCurrency(#Query("base") String base);
}
Java class
public class exchange_currency extends AppCompatActivity {
Api api;
TextView currentCurrency, fromTV, toTV, receivedValue;
EditText enteredValue;
Spinner spinner;
Button button;
List<Model> list;
String keyString;
double valueDouble;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_currency);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.exchangeratesapi.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
spinner = (Spinner) findViewById(R.id.currencyNationalitiesSpinner);
button = (Button) findViewById(R.id.btn);
currentCurrency = (TextView) findViewById(R.id.currentValue);
fromTV = (TextView) findViewById(R.id.actualCurrency);
toTV = (TextView) findViewById(R.id.wantedCurrency);
receivedValue = (TextView) findViewById(R.id.receivedValue);
enteredValue = (EditText) findViewById(R.id.actualET);
api = retrofit.create(Api.class);
createRetrofit();
}
public void createRetrofit() {
Call<Model> call = api.getRates();
call.enqueue(new Callback<Model>() {
#Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (!response.isSuccessful()) {
Toast.makeText(exchange_currency.this, response.code(), Toast.LENGTH_LONG).show();
}
list = Collections.singletonList(response.body());
for (Model model : list) {
Iterator<Map.Entry<String, Double>> entries = model.getRates().entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
keyString = (String) entry.getKey();
valueDouble = (Double) entry.getValue();
toTV.append(keyString + "\n");
receivedValue.append(String.valueOf(valueDouble) + "\n");
toTV.append((CharSequence) model.getRates());
}
}
}
#Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(exchange_currency.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Api that I using https://exchangeratesapi.io/
exemplary GET response from API
{"base":"EUR","rates":{"BGN":1.9558,"NZD":1.7056,"ILS":4.0147,"RUB":73.2104,"CAD":1.5117,"USD":1.1226,"PHP":58.898,"CHF":1.1307,"ZAR":15.9746,"AUD":1.6162,"JPY":123.0,"TRY":6.7732,"HKD":8.8112,"MYR":4.6818,"THB":35.362,"HRK":7.4113,"NOK":9.799,"IDR":16199.12,"DKK":7.4691,"CZK":25.751,"HUF":324.23,"GBP":0.86723,"MXN":21.5178,"KRW":1333.2,"ISK":137.8,"SGD":1.5366,"BRL":4.4743,"PLN":4.3061,"INR":79.0375,"RON":4.7615,"CNY":7.7252,"SEK":10.779},"date":"2019-05-14"}
these lines here
#SerializedName("rates")
private Map<String, Double> rates;
Should instead be like this
#SerializedName("rates")
private Rates rates;
Then in the onResponse you can get each of the values from the response like
Log.d("check", "CAD: "+response.body().getRates().getCAD());
Log.d("check", "GBP: "+response.body().getRates().getGBP());
Which returns
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: CAD: 1.5117
2019-05-14 17:27:16.015 6816-6816/com.test.testing D/check: GBP: 0.86723
Does this answer your question?

Getting null from POJO after using JACKSON ObjectMapper

I'm struggling whit this problem for a while and can't find a solution.
My intention is to retrieve a POJO from the following JSON using Jackson:
{
"date": "2018-11-27",
"rates": {
"BGN": 1.9558,
"CAD": 1.5018,
"BRL": 4.4011,
"HUF": 324.06,
"DKK": 7.4617,
"JPY": 128.66,
"ILS": 4.2215,
"TRY": 5.9313,
"RON": 4.6583,
"GBP": 0.88748,
"PHP": 59.439,
"HRK": 7.4275,
"NOK": 9.7325,
"USD": 1.1328,
"MXN": 23.1784,
"AUD": 1.5631,
"IDR": 16410.59,
"KRW": 1279.17,
"HKD": 8.8679,
"ZAR": 15.632,
"ISK": 141,
"CZK": 25.914,
"THB": 37.371,
"MYR": 4.7498,
"NZD": 1.6647,
"PLN": 4.2902,
"SEK": 10.2823,
"RUB": 75.6401,
"CNY": 7.8708,
"SGD": 1.5582,
"CHF": 1.1309,
"INR": 80.162
},
"base": "EUR"
}
I solved it with the following code:
public class JsonToPojo {
private static final String URL_LATEST = "https://api.exchangeratesapi.io/latest";
public static String getJson() {
try {
URL url = new URL(URL_LATEST);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
response.append(inputLine);
}
bufferedReader.close();
urlConnection.disconnect();
return response.toString();
} catch (IOException e) {
e.getStackTrace();
return null;
}
}
}
This is my POJO:
public class Currency {
private String date;
private Rates rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Rates getRates() {
return rates;
}
public void setRates(Rates rates) {
this.rates = rates;
}
}
Class using ObjectMapper:
public class CurrencyService {
public static Currency getLatestCurrency(){
try {
ObjectMapper mapper = new ObjectMapper();
Currency currency = mapper.readValue(JsonToPojo.getJson(), Currency.class);
return currency;
}catch (IOException e){
e.getStackTrace();
return null;
}
}
}
When I'm trying to call the get method on my POJO object, I'm getting a NullPointException, so something is wrong with databinding.
my Rates class.
public class Rates {
private float BGN;
private float CAD;
private float BRL;
private float HUF;
private float DKK;
private float JPY;
private float ILS;
private float TRY;
private float RON;
private float GBP;
private float PHP;
private float HRK;
private float NOK;
private float ZAR;
private float MXD;
private float AUD;
private float USD;
private float KRW;
private float HKD;
private float EUR;
private float ISK;
private float CZK;
private float THB;
private float MYR;
private float NZD;
private float PLN;
private float CHF;
private float SEK;
private float CNY;
private float SGD;
private float INR;
private float IDR;
private float RUB;
public void setBGN(Float BGN) {
this.BGN = BGN;
}
public void setCAD(Float CAD) {
this.CAD = CAD;
}
public void setBRL(Float BRL) {
this.BRL = BRL;
}
public void setHUF(Float HUF) {
this.HUF = HUF;
}
public void setDKK(Float DKK) {
this.DKK = DKK;
}
public void setJPY(Float JPY) {
this.JPY = JPY;
}
public void setILS(Float ILS) {
this.ILS = ILS;
}
public void setTRY(Float TRY) {
this.TRY = TRY;
}
public void setRON(Float RON) {
this.RON = RON;
}
public void setGBP(Float GBP) {
this.GBP = GBP;
}
public void setPHP(Float PHP) {
this.PHP = PHP;
}
public void setHRK(Float HRK) {
this.HRK = HRK;
}
public void setNOK(Float NOK) {
this.NOK = NOK;
}
public void setZAR(Float ZAR) {
this.ZAR = ZAR;
}
public void setMXD(Float MXD) {
this.MXD = MXD;
}
public void setAUD(Float AUD) {
this.AUD = AUD;
}
public void setUSD(Float USD) {
this.USD = USD;
}
public void setKRW(Float KRW) {
this.KRW = KRW;
}
public void setHKD(Float HKD) {
this.HKD = HKD;
}
public void setEUR(Float EUR) {
this.EUR = EUR;
}
public void setISK(Float ISK) {
this.ISK = ISK;
}
public void setCZK(Float CZK) {
this.CZK = CZK;
}
public void setTHB(Float THB) {
this.THB = THB;
}
public void setMYR(Float MYR) {
this.MYR = MYR;
}
public void setNZD(Float NZD) {
this.NZD = NZD;
}
public void setPLN(Float PLN) {
this.PLN = PLN;
}
public void setCHF(Float CHF) {
this.CHF = CHF;
}
public void setSEK(Float SEK) {
this.SEK = SEK;
}
public void setCNY(Float CNY) {
this.CNY = CNY;
}
public void setSGD(Float SGD) {
this.SGD = SGD;
}
public void setINR(Float INR) {
this.INR = INR;
}
public void setIDR(Float IDR) {
this.IDR = IDR;
}
public void setRUB(Float RUB) {
this.RUB = RUB;
}
public Float getBGN() {
return BGN;
}
public Float getCAD() {
return CAD;
}
public Float getBRL() {
return BRL;
}
public Float getHUF() {
return HUF;
}
public Float getDKK() {
return DKK;
}
public Float getJPY() {
return JPY;
}
public Float getILS() {
return ILS;
}
public Float getTRY() {
return TRY;
}
public Float getRON() {
return RON;
}
public Float getGBP() {
return GBP;
}
public Float getPHP() {
return PHP;
}
public Float getHRK() {
return HRK;
}
public Float getNOK() {
return NOK;
}
public Float getZAR() {
return ZAR;
}
public Float getMXD() {
return MXD;
}
public Float getAUD() {
return AUD;
}
public Float getUSD() {
return USD;
}
public Float getKRW() {
return KRW;
}
public Float getHKD() {
return HKD;
}
public Float getEUR() {
return EUR;
}
public Float getISK() {
return ISK;
}
public Float getCZK() {
return CZK;
}
public Float getTHB() {
return THB;
}
public Float getMYR() {
return MYR;
}
public Float getNZD() {
return NZD;
}
public Float getPLN() {
return PLN;
}
public Float getCHF() {
return CHF;
}
public Float getSEK() {
return SEK;
}
public Float getCNY() {
return CNY;
}
public Float getSGD() {
return SGD;
}
public Float getINR() {
return INR;
}
public Float getIDR() {
return IDR;
}
public Float getRUB() {
return RUB;
}
}
I've checked your code locally, and have got it working. I didn't have a Rates class, so I used a Map instead (to map the name, with the rate (float)):
import java.util.Map;
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Map<String, Float> getRates() {
return rates;
}
public Float getSingleRate(String rateKey) {
if (rates.containsKey(rateKey)) {
return rates.get(rateKey);
}
return 0.0F;
}
public void setRates(Map<String, Float> rates) {
this.rates = rates;
}
}
I have added the following main() method to your JSonToPojo class:
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Currency currency = new Currency();
String jsonStr = getJson();
try {
currency = mapper.readValue(jsonStr, Currency.class);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(jsonStr);
System.out.println(currency.getSingleRate("BGN"));
System.out.println("finished");
}
Running the main() method, produces the following output (I have used [snip] instead of printing out all the JSon (twice)):
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
{"date":"2018-11-27","rates": {"BGN":1.9558, [snip] }
1.9558
finished
The output for "BGN" is:
1.9558
You can refer to http://www.jsonschema2pojo.org/ to get the correct pojo for your json.
Below is the one I created (moderatley modified)
You can replace like Object date with Date date and so on. If it doesn't work than there is probably some error in your POJO
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Example {
#JsonProperty("date")
private Object date;
#JsonProperty("rates")
private Object rates;
#JsonProperty("base")
private Object base;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("date")
public Object getDate() {
return date;
}
#JsonProperty("date")
public void setDate(Object date) {
this.date = date;
}
#JsonProperty("rates")
public Object getRates() {
return rates;
}
#JsonProperty("rates")
public void setRates(Object rates) {
this.rates = rates;
}
#JsonProperty("base")
public Object getBase() {
return base;
}
#JsonProperty("base")
public void setBase(Object base) {
this.base = base;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return "date:" + date.toString() +
",\nrates:" + rates.toString() +
",\nbase: " + base.toString();
}
}
And here is the driver class in which you can read the object and pass in the user defined file path ( i have set it to "test-json.json"). You can update this with your local file path address.
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String... args){
Main main = new Main();
Example example = main.readObjectDataFromJsonFile(Example.class,"test-json.json");
System.out.println(example);
}
public <T> T readObjectDataFromJsonFile(Class<T> clazz, String jsonFilePath) {
T populatedObject = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
String objectJson = "";
Stream<String> lines = Files.lines(Paths.get(jsonFilePath));
objectJson = lines.collect(Collectors.joining());
lines.close();
populatedObject = objectMapper.readValue(objectJson, clazz);
} catch (IOException ioException) {
System.out.println("Exception in reading json file");
System.out.println(ioException.getMessage());
}
return populatedObject;
}
}
you can use
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
without any change to your Pojos, but I had to add MXN as a property to Rates class. But ideal way to handle this is having a Map for the rates. Because it can change any time as I understood, either way its easier for access. So change Currency class as follows.
public class Currency {
private String date;
private Map<String, Float> rates;
private String base;
// getters and setters
}
access exchange rates as getRates().get('MXN') // returns value.

How can I set My Json Value in Adapter

I Am Having two JsonArray in Which there is JsonObject I have Got the String of each value but the problem is that when i am passing i into adapter I am getting indexOutofbound exeption because my value are getting Store in my object class so can any one help me how can i send my data to Object so that i can inflate to recyclerView.
private void callola() {
progressDialog = new ProgressDialog(CabBookingActivity.this);
progressDialog.setMessage("Loading ...");
progressDialog.setCancelable(false);
progressDialog.show();
final RequestQueue queue = Volley.newRequestQueue(CabBookingActivity.this);
String url = "https://www.reboundindia.com/app/application/ola/ride_estimate.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.setCancelable(true);
progressDialog.dismiss();
Log.e("sushil Call ola response", response);
try {
JSONObject mainObj = new JSONObject(response);
arrayList = new ArrayList<>();
String result = mainObj.getString("result");
int i, j;
ArrayList categoriess, Ride;
if (result.equals("606")) {
JSONObject message = mainObj.getJSONObject("message");
categories = message.getJSONArray("categories");
ride_estimate = message.getJSONArray("ride_estimate");
// JSONArray ride_estimate = message.getJSONArray("ride_estimate");
for (i = 0; i < categories.length(); i++) {
Log.e("sushil", String.valueOf(i));
jsonObject = categories.getJSONObject(i);
id = jsonObject.getString("id");
display_name = jsonObject.getString("display_name");
image = jsonObject.getString("image");
eta = jsonObject.getString("eta");
Log.e("OutPut", id + " " + eta + " " + image + " " + amount_min + " " + amount_max);
}
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
}
}
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
Log.e("sushil ride_estimate", distance + " " + amount_min + " " + amount_max);
AdapterOlaUber adapterOlaUber = new AdapterOlaUber(context, arrayList, CabBookingActivity.this);
recyclerView.setAdapter(adapterOlaUber);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("pickup_lat", "" + pickLat);
params.put("pickup_lng", "" + pickLong);
params.put("drop_lat", String.valueOf(dropLat));
params.put("drop_lng", String.valueOf(dropLong));
params.put("category", "all");
params.put("token", token);
Log.e("sushil param", String.valueOf(params));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
Here is my JSONRESPONSE
{
"result":"606",
"message":{
"categories":[
{
"id":"micro",
"display_name":"Micro",
"currency":"INR",
"distance_unit":"kilometre",
"time_unit":"minute",
"eta":5,
"distance":"0.7",
"ride_later_enabled":"true",
"image":"http:\/\/d1foexe15giopy.cloudfront.net\/micro.png",
"cancellation_policy":{
"cancellation_charge":50,
"currency":"INR",
"cancellation_charge_applies_after_time":5,
"time_unit":"minute"
},
"fare_breakup":[
{
"type":"flat_rate",
"minimum_distance":0,
"minimum_time":0,
"base_fare":50,
"minimum_fare":60,
"cost_per_distance":6,
"waiting_cost_per_minute":0,
"ride_cost_per_minute":1.5,
"surcharge":[
],
"rates_lower_than_usual":false,
"rates_higher_than_usual":false
}
]
},
{ },
{ },
{ },
{ },
{ },
{ },
{ },
{ }
],
"ride_estimate":[
{
"category":"prime_play",
"distance":3.99,
"travel_time_in_minutes":30,
"amount_min":155,
"amount_max":163,
"discounts":{
"discount_type":null,
"discount_code":null,
"discount_mode":null,
"discount":0,
"cashback":0
}
},
{ },
{ },
{ },
{ },
{ },
{ },
{ }
]
}
}
My Problem is that how can send the data in model.
My Model Should contain data Like id,displayName,amountMin,eta,image,amountMax
First of all you need to make two different models for category and ride_estimate.Because they both are in different loops. Also try this
for (j = 0; j < ride_estimate.length(); j++) {
Log.e("sushil", String.valueOf(j));
rideestimate = ride_estimate.getJSONObject(j);
distance = rideestimate.getString("distance");
amount_min = rideestimate.getString("amount_min");
amount_max = rideestimate.getString("amount_max");
category = rideestimate.getString("category");
OlaUberModel olaUberModel = new OlaUberModel(category, display_name, amount_min, eta, image, amount_max);
arrayList.add(olaUberModel);
}
May be this would helpful for you..
Thanks!
replace
eta = jsonObject.getString("eta");
by
int eta = jsonObject.getInt("eta");
On the basis of id of any cab type "prime" you can fetch image. what say
create some class as per your data
-----------------------------------com.example.CancellationPolicy.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class CancellationPolicy {
#SerializedName("cancellation_charge")
#Expose
private Integer cancellationCharge;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("cancellation_charge_applies_after_time")
#Expose
private Integer cancellationChargeAppliesAfterTime;
#SerializedName("time_unit")
#Expose
private String timeUnit;
public Integer getCancellationCharge() {
return cancellationCharge;
}
public void setCancellationCharge(Integer cancellationCharge) {
this.cancellationCharge = cancellationCharge;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getCancellationChargeAppliesAfterTime() {
return cancellationChargeAppliesAfterTime;
}
public void setCancellationChargeAppliesAfterTime(Integer cancellationChargeAppliesAfterTime) {
this.cancellationChargeAppliesAfterTime = cancellationChargeAppliesAfterTime;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
}
-----------------------------------com.example.Category.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("currency")
#Expose
private String currency;
#SerializedName("distance_unit")
#Expose
private String distanceUnit;
#SerializedName("time_unit")
#Expose
private String timeUnit;
#SerializedName("eta")
#Expose
private Integer eta;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("ride_later_enabled")
#Expose
private String rideLaterEnabled;
#SerializedName("image")
#Expose
private String image;
#SerializedName("cancellation_policy")
#Expose
private CancellationPolicy cancellationPolicy;
#SerializedName("fare_breakup")
#Expose
private List<FareBreakup> fareBreakup = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getDistanceUnit() {
return distanceUnit;
}
public void setDistanceUnit(String distanceUnit) {
this.distanceUnit = distanceUnit;
}
public String getTimeUnit() {
return timeUnit;
}
public void setTimeUnit(String timeUnit) {
this.timeUnit = timeUnit;
}
public Integer getEta() {
return eta;
}
public void setEta(Integer eta) {
this.eta = eta;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getRideLaterEnabled() {
return rideLaterEnabled;
}
public void setRideLaterEnabled(String rideLaterEnabled) {
this.rideLaterEnabled = rideLaterEnabled;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public CancellationPolicy getCancellationPolicy() {
return cancellationPolicy;
}
public void setCancellationPolicy(CancellationPolicy cancellationPolicy) {
this.cancellationPolicy = cancellationPolicy;
}
public List<FareBreakup> getFareBreakup() {
return fareBreakup;
}
public void setFareBreakup(List<FareBreakup> fareBreakup) {
this.fareBreakup = fareBreakup;
}
}
-----------------------------------com.example.Discounts.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Discounts {
#SerializedName("discount_type")
#Expose
private Object discountType;
#SerializedName("discount_code")
#Expose
private Object discountCode;
#SerializedName("discount_mode")
#Expose
private Object discountMode;
#SerializedName("discount")
#Expose
private Integer discount;
#SerializedName("cashback")
#Expose
private Integer cashback;
public Object getDiscountType() {
return discountType;
}
public void setDiscountType(Object discountType) {
this.discountType = discountType;
}
public Object getDiscountCode() {
return discountCode;
}
public void setDiscountCode(Object discountCode) {
this.discountCode = discountCode;
}
public Object getDiscountMode() {
return discountMode;
}
public void setDiscountMode(Object discountMode) {
this.discountMode = discountMode;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Integer getCashback() {
return cashback;
}
public void setCashback(Integer cashback) {
this.cashback = cashback;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private String result;
#SerializedName("message")
#Expose
private Message message;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
-----------------------------------com.example.FareBreakup.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FareBreakup {
#SerializedName("type")
#Expose
private String type;
#SerializedName("minimum_distance")
#Expose
private Integer minimumDistance;
#SerializedName("minimum_time")
#Expose
private Integer minimumTime;
#SerializedName("base_fare")
#Expose
private Integer baseFare;
#SerializedName("minimum_fare")
#Expose
private Integer minimumFare;
#SerializedName("cost_per_distance")
#Expose
private Integer costPerDistance;
#SerializedName("waiting_cost_per_minute")
#Expose
private Integer waitingCostPerMinute;
#SerializedName("ride_cost_per_minute")
#Expose
private Double rideCostPerMinute;
#SerializedName("surcharge")
#Expose
private List<Object> surcharge = null;
#SerializedName("rates_lower_than_usual")
#Expose
private Boolean ratesLowerThanUsual;
#SerializedName("rates_higher_than_usual")
#Expose
private Boolean ratesHigherThanUsual;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinimumDistance() {
return minimumDistance;
}
public void setMinimumDistance(Integer minimumDistance) {
this.minimumDistance = minimumDistance;
}
public Integer getMinimumTime() {
return minimumTime;
}
public void setMinimumTime(Integer minimumTime) {
this.minimumTime = minimumTime;
}
public Integer getBaseFare() {
return baseFare;
}
public void setBaseFare(Integer baseFare) {
this.baseFare = baseFare;
}
public Integer getMinimumFare() {
return minimumFare;
}
public void setMinimumFare(Integer minimumFare) {
this.minimumFare = minimumFare;
}
public Integer getCostPerDistance() {
return costPerDistance;
}
public void setCostPerDistance(Integer costPerDistance) {
this.costPerDistance = costPerDistance;
}
public Integer getWaitingCostPerMinute() {
return waitingCostPerMinute;
}
public void setWaitingCostPerMinute(Integer waitingCostPerMinute) {
this.waitingCostPerMinute = waitingCostPerMinute;
}
public Double getRideCostPerMinute() {
return rideCostPerMinute;
}
public void setRideCostPerMinute(Double rideCostPerMinute) {
this.rideCostPerMinute = rideCostPerMinute;
}
public List<Object> getSurcharge() {
return surcharge;
}
public void setSurcharge(List<Object> surcharge) {
this.surcharge = surcharge;
}
public Boolean getRatesLowerThanUsual() {
return ratesLowerThanUsual;
}
public void setRatesLowerThanUsual(Boolean ratesLowerThanUsual) {
this.ratesLowerThanUsual = ratesLowerThanUsual;
}
public Boolean getRatesHigherThanUsual() {
return ratesHigherThanUsual;
}
public void setRatesHigherThanUsual(Boolean ratesHigherThanUsual) {
this.ratesHigherThanUsual = ratesHigherThanUsual;
}
}
-----------------------------------com.example.Message.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("categories")
#Expose
private List<Category> categories = null;
#SerializedName("ride_estimate")
#Expose
private List<RideEstimate> rideEstimate = null;
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<RideEstimate> getRideEstimate() {
return rideEstimate;
}
public void setRideEstimate(List<RideEstimate> rideEstimate) {
this.rideEstimate = rideEstimate;
}
}
-----------------------------------com.example.RideEstimate.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RideEstimate {
#SerializedName("category")
#Expose
private String category;
#SerializedName("distance")
#Expose
private Double distance;
#SerializedName("travel_time_in_minutes")
#Expose
private Integer travelTimeInMinutes;
#SerializedName("amount_min")
#Expose
private Integer amountMin;
#SerializedName("amount_max")
#Expose
private Integer amountMax;
#SerializedName("discounts")
#Expose
private Discounts discounts;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getDistance() {
return distance;
}
public void setDistance(Double distance) {
this.distance = distance;
}
public Integer getTravelTimeInMinutes() {
return travelTimeInMinutes;
}
public void setTravelTimeInMinutes(Integer travelTimeInMinutes) {
this.travelTimeInMinutes = travelTimeInMinutes;
}
public Integer getAmountMin() {
return amountMin;
}
public void setAmountMin(Integer amountMin) {
this.amountMin = amountMin;
}
public Integer getAmountMax() {
return amountMax;
}
public void setAmountMax(Integer amountMax) {
this.amountMax = amountMax;
}
public Discounts getDiscounts() {
return discounts;
}
public void setDiscounts(Discounts discounts) {
this.discounts = discounts;
}
}
Now compile a library compile 'com.google.code.gson:gson:2.8.2'
then write few line to get your data fill in class
Gson gson = new Gson();
Example example = gson.fromJson(mainObj, Example.class);
Now you can try to fetch your categories like this
example.getCategories();

Polymorphism java loop error

I'm having a problem regarding a polymorphic invocation inside a loop.
I have an abstract class called Item that has two subclasses ClothingItem and SportItem and an abstract method called printBudgetGST(Items[] item) to return a string of an item with updated pricing which include tax.
Item Class :
public abstract class Item
{
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST(Item[] items);
}
ClothingItem class
public class ClothingItem extends Item
{
public ClothingItem(){
}
public ClothingItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
#Override
public String printBudgetGST(Item[] item)
{
String stringitem ="";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true&&item[i].getCurrentPrice()<100.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
SportsItem class:
public class SportsItem extends Item
{
public SportsItem(){
}
public SportsItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
public String printBudgetGST(Item[] item)
{
String stringitem = "";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true &&item[i].getCurrentPrice()<150.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + "SportsItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
Test class :
public class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem()
{
for(int i =0 ;i<itemList.length;i++)
{
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST(itemList).length()>0)
{
System.out.println(itemList[i].printBudgetGST(itemList));
}
}
}
}
public class TestRetailItem {
public static void main(String[] args)
{
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
OUTPUT :
The output should return a list of items which is on tax(GST) and with the updated pricing information like the example below
The problem is that you are passing to printBudgetGST the whole array of items and iterating over that array inside your implementations of printBudgetGST. Instead, you should remove that parameter and inside printBudgetGST you should simply call getCurrentPrice() and getCode() on this rather than on each item[i].
In addition, you are doing the check for maximum price (< 100 or < 150) inside the item subclasses but it's best to do this alongside the other checks in printItem. Because the max price depends on the subclass (SportsItem vs ClothinItem) I recommend you to create an abstract method boolean isOnBudget() in Item and implement accordingly in those two subclasses.
A fully fixed version of your code is
public abstract class Item {
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST();
public abstract boolean isOnBudget();
}
class ClothingItem extends Item {
public ClothingItem() {
}
public ClothingItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
#Override
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 100.00;
}
}
class SportsItem extends Item {
public SportsItem() {
}
public SportsItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + "SportsItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 150.00;
}
}
class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem() {
for(int i =0 ;i<itemList.length;i++) {
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST().length()>0 && itemList[i].isOnBudget())
{
System.out.println(itemList[i].printBudgetGST());
}
}
}
}
class TestRetailItem {
public static void main(String[] args) {
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}

Cannot run through loop to getAllPassengers

Hey i want to loop through planes to get all passengers and add them to a count to display all passengers for all planes. But im getting an error: Cannot iterate over an array or an instance.
Here is the method:
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : plane.getPassengerNumber())
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
Plane
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
public Plane()
{
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public boolean isLanded() {
return isLanded;
}
public void setLanded(boolean isLanded) {
this.isLanded = isLanded;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
passengerNumber is an int. You need to iterate over an Iterable such as an ArrayList:
for (Plane plane: myPlaneList) {
passengers += plane.getPassengerNumber();
}
You are trying to iterate through Plane objects, but your collection is just an int. You'll need a collection of Plane objects
int passengers = 0;
for(Plane plane : myPlanes)
{
passengers += plane.getPassengerNumber();
}
You are trying to iterate over an int, you need to iterate over an java.util.Iterable
Your posted code does not contain the information needed to answer this question.
You are showing us the class Plane, but in order to have more than one plane, you probably have a List<Plane> or a Plane[] somewhere else in the code. Here's one example that would work:
public class Main {
List<Plane> allPlanes; // Load in the omitted code somewhere else
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : allPlanes) // note the change
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
}

Categories

Resources