2012-07-15 59 views
-1

您好,我有一个显示一个Twitter时间轴到一个TextView工作代码:转换“JSON数据的TextView”到“JSON数据的ListView”

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的

我发现在计算器上一个代码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... 
} 

我试图这样做,但我不能让我的工作 会有人帮助转换的C颂赞我吗?我认为所有必要的信息都在第一个代码中。

+0

究竟是不是工作?是不是列表视图显示或它是空的还是显示错误的数据? – 2012-07-15 12:58:34

+0

它显示了什么?任何“错误”?任何“崩溃”? – 2012-07-15 12:58:39

+0

第一个代码正在工作,但我想要使用ListView,因此我在另一个StackOverFlow问题中找到第二个代码,我想用它来显示我的数据,而不是那个国家等等。所以我想如果有人能帮我重新格式化在第二个代码中,所以我有一个ListView而不是TextView。 – basnijkamp 2012-07-15 13:00:53

回答

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); 
+0

非常感谢,它的工作我只改变了字符串temp; to String temp =“”;所以它正在工作,但我也喜欢,导致整个tweet正在显示,只有1条规则才会显示,所以你不会看到整个tweet只是一个部分,当你点击它显示了整个推文。 – basnijkamp 2012-07-15 13:42:36