6

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

Pragnani
  • 19,755
  • 6
  • 46
  • 74

3 Answers3

2

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);
Armand
  • 21,079
  • 16
  • 81
  • 113
Pragnani
  • 19,755
  • 6
  • 46
  • 74
1

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);
Bhavesh Hirpara
  • 21,576
  • 12
  • 60
  • 102
0

Spinners have no problem accepting arrays. So simply extract a java array from your json and pass that array to the spinner. There are many examples online for how to turn json into java array, such as How to parse a JSON and turn its values into an Array?. And for creating spinner with java array: Android: Create spinner programmatically from array

Community
  • 1
  • 1
learner
  • 11,452
  • 24
  • 87
  • 160
  • How to extract array from json ?? – Benjamin Ares Varga Mar 17 '13 at 15:08
  • Notice that my response gives you two links. one for json to array and one for array to spinner. It the link http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values-into-an-array is not sufficient, you can look it up on google and check out other resources. – learner Mar 17 '13 at 15:14