在我的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);
});
}
答案 0 :(得分:1)
我面临一个错误,整个列表显示在一个列表项中。但是 我收到4件物品
在load_data();
内调用for-loop
,用于从JSONArray
ArrayList
获取数据
将load_data();
移到for-loop
之外,以在ListView的单独行中显示每个项目
答案 1 :(得分:0)
按照:
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();
答案 2 :(得分:0)
用空列表设置适配器一次。
结束后解析Jsonarray并添加数据,adapter.notifyDataSetChanged();
答案 3 :(得分:0)
替换它:
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();