Cómo leer datos json de URL en Android
Tengo algunos problemas con el siguiente código. Estoy tratando de leer la siguiente URL de Reddit
https://www.reddit.com/r/earthporn/.json?after=
Aquí está el código que no se está ejecutando correctamente.
public static String readContents(String url){
try{
InputStream input= new URL(url).openStream();
Reader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
String line, str;
str = "";
while ((line=in.readLine()) != null) {
str += line;
System.out.println(line);
}
return str;
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
}
Y aquí es donde lo llamo
List<Post> fetchPosts(){
String raw=RemoteData.readContents(url);
List<Post> list=new ArrayList<Post>();
try{
JSONObject data=new JSONObject(raw).getJSONObject("data");
JSONArray children=data.getJSONArray("children");
//Using this property we can fetch the next set of
//posts from the same subreddit
after=data.getString("after");
for(int i=0;i<children.length();i++){
JSONObject cur=children.getJSONObject(i)
.getJSONObject("data");
Post p=new Post();
p.title=cur.optString("title");
p.url=cur.optString("url");
p.numComments=cur.optInt("num_comments");
p.points=cur.optInt("score");
p.author=cur.optString("author");
p.subreddit=cur.optString("subreddit");
p.permalink=cur.optString("permalink");
p.domain=cur.optString("domain");
p.id=cur.optString("id");
p.thumbnail=cur.optString("thumbnail");
if(p.title!=null)
list.add(p);
}
}catch(Exception e){
Log.e("fetchPosts()",e.toString());
}
return list;
}
Al depurar obtengo los siguientes resultados: Raw se deja vacío.
¿Alguien tiene alguna idea de por qué esto no está leyendo nada? Espero haber incluido suficiente código para que tenga sentido. Si necesita más, hágamelo saber.