this is my web service for sending and receiving a string value with key
Urls.class
public class Urls {
public static final String MAIN_URL="example.com";
}
API.class
public interface API {
#POST("user.php")
Call<MainResponse> registerUser(#Body User user);
#POST("user.php")
Call<MainResponse>loginUser(#Body User user);
#POST("contact.php")
Call<MainResponse>checkNumber(#Body Phone phone);
}
WebService.class
public class WebService {
private static WebService instance;
private API api;
public WebService() {
OkHttpClient client = new OkHttpClient.Builder().build();
Retrofit retrofit = new Retrofit.Builder().client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Urls.MAIN_URL)
.build();
api = retrofit.create(API.class);
}
public static WebService getInstance() {
if (instance == null) {
instance = new WebService();
}
return instance;
}
public API getApi() {
return api;
}
}
MainResponse.class
public class MainResponse {
#SerializedName("status")
public int status;
#SerializedName("message")
public String message;
}
Phone.class
public class Phone {
#SerializedName("phone")
public String phone;
}
MainActivity.class
Phone phone=new Phone();
phone.phone=contactsString[0];
WebService.getInstance().getApi().checkNumber(phone).enqueue(new Callback<MainResponse>() {
#Override
public void onResponse(Call<MainResponse> call, Response<MainResponse> response) {
if (response.body().status==1){
//do something
}
}
#Override
public void onFailure(Call<MainResponse> call, Throwable t) {
}
});
My question is how to edit this to send an array filled with values contactsString[] and receive another array
Your service is in a way to get single request and give you back single response, you should change server side service if you are the backend developer of the service, to get a list of request and give back a list of result
this is your current service:
#POST("contact.php")
Call<MainResponse>checkNumber(#Body Phone phone);
server side developer should change service for you to be able to send in body an object like this for Phones:
public class Phones {
#SerializedName("phones")
public List<String> phones;
}
and in your response you should get list of status and messages with request phones
response like this:
public class MainResponse {
public List<PhoneStatusResponse> phonesStatusList;
}
public class PhoneStatusResponse {
#SerializedName("status")
public int status;
#SerializedName("message")
public String message;
#SerializedName("phoneRequest")
public String phone;
}
Related
I want to call an api endpoint and display the associated response in my android app.
The api takes a parameter user_name and return response of that user.
Response is in json array consisting json of date, location and img (base64).
RESPONSE
[
{
"id": "602a1901a54781517ecb717c",
"date": "2021-02-15T06:47:29.191000",
"location": "mall",
"img": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCASvBLADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/
}
]
the issue I am facing is I am not able to store the response and parse it.
I am using retrofit for this.
There is no issue in the api call the server gets a successfull request the issue is in the client side (android app).
Here is the code that i currently have.
ApiInterface.java
interface ApiInterface {
#FormUrlEncoded
#POST("end_point")
Call<List<Task>>getstatus(#Field("user_name") String user_name);
}
Task.java
public class Task {
#SerializedName("user_name")
public String user_name;
public Task(String user_name) {
user_name = user_name.substring(1, user_name.length()-1);
this.user_name= user_name;
}
public String getUser() {
return user_name;
}
}
MainActivity.java
private void LoginRetrofit(String user_name) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.build();
final ApiInterface request = retrofit.create(ApiInterface.class);
Call<List<Task>> call = request.getstatus(user_name);
Toast.makeText(getApplicationContext(), "user_name" + " " + call.request(), Toast.LENGTH_LONG).show();
call.enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
try {
List<Task> rs=response.body();
Toast.makeText(getApplicationContext(), "Response" + " "+rs, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.d("REsponse error",e.getMessage());
}
}
#Override
public void onFailure(Call<List<Task>> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
This is the response which is being returned.
In MainActivity.java file, update the code as below as you are printing rs object in your toast message, it prints only the object address not the value in it. So to print the value of the object you received, you must call the methods of the object to get value like as.
MainActivity.java
private void LoginRetrofit(String user_name) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("url")
.addConverterFactory(GsonConverterFactory.create())
.build();
...
call.enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
try {
List<Task> rs=response.body();
if(rs.size() > 0){
Task user = rs.get(0);
String id = user.getId();
String location = user.getLocation();
Toast.makeText(getApplicationContext(),"Response : Id="+id+" and location="+location, Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("REsponse error",e.getMessage());
}
}
...
});
}
and update the Task model as
Task.java
public class Task {
#SerializedName("id") public String id;
#SerializedName("date") public String date;
#SerializedName("location") public String location;
#SerializedName("img") public String img;
public Task(String id, String date, String location, String img) {
this.id=id;
this.date=date;
this.location=location;
this.img=img;
}
public String getId(){ return this.id; }
public String getDate(){ return this.date; }
public String getLocation(){ return this.location; }
public String getImg(){ return this.img; }
}
Your data model class variables should be serialized or to have names as same as in the response , so that retrofit can be able to bind response values to your model variables .
Also you must have a variable in your model class for each key-value pair in your response that you want to use .
check this example to get how retrofit really work .
I am able to get data from database using retrofit and REST api but facing errors in Posting data. Post works using postman but not through retrofit.I have been unable to locate the error.I have tried changing endpoint, that is, "rest" and "rest/" but still get not found error.
ApiView of Post in Django RESTful api: view.py
def post(self,request):
serializer =table_restSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'results':serializer.data},status=201)
return Response(serializer.errors, status=404)
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest',views.restSerializer.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns)
serializer.py:
class table_restSerializer(serializers.ModelSerializer):
class Meta:
model = table_rest
fields = '__all__'
My android code:
Interface
public interface ApiInterface {
#GET("rest")
Call<CustomViewResponse> getJsonFromSid();
#POST("rest")
Call<CustomViewResponse> createTask(#Body CustomViewHolder task);
}
CustomViewHolder class:
public class CustomViewHolder {
#SerializedName("id")
private Integer id;
#SerializedName("tt")
private String tt;
#SerializedName("varr")
private Integer varr;
#SerializedName("edi")
private String edi;
public CustomViewHolder(String tt, Integer varr, String edi){
this.tt = tt;
this.varr = varr;
this.edi = edi;
}
public Integer getid(){
return id;
}
/*public void setid(Integer id){
this.id = id;
}*/
public String gettt()
{
return tt;
}
public void settt(String tt){
this.tt = tt;
}
public Integer getvarr(){
return varr;
}
public void setvarr(Integer varr){
this.varr = varr;
}
public String getedi(){
return edi;
}
public void setedi(String edi){
this.edi = edi;
}
}
CustomViewResponse class
public class CustomViewResponse {
#SerializedName("results")
private List<CustomViewHolder> results;
public List<CustomViewHolder> getResults(){
return results;
}
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.sid_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
ApiInterface apiService1 = ApiClient.getClient().create(ApiInterface.class);
Call<CustomViewResponse> call = apiService.getJsonFromSid();
CustomViewHolder cc = new CustomViewHolder("my task title",22,"a string");
call.enqueue(new Callback<CustomViewResponse>() {
#Override
public void onResponse(Call<CustomViewResponse> call, Response<CustomViewResponse> response) {
int statuscode = response.code();
List<CustomViewHolder> customViewHolders = response.body().getResults();
recyclerView.setAdapter(new AdapterSid(customViewHolders, R.layout.list_item_sid, getApplicationContext()));
}
#Override
public void onFailure(Call<CustomViewResponse> call, Throwable t) {
Log.e("TAG main", t.toString());
}
});
call1.enqueue(new Callback<CustomViewResponse>() {
#Override
public void onResponse(Call<CustomViewResponse> call1, Response<CustomViewResponse> respo) {
int statuscode = respo.code();
Log.d("Message", "code..."+respo.code() + " message..." + respo.message());
CustomViewResponse respon = respo.body();
if (respon == null){
Log.e("Error",""+statuscode+ "......"+ respo.message()+"....null body");
}
}
#Override
public void onFailure(Call<CustomViewResponse> call1, Throwable t) {
Log.e(TAG, t.toString());
}
});
}
Following is my table structure:
class table_rest(models.Model):
tt = models.CharField(max_length=10,default = 12)
varr = models.IntegerField(default=30)
edi = models.CharField(max_length=1000,default='44')
def __str__(self):
return self.tt
Using postman my Json body which gets successfully saved is :
{
"tt": "hello",
"varr": 911,
"edi": "emergency. Can't find solution"
}
Please add an extra URL.
urlpatterns = [
url(r'^admin/', admin.site.urls), # Any URL starting with admin(ex: http://testdomainname.com/admin/xyz)
url(r'^rest/$',views.restSerializer.as_view()), # Any URL starting with only rest(ex: http://testdomainname.com/rest/)
url(r'^$',views.restSerializer.as_view()), # Any empty URL with '' (ex: http://testdomainname.com/)
]
First I included the url pattern as suggested by Dinesh Mandepudi. Then I made changes to my regex in retrofit. It was url issue that I was not confronting when using postman. I just added '/' at the beginning of my post regex.
public interface ApiInterface {
#GET("/rest")
Call<CustomViewResponse> getJsonFromSid();
#POST("/rest/")
Call<CustomViewResponse> createTask(#Body CustomViewHolder task);
}
Also a silly mistake is I was trying to add a string of 13 length in the database column while I had set the limit to 10.
I'm developing a rest client using retrofit. The rest server is using oauth as authentication. For this task I don't have to care about the token expiring. So basically I first make a request for the token and then append that to all subsequent calls.
As of now I'm using two classes. One to get the access token and another one for everything else. I think I would like to merge these two... but I'm not sure how to do that.
The first class only has one method which takes a username and password and a retrofit callback interface. I like the simplicity of the callback but would like to somehow abstract it so I could easily change from retrofit to something else if needed.
public class RequestAccessToken implements IRequestAccessToken {
private String username;
private String password;
private IRestAPI client;
public RequestAccessToken()
{
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Config.ENDPOINT)
.build();
client = restAdapter.create(IRestAPI.class);
}
#Override
public void requestAccessToken(String username, String password, Callback callback) {
String grantType = Config.grantType;
String clientId = Config.clientId;
String clientSecret = Config.clientSecret;
client.getAccessToken(grantType, username, password, clientId, clientSecret, callback);
}
}
The second class takes the access token as constructor argument and appends it to all http requests.
public class RestClient implements IRestClient {
private static final String TAG = RestClient.class.getSimpleName();
private IRestAPI client;
public RestClient(final String accessToken)
{
RequestInterceptor requestInterceptor = new RequestInterceptor()
{
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", "Bearer " + accessToken);
}
};
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Config.ENDPOINT)
.setRequestInterceptor(requestInterceptor)
.build();
client = restAdapter.create(IRestAPI.class);
}
#Override
public List<User> requestUsers() {
return client.requestUsers();
}
#Override
public List<Soemthing> requestSomething() {
return client.requestSomething();
}
#Override
public List<SoemthingElse> requestSomethingElse() {
return client.requestSomethingElse();
}
}
I would love some input and suggestions on how to do this better and perhaps merge the two classes. I'm thinking of making the requestAccessToken method of the RequestAccessToken a static member of the RestClient class. At least that would merge the two class. But I'm using a factory to create the RestClient and if I declare a static method on it which I use throughout my code I get tight coupling... Suggestions?
After discussing this elsewhere I came up with the following code.
public class RestClient implements IRestClient {
private static final String TAG = RestClient.class.getSimpleName();
private IRestAPI client;
private String username;
private String password;
private RequestAccessToken requestAccessToken;
private Access access;
private static RestClient singleton;
// TODO: use Dagger
public static RestClient getInstance()
{
if(singleton == null)
{
singleton = new RestClient();
}
return singleton;
}
/**
* Access declared as private to prevent instantiation outside of this class.
*/
private RestClient()
{
requestAccessToken = new RequestAccessToken();
}
/**
* Request an access token.
*
* #return A string containing the access token
*/
public String requestAccessToken(String username, String password)
{
this.username = username;
this.password = password;
this.access = requestAccessToken.requestAccessToken(username, password);
return this.access.getAccess_token();
}
/**
* Wrapper for {#link #requestAccessToken(String, String) requestAccessToken}
* #return
*/
public String requestAccessToken()
{
if(username == null || password == null) {
throw new IllegalArgumentException("missing user/pass");
}
return requestAccessToken(username, password);
}
/**
* Eventually we want to look at Access.getExpires_in() and return weather or not the token is
* expired.
*
* #return value indicating weather or not the token is expired.
*/
public boolean isAccessTokenExpired()
{
return false;
}
/**
* Return an instance of a rest client with a valid access token.
* #return
*/
private IRestAPI getClient()
{
if(access == null)
{
requestAccessToken();
}
if(isAccessTokenExpired())
{
// Refresh token
}
if(client == null) {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", "Bearer " + access.getAccess_token());
}
};
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Config.ENDPOINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setRequestInterceptor(requestInterceptor)
.build();
client = restAdapter.create(IRestAPI.class);
}
return client;
}
/**
* Login to the api and get a access token.
*
* #param username
* #param password
*/
#Override
public void login(String username, String password)
{
Log.d(TAG, "login");
requestAccessToken(username, password);
}
/**
* Request a list of organizations.
* #return List of Organizations.
*/
#Override
public List<Organization> requestOrganizations() {
Log.d(TAG, "requestOrganizations");
// TODO: error handling
// TODO: caching... which isn't http
return getClient().requestOrganizations();
}
// Add more api requests here
}
I am trying to pull data from class in another class and populate a JPanel with the data, but it is not working for some reason.
Here is the full restConnector class where I pull the JSON data.
As far as I know this works fine.
public class restConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(restConnector.class);
private static final restConnector INSTANCE = new restConnector();
public static restConnector getInstance() {
return restConnector.INSTANCE;
}
private restConnector(){
}
private static String user = "ss";
private static String pwd = "ee
public static String encode(String user, String pwd) {
final String credentials = user+":"+pwd;
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(credentials.getBytes());
}
//Open REST connection
public static void init() {
restConnector.LOGGER.info("Starting REST connection...");
try {
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
WebResource webResource = client.resource("https://somewebpage.com/
String url = "activepersonal";
ClientResponse response = webResource
.path("api/alerts/")
.queryParam("filter", ""+url)
.header("Authorization", "Basic "+encode(user, pwd))
.header("x-api-version", "1")
.accept("Application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
}else{
restConnector.LOGGER.info("REST connection STARTED.");
}
String output = response.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new MyNameStrategy());
try {
List<Alert> alert = mapper.readValue(output, new TypeReference<List<Alert>>(){});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
}
}
However, when I try to pull the data in another class it gives me just null values from the system.out.print inside refreshData() method. Here is the code that is supposed to print the data
public class Application{
Alert alerts = new Alert();
public Application() {
refreshData();
}
private void initComponents() {
restConnector.init();
refreshData();
}
private void refreshData() {
System.out.println("appalertList: "+alerts.getComponentAt(0));
}
}
Here is my Alert class
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(Include.NON_EMPTY)
public class Alert {
private int pasID;
private String status;
private boolean shared;
private String header;
private String desc;
public int getPasID() {
return pasID;
}
public void setPasID(int pasID) {
this.pasID = pasID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\n***** Alert Details *****\n");
sb.append("PasID="+getPasID()+"\n");
sb.append("Status="+getStatus()+"\n");
sb.append("Shared="+isShared()+"\n");
sb.append("Header="+getHeader()+"\n");
sb.append("Description="+getDesc()+"\n");
sb.append("*****************************");
return sb.toString();
}
public String getComponentAt(int i) {
return toString();
}
}
I'm kind a lost with this and been stuck here for a couple of days already so all help would be really appreciated. Thanks for the help in advance.
Edit: Formatted the code a bit and removed the NullPointerException as it was not happening anymore.
As stated in comments:
Me: In your first bit of code you have this try { List<Alert> alert.., but you do absolutely nothing with the newly declared alert List<Alert>. It this where the data is supposed to be coming from?
OP: I'm under the impression that that bit of code is the one that pushes the JSON Array to the Alert.class. Is there something I'm missing there?
Me: And what makes you think it does that? All it does is read the json, and the Alert.class argument is the class type argument, so the mapper know the results should be mapped to the Alert attributes when it creates the Alert objects. That's how doing List<Alert> is possible, because passing Alert.class decribes T in List<T>. The List<Alert> is what's returned from the reading, but you have to determine what to actually do with the list. And currently, you do absolutely nothing with it
You maybe want to change the class just a bit.
Now this is in no way a good design, just an example of how you can get it to work. I would take some time to sit and think about how you want the restConnector to be fully utilized
That being said, you can have a List<Alert> alerts; class member in the restConnector class. And have a getter for it
public class restConnector {
private List<Alert> alerts;
public List<Alert> getAlerts() {
return alerts;
}
...
}
Then when deserializing with the mapper, assign the value to private List<Alert> alerts. What you are doing is declaring a new locally scoped list. So instead of
try {
List<Alert> alert = mapper.readValue...
do this instead
try {
alerts = mapper.readValue
Now the class member is assigned a value. So in the Application class you can do something like
public class Application {
List<Alert> alerts;
restConnector connect;
public Application() {
initComponents();
}
private void initComponents() {
connector = restConnector.getInstance();
connector.init();
alerts = connector.getAlerts();
refreshData();
}
private void refreshData() {
StringBuilder sb = new StringBuilder();
for (Alert alert : alerts) {
sb.append(alert.toString()).append("\n");
}
System.out.println("appalertList: "+ sb.toString());
}
}
Now you have access to the Alerts in the list.
But let me reiterate: THIS IS A HORRIBLE DESIGN. For one you are limiting the init method to one single call, in which it is only able to obtain one and only one resource. What if the rest service needs to access a different resource? You have made the request set in stone, so you cant.
Take some time to think of some good OOP designs where the class can be used for different scenarios.
I'm using Robospice with Retrofit ans ORMLite modules. Retrofit part working good. I have City model for Retrofit:
City.java:
public class City {
public int city_id;
public String name;
#SuppressWarnings("serial")
public static class List extends ArrayList<City> {
}
}
I'm taking this model from server by GET-request:
MyApi.java
public interface MyAPI {
#GET("/cities")
City.List getCities();
}
This part works fine by calling this method:
getSpiceManager().execute(mRequestCity, "city", DurationInMillis.ONE_MINUTE, new ListCityRequestListener());
and listener:
public final class ListCityRequestListener implements RequestListener<City.List> {
#Override
public void onRequestFailure(SpiceException spiceException) {
Toast.makeText(RegisterActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestSuccess(final City.List result) {
Toast.makeText(RegisterActivity.this, "success", Toast.LENGTH_SHORT).show();
updateCities(result);
}
}
At this time i want to download city list once from server and store this list into sqlitedb by ORMLite module. I've created ORMLite model:
City.java
#DatabaseTable(tableName = "city")
public class City {
public final static String DB_CITY_ID_FIELD_NAME = "id";
public final static String DB_CITY_NAME_FIELD_NAME = "name";
#DatabaseField(canBeNull = false, dataType = DataType.INTEGER, columnName = DB_CITY_ID_FIELD_NAME)
int id;
#DatabaseField(canBeNull = false, dataType = DataType.STRING, columnName = DB_CITY_NAME_FIELD_NAME)
private String name;
public City() {
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("id = ").append(id);
sb.append(", ").append("name = ").append(name);
return sb.toString();
}
}
My RetrofitSpiceService.java looks like this:
public class RetrofitSpiceService extends RetrofitGsonSpiceService {
private final static String BASE_URL = "http://example.com/api/v1";
private final static UserFunctions userFunctions = new UserFunctions();
#Override
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
List< Class< ? >> classCollection = new ArrayList< Class< ? >>();
// add persisted classes to class collection
classCollection.add( City.class );
// init
RoboSpiceDatabaseHelper databaseHelper = new RoboSpiceDatabaseHelper( application, "sample_database.db", 1 );
InDatabaseObjectPersisterFactory inDatabaseObjectPersisterFactory = new InDatabaseObjectPersisterFactory( application, databaseHelper, classCollection );
cacheManager.addPersister( inDatabaseObjectPersisterFactory );
return cacheManager;
}
#Override
protected Builder createRestAdapterBuilder() {
Builder mBuilder = super.createRestAdapterBuilder();
mBuilder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
if (userFunctions.isUserLoggedIn()) {
request.addHeader("Authorization", userFunctions.getToken());
}
}
});
return mBuilder;
}
#Override
public void onCreate() {
super.onCreate();
addRetrofitInterface(MyAPI.class);
}
#Override
protected String getServerUrl() {
return BASE_URL;
}
}
I can't understand how can i store and read data from my City database? How do i need to change RetrofitSpiceService? I want download data by Retrofit and store it to database by ORMLite. My CacheManager is correct, i.e. will work properly? Maybe I misunderstand how the module Robospice-ORMLite works?
Thanks a lot!
When you make execute() call with cache key and duration Robospice will store your response into database.
getSpiceManager().execute(mRequestCity, "city", DurationInMillis.ONE_MINUTE, new ListCityRequestListener());
All following requests during one minute will get data from this cache, and then it makes network call. If you want to get data only from cache take a look on getSpiceManager().getFromCache() method. I think it's what you are looking for.