List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:com.swisscom.android.sunshine.data.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from w ww . ja va2 s . c o m*/ */ private Void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "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"; 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and 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(WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); } return null; }
From source file:cn.code.notes.gtask.remote.GTaskManager.java
private void initGTaskList() throws NetworkFailureException { if (mCancelled) return;//from w w w. ja v a 2 s. c om GTaskClient client = GTaskClient.getInstance(); try { JSONArray jsTaskLists = client.getTaskLists(); // init meta list first mMetaList = null; for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { mMetaList = new TaskList(); mMetaList.setContentByRemoteJSON(object); // load meta data JSONArray jsMetas = client.getTaskList(gid); for (int j = 0; j < jsMetas.length(); j++) { object = (JSONObject) jsMetas.getJSONObject(j); MetaData metaData = new MetaData(); metaData.setContentByRemoteJSON(object); if (metaData.isWorthSaving()) { mMetaList.addChildTask(metaData); if (metaData.getGid() != null) { mMetaHashMap.put(metaData.getRelatedGid(), metaData); } } } } } // create meta list if not existed if (mMetaList == null) { mMetaList = new TaskList(); mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META); GTaskClient.getInstance().createTaskList(mMetaList); } // init task list for (int i = 0; i < jsTaskLists.length(); i++) { JSONObject object = jsTaskLists.getJSONObject(i); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { TaskList tasklist = new TaskList(); tasklist.setContentByRemoteJSON(object); mGTaskListHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist); // load tasks JSONArray jsTasks = client.getTaskList(gid); for (int j = 0; j < jsTasks.length(); j++) { object = (JSONObject) jsTasks.getJSONObject(j); gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); Task task = new Task(); task.setContentByRemoteJSON(object); if (task.isWorthSaving()) { task.setMetaInfo(mMetaHashMap.get(gid)); tasklist.addChildTask(task); mGTaskHashMap.put(gid, task); } } } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); throw new ActionFailureException("initGTaskList: handing JSONObject failed"); } }
From source file:cn.code.notes.gtask.remote.GTaskManager.java
private void addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return;//from w w w . j a va 2 s . c om } SqlNote sqlNote; if (node instanceof TaskList) { if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); } else if (node.getName() .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); } else { sqlNote = new SqlNote(mContext); sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setParentId(Notes.ID_ROOT_FOLDER); } } else { sqlNote = new SqlNote(mContext); JSONObject js = node.getLocalJSONFromContent(); try { if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); if (note.has(NoteColumns.ID)) { long id = note.getLong(NoteColumns.ID); if (DataUtils.existInNoteDatabase(mContentResolver, id)) { // the id is not available, have to create a new one note.remove(NoteColumns.ID); } } } if (js.has(GTaskStringUtils.META_HEAD_DATA)) { JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (data.has(DataColumns.ID)) { long dataId = data.getLong(DataColumns.ID); if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { // the data id is not available, have to create // a new one data.remove(DataColumns.ID); } } } } } catch (JSONException e) { Log.w(TAG, e.toString()); e.printStackTrace(); } sqlNote.setContent(js); Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); if (parentId == null) { Log.e(TAG, "cannot find task's parent id locally"); throw new ActionFailureException("cannot add local node"); } sqlNote.setParentId(parentId.longValue()); } // create the local node sqlNote.setGtaskId(node.getGid()); sqlNote.commit(false); // update gid-nid mapping mGidToNid.put(node.getGid(), sqlNote.getId()); mNidToGid.put(sqlNote.getId(), node.getGid()); // update meta updateRemoteMeta(node.getGid(), sqlNote); }
From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private FeatureCollection decodeFeatureCollection(JSONObject object) throws JSONException { FeatureCollection fCollection = null; JSONArray array = object.getJSONArray("features"); if (array != null) { fCollection = new FeatureCollection(); for (int i = 0; i < array.length(); i++) { JSONObject o = array.getJSONObject(i); if (o.get("type").equals("Feature")) { Feature f = this.decodeFeature(o); fCollection.addFeature(f); }//w w w.ja v a 2 s . c om } } return fCollection; }
From source file:com.microsoft.applicationinsights.test.framework.telemetries.RequestTelemetryItem.java
/** * Converts JSON object to Request TelemetryItem * @param json The JSON object//from w ww . j a va 2s. c om */ private void initRequestTelemetryItem(JSONObject json) throws URISyntaxException, JSONException { System.out.println("Converting JSON object to RequestTelemetryItem"); JSONObject requestProperties = json.getJSONArray("request").getJSONObject(0); String address = requestProperties.getString("url"); Integer port = requestProperties.getJSONObject("urlData").getInt("port"); Integer responseCode = requestProperties.getInt("responseCode"); String requestName = requestProperties.getString("name"); JSONArray parameters = requestProperties.getJSONObject("urlData").getJSONArray("queryParameters"); Hashtable<String, String> queryParameters = new Hashtable<String, String>(); for (int i = 0; i < parameters.length(); ++i) { JSONObject parameterPair = parameters.getJSONObject(i); String name = parameterPair.getString("parameter"); String value = parameterPair.getString("value"); queryParameters.put(name, value); } this.setProperty("uri", address); this.setProperty("port", port.toString()); this.setProperty("responseCode", responseCode.toString()); this.setProperty("requestName", requestName); for (String key : queryParameters.keySet()) { this.setProperty("queryParameter." + key, queryParameters.get(key)); } }
From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java
private void updateToolList(Set<Map.Entry<String, ArrayList<ToolEntry>>> tools, final LinearLayout toolContainer) { if (fiskInfoUtility.isNetworkAvailable(getActivity())) { List<ToolEntry> localTools = new ArrayList<>(); final List<ToolEntry> unconfirmedRemovedTools = new ArrayList<>(); final List<ToolEntry> synchedTools = new ArrayList<>(); for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) { for (final ToolEntry toolEntry : dateEntry.getValue()) { if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) { continue; } else if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED) { synchedTools.add(toolEntry); } else if (!(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED)) { localTools.add(toolEntry); } else { unconfirmedRemovedTools.add(toolEntry); }//from www. j a v a 2s. c o m } } barentswatchApi.setAccesToken(user.getToken()); Response response = barentswatchApi.getApi().geoDataDownload("fishingfacility", "JSON"); if (response == null) { Log.d(TAG, "RESPONSE == NULL"); } byte[] toolData; try { toolData = FiskInfoUtility.toByteArray(response.getBody().in()); JSONObject featureCollection = new JSONObject(new String(toolData)); JSONArray jsonTools = featureCollection.getJSONArray("features"); JSONArray matchedTools = new JSONArray(); UserSettings settings = user.getSettings(); for (int i = 0; i < jsonTools.length(); i++) { JSONObject tool = jsonTools.getJSONObject(i); boolean hasCopy = false; for (int j = 0; j < localTools.size(); j++) { if (localTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss), Locale.getDefault()); SimpleDateFormat sdfMilliSecondsRemote = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss), Locale.getDefault()); SimpleDateFormat sdfRemote = new SimpleDateFormat( getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault()); sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC")); /* Timestamps from BW seem to be one hour earlier than UTC/GMT? */ sdfMilliSecondsRemote.setTimeZone(TimeZone.getTimeZone("GMT-1")); sdfRemote.setTimeZone(TimeZone.getTimeZone("GMT-1")); Date localLastUpdatedDateTime; Date localUpdatedBySourceDateTime; Date serverUpdatedDateTime; Date serverUpdatedBySourceDateTime = null; try { localLastUpdatedDateTime = sdfMilliSeconds .parse(localTools.get(j).getLastChangedDateTime()); localUpdatedBySourceDateTime = sdfMilliSeconds .parse(localTools.get(j).getLastChangedBySource()); serverUpdatedDateTime = tool.getJSONObject("properties") .getString("lastchangeddatetime").length() == getResources() .getInteger(R.integer.datetime_without_milliseconds_length) ? sdfRemote.parse(tool.getJSONObject("properties") .getString("lastchangeddatetime")) : sdfMilliSecondsRemote .parse(tool.getJSONObject("properties") .getString("lastchangeddatetime")); if (tool.getJSONObject("properties").has("lastchangedbysource")) { serverUpdatedBySourceDateTime = tool.getJSONObject("properties") .getString("lastchangedbysource").length() == getResources() .getInteger(R.integer.datetime_without_milliseconds_length) ? sdfRemote.parse(tool.getJSONObject("properties") .getString("lastchangedbysource")) : sdfMilliSecondsRemote .parse(tool.getJSONObject("properties") .getString("lastchangedbysource")); } if ((localLastUpdatedDateTime.equals(serverUpdatedDateTime) || localLastUpdatedDateTime.before(serverUpdatedDateTime)) && serverUpdatedBySourceDateTime != null && (localUpdatedBySourceDateTime.equals(serverUpdatedBySourceDateTime) || localUpdatedBySourceDateTime .before(serverUpdatedBySourceDateTime))) { localTools.get(j).updateFromGeoJson(tool, getActivity()); localTools.get(j).setToolStatus(ToolEntryStatus.STATUS_RECEIVED); } else if (serverUpdatedBySourceDateTime != null && localUpdatedBySourceDateTime.after(serverUpdatedBySourceDateTime)) { // TODO: Do nothing, local changes should be reported. } else { // TODO: what gives? } } catch (ParseException e) { e.printStackTrace(); } localTools.remove(j); j--; hasCopy = true; break; } } for (int j = 0; j < unconfirmedRemovedTools.size(); j++) { if (unconfirmedRemovedTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { hasCopy = true; unconfirmedRemovedTools.remove(j); j--; } } for (int j = 0; j < synchedTools.size(); j++) { if (synchedTools.get(j).getToolId() .equals(tool.getJSONObject("properties").getString("toolid"))) { hasCopy = true; synchedTools.remove(j); j--; } } if (!hasCopy && settings != null) { if ((!settings.getVesselName().isEmpty() && (FiskInfoUtility.ReplaceRegionalCharacters(settings.getVesselName()) .equalsIgnoreCase(tool.getJSONObject("properties").getString("vesselname")) || settings.getVesselName().equalsIgnoreCase( tool.getJSONObject("properties").getString("vesselname")))) && ((!settings.getIrcs().isEmpty() && settings.getIrcs().toUpperCase() .equals(tool.getJSONObject("properties").getString("ircs"))) || (!settings.getMmsi().isEmpty() && settings.getMmsi() .equals(tool.getJSONObject("properties").getString("mmsi"))) || (!settings.getImo().isEmpty() && settings.getImo() .equals(tool.getJSONObject("properties").getString("imo"))))) { matchedTools.put(tool); } } } if (matchedTools.length() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button addToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); final List<ToolConfirmationRow> matchedToolsList = new ArrayList<>(); for (int i = 0; i < matchedTools.length(); i++) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), matchedTools.getJSONObject(i)); linearLayoutToolContainer.addView(confirmationRow.getView()); matchedToolsList.add(confirmationRow); } addToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolConfirmationRow row : matchedToolsList) { if (row.isChecked()) { ToolEntry newTool = row.getToolEntry(); user.getToolLog().addTool(newTool, newTool.getSetupDateTime().substring(0, 10)); ToolLogRow newRow = new ToolLogRow(v.getContext(), newTool, utilityOnClickListeners.getToolEntryEditDialogOnClickListener( getActivity(), getFragmentManager(), mGpsLocationTracker, newTool, user)); row.getView().setTag(newTool.getToolId()); toolContainer.addView(newRow.getView()); } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } if (unconfirmedRemovedTools.size() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); infoTextView.setText(R.string.removed_tools_information_text); archiveToolsButton.setText(R.string.ok); cancelButton.setVisibility(View.GONE); for (ToolEntry removedEntry : unconfirmedRemovedTools) { ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null); removedToolRow.setToolNotificationImageViewVisibility(false); removedToolRow.setEditToolImageViewVisibility(false); linearLayoutToolContainer.addView(removedToolRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry removedEntry : unconfirmedRemovedTools) { removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); for (int i = 0; i < toolContainer.getChildCount(); i++) { if (removedEntry.getToolId() .equals(toolContainer.getChildAt(i).getTag().toString())) { toolContainer.removeViewAt(i); break; } } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); dialog.show(); } if (synchedTools.size() > 0) { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView infoTextView = (TextView) dialog.findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); infoTextView.setText(R.string.unexpected_tool_removal_info_text); archiveToolsButton.setText(R.string.archive); for (ToolEntry removedEntry : synchedTools) { ToolLogRow removedToolRow = new ToolLogRow(getActivity(), removedEntry, null); removedToolRow.setToolNotificationImageViewVisibility(false); removedToolRow.setEditToolImageViewVisibility(false); linearLayoutToolContainer.addView(removedToolRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry removedEntry : synchedTools) { removedEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); for (int i = 0; i < toolContainer.getChildCount(); i++) { if (removedEntry.getToolId() .equals(toolContainer.getChildAt(i).getTag().toString())) { toolContainer.removeViewAt(i); break; } } } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } if (unconfirmedRemovedTools.size() > 0) { // TODO: If not found server side, tool is assumed to be removed. Inform user. final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.reported_tools_removed_title); TextView informationTextView = (TextView) dialog .findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); informationTextView.setText(getString(R.string.removed_tools_information_text)); cancelButton.setVisibility(View.GONE); archiveToolsButton.setText(getString(R.string.ok)); for (ToolEntry toolEntry : unconfirmedRemovedTools) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry); linearLayoutToolContainer.addView(confirmationRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry toolEntry : unconfirmedRemovedTools) { toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); dialog.show(); } if (synchedTools.size() > 0) { // // TODO: Prompt user: Tool was confirmed, now is no longer at BW, remove or archive? final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_confirm_tools_from_api, R.string.tool_confirmation); TextView informationTextView = (TextView) dialog .findViewById(R.id.dialog_description_text_view); Button cancelButton = (Button) dialog.findViewById(R.id.dialog_bottom_cancel_button); Button archiveToolsButton = (Button) dialog.findViewById(R.id.dialog_bottom_add_button); final LinearLayout linearLayoutToolContainer = (LinearLayout) dialog .findViewById(R.id.dialog_confirm_tool_main_container_linear_layout); informationTextView.setText(getString(R.string.unexpected_tool_removal_info_text)); archiveToolsButton.setText(getString(R.string.ok)); for (ToolEntry toolEntry : synchedTools) { ToolConfirmationRow confirmationRow = new ToolConfirmationRow(getActivity(), toolEntry); linearLayoutToolContainer.addView(confirmationRow.getView()); } archiveToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (ToolEntry toolEntry : synchedTools) { toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); } user.writeToSharedPref(v.getContext()); dialog.dismiss(); } }); cancelButton.setOnClickListener(utilityOnClickListeners.getDismissDialogListener(dialog)); dialog.show(); } user.writeToSharedPref(getActivity()); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }
From source file:fiskinfoo.no.sintef.fiskinfoo.MyToolsFragment.java
private void generateAndSendGeoJsonToolReport() { FiskInfoUtility fiskInfoUtility = new FiskInfoUtility(); JSONObject featureCollection = new JSONObject(); try {/*from www .j a v a 2s . co m*/ Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet(); JSONArray featureList = new JSONArray(); for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) { for (final ToolEntry toolEntry : dateEntry.getValue()) { if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) { continue; } toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED : ToolEntryStatus.STATUS_SENT_UNCONFIRMED); JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker); featureList.put(gjsonTool); } } if (featureList.length() == 0) { Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show(); return; } user.writeToSharedPref(getActivity()); featureCollection.put("features", featureList); featureCollection.put("type", "FeatureCollection"); featureCollection.put("crs", JSONObject.NULL); featureCollection.put("bbox", JSONObject.NULL); String toolString = featureCollection.toString(4); if (fiskInfoUtility.isExternalStorageWritable()) { fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(), getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false); String directoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); String fileName = directoryPath + "/FiskInfo/api_setting.json"; File apiSettingsFile = new File(fileName); String recipient = null; if (apiSettingsFile.exists()) { InputStream inputStream; InputStreamReader streamReader; JsonReader jsonReader; try { inputStream = new BufferedInputStream(new FileInputStream(apiSettingsFile)); streamReader = new InputStreamReader(inputStream, "UTF-8"); jsonReader = new JsonReader(streamReader); jsonReader.beginObject(); while (jsonReader.hasNext()) { String name = jsonReader.nextName(); if (name.equals("email")) { recipient = jsonReader.nextString(); } else { jsonReader.skipValue(); } } jsonReader.endObject(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } } recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient; String[] recipients = new String[] { recipient }; Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/plain"); String toolIds; StringBuilder sb = new StringBuilder(); sb.append("Redskapskoder:\n"); for (int i = 0; i < featureList.length(); i++) { sb.append(Integer.toString(i + 1)); sb.append(": "); sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId")); sb.append("\n"); } toolIds = sb.toString(); intent.putExtra(Intent.EXTRA_EMAIL, recipients); intent.putExtra(Intent.EXTRA_TEXT, toolIds); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header)); File file = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/FiskInfo/Redskapsrapport.geojson"); Uri uri = Uri.fromFile(file); intent.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header))); } } catch (JSONException e) { e.printStackTrace(); } }
From source file:net.olejon.mdapp.LvhAdapter.java
@Override public void onBindViewHolder(CategoryViewHolder viewHolder, int i) { try {//from w w w . j a v a2 s. co m final String color; final String icon; final JSONObject categoriesJsonObject = mCategories.getJSONObject(i); switch (i) { case 0: { color = "#F44336"; icon = "lvh_urgent"; viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.red)); viewHolder.icon.setImageResource(R.drawable.ic_favorite_white_24dp); break; } case 1: { color = "#9C27B0"; icon = "lvh_symptoms"; viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.purple)); viewHolder.icon.setImageResource(R.drawable.ic_stethoscope); break; } case 2: { color = "#FF9800"; icon = "lvh_injuries"; viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.orange)); viewHolder.icon.setImageResource(R.drawable.ic_healing_white_24dp); break; } case 3: { color = "#009688"; icon = "lvh_administrative"; viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.teal)); viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp); break; } default: { color = "#009688"; icon = "lvh_administrative"; viewHolder.card.setCardBackgroundColor(mContext.getResources().getColor(R.color.teal)); viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp); } } viewHolder.title.setText(categoriesJsonObject.getString("title")); viewHolder.categories.removeAllViews(); final JSONArray categoriesJsonArray = categoriesJsonObject.getJSONArray("categories"); for (int f = 0; f < categoriesJsonArray.length(); f++) { final JSONObject categoryJsonObject = categoriesJsonArray.getJSONObject(f); final String title = categoryJsonObject.getString("title"); final String subcategories = categoryJsonObject.getString("subcategories"); TextView textView = (TextView) mLayoutInflater.inflate(R.layout.activity_lvh_card_categories_item, null); textView.setText(categoryJsonObject.getString("title")); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, LvhCategoriesActivity.class); intent.putExtra("color", color); intent.putExtra("icon", icon); intent.putExtra("title", title); intent.putExtra("subcategories", subcategories); mContext.startActivity(intent); } }); viewHolder.categories.addView(textView); } animateView(viewHolder.card, i); } catch (Exception e) { Log.e("LvhAdapter", Log.getStackTraceString(e)); } }
From source file:com.sublimis.urgentcallfilter.Magic.java
public static JSONObject jsonGetObject(JSONArray jsonArray, int index) { JSONObject retVal = null;/* w ww .j av a2 s .co m*/ try { retVal = jsonArray.getJSONObject(index); } catch (Exception e) { } return retVal; }
From source file:com.android.browser.GearsSettingsDialog.java
public void setup() { // First let's add the permissions' resources LOCAL_STORAGE.setResources(R.string.settings_storage_title, R.string.settings_storage_subtitle_on, R.string.settings_storage_subtitle_off); LOCATION_DATA.setResources(R.string.settings_location_title, R.string.settings_location_subtitle_on, R.string.settings_location_subtitle_off); // add the permissions to the list of permissions. mPermissions = new Vector<PermissionType>(); mPermissions.add(LOCAL_STORAGE);/* w ww . j av a2 s.c om*/ mPermissions.add(LOCATION_DATA); OriginPermissions.setListener(this); setupDialog(); // We manage the permissions using three vectors, mSitesPermissions, // mOriginalPermissions and mCurrentPermissions. // The dialog's arguments are parsed and a list of permissions is // generated and stored in those three vectors. // mOriginalPermissions is a separate copy and will not be modified; // mSitesPermissions contains the current permissions _only_ -- // if an origin is removed, it is also removed from mSitesPermissions. // Finally, mCurrentPermissions contains the current permissions and // is a clone of mSitesPermissions, but removed sites aren't removed, // their permissions are simply set to PERMISSION_NOT_SET. This // allows us to easily generate the final difference between the // original permissions and the final permissions, while directly // using mSitesPermissions for the listView adapter (SettingsAdapter). mSitesPermissions = new Vector<OriginPermissions>(); mOriginalPermissions = new Vector<OriginPermissions>(); try { JSONObject json = new JSONObject(mDialogArguments); if (json.has("permissions")) { JSONArray jsonArray = json.getJSONArray("permissions"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject infos = jsonArray.getJSONObject(i); String name = null; int localStorage = PermissionType.PERMISSION_NOT_SET; int locationData = PermissionType.PERMISSION_NOT_SET; if (infos.has("name")) { name = infos.getString("name"); } if (infos.has(LOCAL_STORAGE_STRING)) { JSONObject perm = infos.getJSONObject(LOCAL_STORAGE_STRING); if (perm.has("permissionState")) { localStorage = perm.getInt("permissionState"); } } if (infos.has(LOCATION_DATA_STRING)) { JSONObject perm = infos.getJSONObject(LOCATION_DATA_STRING); if (perm.has("permissionState")) { locationData = perm.getInt("permissionState"); } } OriginPermissions perms = new OriginPermissions(name); perms.setPermission(LOCAL_STORAGE, localStorage); perms.setPermission(LOCATION_DATA, locationData); mSitesPermissions.add(perms); mOriginalPermissions.add(new OriginPermissions(perms)); } } } catch (JSONException e) { Log.e(TAG, "JSON exception ", e); } mCurrentPermissions = (Vector<OriginPermissions>) mSitesPermissions.clone(); View listView = findViewById(R.id.sites_list); if (listView != null) { ListView list = (ListView) listView; mListAdapter = new SettingsAdapter(mActivity, mSitesPermissions); list.setAdapter(mListAdapter); list.setScrollBarStyle(android.view.View.SCROLLBARS_OUTSIDE_INSET); list.setOnItemClickListener(mListAdapter); } if (mDebug) { printPermissions(); } }