ramonthegreat
ramonthegreat

Reputation: 55

Put "List of Objects" in KrollDict with Titanium Android Module Development

I have a custom class declared in the module source code.

public class Friend{
    public String name;
    public List<String> phoneNumbers;
    public List<String> emailAddresses;

    public Friend(String name, List<String>emailAddresses, 
    List<String>phoneNumbers){
        this.name = name;
        this.emailAddresses = emailAddresses;
        this.phoneNumbers = phoneNumbers;
    }
}

I declared an Android Method in the Module

@Kroll.method
protected synchronized void getListOfObjects(){
    List<String> emailAddresses = Arrays.asList("[email protected]", "[email protected]", "[email protected]");
    List<String> phoneNumbers = Arrays.asList("1", "2", "3");

    List<Friend> friendList = new ArrayList<Friend>();
    friendList.add(new Friend("test1", emailAddresses, phoneNumbers));
    friendList.add(new Friend("test2", emailAddresses, phoneNumbers));
    friendList.add(new Friend("test3", emailAddresses, phoneNumbers));


    KrollDict kd = new KrollDict();
    kd.put("friendList", friendList);
    if (hasListeners("onShow")) {
        fireEvent("onShow", kd);
    }
}

Upon Calling the getListOfOjects method in the Titanium App

module.getListOfObjects();
module.addEventListener('onShow', function(e){
    Ti.API.info(JSON.stringify(e.friendList));
});

I cant seem to retrieve the friendList object.

The EXPECTED RESULT that I wanted to achieve would be like this

[
    {test1, ["[email protected]", "[email protected]", "[email protected]"], ["1", "2", "3"]},
    {test2, ["[email protected]", "[email protected]", "[email protected]"], ["1", "2", "3"]},
    {test3, ["[email protected]", "[email protected]", "[email protected]"], ["1", "2", "3"]}
]

The question is, HOW TO ACHIEVE THE EXPECTED RESULT BASED ON THE SAMPLE CODES ABOVE?

Upvotes: 0

Views: 176

Answers (2)

miga
miga

Reputation: 4055

Another option is to return an object array like this:

KrollDict kd = new KrollDict();
Object[] obj = new Object[friendList.size()];

for (int i=0; i< friendList.size(); ++i){
    KrollDict model = new KrollDict();
    model.put("name", friendList.get(i).name);
    // ...
    obj[i] = model;
}

kd.put("list", obj);
fireEvent("onShow", kd);

That way you'll have an array in your event and don't need to convert that string into json later on.

If you want to use a JSON you can use TiConvert with toJSON, toJSONArray or toJSONString depending on your parameter. No need for Gson.

Upvotes: 0

ramonthegreat
ramonthegreat

Reputation: 55

Convert the List object into JSON string using GSON and assign the result string to the KrollDict property

KrollDict kd = new KrollDict();
Gson gson = new Gson();
String friendListStr = gson.toJson(friendList);
kd.put("friendList", friendListStr);

Upvotes: 0

Related Questions