説明: OnRespose メソッドでは、froecast.io から受信したデータをログに表示できますが、「response.body().string()」、つまり、forecast.io からのデータを引数 (文字列) としてメソッド getCurrentDetails に渡している場合、メソッドは受信していますnull および JSONObject が null ポインター例外をスローしています。
試行済み: 複数の catch ブロックを介して例外を処理します。
double latitude = -122.423;
double longitude = 37.8267;
String apiKey = "cac63237c81f5312b496ed8cce991b40";
String forecastURL = "https://api.forecast.io/forecast/"+apiKey+"/"+longitude+","+latitude+"";
if(isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastURL).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
try {
Log.v(TAG, response.body().string());
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(response.body().string());
} else {
alertUserAboutProblem();
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught: ", e);
}
catch(JSONException e){
Log.e(TAG,"Exception Caught: ", e);
}
}
});
Log.e(TAG, "Program is still running");
}
else{
Toast.makeText(MainActivity.this,"Network_Unavaliable",Toast.LENGTH_LONG).show();
}
}
private CurrentWeather getCurrentDetails(String string) throws JSONException {
------>>>>> JSONObject jsonObject = new JSONObject(string); 文字列タイムゾーン = jsonObject.getString("タイムゾーン");
JSONObject currently =jsonObject.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setPrecipIntensity(currently.getDouble("percipIntensity"));
currentWeather.setTimeZone(timezone);
Toast.makeText(MainActivity.this,String.valueOf(currently.getLong("time")),Toast.LENGTH_LONG).show();
// Log.d(TAG, String.valueOf(currentWeather.getTime()));
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo coninfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(coninfo!=null && coninfo.isConnected()){
isAvailable = true;
return isAvailable;
}
return false;
}
private void alertUserAboutProblem() {
AlertDialogFragment dialog =new AlertDialogFragment();
dialog.show(getFragmentManager(),TAG);
}
}