6

我有个问题。我没有将 JSONArray 设置为 Spinner。我的 JSON 外观["category1","category2","category3"] 如何让这个 JSONArray 变成微调器?不知道我的代码好不好

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;

    }
}

我需要你的帮助。谢谢

4

3 回答 3

2

我在 ArrayAdapter 中找不到任何接受 JSONArray 对象的构造函数,如果您有任何疑问,请参阅Array Adapter

您需要传递 List 而不是 JSONArray。而且, 你正在执行 UI 线程的网络操作,所以你会得到NetworkOnMainThread异常。低版本没问题,但高版本会抛出异常。尝试使用AsyncTask获取值或单独的线程

所以得到这样的列表

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);
于 2013-03-17T14:53:47.933 回答
1

第一个解决方案

实际上我在 ArrayAdapter 中没有找到任何需要 JSONArray 的构造函数。如果您JSONArray拥有所有字符串元素,那么

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 "";
    }
}
}

我得到了我的 logcat 输出

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

第二种解决方案

您是否尝试过使用 GSON lib 进行 json 解析?它将 Java 对象转换为它们的JSON表示形式。

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);
于 2013-03-17T14:53:51.957 回答
0

微调器接受数组没有问题。因此,只需从您的 json 中提取一个 java 数组并将该数组传递给微调器。网上有很多关于如何将json转成java数组的例子,比如How to parse a JSON and turn its values into an Array?. 对于使用 java 数组创建微调器:Android: Create spinner programmatically from array

于 2013-03-17T14:59:29.303 回答