I want to get current/historical bitcoin price by using JSON..
However, the code shows a following error
Exception in thread "main" java.lang.NullPointerException at RwithJlab.Basic.main(Basic.java:19)
---------------------------------code---------------------------------
package RwithJlab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Basic
{
public static void main(String[] args) throws MalformedURLException, IOException, JSONException
{
JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
JSONArray data_array = data.getJSONArray("values");
for (int i = 0; i < ((CharSequence) data_array).length(); i++)
{
JSONObject price_point = (JSONObject) data_array.get(i);
// Unix time
int x = price_point.getInt("1364062505");
// Bitcoin price at that time
double y = price_point.getDouble("y");
// Do something with x and y.
System.out.println(x);
}
}
public static JSONObject getJSONfromURL(String URL) throws JSONException
{
try
{
URLConnection uc;
URL url = new URL(URL);
uc = url.openConnection();
uc.setConnectTimeout(10000);
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
uc.connect();
BufferedReader rd = new BufferedReader(
new InputStreamReader(uc.getInputStream(),
Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char)cp);
}
String jsonText = (sb.toString());
return new JSONObject(jsonText.toString());
} catch (IOException ex)
{
return null;
}
}
}
please help
You should at least log Exceptions when you catch them, otherwise you are out of clue when that exception occurs.
In your case you are catching an IOException
and returning null
. This results in a NullPointerException
later, but you cannot see the root cause.
Log that IOException
(at least call ex.printStackTrace()
) and you will see the real reason.