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
Related
I'm very new in Android and Java Programming and currently developing my skill.
now, i faced a problem with accessing Arraylist from JSONresponse.
It's just i don't know how to initiate my Variable based on Json nested object, and access it without setting it to recylerview etc.
so this is the JSON
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
ResponseModel class
public class ResponseModel {
private int kode;
private String pesan,sql;
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
ResponseModel class
public class DataModel {
private int Id_Perizinan, Id_Ortu;
private String NamaLengkapSantri, NamaLengkapOrtu, Alasan_Izin, Tgl_Pengajuan,
Durasi_Izin, Tgl_Kembali;
public int getId_Perizinan() {
return Id_Perizinan;
}
public void setId_Perizinan(int id_Perizinan) {
Id_Perizinan = id_Perizinan;
}
public int getId_Ortu() {
return Id_Ortu;
}
public void setId_Ortu(int id_Ortu) {
Id_Ortu = id_Ortu;
}
public String getNamaLengkapSantri() {
return NamaLengkapSantri;
}
public void setNamaLengkapSantri(String namaLengkapSantri) {
NamaLengkapSantri = namaLengkapSantri;
}
public String getNamaLengkapOrtu() {
return NamaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
NamaLengkapOrtu = namaLengkapOrtu;
}
public String getAlasan_Izin() {
return Alasan_Izin;
}
public void setAlasan_Izin(String alasan_Izin) {
Alasan_Izin = alasan_Izin;
}
public String getTgl_Pengajuan() {
return Tgl_Pengajuan;
}
public void setTgl_Pengajuan(String tgl_Pengajuan) {
Tgl_Pengajuan = tgl_Pengajuan;
}
public String getDurasi_Izin() {
return Durasi_Izin;
}
public void setDurasi_Izin(String durasi_Izin) {
Durasi_Izin = durasi_Izin;
}
public String getTgl_Kembali() {
return Tgl_Kembali;
}
public void setTgl_Kembali(String tgl_Kembali) {
Tgl_Kembali = tgl_Kembali;
}
and this is how I try to retrieve the data
public void loginAplikasi(){
APIRequestData apiRequestData = RetroServer.koneksiRetrofit().create(APIRequestData.class);
Call<ResponseModel> loginApp = apiRequestData.ardLogin(username,password);
loginApp.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
listData = response.body().getData();
int Id_Ortu = 0;
String NamaLengkapOrtu;
alertDialog(NamaLengkapOrtu);
} else {
alertDialog(pesan);
}
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
alertDialog(t.getMessage());
}
});
}
i successfully catched 'kode' and 'pesan' From JSON by using
int kode = response.body().getKode();
String pesan = response.body().getPesan();
i've declared a listData as new arraylist
List<DataModel> listData = new ArrayList<>();
however, how can i access the value of
listData = response.body().getData();
which contained array inside of data
so i can initiate variable ( NamaLengkapOrtu = listdata(arrayIndex) )
Thanks in advance.
The issue with DataModel class.
public class DataModel {
#SerializedName("Id_Ortu")
#Expose
private String idOrtu;
#SerializedName("NamaLengkapOrtu")
#Expose
private String namaLengkapOrtu;
public String getIdOrtu() {
return idOrtu;
}
public void setIdOrtu(String idOrtu) {
this.idOrtu = idOrtu;
}
public String getNamaLengkapOrtu() {
return namaLengkapOrtu;
}
public void setNamaLengkapOrtu(String namaLengkapOrtu) {
this.namaLengkapOrtu = namaLengkapOrtu;
}
}
Then you can access data as follows:
String namaLengkapOrtu = listdata.get(index).getNamaLengkapOrtu();
String idOrtu = listdata.get(index).getIdOrtu();
As your JSON response is:
{"kode":1,
"pesan":"Anda Berhasil Login",
"data":[{"Id_Ortu":"1","NamaLengkapOrtu":"Alpiyan
Yamin"}]}
Use the below annotation in your model class:
#SerializedName("data")
#Expose
Here, "data" is the key you want to get from JSON.
Try to use this ResponseModel class:
public class ResponseModel {
private int kode;
private String pesan,SQL;
#SerializedName("data")
#Expose
private List<DataModel> data;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public int getKode() {
return kode;
}
public void setKode(int kode) {
this.kode = kode;
}
public String getPesan() {
return pesan;
}
public void setPesan(String pesan) {
this.pesan = pesan;
}
public List<DataModel> getData() {
return data;
}
public void setData(List<DataModel> data) {
this.data = data;
}
}
I keep receiving a 400 BAD request when sending a POST request using RestTemplate.
i am sending a list of object and for that i've created a class AllCars witch hase as an field listof Cars this my class:
public class AllCars {
private List<Cars> listcars;
public AllCars() {
}
public AllCars(List<Cars> listcars) {
this.listcars = listcars;
}
public List<Cars> getListcars() {
return listcars;
}
public void setListcars(List<Cars> listcars) {
this.listcars = listcars;
}
}
Cars class
public class Cars {
private Long id;
private long speed;
private String color;
public Cars() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
this is my client side code:
private class SendData extends AsyncTask<AllCars, Object, AllCars> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getContext(), "Downloading", "Downloading..Please Wait", true);
}
#Override
protected AllCars doInBackground(AllCars... params) {
try {
// urls
final String urlCars = "http://myurl/addCars";
publishProgress(0);
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
AllCars result = restTemplate.postForObject(urlAllCars, params[0], AllCars.class);
return result;
} catch (Exception e) {
Log.e("mainactivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(AllCars ob) {
if(ob instanceof AllCars)
Log.d("AllCars", "success " );
else
Log.d("No Result ", "");
progressDialog.cancel();
}
}
and this is my server side code:
#Requesrmaping (vlaue = "/addCars", method=RequestMethod.POST)
public ResponseEntity<AllCars>addCars(#RequestBody AllCars allcars){
List<Cars> listcar= allcars.getListcars();
return new ResponsEntity<AllCars>(allcars,HttpStatus.ok)
}
this code works when the listcare has one object but when it have more than one object it doesn't work could any body help me
I tried to implement custom TiledDataSource for using with paging library. When I used LivePagedListProvider like returns type for my Dao method it worked fine (after table items updating - ui updated automatically).
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC")
LivePagedListProvider<Artist> loadArtists();
But when I try implement custom TiledDataSource for LivePagerListProvider table updates not triggered my observers.
Abstract generic class:
public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {
#Override
public int countItems() {
return DataSource.COUNT_UNDEFINED;
}
#Override
public List<ResultType> loadRange(int startPosition, int count) {
fetchFromNetwork(startPosition, count);
return loadFromDb(startPosition, count);
}
#WorkerThread
private void fetchFromNetwork(int startPosition, int count) {
if (createCall(startPosition, count) != null)
try {
Response<RequestType> response = createCall(startPosition, count).execute();
if (response.isSuccessful() && response.code() == 200) {
saveCallResult(response.body());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#WorkerThread
protected abstract void saveCallResult(#NonNull RequestType item);
#WorkerThread
protected abstract List<ResultType> loadFromDb(int startPosition, int count);
#WorkerThread
protected abstract Call<RequestType> createCall(int startPosition, int count);
public LiveData<PagedList<ResultType>> getAsLiveData() {
return new LivePagedListProvider<Integer, ResultType>() {
#Override
protected DataSource<Integer, ResultType> createDataSource() {
return PagedNetworkBoundResource.this;
}
}.create(0, new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(20)
.setInitialLoadSizeHint(20)
.build());
}
}
My dao method for this case:
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC LIMIT (:limit) OFFSET (:offset)")
List<Artist> loadArtists(int offset, int limit);
I update Table.States.PLAY_STATE.
public void updatePlayerState(PlayerStateEntity state){
new Thread(() -> {
dao.deleteState();
dao.insertState(state);
}).run();
}
#Dao
public interface PlayStateDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertState(PlayerStateEntity playEntity);
#Query("DELETE FROM " + Table.States.PLAY_STATE)
void deleteState();
#Query("SELECT * FROM "+Table.States.PLAY_STATE)
PlayerStateEntity getPlayerState();
}
#Entity(tableName = Table.States.PLAY_STATE)
public class PlayerStateEntity extends IdEntity {
#ColumnInfo(name = "album_played_id")
private Long albumPlayedId = -1L;
#ColumnInfo(name = "track_played_id")
private Long trackPlayedId = -1L;
#ColumnInfo(name = "artist_played_id")
private Long artistPlayedId = -1L;
#ColumnInfo(name = "state")
private PlayingState state;
#ColumnInfo(name = "playing_type")
private PlayingType playingType;
public Long getAlbumPlayedId() {
return albumPlayedId;
}
public void setAlbumPlayedId(Long albumPlayedId) {
this.albumPlayedId = albumPlayedId;
}
public Long getTrackPlayedId() {
return trackPlayedId;
}
public void setTrackPlayedId(Long trackPlayedId) {
this.trackPlayedId = trackPlayedId;
}
public Long getArtistPlayedId() {
return artistPlayedId;
}
public void setArtistPlayedId(Long artistPlayedId) {
this.artistPlayedId = artistPlayedId;
}
public PlayingState getState() {
return state;
}
public void setState(PlayingState state) {
this.state = state;
}
public PlayingType getPlayingType() {
return playingType;
}
public void setPlayingType(PlayingType playingType) {
this.playingType = playingType;
}
}
class Artist extends PlayEntity{
private String name;
private String link;
private String picture;
#ColumnInfo(name = "picture_small")
private String pictureSmall;
#ColumnInfo(name = "picture_medium")
private String pictureMedium;
#ColumnInfo(name = "picture_big")
private String pictureBig;
#ColumnInfo(name = "picture_xl")
private String pictureXl;
private Boolean radio;
private String tracklist;
private Integer position;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getPictureSmall() {
return pictureSmall;
}
public void setPictureSmall(String pictureSmall) {
this.pictureSmall = pictureSmall;
}
public String getPictureMedium() {
return pictureMedium;
}
public void setPictureMedium(String pictureMedium) {
this.pictureMedium = pictureMedium;
}
public String getPictureBig() {
return pictureBig;
}
public void setPictureBig(String pictureBig) {
this.pictureBig = pictureBig;
}
public String getPictureXl() {
return pictureXl;
}
public void setPictureXl(String pictureXl) {
this.pictureXl = pictureXl;
}
public Boolean getRadio() {
return radio;
}
public void setRadio(Boolean radio) {
this.radio = radio;
}
public String getTracklist() {
return tracklist;
}
public void setTracklist(String tracklist) {
this.tracklist = tracklist;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
#Override
public boolean isItemPlaying() {
return getId() == getArtistPlayedId().longValue() && getPlayingType() == PlayingType.Artist && getState() == PlayingState.Playing;
}
}
public abstract class PlayEntity extends PlayerStateEntity {
public abstract boolean isItemPlaying();
}
public class ArtistsRepository {
private final ChartArtistDao chartArtistDao;
private final DeezerService deezerService;
#Inject
public ArtistsRepository(ChartArtistDao chartArtistDao, DeezerService deezerService) {
this.chartArtistDao = chartArtistDao;
this.deezerService = deezerService;
}
public LiveData<PagedList<ChartArtistDao.Artist>> getArtist() {
return new PagedNetworkBoundResource<ChartArtistDao.Artist, ModelList<ChartArtistEntity>>() {
#Override
protected void saveCallResult(#NonNull ModelList<ChartArtistEntity> item) {
if (item != null) {
chartArtistDao.saveArtists(item.getItems());
}
}
#Override
protected List<ChartArtistDao.Artist> loadFromDb(int startPosition, int count) {
return chartArtistDao.loadArtists(startPosition, count);
}
#Override
protected Call<ModelList<ChartArtistEntity>> createCall(int startPosition, int count) {
return deezerService.getChartArtist(startPosition, count);
}
}.getAsLiveData();
}
}
For each Artist items I add fields from PlayerStateEntity (not good solution but this easy way to represent state of ui items). After PlayerStateEntity table updates Room should notify about data changes, but doesn't do it.
I understand that Room doesn't know about query what I used, and can't updates my RecyclerView which provide by paging library. But maybe some one knows how to notify Room about tables which I used inside mine DataSource for future triggering ui updates?
The problem was related with custom DataSource realization. When data has changed, LivePagedListProvider should create a new DataSource instance for right ui updating. I used the same instance, so my previous solution is not right.
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();
I have this json string to parse {"uid":8,"totalPoints":"7740"}
I have written the below class for this.
public class Points extends WebRequest implements IWebRequest {
private static final String CLASS_TAG = Points.class.getSimpleName();
private WebAPIResponse mWebAPIResponse;
private int mUserId;
/**
* Initialize object
* #param urlEndPoint
* #param uiDelegate
* #param appContext
* #param webServiceRequestCallback
*/
public Points(String urlEndPoint, IUIDelegate uiDelegate,
WeakReference<Context> appContext,
IWebServiceRequestCallback webServiceRequestCallback) {
super(urlEndPoint, uiDelegate, appContext, webServiceRequestCallback);
}
#Override
public String parseResponse(String responseString) {
if (MBUtil.isEmpty(responseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
this.mWebAPIResponse = webAPIResponse;
Errors errors = webAPIResponse.getErrors();
if (errors != null) {
errMsg = errors.getMsg();
}
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
#Override
public JSONObject buildRequestBody() {
JSONObject jsonObject = new JSONObject();
Context context = getAppContext();
if(context == null) {
return jsonObject;
}
try {
// Authentication body parameters
JSONObject authenticationJsonObject = new JSONObject();
authenticationJsonObject.put(context.getString(R.string.key_points_uid), mUserId);
return authenticationJsonObject;
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
}
return jsonObject;
}
public int getUserId() {
return mUserId;
}
public void setUserId(int mUserId) {
this.mUserId = mUserId;
}
public WebAPIResponse getWebAPIResponse() {
return mWebAPIResponse;
}
public void setWebAPIResponse(WebAPIResponse mWebAPIResponse) {
this.mWebAPIResponse = mWebAPIResponse;
}
public static class WebAPIResponse {
private Data pointsData;
private Errors errors;
public Data getPointsData() {
return pointsData;
}
public void setPointsData(Data pointsData) {
this.pointsData = pointsData;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
}
public static class Data {
#JsonProperty("uid")
private int uid;
#JsonProperty("totalPoints")
private int totalPoints;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getTotalPoints() {
return totalPoints;
}
public void setTotalPoints(int totalPoints) {
this.totalPoints = totalPoints;
}
}
}
I getting proper response in parseResponse() method which is,
responseString = {"uid":8,"totalPoints":"7740"}
But in the same pasreResponse() method once it reached to this line
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
Not responding any thing and unable to parse the string. Please anyone check whether my parsing class is correct or not and why it is not parsing.
With your responseString = {"uid":8,"totalPoints":"7740"} you just can deserialize it by Data object only.
Data data = objectMapper.readValue(responseString, Data.class);
If you want to deserialize your JSON String to WebAPIResponse object, your responseString must be:
{"pointsData":{"uid":8,"totalPoints":"7740"}, "errors": ...}