-1

您好,我有一个工作代码,可以将 twitter 时间线显示到 textview 中:

    void examineJSONdata()
{
    TextView tvData = (TextView) findViewById(R.id.txtData);
    try
    {
        String x = "";
        InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
        byte [] buffer = new byte[is.available()];
        while (is.read(buffer) != -1);
        String jsontext = new String(buffer);
        JSONArray entries = new JSONArray(jsontext);

        x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n";

        int i;
        for (i=0;i<entries.length();i++)
        {
            JSONObject post = entries.getJSONObject(i);
            x += "------------\n";
            x += "Date:" + post.getString("created_at") + "\n";
            x += "Post:" + post.getString("text") + "\n\n";
        }
        tvData.setText(x);
    }
    catch (Exception je)
    {
        tvData.setText("Error w/file: " + je.getMessage());
    }
}

现在我想尝试使用 ListView 而不是 TextView

我在 StackOverFlow Android App 上找到了一个代码:JSON array from web to listview

ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
        JSONArray array = (JSONArray) new JSONTokener(json).nextValue();

        String[] stringarray = new String[array.length()];
        for (int i = 0; i < array.length(); i++) {
            stringarray[i] = array.getString(i);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray); 
        list.setAdapter(adapter);
} catch (JSONException e) {
        // handle JSON parsing exceptions...
}

我试过这样做,但我无法工作 有人能帮我转换代码吗?我认为所有必要的信息都在第一个代码中。

4

1 回答 1

0
    String x = "";
    InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
    byte [] buffer = new byte[is.available()];
    while (is.read(buffer) != -1);
    String jsontext = new String(buffer);
    JSONArray array = new JSONArray(jsontext);
    String[] stringarray = new String[array.length()];

int i;
    for (i=0;i<array.length();i++)
    {
        JSONObject post = array.getJSONObject(i);
        String temp;

        temp += "Date:" + post.getString("created_at") + "\n";
        temp += "Post:" + post.getString("text");
        stringarray[i]=temp;
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  android.R.layout.simple_list_item_1, stringarray); 
    list.setAdapter(adapter);
于 2012-07-15T13:34:25.330 回答