【发布时间】:2017-07-09 17:58:21
【问题描述】:
我在 php 脚本的 android 应用程序中遇到了 json 对象的问题。在 Log.i(finalJson,"json object") 我看到我 logcat json 异步任务只返回列表中的第一个元素。我在 POSTMAN 中测试我的 php,它看起来像:
[
{
"ID": "1",
"Description": "Plisani meda",
"Price": "1000",
"Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
},
{
"ID": "2",
"Description": "poni",
"Price": "2000",
"Image": "http://www.volimsvojdom.rs/wf-proizvodiPics/47188/plisana-igracka-mis-u-pantalonama-LB80322.jpg"
}
]
public class JSONTask extends AsyncTask<String,String,List<Prozivod>>
{
@Override
protected List<Prozivod> doInBackground(String... params) {
HttpURLConnection connection=null;
BufferedReader reader=null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer=new StringBuffer();
String line="";
while((line=reader.readLine())!=null)
{
buffer.append(line);
}
String finalJson=buffer.toString();
JSONArray jsonArray=new JSONArray(finalJson);
Log.i(finalJson,"json object");
List<Products> listOfItems=new ArrayList<>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject itemJson=jsonArray.getJSONObject(i);
Products p=new Products();
p.setProizvodID(proizvodJson.getInt("ID"));
p.setCena(proizvodJson.getInt("Price"));
p.setOpis(proizvodJson.getString("Description"));
p.setSlika(proizvodJson.getString("Image"));
listOfItems.add(p);
return listOfItems;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}finally {
if(connection!=null){connection.disconnect();}
}
try{if(reader!=null){reader.close();}}
catch (IOException e) {
e.printStackTrace();
}
return null ;
}
感谢您的帮助!
【问题讨论】:
-
您正在从
for循环内部返回。这就是为什么它在一次迭代后终止。您可能希望在 for 循环之后返回列表 -
返回列表项;将此行移出 for 循环
-
建议:使用 Retrofit 而不是 AsyncTask
-
谢谢,我现在看到我将返回列表放入循环中。再次感谢!
标签: android json android-asynctask