Este ejercicio sencillo no funciona en Android 7.0 y en versiones anteriores de Android si funciona, ¿por qué puede ser?`
@Override
protected String doInBackground(String... params) {
String cadena = params[0];
URL url = null;//
String devuelve = "";
try {
url = new URL(cadena);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
"(Linux: Android 7.0; es-ES) Ejemplo HTTP");
int respuesta = connection.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject respuestaJSON = new JSONObject(result.toString());
String resultJSON = respuestaJSON.getString("estado");
if (resultJSON == "1") {
JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumnos");
for (int i = 0; i < alumnosJSON.length(); i++) {
devuelve = devuelve + alumnosJSON.getJSONObject(i).getString("id_alumno") + " " +
alumnosJSON.getJSONObject(i).getString("nombre") + " " +
alumnosJSON.getJSONObject(i).getString("direccion") + "\n";
}
} else if (resultJSON == "2") {
devuelve = "No hay resultados";
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return devuelve;
}`
En version 7.0, cuando compruebo que resultJSON == "1" me saca del if como si no fuera = 1 y sí lo es.
Cuando pruebo con otra version de Android o quito el if, funciona correctamente
equals
, pero veo otra cosa extraña en tu código:} else if (resultJSON == "2") {
y luego no hay máselse
para cerrar. Debería ser:if () {...} else if () { ... } else { ... }