Skip to content

Instantly share code, notes, and snippets.

@sidward35
Created July 26, 2017 22:52
Show Gist options
  • Select an option

  • Save sidward35/805dd0c0112ccad2f8bcf213e4070cb4 to your computer and use it in GitHub Desktop.

Select an option

Save sidward35/805dd0c0112ccad2f8bcf213e4070cb4 to your computer and use it in GitHub Desktop.
Android JSON Parser
package com.sid.nasaapod;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject json = null;
static String output = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
URL _url;
HttpURLConnection urlConnection;
try {
_url = new URL(url);
urlConnection = (HttpURLConnection) _url.openConnection();
}
catch (MalformedURLException e) {
Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
return null;
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
try {
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder(is.available());
String line;
while ((line = reader.readLine()) != null) {
total.append(line).append('\n');
}
output = total.toString();
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
finally{
urlConnection.disconnect();
}
try {
json = new JSONObject(output);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return json;
}
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.getJSONFromUrl("https://api.nasa.gov/planetary/apod?api_key=uZvWdb4HL99nymXFPQlFfUBVZSuumS0MvqlVUHXs&date="+date, null);
String desc="No description.";
try {
desc = jsonObject.get("explanation").toString();
} catch (JSONException e) {e.printStackTrace();}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment