List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:com.mclinic.json.PatientConverter.java
public JSONArray serialize(final List<Patient> patients) throws JSONException { JSONArray array = new JSONArray(); for (Patient patient : patients) array.put(serialize(patient)); return array; }
From source file:com.vinexs.tool.XML.java
private static Object getChildJSONObject(org.w3c.dom.Element tag) { int i, k;// w w w. j a va 2 s . co m //get attributes && child nodes NamedNodeMap attributes = tag.getAttributes(); NodeList childNodes = tag.getChildNodes(); int numAttr = attributes.getLength(); int numChild = childNodes.getLength(); //get element nodes Boolean hasTagChild = false; Map<String, ArrayList<Object>> childMap = new HashMap<>(); for (i = 0; i < numChild; i++) { Node node = childNodes.item(i); //not process non-element node if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) { continue; } hasTagChild = true; org.w3c.dom.Element childTag = (org.w3c.dom.Element) node; String tagName = childTag.getTagName(); if (!childMap.containsKey(tagName)) { childMap.put(tagName, new ArrayList<>()); } childMap.get(tagName).add(getChildJSONObject(childTag)); } if (numAttr == 0 && !hasTagChild) { // Return String return stringToValue(tag.getTextContent()); } else { // Return JSONObject JSONObject data = new JSONObject(); if (numAttr > 0) { for (i = 0; i < numAttr; i++) { Node attr = attributes.item(i); try { data.put(attr.getNodeName(), stringToValue(attr.getNodeValue())); } catch (JSONException e) { e.printStackTrace(); } } } if (hasTagChild) { for (Map.Entry<String, ArrayList<Object>> tagMap : childMap.entrySet()) { ArrayList<Object> tagList = tagMap.getValue(); if (tagList.size() == 1) { try { data.put(tagMap.getKey(), tagList.get(0)); } catch (JSONException e) { e.printStackTrace(); } } else { JSONArray array = new JSONArray(); for (k = 0; k < tagList.size(); k++) { array.put(tagList.get(k)); } try { data.put(tagMap.getKey(), array); } catch (JSONException e) { e.printStackTrace(); } } } } else { try { data.put("content", stringToValue(tag.getTextContent())); } catch (JSONException e) { e.printStackTrace(); } } return data; } }
From source file:ub.botiga.data.User.java
public void save(JSONObject root) throws JSONException { root.put("name", mName); root.put("credit", mCredit); JSONArray array = new JSONArray(); for (Product p : mProducts.values()) { array.put(p.getName()); }//from w w w .ja v a 2 s. c om root.put("products", array); }
From source file:fr.pasteque.client.sync.SendProcess.java
/** * Sends new customer to server.//from w w w. j ava 2s . c o m * @return true if customers were send, false otherwise */ private boolean sendCustomer() { if (Data.Customer.resolvedIds.size() > 0) { Log.i(LOG_TAG, "Customer Sync: There are saved local customer ids"); } if (!this.sendCustomer) { SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE); instance.nextArchive(); return false; } JSONArray cstJArray = new JSONArray(); for (Customer c : Data.Customer.createdCustomers) { try { // requiered hack to avoid errors. Prepaid is local storage // use but the prepaid amount will be calculated from tickets // lines by Pastequ-API double storedCustomerPrepaid = c.getPrepaid(); c.setPrepaid(0); JSONObject o = c.toJSON(); cstJArray.put(o); c.setPrepaid(storedCustomerPrepaid); } catch (JSONException e) { Log.d(LOG_TAG, c.toString(), e); SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED); return false; } } this.subprogress++; this.refreshFeedback(); Map<String, String> postBody = SyncUtils.initParams(this.ctx, "CustomersAPI", "save"); postBody.put("customers", cstJArray.toString()); URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), null, postBody, new CustHandler(this, this.listener)); return true; }
From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java
private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric, HashMap<String, String> tags) throws OpenTSDBException { urlString = urlString + API_METHOD;//from w ww .j ava2 s . c o m String result = ""; try { HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString); OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream()); JSONObject mainObject = new JSONObject(); mainObject.put("start", startEpoch); mainObject.put("end", endEpoch); JSONArray queryArray = new JSONArray(); JSONObject queryParams = new JSONObject(); queryParams.put("aggregator", "sum"); queryParams.put("metric", metric); queryArray.put(queryParams); if (tags != null) { JSONObject queryTags = new JSONObject(); Iterator<Entry<String, String>> entries = tags.entrySet().iterator(); while (entries.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) entries.next(); queryTags.put((String) entry.getKey(), (String) entry.getValue()); } queryParams.put("tags", queryTags); } mainObject.put("queries", queryArray); String queryString = mainObject.toString(); wr.write(queryString); wr.flush(); wr.close(); result = TimeSeriesUtility.readHttpResponse(httpConnection); } catch (IOException e) { throw new OpenTSDBException("Unable to connect to server", e); } catch (JSONException e) { throw new OpenTSDBException("Error on request data", e); } return TimeSeriesUtility.makeResponseJSONArray(result); }
From source file:uk.ac.dundee.computing.aec.sensorsync.lib.RenderJSON.java
protected JSONObject getJSON(Object thing) { // TODO Auto-generated method stub Object temp = thing;//from ww w. jav a2 s.com Class c = temp.getClass(); String className = c.getName(); if (className.compareTo("java.util.LinkedList") == 0) { //Deal with a linked list List Data = (List) thing; Iterator iterator; JSONObject JSONObj = new JSONObject(); JSONArray Parts = new JSONArray(); iterator = Data.iterator(); while (iterator.hasNext()) { Object Value = iterator.next(); JSONObject obj = ProcessObject(Value); try { Parts.put(obj); } catch (Exception JSONet) { System.out.println("JSON Fault" + JSONet); } } try { JSONObj.put("Data", Parts); } catch (Exception JSONet) { System.out.println("JSON Fault" + JSONet); } if (JSONObj != null) { return (JSONObj); } } else { Object Data = thing; JSONObject obj = ProcessObject(Data); if (obj != null) { return (obj); } } return null; }
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); }/* w w w .ja v a2 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 {// w ww . j a va 2 s . com 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:feedme.controller.SearchRestServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from www .ja v a2s .co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); request.setCharacterEncoding("UTF-8"); String city = request.getParameter("where");//get the city int category = Integer.parseInt(request.getParameter("what"));//get the category int page = 1; int recordsPerPage = 6; if (request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } List<Restaurant> restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(0, recordsPerPage, category, city);//getting a list of restaurants by category and cities int noOfRecords = restaurants.size(); int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage); if (isAjaxRequest(request)) { try { restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity( (page - 1) * recordsPerPage, recordsPerPage, category, city);//getting a list of restaurants by category and cities JSONObject restObj = new JSONObject(); JSONArray restArray = new JSONArray(); for (Restaurant rest : restaurants) { restArray.put(new JSONObject().put("resturent", rest.toJson())); } restObj.put("resturent", restArray); restObj.put("noOfPages", noOfPages); restObj.put("currentPage", page); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.print(restObj); response.getWriter().flush(); return; } catch (JSONException e) { e.printStackTrace(); } } request.setAttribute("noOfPages", noOfPages); request.setAttribute("currentPage", page); request.setAttribute("restaurants", restaurants);//return the restaurants to the client RequestDispatcher dispatcher = request.getRequestDispatcher("website/search_rest.jsp"); dispatcher.forward(request, response); }
From source file:com.sublimis.urgentcallfilter.Magic.java
public static JSONArray jsonArrayRemove(JSONArray jsonArray, int index) { JSONArray newJsonArray = jsonArray; 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) { }/* w w w . ja v a2 s .c om*/ } } } return newJsonArray; }