List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:org.protorabbit.Config.java
public String getIncludeFileName(JSONObject template, String tid) { if (template.has("properties")) { try {//from w w w . j av a2s.co m JSONObject properties = template.getJSONObject("properties"); if (properties.has(tid)) { JSONObject to = properties.getJSONObject(tid); return to.getString("value"); } } catch (JSONException e) { getLogger().log(Level.SEVERE, "Error parsing include file name.", e); } } return null; }
From source file:fr.pasteque.client.sync.SendProcess.java
private boolean parseCustomer(JSONObject resp) { try {//from ww w . jav a 2 s. co m // Were customers properly send ? JSONObject o = resp.getJSONObject("content"); JSONArray ids = o.getJSONArray("saved"); int createdCustomerSize = Data.Customer.createdCustomers.size(); for (int i = 0; i < createdCustomerSize; i++) { String tmpId = Data.Customer.createdCustomers.get(i).getId(); String serverId = ids.getString(i); if (tmpId == null) continue; // Should never happen. // Updating local info for (Customer c : Data.Customer.customers) { if (c.getId().equals(tmpId)) { c.setId(serverId); break; } } for (Ticket t : Data.Session.currentSession(this.ctx).getTickets()) { Customer c = t.getCustomer(); if (c != null && c.getId().equals(tmpId)) { c.setId(serverId); } } for (Receipt r : Data.Receipt.getReceipts(this.ctx)) { Customer c = r.getTicket().getCustomer(); if (c != null && c.getId().equals(tmpId)) { c.setId(serverId); } } Data.Customer.resolvedIds.put(tmpId, serverId); } // Sending Customer completed Data.Customer.createdCustomers.clear(); Data.Customer.save(this.ctx); Data.Session.save(this.ctx); Data.Receipt.save(this.ctx); Log.i(LOG_TAG, "Customer Sync: Saved new local customer ids"); this.sendCustomer = false; this.subprogress = 0; SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE); instance.nextArchive(); return true; } catch (JSONException e) { // Customer not send properly. Log.i(LOG_TAG, "Error while parsing customer result", e); SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED); } catch (IOError e) { Log.i(LOG_TAG, "Could not save customer data in parse customer", e); SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED); } return false; }
From source file:com.easemob.chatuidemo.DemoHXSDKHelper.java
public String getRobotMenuMessageDigest(EMMessage message) { String title = ""; try {//from ww w .j a v a2s . c o m JSONObject jsonObj = message.getJSONObjectAttribute(Constant.MESSAGE_ATTR_ROBOT_MSGTYPE); if (jsonObj.has("choice")) { JSONObject jsonChoice = jsonObj.getJSONObject("choice"); title = jsonChoice.getString("title"); } } catch (Exception e) { } return title; }
From source file:com.scigames.slidegame.Registration3MassActivity.java
public void onResultsSucceeded(String[] serverResponseStrings, JSONObject serverResponseJSON) throws JSONException { Log.d(TAG, "LOGIN SUCCEEDED: "); for (int i = 0; i < serverResponseStrings.length; i++) { //just print everything returned as a String[] for fun Log.d(TAG, "[" + i + "] " + serverResponseStrings[i]); }/*from ww w . j ava2s . c om*/ JSONObject thisStudent; thisStudent = serverResponseJSON.getJSONObject("student"); Log.d(TAG, "this student: "); Log.d(TAG, thisStudent.toString()); Log.d(TAG, "...onResultsSucceeded"); Intent i = new Intent(Registration3MassActivity.this, Registration4PhotoActivity.class); Log.d(TAG, "new Intent"); i.putExtra("fName", firstNameIn); i.putExtra("lName", lastNameIn); i.putExtra("studentId", serverResponseStrings[0]); i.putExtra("visitId", serverResponseStrings[1]); Log.d(TAG, "startActivity..."); Registration3MassActivity.this.startActivity(i); Log.d(TAG, "...startActivity"); }
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./* w w w . j ava 2 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 addLocalNode(Node node) throws NetworkFailureException { if (mCancelled) { return;// w w w . ja v a2 s. co m } 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 Feature decodeFeature(JSONObject object) throws JSONException { Feature feature = null;// w w w. j a v a 2 s .c o m JSONObject geom = object.getJSONObject("geometry"); if (geom != null) { IGeometry geometry = this.decodeGeometry(geom); feature = new Feature(geometry); } // JSONObject properties = object.getJSONObject("properties"); // String text = properties.get("TEXT").toString(); // int id = Integer.valueOf(properties.get("ID").toString()).intValue(); // double cost = Double.valueOf(properties.get("COST").toString()) // .doubleValue(); // double length = Double.valueOf(properties.get("LENGTH").toString()) // .doubleValue(); // RouteProperties r = new RouteProperties(text, cost, length); // feature.setID(id); // feature.setProp(r); return feature; }
From source file:com.geecko.QuickLyric.tasks.CoverArtLoader.java
@Override protected String doInBackground(Object... objects) { Lyrics lyrics = (Lyrics) objects[0]; lyricsViewFragment = (LyricsViewFragment) objects[1]; String url = lyrics.getCoverURL(); if (url == null) { try {/*from w ww .ja v a 2 s . c o m*/ String html = Net.getUrlAsString(new URL(String.format( "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=%s&artist=%s&track=%s&format=json", Keys.lastFM, URLEncoder.encode(lyrics.getArtist(), "UTF-8"), URLEncoder.encode(lyrics.getTrack(), "UTF-8")))); JSONObject json = new JSONObject(html); url = json.getJSONObject("track").getJSONObject("album").getJSONArray("image").getJSONObject(2) .getString("#text"); if (url.contains("noimage")) url = null; } catch (JSONException | IOException e) { e.printStackTrace(); } } return url; }
From source file:com.microsoft.applicationinsights.test.framework.telemetries.RequestTelemetryItem.java
/** * Converts JSON object to Request TelemetryItem * @param json The JSON object//from ww w .j a v a 2 s . 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 . ja va2s .c om } } 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(); } } }