Nitish Dash Nitish Dash - 5 months ago 46
JSON Question

How to change the RequestInterface dynamically while parsing limited JSON using Retrofit?

I am trying to incorporate the endless recyclerview by populating it with data fetched from a json source. Now, I am using the Wordpress JSON API.

The problem is that, my JSON is very large. Also, instead of loading all the data in the RecyclerView at once, I want the user to scroll down in order to fetch new data.

To get limited JSON, I am appending the &offset=10 tag. But, the problem is that every time the user scrolls down, I need to change the @GET url...

But my Interface looks like this:

import retrofit2.Call;
import retrofit2.http.GET;

public interface RequestInterface {

@GET("?json=get_posts&include=title,excerpt,content,attachments&offset=10")
Call<JSONResponse> getJSON();
}


So, when I pass the request code from my MainActivity:

public void getFeed() {

Call<JSONResponse> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<JSONResponse>() {
@Override


public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccess()) {
flowerList = new ArrayList<>(Arrays.asList(response.body().getPosts()));
Toast.makeText(getApplicationContext(),flowerList.get(0).getTitle()+"",Toast.LENGTH_LONG).show();


for (int i = 0; i < flowerList.size(); i++) {
ModelClass flower = flowerList.get(i);

SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);

mAdapter.addFlyp(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}

@Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();


}


});
}


How can I change the offset value by passing an integer to the interface?

Answer

Pass the offset value as a parameter to your method:

public interface RequestInterface {

    @GET("?json=get_posts&include=title,excerpt,content,attachments")
    Call<JSONResponse> getJSON(@Query("offset") int offset);
}
Comments