List of usage examples for org.json JSONArray length
public int length()
From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private double[][] decodeLineStringCoords(JSONArray coordinates) throws JSONException { int size = coordinates.length(); double[][] coordsLineStr = new double[2][size]; for (int i = 0; i < size; i++) { JSONArray lineStrCoord = coordinates.getJSONArray(i); double[] coords = this.decodeCoordinates(lineStrCoord); coordsLineStr[0][i] = coords[0]; coordsLineStr[1][i] = coords[1]; }/*from w w w .ja v a 2s. c o m*/ return coordsLineStr; }
From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private double[] decodeCoordinates(JSONArray coordinates) throws JSONException { double[] coords = new double[2]; int size = coordinates.length(); for (int i = 0; i < size; i++) { coords[i] = Double.parseDouble(coordinates.get(i).toString()); }/*from w w w .java2s . com*/ return coords; }
From source file:com.microsoft.applicationinsights.test.framework.telemetries.RequestTelemetryItem.java
/** * Converts JSON object to Request TelemetryItem * @param json The JSON object// w w w. j a v a 2 s.co m */ 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 ww w . j av a 2 s.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 w w w .jav a2 s. c o 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:com.eutectoid.dosomething.picker.GraphObjectCursor.java
public void addGraphObjects(JSONArray graphObjects) { for (int i = 0; i < graphObjects.length(); ++i) { this.graphObjects.add(graphObjects.optJSONObject(i)); }// w w w . j a v a2s . co m }
From source file:net.olejon.mdapp.LvhAdapter.java
@Override public void onBindViewHolder(CategoryViewHolder viewHolder, int i) { try {/*from w ww . ja v a2 s . com*/ 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 JSONArray jsonArrayRemove(JSONArray jsonArray, int index) { JSONArray newJsonArray = jsonArray;/*from w w w . j a va2s. c om*/ if (jsonArray != null) { newJsonArray = new JSONArray(); int len = jsonArray.length(); for (int i = 0; i < len; i++) { // Excluding the item at position if (i != index) { try { newJsonArray.put(jsonArray.get(i)); } catch (Exception e) { } } } } return newJsonArray; }
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 a va 2 s . co m*/ 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(); } }
From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java
private JSONArray getFacesJSONArray(SparseArray<Face> faces) { int numFaces = faces.size(); JSONArray facesResult = new JSONArray(); for (int i = 0; i < numFaces; i++) { Face face = faces.valueAt(i);/* ww w . j a v a 2 s . co m*/ String faceJSON = getFaceJSON(face); if (faceJSON != null) { facesResult.put(faceJSON); } else { AIR.log("Error making JSON out of Face object"); } } AIR.log("Parsed " + facesResult.length() + " faces"); return facesResult; }