我的AsyncTask类有问题。我的问题是我的类只显示三个值“name”json数组,它应该显示5或更多。有谁知道错误吗?
我的json数组:
{"productos":[{"id_oferta":"197","total":"3","nombre":"nombrE","precio":"4.30-20.50","imagen":"http:\/\/www.ofertapp.es\/images\/app\/comercios\/4.jpg","descripcion":"Breve descripci\u00f3n del negocio. El cual, se ofrece varios servicios como por ejemplo: \u00bfA qu\u00e9 p\u00fablico va dirigido? \u00bfCuantas unidades contiene?\u00bf D\u00f3nde est\u00e1 localizado? Por otro lado, decir que la oferta s\u00f3lo estar\u00e1 disponible en los meses Noviembre y Diciembre. Para poder disfrutar de esta oferta simplemente dir\u00edjase a nuestra tienda y te daremos instrucciones. Esperamos verte por aqu\u00ed y que disfrutes s\u00f3lo, con tu pareja o amigos.","direccion":"direccion","telefono":"telefono","latitud":"37.119571803396475","longitud":"-5.451107025146484","horariomanana":"9:40","horariotarde":"20:00","email":"email@email.com","id_cat":"1","id_usuario":"10","disp":"1","actions":[]},{"id_oferta":"199","total":null,"nombre":"migato","precio":"3","imagen":"http:\/\/www.ofertapp.es\/images\/app\/comercios\/gatp.jpg","descripcion":"424","direccion":"424","telefono":"42","latitud":"37.119330660753164","longitud":"-5.449090003967285","horariomanana":"7:50 - 20:","horariotarde":"21:00","email":"asd@ads.com","id_cat":"1","id_usuario":"7","disp":"1","actions":[]},{"id_oferta":"200","total":"2","nombre":"nombre2","precio":"4.30","imagen":"http:\/\/www.ofertapp.es\/images\/app\/comercios\/5.jpg","descripcion":"desc","direccion":"direccion","telefono":"telefono","latitud":"37.119571803396475","longitud":"-5.451107025146484","horariomanana":"","horariotarde":"","email":"","id_cat":"1","id_usuario":"7","disp":"1","actions":[]},{"id_oferta":"201","total":"2","nombre":"Nombre43","precio":"4.30","imagen":"http:\/\/www.ofertapp.es\/images\/app\/comercios\/6.jpg","descripcion":"desc","direccion":"direccion","telefono":"telefono","latitud":"37.119571803396475","longitud":"-5.451107025146484","horariomanana":"","horariotarde":"","email":"","id_cat":"1","id_usuario":"7","disp":"1","actions":[]},{"id_oferta":"203","total":null,"nombre":"Probando","precio":"3.30-20.50","imagen":"http:\/\/www.ofertapp.es\/images\/app\/comercios\/35.jpg","descripcion":"desc","direccion":"direccion","telefono":"telefono","latitud":"37.119571803396475","longitud":"-5.451107025146484","horariomanana":"9:40","horariotarde":"20:00","email":"email@email.com","id_cat":"1","id_usuario":"7","disp":"1","actions":[]}],"errorCode":0,"errorString":"Todo correcto"}
MainActivity.class
public class MainActivity extends Activity {
private ProgressDialog pDialog;
private static String url = "http://www.url.domain";
JSONArray user = null;
private static final String TAG_USER = "productos";
private static final String TAG_ID = "nombre";
private static final String imagen = "imagen";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainlayout);
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Obteniendo datos ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONfromURL(url);
Log.e("count -> ", ""+json.length());
//SHOW 5 items
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
for (int i = 0; i < json.length(); i++) {
JSONObject c = user.getJSONObject(i);
String id = c.getString(TAG_ID);
String image = c.getString(imagen);
Log.e("count...",""+id);
//SHOW 3 ITEMS, WHY?
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.class
公共类JSONParser {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient() ;
HttpPost httppost = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000; //3Segs == 3000
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 15000; // 5000 == 5 segs
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httppost);
/* CODE RESPONSE */
int responseCode = response.getStatusLine().getStatusCode();
//Log.e("responseCode","" + responseCode);
String ss = response.getStatusLine().toString();
//Log.e("responseCode","" + ss);
if (responseCode == 200) {
HttpEntity entity = response.getEntity();
is = entity.getContent();
} else {
Log.e("responseCode","");
}
}catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
} 谁能帮我?此致!
答案 0 :(得分:0)
确实存在一个错误,这解释了为什么当你这样做时你会得到3:
user = json.getJSONArray(TAG_USER);
for (int i = 0; i < json.length(); i++) { // should be user.length() !
...
}
您应该迭代user
,它是用户的JSONArray,实际上包含5个条目。执行json.length()
时,实际上是在计算响应有多少个键/值条目,即3(productos,errorCode,errorString)。
然而(!)这并不能解释为什么你在这里得到5:
JSONObject json = jParser.getJSONfromURL(url);
Log.e("count -> ", ""+json.length());
因为它似乎是相同的响应JSONObject,而不是user
数组...
希望这可以让你在正确的轨道上解决问题。