Strongloop/Loopback findAll feature returns null - android

I'm developing an Android application in conjunction with Strongloop/Loopback. I've stored my data in a MySQL database and have no problem mapping this with Strongloop/Loopback. However, when retrieving the values from the database using Strongloop/Loopback, the list always return a size but with null values. Can't figure out what is wrong. Can anybody help me with this? Many thanks :)
Here is my json response for the database when access from Strongloop:
[
{
"rewards_image_name": "http://x.x.x.x/projects/images/rewards_1.png",
"rewards_equivalent_points": "10",
"id": 1 }, {
"rewards_image_name": "http://x.x.x.x/projects/images/rewards_2.png",
"rewards_equivalent_points": "20",
"id": 2 }, {
"rewards_image_name": "http://x.x.x.x/projects/images/rewards_3.png",
"rewards_equivalent_points": "30",
"id": 3 }, {
"rewards_image_name": "http://x.x.x.x/projects/images/rewards_4.png",
"rewards_equivalent_points": "40",
"id": 4 }
]
Here is my code for getting the list:
StrongloopClient strongloopClient = new StrongloopClient(this.context);
RestAdapter adapter = strongloopClient.getLoopBackAdapter("Rewards", "GET");
StrongloopRewardsModelRepository strongloopRewardsModelRepository = adapter.createRepository(StrongloopRewardsModelRepository.class);
strongloopRewardsModelRepository.findAll(new ListCallback<StrongloopRewardsModel>() {
#Override
public void onSuccess(List<StrongloopRewardsModel> arg0) {
Log.e("", "GetAllRewards success: " + arg0.get(0).getEquivalentPoints());
}
#Override
public void onError(Throwable arg0) {
Log.e("", "GetAllRewards error: " + arg0);
}
});
Here is the StrongloopClient:
public class StrongloopClient {
private Context context;
private RestAdapter adapter;
public StrongloopClient(Context contxt) {
context = contxt;
}
public RestAdapter getLoopBackAdapter(String transaction, String operation) {
if (adapter == null) {
adapter = new RestAdapter(context, "http://192.168.44.101:3000/api");
adapter.getContract().addItem(
new RestContractItem("/" + transaction, operation),
transaction);
}
return adapter;
}
Here is the code for Repository:
public class StrongloopRewardsModelRepository extends ModelRepository<StrongloopRewardsModel>{
public StrongloopRewardsModelRepository() {
super("Rewards", "Rewards", StrongloopRewardsModel.class);
}
}
And this is the Model:
public class StrongloopRewardsModel extends Model {
private Integer rewardsImageId;
private String rewardImageName;
private String equivalentPoints;
public Integer getRewardsImageId() {
return rewardsImageId;
}
public void setRewardsImageId(Integer rewardsImageId) {
this.rewardsImageId = rewardsImageId;
}
public String getRewardImageName() {
return rewardImageName;
}
public void setRewardImageName(String rewardImageName) {
this.rewardImageName = rewardImageName;
}
public String getEquivalentPoints() {
return equivalentPoints;
}
public void setEquivalentPoints(String equivalentPoints) {
this.equivalentPoints = equivalentPoints;
}
}

Finally, I've found what was wrong. POJOs should match the fields of models created in models.json. Thanks for your time.
However, my other question is that, when I used filters for querying such as passing the filters as part of "parameters" being passed to Strongloop adapter, it seems to return all of the model instances instead of filtered ones. Same code from my question, just that getLoopbackAdapter("Rewards","GET") becomes "Rewards?filter[where][rewards_equivalent_points]=10","GET"). Any ideas why it behaved like that? Thanks :)

This is because your search didn't find any instance. I'm not sure if you need to handle this on your App or if the SDK deals with that.
For example, when trying to search by an element[1] through the rest interface, it gets converted to 404 (not found): rest: {after: convertNullToNotFoundError}
https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/dao.js#L771

Related

Getting Nested JsonObjects & Arrays Using Retrofit Library

