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?
Related
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.
Here is the intentservice where I get error in logout
public class intentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
RequestQueue queue = MyVolley.getRequestQueue(this);
queue = MyVolley.getRequestQueue(this);
GsonRequest<Routes> gsonRequest = new GsonRequest<Routes>(
url_routes + key, Routes.class, null, createMyReqSuccessListenerRoutes(key),
createMyReqErrorListenerRoutes());
queue.add(gsonRequest);
Function for receive in intentservice
private Response.Listener<Routes> createMyReqSuccessListenerRoutes(final int key) {
return new Response.Listener<Routes>() {
#SuppressLint("LongLogTag")
#Override
public void onResponse(Routes response) {
if (ds.checkTable(DataBaseHelper.TABLE_NAME_TRANSPORT)) {
ds.createTableRoute();
final int size = response.getResults().size();
if (size > 0) {
final int part = 100 / size;
int i;
for (i = 0; i < size; i++) {
ds.insertRoutes(DataBaseHelper.TABLE_NAME_ROUTE,
response.getResults().get(i).getRoute(),
response.getResults().get(i).getStop_id(),
response.getResults().get(i).getNum(),
response.getResults().get(i).getLat(),
response.getResults().get(i).getLon(),
response.getResults().get(i).getRadius(),
response.getResults().get(i).getAudio(),
response.getResults().get(i).getEnd(),
response.getResults().get(i).getMove_time(),
response.getResults().get(i).getStop_time(),
response.getResults().get(i).getPlayonce(),
response.getResults().get(i).getName(),
key
);
}
}
}
}
}
}
Call it from another activity
serviceintentRoute = new Intent(DataBase.this, intentService.class);
startService(serviceintentRoute.putExtra("key", idp));
My RouteData class
public class RoutesData {
private Integer route;
private Integer stop_id;
private Integer num;
private String name;
private String lat;
private String lon;
private Integer radius;
private String audio;
private Integer stop_time;
private Integer move_time;
private Integer end;
private Integer trid;
public RoutesData() {
}
public Integer getRoute() {
return route;
}
public void setRoute(Integer route) {
this.route = route;
}
public Integer getStop_id() {
return stop_id;
}
public void setStop_id(Integer stop_id) {
this.stop_id = stop_id;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getRadius() {
return radius;
}
public void setRadius(Integer radius) {
this.radius = radius;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTrid() {
return trid;
}
public void setTrid(Integer trid) {
this.trid = trid;
}
public Integer getStop_time() {
return stop_time;
}
public void setStop_time(Integer stop_time) {
this.stop_time = stop_time;
}
public Integer getMove_time() {
return move_time;
}
public void setMove_time(Integer move_time) {
this.move_time = move_time;
}
}
And Routes
public class Routes {
public ArrayList<RoutesData> data;
public Routes(ArrayList<RoutesData> data) {
this.data = data;
}
#Override
public String toString() {
return "Response [results=" + data + "]";
}
public ArrayList<RoutesData> getResults() {
return data;
}
}
Class MyVolley
public class MyVolley {
private static RequestQueue mRequestQueue;
private Context context;
public MyVolley() {
}
static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
int cacheSize = 1024 * 1024 * memClass / 8;
// mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
}
public static RequestQueue getRequestQueue(Context mContext) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext);
}
return mRequestQueue;
}
}
class gsonrequest
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.d("Response.success", json.toString());
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
I don`t know how to receive all data
Logcat output in Android Studio
The logout
D/Response.success: {"status":true,"data"
:[{"route":1,"num":1,"stop_id":30,"name":"\u043f\u043b.......etc..
not full the line, the next line I had the error
D/ERROR RESPONSE: ERROR RESPONSE Routes
If I understand right the memory is not enough for all array of json massive
I had tried to increase it via
int cacheSize = 2048 * 2048 * memClass / 8;
but not luck
I had to receive all massive not devided it
Sorry for my formatted code
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);
I have been asked to implement a printDailyCost method which should call the getDailyCost method and format the value returned to two
decimal places. It should then print this value along with a £ sign.
So far I have:
public abstract class Suit {
private String colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
private double totalPrice;
public Suit(String colour, double dailyCost, int trouserLength,
int jacketChestSize, boolean available, double totalPrice) {
super();
this.colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
public String getColour() {
return colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean isAvailable() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailable(boolean available) {
this.available = available;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public void calcTotalPrice(int numDaysHired){
this.totalPrice = dailyCost * numDaysHired;
}
public String printDailyCost() {
return printDailyCost();
}
}
My Question is how would I amend my printDailyCost method to call the getDailyCost method and format the value returned to two
decimal places then print with a £ sign?
Check this out:
java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.UK);
System.out.println(format.format(getDailyCost()));
You can simply add them together and return it:
public String printDailyCost() {
return getDailyCost() + " £";
}
However I don't recommend to concatenate String with this way. Better use the following method using StringBuilder, that concatenates strings in the correct way:
public String printDailyCost() {
return (new StringBuilder().append(getDailyCost()).append(" £")).toString();
}
Or if you want to print it out to console, just do this:
System.out.println(getDailyCost() + " £");
I am getting data from gemfire
List<String> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);
which is like below:
[('price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'), ('price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996')]
This is a list of String I am getting.Currently I have 3 values in list.
I have a pojo class like below:
public class StockInfo {
// #Id
#JsonProperty("symbol")
private String symbol;
#JsonProperty("price")
private String price;
#JsonProperty("volume")
private String volume;
#JsonProperty("pe")
private String pe;
#JsonProperty("eps")
private String eps;
#JsonProperty("week53low")
private String week53low;
#JsonProperty("week53high")
private String week53high;
#JsonProperty("daylow")
private String daylow;
#JsonProperty("dayhigh")
private String dayhigh;
#JsonProperty("movingav50day")
private String movingav50day;
#JsonProperty("marketcap")
private String marketcap;
#JsonProperty("time")
private String time;
private String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getPe() {
return pe;
}
public void setPe(String pe) {
this.pe = pe;
}
public String getEps() {
return eps;
}
public void setEps(String eps) {
this.eps = eps;
}
public String getWeek53low() {
return week53low;
}
public void setWeek53low(String week53low) {
this.week53low = week53low;
}
public String getWeek53high() {
return week53high;
}
public void setWeek53high(String week53high) {
this.week53high = week53high;
}
public String getDaylow() {
return daylow;
}
public void setDaylow(String daylow) {
this.daylow = daylow;
}
public String getDayhigh() {
return dayhigh;
}
public void setDayhigh(String dayhigh) {
this.dayhigh = dayhigh;
}
public String getMovingav50day() {
return movingav50day;
}
public void setMovingav50day(String movingav50day) {
this.movingav50day = movingav50day;
}
public String getMarketcap() {
return marketcap;
}
public void setMarketcap(String marketcap) {
this.marketcap = marketcap;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
How do I create a List of StockInfo class object from the value I am getting from restTemplate.getForObject
I think you could just use:
List<StockInfo> objects = restTemplate.getForObject(geodeURL+"/gemfire-api/v1/queries/adhoc?q=SELECT * FROM /region s",List.class);