/** * Parses the raw JSON resource specified by {@code metadataResId}. The JSON is expected to be in * this format: { "apiVersion": <version number (string)>, "densities": [ { "density": <density * (int)>, "width": <unscaled sprite width (int)>, "height": <unscaled sprite height (int)>, * "rectangles": [ [<list of ints for frame 0>], [<list of ints for frame 1>], ...... ] }, { * "density": <density (int)>, "width": <unscaled sprite width (int)>, "height": <unscaled sprite * height (int)>, "rectangles": [ [<list of ints for frame 0>], [<list of ints for frame 1>], * ...... ] }, ...... ] } * * @param metadataResId The id of the raw resource containing JSON to parse. * @param bitmapDensity The density of the unscaled {@link Bitmap} that was loaded. * @param resources A {@link Resources} instance to load assets from. * @throws IOException */ @VisibleForTesting void parseMetadata(int metadataResId, int bitmapDensity, Resources resources) throws IOException { InputStream inputStream = resources.openRawResource(metadataResId); JsonReader reader = new JsonReader(new InputStreamReader(inputStream)); try { reader.beginObject(); // Start reading top-level object. // Check apiVersion. String name = reader.nextName(); assert name.equals("apiVersion"); String version = reader.nextString(); assert version.equals("1.0"); // Parse array of densities. name = reader.nextName(); assert name.equals("densities"); reader.beginArray(); // Start reading array of densities. while (reader.hasNext()) { reader.beginObject(); // Start reading object for this density. boolean foundDensity = parseMetadataForDensity(reader, bitmapDensity); reader.endObject(); // Stop reading object for this density. if (foundDensity) break; } } finally { reader.close(); inputStream.close(); } }
private void refreshEarthquakes() { // Get the JSON URL url; try { String quakeFeed = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"; url = new URL(quakeFeed); URLConnection connection; connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { // Clear the old earthquakes earthquakes.clear(); readEarthquakes(reader); } finally { reader.close(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } }
private static String[] getParametersFromIntent(Intent intent) { if (intent == null) { return null; } String[] parameters = intent.getStringArrayExtra("parameters"); if (parameters != null) { return parameters; } String encodedParameters = intent.getStringExtra("encodedParameters"); if (encodedParameters != null) { JsonReader reader = new JsonReader(new StringReader(encodedParameters)); List<String> parametersList = new ArrayList<String>(); try { reader.beginArray(); while (reader.hasNext()) { parametersList.add(reader.nextString()); } reader.endArray(); reader.close(); return parametersList.toArray(new String[parametersList.size()]); } catch (IOException e) { Log.w(TAG, e.getMessage(), e); } } return null; }
@Override public void onMessage(int instanceId, String message) { StringReader contents = new StringReader(message); JsonReader reader = new JsonReader(contents); int requestId = -1; String cmd = null; String url = null; try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(TAG_CMD)) { cmd = reader.nextString(); } else if (name.equals(TAG_REQUEST_ID)) { requestId = reader.nextInt(); } else if (name.equals("url")) { url = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); reader.close(); if (cmd != null && cmd.equals(CMD_REQUEST_SHOW) && requestId >= 0) { handleRequestShow(instanceId, url, requestId); } } catch (IOException e) { Log.d(TAG, "Error: " + e); } }
private void findHourlyWeather(final ForecastReport forecastReport, final boolean isSendReponse) { HttpURLConnection urlConnection = null; try { LocationVO locationVO = forecastReport.locationVO; URL url = new URL( String.format( UtilServiceAPIs.API_WUNDERGROUND, locationVO.getCountryCode().equals("US") ? locationVO.getStateCode() : locationVO.getCountryCode(), locationVO.getPlace())); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); parseHourlyWeather(reader, forecastReport, isSendReponse); reader.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } }
private List<SnippetListItem> readJsonStream(InputStream in) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { return readRecommendationsArray(reader); } finally { reader.close(); } }
private void readJsonStream(InputStream in) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { readMessagesArray(reader); } finally { reader.close(); } }
public ArrayList parse(InputStream in) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { return readMessagesArray(reader); } finally { reader.close(); } }
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public static final List<Place> GetPlaces(String source) throws IOException { ArrayList<Place> places = new ArrayList<Place>(); JsonReader reader = null; try { reader = new JsonReader(new StringReader(source)); reader.beginArray(); while (reader.hasNext()) { String Code = null; String Name = null; String HubCode = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("Code")) { Code = reader.nextString(); } else if (name.equals("Name")) { Name = reader.nextString(); } else if (name.equals("HubCode")) { HubCode = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); Place place = new Place(); place.Code = Code; place.Name = Name; place.HubCode = HubCode; places.add(place); } reader.endArray(); } finally { if (reader != null) reader.close(); } return places; }
public static void read() { String filename = String.format(getRootDir() + "/conf.json"); try { FileInputStream fin = new FileInputStream(filename); JsonReader reader = new JsonReader(new InputStreamReader(fin, "UTF-8")); reader.beginObject(); // write common information while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("LENGTH_UNIT")) { LENGTH_UNIT = reader.nextString(); } else if (name.equals("MAP_TYPE")) { MAP_TYPE = reader.nextString(); } else if (name.equals("SPEED_TYPE")) { SPEED_TYPE = reader.nextString(); } else if (name.equals("MIN_DISTANCE")) { MIN_DISTANCE = reader.nextInt(); } else if (name.equals("INTERVAL_LOCATION")) { INTERVAL_LOCATION = reader.nextInt(); } else if (name.equals("INTERVAL_LOCATION_FAST")) { INTERVAL_LOCATION_FAST = reader.nextInt(); } else if (name.equals("LOCATION_ACCURACY")) { LOCATION_ACCURACY = reader.nextInt(); } else if (name.equals("SPEED_AVG")) { SPEED_AVG = reader.nextInt(); } else if (name.equals("GPS_ONLY")) { GPS_ONLY = reader.nextBoolean(); } else if (name.equals("GPS_ONLY")) { ACCELERATE_FACTOR = (float) reader.nextDouble(); } else { reader.skipValue(); } } reader.endObject(); reader.close(); fin.close(); } catch (Exception e) { Log.i(TAG, "read conf from file fail."); } }
private void findDailyWeather(final ForecastReport forecastReport, final boolean isSendReponse) { HttpURLConnection urlConnection = null; try { URL url = new URL( UtilServiceAPIs.API_FORECAST_YQL_URL.replace( "replace_place", URLEncoder.encode(forecastReport.place, "UTF-8"))); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); parseDailyWeather(reader, forecastReport, isSendReponse); reader.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } }
public static final List<NomenclatureItem> GetNomenclatureItems(String source) throws IOException { ArrayList<NomenclatureItem> items = new ArrayList<NomenclatureItem>(); JsonReader reader = null; try { reader = new JsonReader(new StringReader(source)); reader.beginArray(); while (reader.hasNext()) { String Code = null; String Name = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("Code")) { Code = reader.nextString(); } else if (name.equals("Name")) { Name = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); NomenclatureItem item = new NomenclatureItem(); item.Code = Code; item.Name = Name; items.add(item); } reader.endArray(); } finally { if (reader != null) reader.close(); } return items; }
private List<NameValuePair> ParseJsonFlatListToListNvp(ByteArrayOutputStream out) throws IOException { List<NameValuePair> listNvpResult = null; JsonReader reader = new JsonReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()), "UTF-8")); try { reader.beginObject(); while (reader.hasNext()) { if (listNvpResult == null) { listNvpResult = new LinkedList<NameValuePair>(); } String name = reader.nextName(); String text = reader.nextString(); Log.d("trial", "before adding " + name + ":" + text); listNvpResult.add(new BasicNameValuePair(name, text)); } reader.endObject(); } finally { reader.close(); } return listNvpResult; }
public static Filter.FilterList loadFilter() { Filter.FilterList list = new Filter.FilterList(); list.mainFilter = null; try { InputStream in = GGApp.GG_APP.openFileInput("ggfilter"); JsonReader reader = new JsonReader(new InputStreamReader(in)); reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); Filter f = new Filter(); if (list.mainFilter == null) list.mainFilter = f; else list.add(f); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("type")) f.type = Filter.FilterType.valueOf(reader.nextString()); else if (name.equals("filter")) f.filter = reader.nextString(); else reader.skipValue(); } reader.endObject(); } reader.endArray(); reader.close(); } catch (Exception e) { list.clear(); } if (list.mainFilter == null) { Filter f = new Filter(); list.mainFilter = f; f.type = Filter.FilterType.CLASS; f.filter = ""; } return list; }
protected ArrayList<QuestionResponseModel> downloadURL(String urlString) throws IOException { InputStream is = null; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); /*milliseconds*/ connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); int response = connection.getResponseCode(); // If 200, continue if (response == 200) { is = connection.getInputStream(); JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8")); try { qrArray = new ArrayList<QuestionResponseModel>(); reader.beginArray(); while (reader.hasNext()) { String quest = null; String answ = null; String user = null; String img = null; reader.beginObject(); while (reader.hasNext()) { String currentkey = reader.nextName(); // Log.d("error",currentkey); if (currentkey.equals("question")) { quest = reader.nextString(); } else if (currentkey.equals("answer")) { answ = reader.nextString(); } else if (currentkey.equals("username")) { user = reader.nextString(); } else if (currentkey.equals("imageURL")) { img = reader.nextString(); // ImageView imgView = new ImageView; // new ImageDownloaderTask().execute(img); } else { reader.skipValue(); } } // new DownloadFilesTask().execute(stringUrl); reader.endObject(); qrArray.add(new QuestionResponseModel(quest, answ, img, user)); } reader.endArray(); reader.close(); return qrArray; } catch (IOException e) { // exception } } } finally { if (is != null) { is.close(); // downloadCompleted(); } } return null; }
public static final List<Variant> GetVariants(String source) throws IOException { ArrayList<Variant> variants = new ArrayList<Variant>(); JsonReader reader = null; try { reader = new JsonReader(new StringReader(source)); reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); Variant variant = new Variant(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("Samples")) { reader.beginArray(); while (reader.hasNext()) { Sample sample = new Sample(); reader.beginObject(); String sName = reader.nextName(); if (sName.equals("SampleType")) { sample.SampleType = reader.nextString(); } else if (sName.equals("ContainerType")) { sample.ContainerType = reader.nextString(); } else if (sName.equals("Preparation")) { sample.Preparation = reader.nextString(); } else if (sName.equals("Protocol")) { sample.Protocol = reader.nextString(); } else if (sName.equals("MaxVolume")) { sample.MaxVolume = reader.nextInt(); } else if (sName.equals("CurrentVolume")) { sample.CurrentVolume = reader.nextInt(); } else if (sName.equals("SampleGroup")) { sample.SampleGroup = reader.nextString(); } else if (sName.equals("DeadVolume")) { sample.DeadVolume = reader.nextInt(); } else if (sName.equals("Manipulations")) { reader.beginArray(); while (reader.hasNext()) { Manipulation manipulation = new Manipulation(); reader.beginObject(); String mName = reader.nextName(); if (mName.equals("Code")) { manipulation.Code = reader.nextString(); } else if (mName.equals("Name")) { manipulation.Name = reader.nextName(); } else if (mName.equals("Preparation")) { manipulation.Preparation = reader.nextString(); } else { reader.skipValue(); } reader.endObject(); sample.Manipulations.add(manipulation); } reader.endArray(); } else { reader.skipValue(); } reader.endObject(); variant.Samples.add(sample); } reader.endArray(); } else if (name.equals("RequiredFields")) { reader.beginArray(); while (reader.hasNext()) { RequiredField reqField = new RequiredField(); reader.beginObject(); while (reader.hasNext()) { String rfName = reader.nextName(); if (rfName.equals("Code")) { reqField.Code = reader.nextString(); } else if (rfName.equals("Name")) { reqField.Name = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); variant.RequiredFields.add(reqField); } reader.endArray(); } else { reader.skipValue(); } } reader.endObject(); variants.add(variant); } reader.endArray(); } finally { if (reader != null) reader.close(); } return variants; }
@Override protected Boolean doInBackground(String... params) { // Construct GET request String urlStr = "https://api.nutritionix.com/v1_1/item?id=" + id + "&appId=" + API_ID + "&appKey=" + API_KEY; System.out.println(urlStr); URL url; try { url = new URL(urlStr); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); return false; } HttpURLConnection urlConnection = null; InputStream in = null; // Make GET request and save input try { urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() != 200) { throw new Exception(urlConnection.getErrorStream().toString()); } in = new BufferedInputStream(urlConnection.getInputStream()); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); if (urlConnection != null) { urlConnection.disconnect(); } return false; } JsonReader reader = null; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); food = readFoodInfo(reader); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); food = null; // just to be safe } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); } } } urlConnection.disconnect(); return true; }
@Override protected Boolean doInBackground(String... params) { // Format search term(s) searchTerm = searchTerm.replace(" ", "%20"); // Construct GET request String urlStr = "https://api.nutritionix.com/v1_1/search/" + searchTerm + "?results=0%3A50&fields=item_name%2Citem_id%2Cbrand_name&appId=" + API_ID + "&appKey=" + API_KEY; // System.out.println(urlStr); URL url; try { url = new URL(urlStr); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); return false; } HttpURLConnection urlConnection = null; InputStream in = null; // Make GET request and save input try { urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection.getResponseCode() != 200) { throw new Exception(urlConnection.getErrorStream().toString()); } in = new BufferedInputStream(urlConnection.getInputStream()); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); if (urlConnection != null) { urlConnection.disconnect(); } return false; } JsonReader reader = null; results = null; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); results = readResults(reader); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); displayToast("Error: Please try again.", act); } } } urlConnection.disconnect(); if (results.count == 0) { displayToast("No results found.", act); } else { displayToast("Found " + results.count + " matches.", act); act.runOnUiThread( new Runnable() { public void run() { ListView lv = (ListView) act.findViewById(R.id.resultList); ArrayAdapter<FoodResult> arrayAdapter = new ArrayAdapter<FoodResult>( act.getApplicationContext(), R.layout.list_layout, R.id.foodListText, results.list); lv.setAdapter(arrayAdapter); // set up happens when you click a list item lv.setOnItemClickListener( new AdapterView.OnItemClickListener() { public void onItemClick( AdapterView<?> parent, View view, int position, long id) { FoodResult selectedFood = results.list.get(position); // query database for nutrition info in async task // will also display confirmation prompt with info new NutritionInfoQuery(act, selectedFood.id).execute(); } }); } }); } return true; }