I got tired using this library, this is my first time using it and made a lot of success ways, but i'm a bit confused in getting the following Json :
{
"Guides":
{
"English": {"ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
,"Arabic": {"EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
}
}
Googled and saw a lot of guides and answered, and made my List like this :
public class PostItem {
List<PostItemArabic> Arabic;
List<PostItemEnglish> English;
}
class PostItemArabic{
private String ArabicSony;
private String ArabicNexus;
private String ArabicSamsung;
private String ArabicHTC;
public String getArabicSony() {
return ArabicSony;
}
public void setArabicSony(String arabicSony) {
ArabicSony = arabicSony;
}
public String getArabicNexus() {
return ArabicNexus;
}
public void setArabicNexus(String arabicNexus) {
ArabicNexus = arabicNexus;
}
public String getArabicSamsung() {
return ArabicSamsung;
}
public void setArabicSamsung(String arabicSamsung) {
ArabicSamsung = arabicSamsung;
}
public String getArabicHTC() {
return ArabicHTC;
}
public void setArabicHTC(String arabicHTC) {
ArabicHTC = arabicHTC;
}
}
class PostItemEnglish{
private String EnglishSony;
private String EnglishNexus;
private String EnglishSamsung;
private String EnglishHTC;
public String getEnglishSony() {
return EnglishSony;
}
public void setEnglishSony(String englishSony) {
EnglishSony = englishSony;
}
public String getEnglishNexus() {
return EnglishNexus;
}
public void setEnglishNexus(String englishNexus) {
EnglishNexus = englishNexus;
}
public String getEnglishSamsung() {
return EnglishSamsung;
}
public void setEnglishSamsung(String englishSamsung) {
EnglishSamsung = englishSamsung;
}
public String getEnglishHTC() {
return EnglishHTC;
}
public void setEnglishHTC(String englishHTC) {
EnglishHTC = englishHTC;
}
}
My Model :
private class Model {
private List<PostItem> Guides;
public List<PostItem> getGuides() {
return Guides;
}
public void setGuides(List<PostItem> roms_center) {
this.Guides = roms_center;
}
}
And printing the result like this :
List<PostItem> Guides = response.body().getGuides();
for(int i = 0 ; i < Guides.size() ; i ++ ) {
for (int b = 0; b < Guides.get(i).English.size() ; b++){
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishHTC());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishNexus());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSamsung());
Log.LogInfo("English Result Is: " + Guides.get(i).English.get(i).getEnglishSony());
}
for (int b = 0; b < Guides.get(i).Arabic.size() ; b++){
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicHTC());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicNexus());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSamsung());
Log.LogInfo("Arabic Result Is: " + Guides.get(i).Arabic.get(i).getArabicSony());
}
}
My work isn't correct, and getting a lot of errors,
Here's the last error i got :
`Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 3 column 18 path $.Guides
What's the way to make it correct ? `
Based on your models when you try to get the guides list your telling retrofit to populate an array. Retrofit is then getting the data and finding that it is a single object and not array. So you need to update your model to reflect the data returned. For example:
class PostItem {
List<Language> mLanguages;
}
class Language{
String mLanguageTitle; //for example english
List<String> mData; //for this is your list of data
}
Then in your activity instead of getting guides you would get just a post item for example:
response.body().getPostItem();
Hope it helps !
First of all, you can use the retrofit Gson library.
You can handle this in two ways:
Option 1: reformat your languages in your json to be an array like Doug says.
{
"Guides":
[
{"Lang":"English","ArabicSony":"Test1","ArabicNexus":"Test2","ArabicSamsung":"Test3","ArabicHTC":"Test4"}
, {"Lang":"Arabic","EnglishSony":"Test1","EnglishNexus":"Test2","EnglishSamsung":"Test3","EnglishHTC":"Test4"}
]
}
Then you will need to redesign your class to reflect this structure.
Like Doug sayd:
class PostItem {
List<Language> mLanguages;
}
Option 2: Create a custom json desirializer in your class. this will take the Json and break it down into whatever structure you want it to be.
public class PostItem implements JsonDeserializer
#Override
public MyDesirializer deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jarabic = (JsonObject) json.get("Arabic");
//whatever manipulations you want to do (fill with your own code)
PostItem item = new PostItem();
item.arabic = jarabic;
...
...
return item;
}

