adding a JSON array (from an API) to a listpreference on the android SDK

382 views Asked by At

I need to put the list I get from a json api (also possible with xml) into a listpreference
could anyone please explain me as good as possible how to do it?
example output from api:

JSON: (preferred) 
     [
     "+32486000001",
     "+32486000002" ]


xml: <response>
     <resource>+32486000001</resource>
     <resource>+32486000002</resource>
     </response>

the code I already have to get it:

    String username = prefs.getString("username", null);
    String password = prefs.getString("password", null);
    String response = MVDataHelper.getResponse(username, password, URL_GET_MSISDN);

so the thing I need is to transform the JSonarray to a proper format for the listpreference & a way to add this function to the array.

please help me ASAP

Thanks in advance

p.s.: both entries & entry values should be the array I get here, so no need for mapping or anything

1

There are 1 answers

0
benvd On

I'm pretty sure you can use the following methods in the onCreate method of a class that extends PreferenceActivity: setEntryValues and setEntries. Just pass them an array of strings.

Parsing the JSONArray to a plain array of Strings should be fairly easy:

String[] entries = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
    entries[i] = jsonArray.getString(i);
}

This might fail, depending on the format of your JSON, but that should give you the general idea.