I want to use the open weather api to display the weather in an app. I think Android Studio is not able to connect to the url. This is my code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("JSON", "onCreate");
DownloadWeatherData asyncTask = new DownloadWeatherData();
asyncTask.execute("http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=[APIkey]");
}
private class DownloadWeatherData extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
Log.d("JSON", "doInBackground");
try{
Log.d("JSON", strings[0]);
URL REST = new URL(strings[0]);
URLConnection connect = REST.openConnection();
Log.d("JSON", connect.toString());
InputStream stream = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JSONObject json = new JSONObject(jsonString);
Log.d("JSON", jsonString);
}catch(IOException e){
e.printStackTrace();
Log.d("JSON", "IO EXCEPTION");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
The logcat keeps going into the IO EXCEPTION from the catch block.
I tried adding the following segment of code in the AndriodManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
This did not work. How can I fix this issue?