Dear users of this forum.
I started learning API calls and tried it with some code I found on the old forum.
The goal is i want to use the openweather API to check if it is raining, now the API works and the URL, but It gives me a NullPointerException in the code? the API call doesn’t give me .txt document i put in the map of my code just this:
{“coord”:{“lon”:6.79,“lat”:52.26},“weather”:[{“id”:804,“main”:“Clouds”,“description”:“overcast clouds”,“icon”:“04d”}],“base”:“stations”,“main”:{“temp”:275.93,“feels_like”:272.63,“temp_min”:274.82,“temp_max”:276.48,“pressure”:1016,“humidity”:92},“visibility”:10000,“wind”:{“speed”:2.24,“deg”:80,“gust”:7.6},“clouds”:{“all”:99},“dt”:1609851652,“sys”:{“type”:3,“id”:2010748,“country”:“NL”,“sunrise”:1609832475,“sunset”:1609860895},“timezone”:3600,“id”:0,“name”:“Hengelo”,“cod”:200}
I use this code for my code:
void loadData() {
JSONObject json = loadJSONObject(url+"&APPID="+API_Key);
JSONObject windData = json.getJSONObject(“wind”);
float speed = windData.getFloat(“speed”);
println (speed);
}
I want to add that i just made a simple LoadData call in a different Class nothing special.
When making this call, make sure you include http://
before any url that you might include.
If you use something like this:
String url = "api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey;
JSONObject json = loadJSONObject(url);
You’re going to get a NullPointerException
:
The file "api.openweathermap.org/data/2.5/weather?q={city}&appid={key}" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
NullPointerException
Make sure you include http:// before your url:
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey;
JSONObject json = loadJSONObject(url);
For example, a complete program might look like this:
String city = "{your city}";
String apiKey = "{your api key}";
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey;
JSONObject json = loadJSONObject(url);
JSONObject windData = json.getJSONObject("wind");
float speed = windData.getFloat("speed");
int direction = windData.getInt("deg");
println("Wind Speed: " + speed);
println("Wind Direction: " + direction + "°");
Gives:
>> Wind Speed: 2.63
>> Wind Direction: 291°
tl;dr Use http://
before your url