Parsing framework that deals well with circular references in JSON [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am working on an Android project and am currently trying to figure out how to deserialize some JSON from our APIs that includes reference cycles into an object graph, which I can then manipulate and store in a database. Let me give an example:
{
"id": "24",
"name": "Bob",
"friends": [
{
"id": "13",
"name": "Alice",
"friends": [
{
"id": "24" // and we have a circular reference
}
]
}
]
}
Here, a person object called Bob is friends with person Alice, and Alice is in turn friends with Bob. Since the relationship is recursive, Alice’s friends relationship to Bob is not realized as a full person object anymore but only his id is provided.
What tools do you use to perform the above mentioned steps? I tried to implement the object mapping part with Jackson but failed to find a solution for the cycle requirement. I found an ongoing discussion about this topic that mentions JSOG which might be helpful, but our APIs are fixed and not JSOG compliant.
Basically what I am looking for is something like RestKit (iOS framework) for Android.
Once API is fixed, I'd implement it in this manner:
From DB perspective, I'd have 2 tables - UserTable and RelationsTable to keep all edges of your friends graph:
I.e. the idea is to keep Users in the one table and their relations in Relations table. It allows also to add some extra logic on top of it later (for example, user hides his connection or blocks someone, etc. - any possible edges of the graph). Also, it allows to mitigate issues with circular references.
As a framework to retrieve data from service & parse jsons, I'd use Retrofit.
First, I'd define UserBase and User classes:
public class UserBase {
public string id;
}
public final class User extends UserBase {
public string name;
public List<UserBase> friends;
// user's "real" friends, not just ids, fills from SQLite
public List<User> userFriends;
}
where, as you can see, friends is a list of UserBase objects for Retrofit to parse the object from JSON and userFriends - the list, which we'll fill from SQLite manually in further steps.
Now, let's define some help-classes to operate with DBs:
public interface Dao<TItem> {
void add(List<TItem> items);
void removeAll();
List<TItem> getAll();
}
....
public abstract class AbstractDao<TItem> implements Dao<TItem> {
protected final SQLiteDatabase database;
protected final SqlUtilities sqlUtilities;
public AbstractDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
this.database = database;
this.sqlUtilities = sqlUtilities;
}
}
Now we need Dao's for RelatedTable and for UserTable:
public class UserRelation {
public String mainUserId;
public String relatedUserId;
}
...
public interface UserRelationDao extends Dao<UserRelation> {
...
List<User> getFriends(String userId);
...
}
...
public interface UserDao extends Dao<User> {
...
void addWithIgnore(List<TItem> items);
void update(List<TItem> items);
void upsert(List<TItem> items);
User getById(String userId);
...
}
Once it's done, we can actually implement this interfaces:
DefaultUserRelationDao class:
public class DefaultUserRelationDao extends AbstractDao<UserRelation> implements UserRelationDao {
static final String MAIN_USER_COLUMN = "mainuser";
static final String RELATED_USER_COLUMN = "relateduser";
private static final String[] COLUMN_NAMES = new String[]{
MAIN_USER_COLUMN,
RELATED_USER_COLUMN,
};
private static final String[] COLUMN_TYPES = new String[]{
"TEXT",
"TEXT",
};
private static final String TABLE = "userrelation";
static final String CREATE_TABLE = SqlUtilities.getCreateStatement(TABLE, COLUMN_NAMES, COLUMN_TYPES);
static final String ALL_CONNECTED_USERS =
"SELECT " + Joiner.on(",").join(DefaultUserDao.COLUMN_NAMES) +
" FROM " + UserTable.TABLE_NAME + "," + TABLE +
" WHERE " + RELATED_USER_COLUMN + "=" + DefaultUserDao.USER_ID_COLUMN;
public DefaultUserRelationDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
super(database, sqlUtilities);
}
#Override
public void add(List<UserRelation> userRelations) {
try {
database.beginTransaction();
ContentValues contentValues = new ContentValues();
for (UserRelation relation : userRelations) {
sqlUtilities.setValuesForUsersRelation(contentValues, relation);
database.insertOrThrow(TABLE, null, contentValues);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
#Override
public List<User> getFriends(String userId) {
Cursor cursor = database.rawQuery(ALL_CONNECTED_USERS, new String[]{userId});
return sqlUtilities.getConnectedUsers(cursor);
}
}
and DefaultUserDao class:
public final class DefaultUserDao extends AbstractUDao<User> implements UserDao {
public static final String USER_ID_COLUMN = "userid";
static final String USER_NAME_COLUMN = "username";
public static final String[] COLUMN_NAMES = new String[]{
USER_ID_COLUMN,
USER_NAME_COLUMN,
};
private static final String TABLE = "users";
private static final String SELECT_BY_ID =
SqlUtilities.getSelectWhereStatement(TABLE, COLUMN_NAMES, new String[]{ USER_ID_COLUMN });
static final String CREATE_TABLE = SqlUtilities.getCreateStatement(TABLE, COLUMN_NAMES, COLUMN_TYPES);
public DefaultUserDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
super(database, sqlUtilities);
}
#Override
public void add(List<User> users) {
try {
database.beginTransaction();
ContentValues contentValues = new ContentValues();
for (User user : users) {
sqlUtilities.setValuesForUser(contentValues, user);
database.insertOrThrow(UserTable.TABLE_NAME, null, contentValues);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
#Override
public User getById(String userId) {
return getUserBySingleColumn(SELECT_BY_ID, userId);
}
.....
private User getUserBySingleColumn(String selectStatement, String value) {
Cursor cursor = database.rawQuery(selectStatement, new String[]{value});
List<User> users = sqlUtilities.getUsers(cursor);
return (users.size() != 0) ? users.get(0) : null;
}
}
To create our tables, we need to extend SQLiteOpenHelper and in onCreate() actually create tables:
public final class DatabaseHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "mysuper.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DefaultUserDao.CREATE_TABLE);
db.execSQL(DefaultUserRelationDao.CREATE_TABLE);
}
...
}
Now, I'd suggest to define LocalStorage interface with all possible actions with cache:
get all users
get user by id
add users
add connection between users
etc.
public interface LocalStorage {
User getUserById(String userId);
void addUsers(List<User> users);
....
}
and it's implementation:
public final class SqlLocalStorage implements LocalStorage {
private UserDao userDao;
private UserRelationDao userRelationDao;
private SQLiteDatabase database;
private final Object initializeLock = new Object();
private volatile boolean isInitialized = false;
private SqlUtilities sqlUtilities;
// there database is
// SQLiteOpenHelper helper = new DatabaseHelper(context);
// database = helper.getWritableDatabase();
public SqlLocalStorage(SQLiteDatabase database, SqlUtilities sqlUtilities) {
this.database = database;
this.sqlUtilities = sqlUtilities;
}
#Override
public User getUserById(String userId) {
initialize();
User user = userDao.getById(userId);
if (user == null) {
return null;
}
List<User> relatedUsers = userRelationDao.getFriends(userId);
user.userFriends = relaterUsers;
return user;
}
#Override
public void addUsers(List<User> users) {
initialize();
for (User user : users) {
for (UserBase friend : user) {
UserRelation userRelation = new UserRelation();
userRelation.mainUserId = user.id;
userRelation.relatedUserId = friend.id;
UserRelation userRelationMutual = new UserRelation();
userRelationMutual.mainUserId = friend.id;
userRelationMutual.relatedUserId = user.id;
userRelationDao.add(userRelation);
userRelationMutual.add(userRelation)
}
}
userDao.addWithIgnore(users);
}
void initialize() {
if (isInitialized) {
return;
}
synchronized (initializeLock) {
if (isInitialized) {
return;
}
Log.d(LOG_TAG, "Opens database");
userDao = new DefaultUserDao(database, sqlUtilities);
userRelationDao = new DefaultUserRelationDao(database, sqlUtilities);
isInitialized = true;
}
}
}
Last step - the actual usage of it:
//somewhere in non-UI thread
List<User> users = dataSource.getUsers();
localStorage.addUsers(users);
final User userBob = localStorage.getUserById("42");
NB! I'm heavily using here my custom class SqlUtilities. Unfortunately, it's way too big to post it here, but just an example to give some ideas what's inside - here's how getUsers(Cursor cursor) looks there:
.....
public List<User> getUsers(Cursor cursor) {
ArrayList<User> users = new ArrayList<>();
try {
while (cursor.moveToNext()) {
users.add(getUser(cursor));
}
} finally {
cursor.close();
}
return users;
}
private User getUser(Cursor cursor) {
User user = new User(cursor.getString(0));
user.FullName = cursor.getString(1);
....
return user;
}
.....
I hope, you'll forgive me skipping some details (especially, regarding case, when DB has to be updated, when data is not full and besides getting it from cache, you have to retrieve it from server first, and then load it into the cache, etc). If any crucial part is missing - please, post it in comments and i'll be glad to update the post.
I hope, it will help you.
You can have a look into JSON-RPC. This is a good framework which supports JSON parsing and object mapping of complex object relationship.
I'd say you're trying to solve the wrong problem & the real problem is that your data representation is broken. As well as the circular refs problem its also inefficient in that each friend gets duplicated for each friendship. Better to flatten your list of people like this:
[
{
"id": "13",
"name": "Alice",
"friends": ["24"]
},
{
"id": "24",
"name": "Bob",
"friends": ["13"]
}
]
Store the list in a HashMap<Integer, Person> (or SparseArray<Person>). Job done!

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.

Retrofit: Handling JSON object that dynamically changes its name

I use retrofit.
I have JSON data like this:
{
"elements": {
"159": {
"id": 159,
"name": "Alex"
},
"831": {
"id": 831,
"name": "Sofia"
},
"3125": {
"id": 3125,
"name": "Mark"
}
}
}
Structure of this JSON cannot be configured on my side.
And I want to handle those objects (that dynamically change their names) using retrofit.
I have sth like that now.
Model:
public class Elements{
public ArrayList<ElementsItem> = new Array<ElementsItem>();
//getters setters
public class ElementsItem{
public ArrayList<ElementsItemDetails> = new Array<ElementsItemDetails>();
//getters setters
}
public class ElementItemDetails{
public Integer id;
public String name;
//getters setters
}}
API:
public interface MyApi {
#GET("/file.php?method=getElementDetails")
public void getDetails(#Query("ids") ArrayList<Integer> ids_list, Callback<Elements> callback);
}
And the function where I try to handle data:
public void get_details_for_particular_elements(ArrayList<Integer> ids_list){
Gson gson_gd = new GsonBuilder().registerTypeAdapter(
Elements.class,
new JsonDeserializer<Elements>() {
#Override
public Elementsdeserialize(JsonElement je,
Type type, JsonDeserializationContext jdc)
throws JsonParseException {
// TODO Auto-generated method stub
Log.d("my_app", "Deserialization for Getting Elements Details in progress..");
JsonObject elements= je.getAsJsonObject();
return new Gson().fromJson(elements,
Elements.class);
}
}).create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(Constants.URL)
.setConverter(new GsonConverter(gson_gd)).build();
MyApi myDetails = restAdapter.create(MyApi.class);
myDetails.getDetails(ids_list, new Callback<Elements>() {
#Override
public void success(Elements e, Response response) {
// TODO Auto-generated method stub
Log.d("my_app", "Success! " + e.getElementsItem().get(0).getElementsItemDetails().get(0).getName());
}
#Override
public void failure(RetrofitError retrofitError) {
// TODO Auto-generated method stub
Log.d("my_app", "Failure..." + retrofitError);
}
});
}
I try to handle the name "Alex" and print it in LogCat, but I cannot - application stops. I am sure that this command:
e.getElementsItem().get(0).getElementsItemDetails().get(0).getName()
is wrong, but I don't know any other way how to handle the name value.
How to behave when object name changes (in that case there are three similar objects called in dependance of list of ids ids_list provided? Here: [156,831,3125]
Please help.
As the key for you ElementItemDetails is dynamically generated, you should use a Map to represent the structure.
In your model class Elements:
Replace
public ArrayList<ElementsItem> = new Array<ElementsItem>();
with
Map<String, ElementItemDetails> elemDetails;
Hope this helps.

Categories

Resources