List of usage examples for android.net Uri toString
public abstract String toString();
From source file:com.dycody.android.idealnote.SettingsFragment.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case SPRINGPAD_IMPORT: Uri filesUri = intent.getData(); String path = FileHelper.getPath(getActivity(), filesUri); // An IntentService will be launched to accomplish the import task Intent service = new Intent(getActivity(), DataBackupIntentService.class); service.setAction(DataBackupIntentService.ACTION_DATA_IMPORT_SPRINGPAD); service.putExtra(DataBackupIntentService.EXTRA_SPRINGPAD_BACKUP, path); getActivity().startService(service); break; case RINGTONE_REQUEST_CODE: Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); String notificationSound = uri == null ? null : uri.toString(); prefs.edit().putString("settings_notification_ringtone", notificationSound).apply(); break; default:// w w w .java 2s .c o m Log.e(Constants.TAG, "Wrong element choosen: " + requestCode); } } }
From source file:org.exoplatform.shareextension.service.UploadAction.java
@Override protected boolean doExecute() { String id = uploadInfo.uploadId; String boundary = "----------------------------" + id; String CRLF = "\r\n"; int status = -1; OutputStream output = null;/*from w w w .j a va2s . c o m*/ PrintWriter writer = null; try { // Open a connection to the upload web service StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal") .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id); URL uploadUrl = new URL(stringUrl.toString()); HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection(); uploadReq.setDoOutput(true); uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Pass the session cookies for authentication CookieStore store = ExoConnectionUtils.cookiesStore; if (store != null) { StringBuffer cookieString = new StringBuffer(); for (Cookie cookie : store.getCookies()) { cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "); } uploadReq.addRequestProperty("Cookie", cookieString.toString()); } ExoConnectionUtils.setUserAgent(uploadReq); // Write the form data output = uploadReq.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadInfo.fileToUpload.documentName + "\"").append(CRLF); writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF); writer.append(CRLF).flush(); byte[] buf = new byte[1024]; while (uploadInfo.fileToUpload.documentData.read(buf) != -1) { output.write(buf); } output.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); // Execute the connection and retrieve the status code status = uploadReq.getResponseCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e); } finally { if (uploadInfo != null && uploadInfo.fileToUpload != null && uploadInfo.fileToUpload.documentData != null) try { uploadInfo.fileToUpload.documentData.close(); } catch (IOException e1) { Log.e(LOG_TAG, "Error while closing the upload stream", e1); } if (output != null) try { output.close(); } catch (IOException e) { Log.e(LOG_TAG, "Error while closing the connection", e); } if (writer != null) writer.close(); } if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) { // Exit if the upload went wrong return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName); } status = -1; try { // Prepare the request to save the file in JCR String stringUrl = postInfo.ownerAccount.serverUrl + "/portal" + ExoConstants.DOCUMENT_CONTROL_PATH_REST; Uri moveUri = Uri.parse(stringUrl); moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id) .appendQueryParameter("action", "save") .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace) .appendQueryParameter("driveName", uploadInfo.drive) .appendQueryParameter("currentFolder", uploadInfo.folder) .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build(); HttpGet moveReq = new HttpGet(moveUri.toString()); // Execute the request and retrieve the status code HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq); status = move.getStatusLine().getStatusCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e); } boolean ret = false; if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully"); } else { ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName); } return ret; }
From source file:com.example.jz.mysunshine.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/* w w w . j a va 2 s.co m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) //.appendQueryParameter(API_KEY,API_KEY_VALUE) .build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream; inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.ashokslsk.ashu_sunshine.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }// www . j a va 2 s . co m String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.vrj.udacity.sunshine.app.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/*ww w .j a v a2 s.c o m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are available at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; // Needed in order to get data 10/9/15 Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, OPEN_WEATHER_MAP_API_KEY).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.example.riteden.sunshine.app.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }// w w w. ja va2s .c om String locationQuery = params[0]; Log.v(LOG_TAG, "location = " + locationQuery); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY).build(); URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "check URL:" + url.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.rjfun.cordova.sms.SMSPlugin.java
protected void createContentObserver() { Activity ctx = this.cordova.getActivity(); this.mObserver = new ContentObserver(new Handler()) { public void onChange(boolean selfChange) { this.onChange(selfChange, null); }/* w w w .j a v a 2s . co m*/ public void onChange(boolean selfChange, Uri uri) { ContentResolver resolver = cordova.getActivity().getContentResolver(); Log.d(LOGTAG, ("onChange, selfChange: " + selfChange + ", uri: " + (Object) uri)); int id = -1; String str; if (uri != null && (str = uri.toString()).startsWith(SMS_URI_ALL)) { try { id = Integer.parseInt(str.substring(SMS_URI_ALL.length())); Log.d(LOGTAG, ("sms id: " + id)); } catch (NumberFormatException var6_6) { // empty catch block } } if (id == -1) { uri = Uri.parse(SMS_URI_INBOX); } Cursor cur = resolver.query(uri, null, null, null, "_id desc"); if (cur != null) { int n = cur.getCount(); Log.d(LOGTAG, ("n = " + n)); if (n > 0 && cur.moveToFirst()) { JSONObject json; if ((json = SMSPlugin.this.getJsonFromCursor(cur)) != null) { onSMSArrive(json); } else { Log.d(LOGTAG, "fetch record return null"); } } cur.close(); } } }; ctx.getContentResolver().registerContentObserver(Uri.parse(SMS_URI_INBOX), true, this.mObserver); Log.d(LOGTAG, "sms inbox observer registered"); }
From source file:com.sidviv.sunshine.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/*from ww w.ja v a2s .c o m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "appid"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } // This will only happen if there was an error getting or parsing the forecast. return null; }
From source file:app.com.example.android.sunshine.FetchWeatherTask.java
@Override protected Void doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; }/*ww w.j a v a2 s .co m*/ String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemtping // to parse it. //return null; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } return null; }
From source file:com.aafr.alfonso.sunshine.app.service.SunshineService.java
@Override protected void onHandleIntent(Intent intent) { String locationQuery = intent.getStringExtra(LOCATION_QUERY_EXTRA); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try {/*from w ww . j av a 2 s. c o m*/ // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, locationQuery) .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line); buffer.append("\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. return; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationQuery, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); this.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "Sunshine Service Complete. " + cVVector.size() + " Inserted"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }