0

我有 JSONArray ["category_1","category_2","category_3"] 但我没有得到数据。以及我如何将这些数据设置为 Android 中的微调器或列表视图。

E:

故障在哪里?

public class MainActivity extends Activity {

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

    Spinner spinner;

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

        try {
            JSONArray jsonArray;
            jsonArray = getJSONArrayFromUrl(urlCat);

            final String[] array_spinner = new String[jsonArray.length()];

            //int show_total = jsonArray.length();

            //Toast.makeText(flash_tattoo.this, show_total + "test", Toast.LENGTH_LONG).show();

            for (int i=0; i<jsonArray.length(); i++)
            {
                String styleValue = jsonArray.getJSONArray(0).getString(i);
                array_spinner[i] = styleValue;

            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,array_spinner);

            adapter.setDropDownViewResource(R.layout.activity_main);
            spinner.setAdapter(adapter);


        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    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

1 回答 1

1

您需要将 Json 解析为对象。 这里有一些方法可以做到这一点。然后您将需要创建一个 ArrayListAdapter 并用一个数组列表填充它,请参见此处。而已。

编辑:要改为创建 JsonArray,请参阅此处以向 JSONArray 构造函数提供字符串。

于 2013-03-11T16:09:40.980 回答