我已经习惯了几个小时,基本上我要做的就是创建一个JsonObject并在for循环中获取它的值并将其设置为TextView。它正在工作,但我只得到第二个循环值,以澄清这是我的JsonObject
的输出{"Areas":[{"City":"Dallas","State":"Texas"},{"City":"Seattle","State":"Washington"}]}
然而,我只是 {" City":" Seattle"," State":" Washington"} 我的Textviews setText中循环中的第二个值。我想在Textview中获得第一个和第二个循环。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystates);
try {
// Create my Json Array
JSONObject newJsonObject = new JSONObject();
JSONArray myarray = new JSONArray();
JSONObject states= new JSONObject();
states.put("City", "Dallas");
states.put("State", "Texas");
JSONObject states2= new JSONObject();
states2.put("City", "Seattle");
states2.put("State", "Washington");
myarray.put(states);
myarray.put(states2);
newJsonObject.put("Areas", array);
// Ends Json Array
//set Textviews
TextView citiess = (TextView)findViewById(R.id.citiess);
TextView statess = (TextView)findViewById(R.id.statess);
String cityString="";
String stateString="";
// retrieve Json Array and set For Loop
JSONArray jaLocalstreams = names.getJSONArray("Areas");
for(int position=0;position<jaLocalstreams.length();position++)
{
JSONObject JO = jaLocalstreams.getJSONObject(position);
cityString= JO.getString("City");
stateString = JO.getString("State");
citiess.setText(""+cityString);
statess.setText(""+stateString);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
我几乎缩小了问题区域,我认为这是
citiess.setText(""+cityString);
statess.setText(""+stateString);
setText正在用最新的值替换值,这有什么意义,我怎么能改变它以便它不会这样做?当我把它放在for循环中
System.err.println(cityString+","+stateString);
我得到了达拉斯,德克萨斯和华盛顿州西雅图的循环值。这就是为什么我确信setText是问题,任何建议都会很棒。
答案 0 :(得分:2)
似乎是cityString,stateString在循环上得到覆盖,而setText只会打印最后一个值。在你需要在字符串中附加json值然后在循环后设置这些值为
for (int position = 0; position < jaLocalstreams.length(); position++) {
JSONObject JO = jaLocalstreams.getJSONObject(position);
cityString += JO.getString("City");
stateString += JO.getString("State");
}
citiess.setText("" + cityString);
statess.setText("" + stateString);