Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rjlutz
Last active September 10, 2018 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjlutz/80ac813cdff940111b3dc8134a697f20 to your computer and use it in GitHub Desktop.
Save rjlutz/80ac813cdff940111b3dc8134a697f20 to your computer and use it in GitHub Desktop.
NYT App
package package <<YOUR PACKAGE HERE>>;
import java.util.HashMap;
public class Categories extends HashMap<String, String> {
public Categories() {
put("Home","home");
put("Opinion", "opinion");
put("World", "world");
put("National", "national");
put("Politics", "politics");
put("Upshot", "upshot");
put("NY Region", "nyregion");
put("Business", "business");
put("Technology", "technology");
put("Science", "science");
put("Health", "health");
put("Sports", "sports");
put("Arts", "arts");
put("Books", "books");
put("Movies", "movies");
put("Theater", "theater");
put("Sunday Review", "sundayreview");
put("Fashion", "fashion");
put("Style Magazine", "tmagazine");
put("Food", "food");
put("Travel", "travel");
put("Magazine", "magazine");
put("Real Estate", "realestate");
put("Automobiles", "automobiles");
put("Obituaries", "obituaries");
put("Insider", "insider");
}
}
// Note this class was used early on in the walkthroughs. It was subsequently modified and implemented as an anonymous inner class.
package package <<YOUR PACKAGE HERE>>;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
// we will convert this later to be nested anonymous class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class NYTTask extends AsyncTask<String, Void, String> {
private static final String TAG = "NYTApp";
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
* <p>
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param objects The parameters of the task.
* @return A result, defined by the subclass of this task.
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@Override
protected String doInBackground(String... categories) {
Scanner scanner = null;
HttpURLConnection conn = null;
StringBuilder jsonSB;
String category = categories[0];
try {
URL url = new URL("https://api.nytimes.com/svc/topstories/v2/" + category + ".json?api-key=2c7894bbed624037a0757b46326ccae5");
jsonSB = new StringBuilder();
conn = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(conn.getInputStream());
scanner = new Scanner(in);
// process entire stream
while (scanner.hasNext())
jsonSB.append(scanner.nextLine());
String msg = "(" + conn.getResponseCode() + "):" + conn.getResponseMessage();
Log.v(TAG, "Response" + msg);
// TODO handle non-200 errors here
} catch (IOException e) {
Log.e(TAG, e.getMessage());
return "ERROR";
} finally {
if (scanner != null) scanner.close();
if (conn != null) conn.disconnect();
}
return jsonSB.toString();
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
* <p>
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param s The result of the operation computed by {@link #doInBackground}.
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v(TAG, "json response =" + result);
}
}
service link: https://developer.nytimes.com/
service documentation: https://developer.nytimes.com/top_stories_v2.json#/Documentation/GET/%7Bsection%7D.%7Bformat%7D
(all category names can be found here)
add the permission that we need in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
put this at the same level as application element in the manifest file
package <<YOUR PACKAGE HERE>>;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Stories extends ArrayList<Stories.Story> {
private String json;
private ArrayList<String> titles;
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
@Override
public void clear() {
super.clear();
titles.clear();
}
private Stories() {
super();
titles = new ArrayList<String>();
}
public Stories(String json) {
this();
this.json=json;
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject jo = (JSONObject) results.get(i);
String title = jo.getString("title");
String url = jo.getString("url");
this.add(new Story(title, url));
}
} catch (JSONException e) {
e.printStackTrace();
}
for (Story s : this) // set up an array, so that listview can take advantage of this
titles.add(s.getTitle()); // need to be sure this and titles stay in sync
}
public String getJson() {
return json;
}
public void replace(Stories stories) {
clear();
titles.clear();
addAll(stories);
for (Story s : this)
titles.add(s.getTitle());
}
public ArrayList<String> getTitles() {
return titles;
}
protected class Story {
String title;
String url;
public Story(String title, String url) {
this.title = title;
this.url = url;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment