Retrofit HashMap is null [duplicate] - android

This question already has answers here:
Displaying integer on toast
(4 answers)
Closed 6 years ago.
Hi i'm trying to learn android and currently implementing retrofit and tried to solve this using related post here sadly nothing Helped me pls hear me out.
I have a json data that i need to parse here it is
{
"-KNea90tV5nZlkeqxc3Q": {
"accountName": "Mark Angelo Noquera",
"accountNumber": "12435656443",
"accountType": "Peso Savings"
},
"-KNeaPmBoTXV4mQC6cia": {
"accountName": "Mark Angelo Noquera",
"accountNumber": "12435656444",
"accountType": "Peso Checking"
},
"-KNeaWe_ZbtI9Tn6l-oF": {
"accountName": "Mark Angelo Noquera",
"accountNumber": "12435656445",
"accountType": "Personal Loan"
}}
Then some tutorials told me to use a hashmap so i implemented mine
here is my ModelClass1.class
public class MarkSamples {
public HashMap<String, MarkSample> marksamples;
public HashMap<String, MarkSample> getMarksamples() {
return marksamples;
}}
ModeClass2.class - For handling the objects
public class MarkSample {
#SerializedName("accountName")
public String acntName;
#SerializedName("accountNumber")
public String acntNumber;
#SerializedName("accountType")
public String acntType;
public String getName() {
return (acntName);
}
public void setName(String acntName) {
this.acntName = acntName;
}
public String getNumber() {
return (acntNumber);
}
public void setNumber(String acntNumber) {
this.acntNumber = acntNumber;
}
public String getType() {
return (acntType);
}
public void setType(String acntType) {
this.acntType = acntType;
}
}
My API is here UPDATED
public interface ContactsAPI {
#GET("/api/accounts.json")
public void getSamples(Callback<HashMap<String, MarkSample>> response);}
ANd lastly i'm calling my handler here UPDATED
api.getSamples(new Callback<HashMap<String, MarkSample>>() {
#Override
public void success(HashMap<String, MarkSample> stringMarkSampleHashMap, Response response) {
loading.dismiss();
int mint = stringMarkSampleHashMap.size();
Toast.makeText(mainActivity, mint, Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError error) {
}
});
And everytime i TOast the outcome i got a null value did i implemented it wrong? Im certain i used my RootUrl correctly if this is not the problem what are the other methods i can use? please help me.
here is my Logcat UPDATED
FATAL EXCEPTION: main
Process: com.exist.kelvs.retrofit2, PID: 2517
android.content.res.Resources$NotFoundException: String resource ID #0x3
at android.content.res.Resources.getText(Resources.java:312)
at android.widget.Toast.makeText(Toast.java:286)
at com.exist.kelvs.retrofit2.RetrofitHandler$2.success(RetrofitHandler.java:51)
at com.exist.kelvs.retrofit2.RetrofitHandler$2.success(RetrofitHandler.java:46)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Update api definition to:
#GET("/api/accounts.json")
public void getSamples(Map<String,MarkSample> response);}
And api call to:
api.getSamples(new Callback<Map<String,MarkSample>() {
#Override
public void success(Map<String,MarkSample> samplelist, Response response) {
loading.dismiss();
int mint = samplelist.size();
...
Update:
To get all accountNames add this code to your callback:
...
loading.dismiss();
int mint = 0;
if (samplelist!=null){
mint = samplelist.size();
for (MarkSample item:samplelist.values()){
Log.d("TEST","value: "+item.getName();
}
}
...

Check out this article:
Getting Starter with Retrofit 2
Use Retrofit2 Call with set up converter factory to enqueue your data
Your problem is in serialization:
There is no marksamples field in respond. You don't need special MarkSamples class. Look how you can modify your code:
public interface ContactsAPI {
#GET("/api/accounts.json")
Call<LinkedHashMap<String, MarkSample>> getSamples();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" https://pbcom.firebaseio.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
and request:
ContactsAPI api = ContactsAPI.retrofit.create(ContactsAPI.class);
Call<LinkedHashMap<String, MarkSample>> call = api.getSamples();
call.enqueue(new Callback<LinkedHashMap<String, MarkSample>>() {
#Override
public void onResponse(Call<LinkedHashMap<String, MarkSample>> call, Response<LinkedHashMap<String, MarkSample>> response) {
LinkedHashMap<String, MarkSample>> samples = response.body();
}
#Override
public void onFailure(Call<LinkedHashMap<String, MarkSample>> call, Throwable t) {
}
});

Related

Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to use Volley and send GET request to check data after login.
I have special class 'API' where's all Volley staff.
What I am trying to do is after checking validation in LoginActivity (default android studio template) I want to create API instance in LoginActivity and send GET request to server.
This is only for testing Volley, later I want to create one API instance in some Main class.
Here's my API class:
import android.app.Application;
import android.util.Log;
import com.android.volley.*;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
import java.lang.String;
public class API extends Application {
protected String ServerURL;
protected String GET;
protected String POST;
protected RequestQueue queue;
public API(){
setServerURL("http://localhost:63424");
setGET("http://localhost:63424/api");
setPOST("http://localhost:63424/api");
queue = Volley.newRequestQueue(this);
}
protected void SendGET (String request)
{
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, request, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("ResponseAPI", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.ResponseAPI", error.toString());
}
}
);
queue.add(getRequest);
}
//Logowanie
public boolean CheckLogin (String Login, String Password){
setGET(getGET()+"/Search_Users_/login=/"+Login + "/");
SendGET(getGET());
return true;
}
public String getServerURL() {
return ServerURL;
}
public void setServerURL(String ServerURL) {
ServerURL = ServerURL;
}
public String getGET() {
return GET;
}
public void setGET(String GET) {
this.GET = GET;
}
public String getPOST() {
return POST;
}
public void setPOST(String POST) {
this.POST = POST;
}
}
Here I am trying to create API instance in LoginActivity:
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
Log.d("API", "Zaraz utworze API");
API api = new API();
return api.CheckLogin(mEmail, mPassword);
// TODO: register the new account here.
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
This solution do not work, I get an error:
FATAL EXCEPTION: AsyncTask #1
Process: pawel.cooker, PID: 2646
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getCacheDir()' on a null object reference
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:256)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at pawel.cooker.API.<init>(API.java:17)
at pawel.cooker.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:320)
at pawel.cooker.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:299)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
at java.lang.Thread.run(Thread.java:764) 
There's a problem with Volley, but have no idea what's wrong.
There's problem with Volley
No, there's a problem with your API class.
Make sure you put it in the manifest
<application
android:name=".API"
After that
Don't use a constructor. Use onCreate . OR, don't use Application, and use a Volley-scoped singleton -- see example from documentation
Replace localhost with the actual Server address
public class API extends Application {
public static final String ServerURL = "http://<Use real server here>:63424";
public static final String GET = ServerURL+"/api";
public static final String POST = ServerURL+"/api";
protected RequestQueue queue;
private final API mInstance;
private API() { }
public API getInstance() {
return mInstance;
}
#Override
public void onCreate(){
super.onCreate();
mInstance = this;
queue = Volley.newRequestQueue(this);
}
You can't return blocking value from Async functions. Use the callbacks to pass back the results
protected void sendGET (String url, Response.Listener<JSONObject> onSuccess)
{
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
onSuccess,
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.ResponseAPI", error.toString());
}
}
);
queue.add(getRequest);
}
public void checkLogin (String Login, Response.Listener<JSONObject> onSuccess){
SendGET(GET+"/Search_Users_/login=/"+Login, onSuccess);
}
Don't use new API() when you should instead use ((API) getApplicationContext()) or with the above implementation, API.getInstance()
For example,
API api = API.getInstance();
api.checkLogin(mEmail, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO: register the new account here.
}
});
Most importantly here, you don't need an AsyncTask when using Volley. It's already asynchronous
On a related note, if you are using RESTful APIs, then Retrofit might be more useful

How to fetch data from multiple APIs using RxJava with retrofit 2

I am new to RxJava. I want to fetch data from the JSON API. Assume there are two APIs, API 1 and API 2. We fetch a JSON object "mediaId" from API 1. Now, I want to fetch JSON from API 2 with "mediaId". How can I achieve this using RxJava, along with retrofit in Android?
public void gettdata(final Listerner listerner){
postitemses= new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.mytrendin.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
APiService networkAPI = retrofit.create(APiService.class);
Observable<List<Postitems>> observable = networkAPI.getFriendObservable()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
observable.subscribe(new Observer<List<Postitems>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
listerner.onFailure("oops... Something went wrong");
}
#Override
public void onNext(List<Postitems> postitemsList1) {
Postitems postitems;
for (int i=0;i<postitemsList1.size();i++){
postitems = new Postitems();
int id = postitemsList1.get(i).getId();
String title = postitemsList1.get(i).getTitle().getRendered();
String shortdesc= postitemsList1.get(i).getExcerpt().getRendered();
String mediaid= postitemsList1.get(i).getFeatured_media();
String authorid= postitemsList1.get(i).getAuthor();
String date = postitemsList1.get(i).getDate();
String slug = postitemsList1.get(i).getSlug();
Log.i("Hello-slug",""+slug);
String[] mediaurl= mydata(mediaid);
Log.i("Hello-mediaurl",""+mediaurl);
postitems.setId(id);
postitems.setDate(date);
postitems.setSlug(""+slug);
postitems.setPostExcerpt(shortdesc);
postitems.setPostTitle(title);
postitemses.add(postitems);
}
listerner.showpostitems(postitemses);
}
});
}
public String[] mydata(String mediaid){
final String[] mediaurl = new String[1];
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www.mytrendin.com")
.build();
APiService aPiService = retrofit.create(APiService.class);
Call<Postitems> call = aPiService.getmediaurl(mediaid);
call.enqueue(new Callback<Postitems>() {
#Override
public void onResponse(Call<Postitems> call, Response<Postitems> response) {
Postitems postitemsList1 = response.body();
mediaurl[0] =postitemsList1.getGuid().getRendered();
// mediaurl[0][0] =postitemsList1.get(0).getGuid().getRendered();
}
#Override
public void onFailure(Call<Postitems> call, Throwable t) {
}
});
return mediaurl;
}
error occured
https://www.mytrendin.com
05-09 03:42:09.227 15315-15315/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
05-09 03:42:09.228 15315-15315/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mytrendin.mytrendin, PID: 15315
java.lang.NullPointerException: Attempt to invoke virtual method .mytrendin.dashboard.utils.Po stitems$Guid (ZygoteInit.java:755)
Sure you can use the merge operator along with the IO scheduler.By definition,merge can combine multiple Observables into one by merging their emissions.here is an example,
Observable<Integer> odds = Observable.just(1, 3, 5).subscribeOn(someScheduler);
Observable<Integer> evens = Observable.just(2, 4, 6);
Observable.merge(odds, evens)
.subscribe(new Subscriber<Integer>() {
#Override
public void onNext(Integer item) {
System.out.println("Next: " + item);
}
#Override
public void onError(Throwable error) {
System.err.println("Error: " + error.getMessage());
}
#Override
public void onCompleted() {
System.out.println("Sequence complete.");
}
});
Output :
Next: 1
Next: 3
Next: 5
Next: 2
Next: 4
Next: 6
Sequence complete.
Something like this in your case,
public Observable<Data> getMergedData() {
return Observable.merge(
networkRepository.getData().subscribeOn(Schedulers.io()),
networkRepository.getData().subscribeOn(Schedulers.io())
);
}
Alright there is another way to solve this, first create a observable for both API, then subscribe and observe changes from your first API subscription.Next create a PublishSubject instance. Which is useful because,once an Observer has subscribed, emits all subsequently observed items to the subscriber.For example publish string values from the api response.
private PublishSubject<String> subject = PublishSubject.create();
subject.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).filter((s) -> s.size() > 0).subscribe(new Observer<String>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(String str) {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
}
});
Then to trigger the observable call onNext from the subject.
subject.onNext("some data from api");
Advantages, very flexible to changes to anywhere in your class scope.
Hope this helps.
for the below snippet
call.enqueue(new Callback<Postitems>() {
#Override
public void onResponse(Call<Postitems> call, Response<Postitems> response) {
Postitems postitemsList1 = response.body();
mediaurl[0] =postitemsList1.getGuid().getRendered();
// mediaurl[0][0] =postitemsList1.get(0).getGuid().getRendered();
//use the concept of publish subject here, which i detailed in answer, example
subject.onNext(postitemsList1.getGuid().getRendered());
//the string data will be passed to the above observable for the subject instance.
}
#Override
public void onFailure(Call<Postitems> call, Throwable t) {
}
});

