在我的android应用程序中,我收到了一个JSONArray,我正在解析它,并将其存储在arraylist中,然后将其附加到listview中,但我面临一个错误,整个列表显示在一个列表项中。但我收到了4个项。这就是我所做的一切。
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("topicsJSON",composeJSON());
client.post("http://www.example.com/load_topics.php",params,newAsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
Gson gson = new GsonBuilder().create();
try
{
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Throwable error,String content)
{
if (statusCode == 404)
{
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
else if (statusCode == 500)
{
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
private String composeJSON() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> check_in_List;
check_in_List = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("subject_code",received_subject_code);
check_in_List.add(map);
Gson gson = new GsonBuilder().create();
return gson.toJson(check_in_List);
}
public void load_data()
{
ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
l1.setAdapter(phy);
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String pos = (String) l1.getItemAtPosition(position);
});
}
我面临一个错误,整个列表显示在一个列表项中。但是我收到4件
因为在for-loop
内部调用load_data();
,用于从ArrayList
中的JSONArray
获取数据
将load_data();
移到for-loop
之外,以在ListView 中的单独行中显示每个项目
不要每次都添加列表项,创建适配器,
使用空列表设置适配器一次。
结束解析Jsonarray并添加数据后,adapter.notifyDataSetChanged();
替换此:
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
通过
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
}
load_data();
遵循以下步骤:
private List<String> list = new ArrayList<String>();
try{
JSONArray arr = json.getJSONArray("JSONArray Name");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
list.add(c.getString("Object Name"));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
load_data();