Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONArray to Spinner

I have a problem. I don't set JSONArray to Spinner. My JSON look ["category1","category2","category3"] How to get this JSONArray to spinner? I don't know if my code is well

public class Main extends Activity {

    String urlCat = "http://tvapp.pcrevue.sk/categories.json";

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

         JSONArray jsonArray = getJSONArrayFromUrl(urlCat);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayUseLogoEnabled(false);
        ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, jsonArray);
        actionBar.setListNavigationCallbacks(spinnerMenu, 
                new ActionBar.OnNavigationListener() {

                    @Override
                    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
                        FragmentTransaction tx = getFragmentManager().beginTransaction();
                        switch (itemPosition) {
                        case 0:
                            tx.replace(android.R.id.content, new Tab1Fragment());
                            break;
                        case 1:
                            tx.replace(android.R.id.content, new Tab2Fragment());
                            break;

                        default:
                            break;
                        }
                        tx.commit();
                        return false;
                    }
                });
    }

    public JSONArray getJSONArrayFromUrl(String url) {
        InputStream is = null;
        JSONArray jObj = null;
        String json = "";
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                //json += line;
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

I need your help. Thx

like image 751
Benjamin Ares Varga Avatar asked Mar 17 '13 14:03

Benjamin Ares Varga


2 Answers

I don't find any constructor in ArrayAdapter that Accepts JSONArray object, if you have any doubt refer Array Adapter.

You need to pass the List instead of JSONArray. And also, You are peforming network operation of the UI thread, so you'll get NetworkOnMainThread exception. It will be ok for the lower versions but the heigher version will throw exception. Try using AsyncTask to get the values or a Separate Thread

So get the list like this

ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<jsonArray.length(); i++) {
    list.add(jsonArray.getString(i));
}
ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, list);
like image 106
Pragnani Avatar answered Nov 06 '22 08:11

Pragnani


First solution

Actually I did not find any constructor in ArrayAdapter that needs JSONArray. If your JSONArray is having all string elements then

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        List<String> listist = new ArrayList<String>();

        String res = callGet("http://tvapp.pcrevue.sk/categories.json");
        JSONArray jsonArray = new JSONArray(res);

        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                listist.add("" + jsonArray.get(i));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Log.e("", "listist.size() : " + listist.size());

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String callGet(String urlString) {

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(params, 10000);
    HttpConnectionParams.setConnectionTimeout(params, 10000);
    HttpClient httpclient = new DefaultHttpClient(params);
    HttpGet httppost = new HttpGet(urlString);

    try {

        HttpResponse response = httpclient.execute(httppost);
        return EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        return "";
    }
}
}

I got my logcat output

03-17 21:49:36.821: E/(376): listist.size() : 10

Second solution

Have you tried GSON lib for json parsing? It convert Java Objects into their JSON representation.

List<String> listist = new ArrayList<String>();
iidList = new Gson().fromJson(jsonArray, List.class);

ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(
            actionBar.getThemedContext(),
            android.R.layout.simple_list_item_1, listist);
like image 27
Bhavesh Hirpara Avatar answered Nov 06 '22 10:11

Bhavesh Hirpara