I'm trying to get a JSON file using an URL, but the application is crashing.
JSON file api
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
// Logs show error is in the code below
service.getPopulationData(new Callback<Flag> (){
#Override
public void onResponse(Call<Flag> call, Response<Flag> response) {
Log.d("JSONData", response.body().toString());
}
#Override
public void onFailure(Call<Flag> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<Flag> callback) ;
}
Flag.java
public class Flag {
private int rank;
private String country;
private String population;
private String flag;
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
Edit: Error log can be found here: log
I've tried other solutions mentioned on stackoverflow, but I've been unable to get it right.
Also, I only want the flag URLs from the JSON file. How am I supposed to get it?
You will need the following two pojo class
JsonResponse.java
public class JsonResponse {
#SerializedName("worldpopulation")
#Expose
private List<Worldpopulation> worldpopulation = null;
public List<Worldpopulation> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Worldpopulation> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
Worldpopulation.java
public class Worldpopulation {
#SerializedName("rank")
#Expose
private Integer rank;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private String population;
#SerializedName("flag")
#Expose
private String flag;
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
and make a retrofit call like below
service.getPopulationData(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
**** edited as per requirement ****
and change ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
Call<JsonResponse> getPopulationData() ;
}
and call it like this
made an edit here
ApiService service = retrofit.create(ApiService.class);
Call<JsonResponse> call = service.getPopulationData();
call.enqueue(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
The json you are trying to parse with Retrofit contains a JSON Array as its root worldpopulation , So First you need a class WorldPopulation as follow:
public class WorldPopulation
{
private List<Flag> worldpopulation;
public List<Flag> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Flag> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<WorldPopulation> callback) ;
}
Related
I have an app that is to register people into a platform but I get a response of Unauthenticated each time I submit the form data. The form is submitted using an API which requires a bearer token for each post request with the aid of retrofit. I have been out of touch with Java.
Note: its just a plain form. No authentication has been implemented in the app.
My ApiClient.java class
public class ApiClient {
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("xxxxxxxxxxxxx")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getUserService(){
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
My UserService.java class
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(#Body UserRequest userRequest);
}
My saveUser Method
public void saveUser(UserRequest userRequest){
Call<UserResponse> userResponseCall = ApiClient.getUserService().saveUser(userRequest);
userResponseCall.enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()){
Toast.makeText(MainActivity.this, "Registration Successfull! Click on Reset Form to Start a New Enumeration...", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Registration Failed!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Registration Failed!" +t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
My UserRequest
package com.example.xxxxx;
public class UserRequest {
private String FullName;
private String StickerNumber;
private String Address;
private String Email;
private String Phone;
private String Nationality;
private String State;
private String LGA;
private String RC;
private String DriversLicenseNo;
private String LicenseIssued;
private String LicenseExpiry;
private String VehicleType;
private String VehicleLicense;
private String VehicleTyres;
private String LGAofOperation;
private String NOKFullName;
private String NOKAddress;
private String NOKPhone;
private String NOKEmail;
private String NOKNationality;
private String NOKState;
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getStickerNumber() {
return StickerNumber;
}
public void setStickerNumber(String stickerNumber) {
StickerNumber = stickerNumber;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getNationality() {
return Nationality;
}
public void setNationality(String nationality) {
Nationality = nationality;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getLGA() {
return LGA;
}
public void setLGA(String LGA) {
this.LGA = LGA;
}
public String getRC() {
return RC;
}
public void setRC(String RC) {
this.RC = RC;
}
public String getDriversLicenseNo() {
return DriversLicenseNo;
}
public void setDriversLicenseNo(String driversLicenseNo) {
DriversLicenseNo = driversLicenseNo;
}
public String getLicenseIssued() {
return LicenseIssued;
}
public void setLicenseIssued(String licenseIssued) {
LicenseIssued = licenseIssued;
}
public String getLicenseExpiry() {
return LicenseExpiry;
}
public void setLicenseExpiry(String licenseExpiry) {
LicenseExpiry = licenseExpiry;
}
public String getVehicleType() {
return VehicleType;
}
public void setVehicleType(String vehicleType) {
VehicleType = vehicleType;
}
public String getVehicleLicense() {
return VehicleLicense;
}
public void setVehicleLicense(String vehicleLicense) {
VehicleLicense = vehicleLicense;
}
public String getVehicleTyres() {
return VehicleTyres;
}
public void setVehicleTyres(String vehicleTyres) {
VehicleTyres = vehicleTyres;
}
public String getLGAofOperation() {
return LGAofOperation;
}
public void setLGAofOperation(String LGAofOperation) {
this.LGAofOperation = LGAofOperation;
}
public String getNOKFullName() {
return NOKFullName;
}
public void setNOKFullName(String NOKFullName) {
this.NOKFullName = NOKFullName;
}
public String getNOKAddress() {
return NOKAddress;
}
public void setNOKAddress(String NOKAddress) {
this.NOKAddress = NOKAddress;
}
public String getNOKPhone() {
return NOKPhone;
}
public void setNOKPhone(String NOKPhone) {
this.NOKPhone = NOKPhone;
}
public String getNOKEmail() {
return NOKEmail;
}
public void setNOKEmail(String NOKEmail) {
this.NOKEmail = NOKEmail;
}
public String getNOKNationality() {
return NOKNationality;
}
public void setNOKNationality(String NOKNationality) {
this.NOKNationality = NOKNationality;
}
public String getNOKState() {
return NOKState;
}
public void setNOKState(String NOKState) {
this.NOKState = NOKState;
}
}
Create the OkHttpClient like this
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}).build();
If you most of your https requests need authentication then the first answer is perfect but if some of your requests need then you can pass the header to each methods.
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(
#Header("Authorization") String token,
#Body UserRequest userRequest
);
}
While calling the method simply pass your token along with userRequest.
Please Help me
This is my Models
Cases class
public class Cases {
#SerializedName("new")////this key value from json
#Expose
private String _new;
#SerializedName("active")
#Expose
private Integer active;
#SerializedName("critical")
#Expose
private Integer critical;
#SerializedName("recovered")
#Expose
private Integer recovered;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Integer getCritical() {
return critical;
}
public void setCritical(Integer critical) {
this.critical = critical;
}
public Integer getRecovered() {
return recovered;
}
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Deaths class
public class Deaths {
#SerializedName("new")
#Expose
private String _new;
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String getNew() {
return _new;
}
public void setNew(String _new) {
this._new = _new;
}
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
public class Errors {//this is empty class
}
public class Parameters {//this is empty class
}
Tests class
public class Tests {
#SerializedName("1M_pop")
#Expose
private String _1MPop;
#SerializedName("total")
#Expose
private Integer total;
public String get1MPop() {
return _1MPop;
}
public void set1MPop(String _1MPop) {
this._1MPop = _1MPop;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
Response class
public class Response {
#SerializedName("continent")
#Expose
private String continent;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private Integer population;
#SerializedName("cases")
#Expose
private Cases cases;
#SerializedName("deaths")
#Expose
private Deaths deaths;
#SerializedName("tests")
#Expose
private Tests tests;
#SerializedName("day")
#Expose
private String day;
#SerializedName("time")
#Expose
private String time;
public String getContinent() {
return continent;
}
public String getCountry() {
return country;
}
public Integer getPopulation() {
return population;
}
public Cases getCases() {
return cases;
}
public Deaths getDeaths() {
return deaths;
}
public Tests getTests() {
return tests;
}
public String getDay() {
return day;
}
public String getTime() {
return time;
}
}
Covid19Model class
public class Covid19Model {
#SerializedName("get")
#Expose
private String get;
#SerializedName("parameters")
#Expose
private Parameters parameters;
#SerializedName("errors")
#Expose
private Errors errors;
#SerializedName("results")
#Expose
private Integer results;
#SerializedName("response")
#Expose
private List<Response> response;
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
public Parameters getParameters() {
return parameters;
}
public void setParameters(Parameters parameters) {
this.parameters = parameters;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
public Integer getResults() {
return results;
}
public void setResults(Integer results) {
this.results = results;
}
public List<Response> getResponse() {
return response;
}
public void setResponse(List<Response> response) {
this.response = response;
}
Covid19WebAPI interface
public interface Covid19WebApi {
#Headers({
"x-rapidapi-host:covid-193.p.rapidapi.com",
"x-rapidapi-key:fb818f40c4msh9ed8e59abf0e867p11b3bfjsn0900d33b78ef"//this is my rapidapi key
})
#GET("statistics")
Call<Covid19Model> getData();
}
MainActivity class
public class MainActivity extends AppCompatActivity {//This is my app MainActivity
List<Response> responses;
private static final String BASE_URL = "https://covid-193.p.rapidapi.com/";//this is covid api website
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());//this is convert json
Retrofit retrofit = builder.build();
Covid19WebApi covid19WebApi = retrofit.create(Covid19WebApi.class);
Call<Covid19Model> call = covid19WebApi.getData();//this is call api interfacee method
call.enqueue(new Callback<Covid19Model>() {
#Override
public void onResponse(Call<Covid19Model> call, Response<Covid19Model> response) {
responses = response.body().getResponse();
for (Object data:responses){
System.out.println(data);//This my error (expected begin_array but was begin_object )
}
}
#Override
public void onFailure(Call<Covid19Model> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();//this is toast message failure
}
});
}
}
What is the problem
My error code ("expected begin_array but was begin_object")
I can't find out what the problem is in these codes and the data doesn't come in response and gives an error instead
As you can see in JSON response, errors and parameters are comes as List.
So please change fields to list in Covid19Model
#SerializedName("parameters")
#Expose
private List<Parameters> parameters;
#SerializedName("errors")
#Expose
private List<Errors> errors;
In Daata function try to fetch data from server. Successfully fetched, but data cant be set in ArrayList
List<FlowerListModel>flowerListModels=new ArrayList<>();
Cause i want to set flowerListModels data in FlowerAdapter and show in listview
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
List<FlowerListModel>flowerListModels=new ArrayList<>();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
Here is FlowerListModel class
package bdservers.com.schoolmanagement.Model;
public class FlowerListModel {
private String category;
private String instructions;
private String photo;
private String name;
private String price;
public FlowerListModel(){}
public FlowerListModel(String category, String instructions, String photo, String name,String price){
this.category=category;
this.instructions=instructions;
this.photo=photo;
this.name=name;
this.price=price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
You are setting empty ArrayList to your adapter, I have highlighted the line where you have made the error, and also the correct line that you need
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
/**
* You are setting this empty list to adapter
*List<FlowerListModel>flowerListModels=new ArrayList<>();
*/
List<FlowerListModel> flowerListModels = new ArrayList<>();
flowerListModels = response.body();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
You are creating new empty List here: List<FlowerListModel>flowerListModels=new ArrayList<>();
You can try something like this:
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),response.body());
listView.setAdapter(flowerAdapter);
}
Create BaseResponse model like this
public class BaseResponse {
#SerializedName("data")
private List<Object> alObjects;
public BaseResponse(List<Object> alObjects) {
this.alObjects = alObjects;
}
public List<Object> getAlObjects() {
return alObjects;
}
public void setAlObjects(List<Object> alObjects) {
this.alObjects = alObjects;
}
}
Then get data from server
#POST(Constants.URL_API_DATA)
BaseResponse executeBaseResponse(#Body String mData);
Cheers!!
this is my apicall
public void loadData(String lat,String lon){
pd = new ProgressDialog(getActivity());
pd.setMessage("Loading");
pd.show();
mApi = new RetrofitHelper<AuthApi>().getApi(AuthApi.class);
currentCall = mApi.currentData(lat,lon,units,key);
currentCall.enqueue(new Callback<ResultObject>() {
#Override
public void onResponse(Call<ResultObject> call,
Response<ResultObject> response) {
Log.d("enter","enter");
Log.d("temp",new Integer(response.body().getMain().getTemp()).toString());
temp_current.setText(new Integer(response.body().getMain().getTemp()).toString());
pd.hide();
}
#Override
public void onFailure(Call<ResultObject> call, Throwable t) {
pd.hide();
}
});
}
This logs with the keys "enter" and "temp" doesnot show up on tbe logcat that means it is not entering the OnResponse method
this is my api request inteface
#GET("weather")
Call<ResultObject> currentData(
#Query("lat") String lat,
#Query("lon") String lon,
#Query("units") String units,
#Query("APPID") String APPID
);
this is my result class(json matching),just made required fields for the "main" field in json response.
i dont know if this ResultObject class is parsing the response or not
public class ResultObject{
#Expose
#SerializedName("message")
public String message;
#Expose
#SerializedName("result")
public int result;
#Expose
#SerializedName("main")
public Main main;
public class Main {
#Expose
#SerializedName("temp")
public int temp;
#Expose
#SerializedName("pressure")
public int pressure;
#Expose
#SerializedName("humidity")
public int humidity;
#Expose
#SerializedName("temp_min")
public int temp_min;
#Expose
#SerializedName("temp_max")
public int temp_max;
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
public int getPressure() {
return pressure;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public int getTemp_min() {
return temp_min;
}
public void setTemp_min(int result) {
this.temp_min = temp_min;
}
public int getTemp_max() {
return temp_max;
}
public void setTemp_max(int result) {
this.temp_max = temp_max;
}
}
#Expose
#SerializedName("errors")
public List<String> errors;
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public Main getMain() {
return main;
}
public void setmain(Main main) {
this.main = main;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
I logged the response,which is this
{"coord":{"lon":0,"lat":0},
"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],
"base":"stations",
"main":{"temp":25.71,"pressure":1026.51,"humidity":100,"temp_min":25.71,"temp_max":25.71,"sea_level":1026.58,"grnd_level":1026.51},
"wind":{"speed":6.41,"deg":190.004},
"clouds":{"all":92},
"dt":1497210848,
"sys":{"message":0.0084,"sunrise":1497160571,"sunset":1497204213},"id":6295630,"name":"Earth","cod":200}
I get the response but the OnResponse method does not work
I am not able resolve it, please help
I'm new to Retrofit and JSON and I don't really know how to parse the next json string:
{
"weight":[
{ "bmi":21,
"date":"2016-12-09",
"fat":14.059000015258789,
"logId":1222222222222,
"source":"Aria",
"time":"11:58:24",
"weight":68
},
{ "bmi":21.83,
"date":"2016-12-14",
"logId":1222222222223,
"source":"Aria",
"time":"14:31:39",
"weight":70.7
}
]
}
I just want "weight" and "date" inside weight array. I've created a pojo class following some examples but it's not working.
Also when trying it with my pojo class I couldn't get "weight" as a string (I'll then use it as a double) using .string().
(I know using .toString() shows something like "com.myPackage.MyPojo#xxxx").
For now, I have only been able to get the whole json through ResponseBody:
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
What am I doing wrong? Here are my pojo classes, just an attempt...:
public class WeightList {
#SerializedName("weight")
#Expose
private ArrayList<WeightLogFitbit> weight = new ArrayList<>();
public WeightList(){
}
public ArrayList<WeightLogFitbit> getWeight() {
return weight;
}
public void setWeight(ArrayList<WeightLogFitbit> weight) {
this.weight = weight;
}
}
And:
public class WeightLogFitbit {
//Variables in my JSON
#SerializedName("bmi")
#Expose
private String bmi;
#SerializedName("date")
#Expose
private String date;
#SerializedName("logId")
#Expose
private String logId;
#SerializedName("source")
#Expose
private String source;
#SerializedName("time")
#Expose
private String time;
#SerializedName("weight")
#Expose
private double weight;
#SerializedName("fat")
#Expose
private String fat;
public WeightLogFitbit(){}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBmi(){
return bmi;
}
public void setBmi(String bmi) {
this.bmi = bmi;
}
//
public String getFat(){
return fat;
}
public void setFat(String fat) {
this.fat = fat;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLogId() {
return logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
}
NOTE: I'm using RxSocialConnect library, which implements RxJava, Retrofit 2, OkHttp3 and gson, just in case. I did this following this example.
Rest of classes I'm using:
public class FitbitBtnActivity extends AppCompatActivity {
private FitbitRepository repository;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fitbit_btn);
repository = new FitbitRepository();
setUpFitbit();
}
private void setUpFitbit() {
findViewById(R.id.fitbitbtn).setOnClickListener(v ->
RxSocialConnect.with(this, repository.fitbitService())
.subscribe(response -> response.targetUI().showToken(response.token()),
error -> showError(error))
);
findViewById(R.id.retrievebtn).setOnClickListener(v -> {
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
//Original code from example in RxSocialConnect
/*.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Object>() {
#Override
public void call(Object user) {
FitbitBtnActivity.this.showUserProfile(user.toString());
}
},
error -> FitbitBtnActivity.this.showError(error));*/
}
);
}
And:
public class FitbitRepository {
private final FitbitApiRest fitbitApi;
public FitbitRepository() {
fitbitApi = initFitbitApiRest();
}
private FitbitApiRest initFitbitApiRest() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new OAuth2Interceptor(FitbitApi20.class))
.build();
return new Retrofit.Builder()
.baseUrl(FitbitApiRest.URL_BASE)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build().create(FitbitApiRest.class);
}
FitbitApiRest getFitbitApi() {
return fitbitApi;
}
interface FitbitApiRest {
String URL_BASE = "https://api.fitbit.com";
#GET("myrequest.json")
Call<ResponseBody> getData();
}
OAuth20Service fitbitService() {
final String client_id = "xxxxx";
final String client_secret = "1xxxxxxxxxxxxxxxxxx";
final String redirect_uri = "http://example.com";
final String permissions = "weight";
return new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(redirect_uri)
.scope(permissions)
.build(FitbitApi20.instance());
}
}
You need to add this to your dependencies:
compile 'com.squareup.retrofit2:converter-gson:your-version'
and then add a gson converter to your Retrofit instance like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
and change your call in the api to return WeightList:
Call<WeightList> getData();