Parsing JSON in Retrofit android?

I'm trying to parse the following JSON structure using Retrofit on android.
{
"payload": [
{
"name": "Rice",
"brands": [
{
"name": "Dawat",
"subProducts": [
{
"id": 1,
"name": "Basmati Long Grain",
"creditDays": 20,
"currency": "$",
"willDeliver": false,
"minPrice": 250,
"maxPrice": 400,
"sku": "1Kg",
"uom": ""
}
]
}
]
}
],
"messages": []
}
I have made models using http://www.jsonschema2pojo.org/. The keys I'm particularly are payload-->name, brands-->name and subProducts-->name. Below is what I've tried so far. Can anyone please help? I can't parse this JSON Structure using retrofit
productDetails.enqueue(new Callback<GetProductDetailsByPhoneNumber>() {
#Override
public void onResponse(Call<GetProductDetailsByPhoneNumber> call, Response<GetProductDetailsByPhoneNumber> response) {
Toast.makeText(getApplicationContext(), "Response mil gaya", Toast.LENGTH_LONG);
List<Payload> subProducts = new ArrayList<Payload>(response.body().payload);
}
#Override
public void onFailure(Call<GetProductDetailsByPhoneNumber> call, Throwable t) {
}
});
Interface:
#GET("wholesaler/getProductDetailsByPhoneNumber")
Call<GetProductDetailsByPhoneNumber> getProducts(#Query("phoneNumber") String number);
getDService()
public API getDService(){
/**
* The Retrofit class generates an implementation of the API interface.
*/
if(service == null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(API.class);
}
return service;
}
Payload.java
public class Payload {
public String name;
public List<Brand> brands;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Brand> getBrands() {
return brands;
}
public void setBrands(List<Brand> brands) {
this.brands = brands;
}
}
Try using this, as you are not providing your "Payload"o bject
productDetails.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.body()!=null{
JsonObject jsonObject=response.body();
if(response.code() == 200){
if(jsonObject.has("payload"){
JsonArray dataArray = jsonObject.getAsJsonArray(HAS_DATA);
if (dataArray.size() > 0) {
Toast.makeText(getApplicationContext(), "Response Called", Toast.LENGTH_LONG);
//your further code
}
}
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
//logic for if response fails
}
});
Use this code in your onResponse:
if(response.code()==HttpsURLConnection.HTTP_OK) { //HttpOk is the response code for 200
if (response.body() != null) {
if (response.body().payload!= null) {
//data is there in an array of type payload
//save all the data there
//like you want the name, you can get that by response.body().payload.name and you will get "rice"
//similarly if you want the name which is in subproducts array use : response.body().payload.get(0).brands.get(0).subProducts.get(0).name and you
// will get "Basmati Long Grain"
}
}
}
The code will help you deserialise all the data from the JSON and you can store that wherever you want. Plus I will recommend you to keep a check on other response codes as well(such as 400 for bad request, 500 for internal server error etc). See here, you have your payload in an array, and there was only one element in it, that is why I have used payload.get(0). In case of multiple elements in the array you need to use a loop and then fetch the values, same goes for your brands and subProduct array.
You are trying to get an object PayLoad, and you have
{
"payload": [
{
"name"
this means it doesn't start with a parent, so you need to save the answer in a List like List and letter in the iteration you can use Response.get(position) <-- and this one going to be your payload number position, I hope this can help you

Retrofit parse empty array []

I need to parse list of object, whith can be emply. {"data":[]}
I use tamplated callback CallBack<T>called with
public static DataList {
public List<Data> data
};
api.getData(new Callback<DataList>() {...});
it crashed with error:java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com...DataList
Please help
Your model should work fine. Perhaps your server isn't returning what you think it does, or maybe its not application/json what it's returning?
Here's a quick demo:
Doing a GET on the url http://www.mocky.io/v2/5583c7fe2dda051e04bc699a will return the following json:
{
data: [ ]
}
If you run the following class, you'll see it works just fine:
public class RetrofitDemo {
interface API {
#GET("/5583c7fe2dda051e04bc699a")
void getDataList(Callback<DataList> cb);
}
static class DataList {
List<Data> data;
}
static class Data {
}
public static void main(String[] args) {
API api = new RestAdapter.Builder()
.setEndpoint("http://www.mocky.io/v2")
.build()
.create(API.class);
api.getDataList(new Callback<DataList>() {
#Override
public void success(DataList dataList, Response response) {
System.out.println("dataList=" + dataList);
}
#Override
public void failure(RetrofitError retrofitError) {
throw retrofitError;
}
});
}
}
Your issue is your java model doesn't reflect the data it's trying to deserialize to.
//{"data":[]} does not map to List<Data> data.
// If the server was just returning an array only then it would work.
// It will match to the entity below make sure your cb = Callback<MyItem>
public class MyItem {
List<Data> data;
}

Retrofit - How do define hashmap gson response?

I've looked at this post and need some clarification.
I have a structure that looks like this:
{
"contacts": [
{
"account_id": 3599,
"created_at": 1427556844,
"name": "John Smith",
},
{
"account_id": 3599,
"created_at": 1427155837,
"name": "Carl Johnson",
}
]
}
And I have created it this way:
public class Contacts {
#SerializedName("contacts")
public List<User> contacts;
}
public class User {
#SerializedName("account_id")
int accountId;
#SerializedName("created_at")
String createdAt;
#SerializedName("name")
String name;
}
But when I try to run it with retrofit I get "Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY". According to this post my syntax is correct. But I more into Jake Whartons solution (from the other post mentioned) here, that it actually is a hashmap
Map<String, List<User>>
But changing the contacts object to use Hashmap instead gives me the following error: "Expected BEGIN_ARRAY but was BEGIN_OBJECT". So please help me figure out how to define the objects using retrofit and robospice.
Edited:
I'm using robospice, so I have this:
#Override
public Contacts loadDataFromNetwork() throws Exception {
final AlertPolicies[] myIncidents = {null};
return getService().getContacts();
}
And in the activity I have defined in onStart():
spiceManager.execute(contactsRequest, CACHE_KEY, DurationInMillis.ONE_MINUTE, new ContactsRequestListener());
and the Listener like this:
private final class ContactsRequestListener implements RequestListener<Contacts> {
#Override
public void onRequestFailure(SpiceException spiceException) {
if(Constant.DEBUG) Log.d(TAG, "onRequestFailure: " + spiceException.getMessage());
Toast.makeText(ContactsActivity.this, "failure", Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestSuccess(Contacts contacts) {
if(Constant.DEBUG) Log.d(TAG, "onRequestSuccess");
Toast.makeText(AlertPoliciesActivity.this, "success", Toast.LENGTH_SHORT).show();
if(contacts != null) {
updateContacts(contacts);
}
}
}
Contacts is always null and if I look at the response it says "Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY" and trying the other way as I explained above gives me the other error.
HashMap<Integer,User> hash=new HashMap();
#Override
public void onRequestSuccess(Contacts contacts) {
if(Constant.DEBUG) Log.d(TAG, "onRequestSuccess");
Toast.makeText(AlertPoliciesActivity.this, "success", Toast.LENGTH_SHORT).show();
if(contacts != null) {
for(int i=0;i<contacts.size();i++){
hash.put(contacts.contacts.get(i).accountId,contacts.contacts);
}
}
}
Thanks, but I think the trick, without having to use callback at all, was actually:
#SerializedName("contacts")
public List<User> contacts;
But I'll keep your hashmap in mind.

Categories

Resources