Currently having a problem with an android app where I think the thread is trying to use an object before it's properly instantiated.
Here's the constructor for my class:
String name;
String price;
String percentChange;
String peRatio;
private String ticker;
private JSONObject stockQuote;
public Stock(String ticker) {
this.ticker = ticker;
// Build query and URL.
String url = "http://query.yahooapis.com/v1/public/yql?q=";
String query = "select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(\"" +
ticker +
"\")&env=store://datatables.org/alltableswithkeys&format=json";
url += query;
stockQuote = fetch(url);
name = get("symbol");
price = get("Ask");
}
Here's the fetch() function being used to retrieve a JSONObject from a HTTP response:
private JSONObject fetch(String myurl) throws IOException {
InputStream is = null;
String contentAsString = "";
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
JSONObject queryResult = null;
try {
JSONObject json = new JSONObject(contentAsString);
queryResult = json.getJSONObject("query").getJSONObject("results").getJSONObject("quote");
} catch (JSONException e) {
System.err.println("Failed to decode JSON");
}
return queryResult;
}
and finally here's the get() method, used to retrieve a string from the JSONObject:
public String get(String key) {
String value = null;
try {
value = stockQuote.getString(key);
} catch (JSONException e) {
System.err.println("Couldn't find " + key);
}
return value;
}
A NullPointerException gets thrown by "value = stockQuote.getString(key);" - sometimes, but not everytime. I assume this is because it's trying to access the stockQuote before the HTML response has been parsed?
I'm guessing there's an obvious solution to this, but I haven't encountered this problem before. Any ideas?