titaniumtitanium-mobileappcelerator-titaniumtitanium-modulestitanium-android

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("email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com");
    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, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]},
    {test2, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]},
    {test3, ["email1@yahoo.com", "email2@yahoo.com", "email3@yahoo.com"], ["1", "2", "3"]}
]

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


Solution

  • 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);