我正在尝试根据请求的结果将项目添加到列表视图中。但是,列表不会更新。我有一个贯穿的for循环并添加了所有的县,并且在add county方法中它将notifyDataSetChanged()
。但是,这不会更新GUI
。以下是我的示例代码。
new Response.Listener<JSONArray>() {
// Takes the response from the JSON request
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject countryObject = response.getJSONObject(i);;
String flagURI= ""+countryObject.getString("flag");
String studentOne = ""+countryObject.getString("studentOne");
String studentTwo = ""+countryObject.getString("studentTwo");
String teacher = ""+ countryObject.getString("teacher");
String name = ""+ countryObject.getString("Name");
rez=rez+""+countryAdapter.getCount();
countryAdapter.add(new Country(name, teacher, studentOne, studentTwo,0,0,flagURI));;
}
tvName = (TextView) findViewById( R.id.tvName );
tvName.setText( "one");
countryAdapter.updateList(countries);
tvName.setText( rez);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
tvName = (TextView) findViewById( R.id.tvName );
tvName.setText( "BAD NEWS1" + e);
e.printStackTrace();
}
catch (Exception e) {
tvName = (TextView) findViewById( R.id.tvName );
tvName.setText( "BAD NEWS3" + e);
}
}
},
public class CountryAdapter extends BaseAdapter {
LayoutInflater mInflater;
String score;
ArrayList<Country> countries;
public CountryAdapter(Context c,Country[] country) {
this.countries = new ArrayList<Country>( Arrays.asList(country));;
mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateList(Country[] data) {
this.countries = new ArrayList<Country>( Arrays.asList(data));;
this.notifyDataSetChanged();
}
public void add(Country data) {
this.countries.add(data);
}
}
答案 0 :(得分:1)
在for循环中
countryAdapter.add(new Country(name, teacher, studentOne, studentTwo,0,0,flagURI));;
使用add方法在countryAdapter的countries对象中添加Country对象。 然后,在循环后面的行:
countryAdapter.updateList(countries);
这里是&#34;国家&#34;在updateList方法中传递的list对象,替换countryAdapter类的countries列表对象。
您必须更新主要类别&#34;国家&#34; for循环中的对象。
countries.add(new Country(name, teacher, studentOne, studentTwo,0,0,flagURI));