Reputation: 113
I have a problem with json object in android application from php script. On Log.i(finalJson,"json object") i see i logcat that json async task return only first element from list. I test my php in POSTMAN and it looks like:
[
{
"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 ;
}
Thank's for any help!
Upvotes: 0
Views: 404
Reputation: 2170
You are returning the list just after it iterates once. Try this :
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;
Hope this helps.
Upvotes: 1