List of usage examples for org.json JSONArray getInt
public int getInt(int index) throws JSONException
From source file:run.ace.NativeHost.java
void send(final JSONArray messages, final CallbackContext callbackContext) { final Activity activity = _activity; Runnable runnable = new Runnable() { public void run() { try { Object returnValue = null; boolean hasReturnValue = false; // Needed because null can be a valid return value int numMessages = messages.length(); for (int i = 0; i < numMessages; i++) { Object instance = null; Handle handle;/*from w w w . j a va2 s .c o m*/ JSONArray message = messages.getJSONArray(i); //android.util.Log.d("Ace", "TODO: MSG: " + message); int messageType = message.getInt(0); switch (messageType) { case IncomingMessages.MSG_CREATE: instance = IncomingMessages.create(message, activity); handle = Handle.fromJSONObject(message.getJSONObject(1)); handle.register(instance); break; case IncomingMessages.MSG_SET: IncomingMessages.set(message); break; case IncomingMessages.MSG_INVOKE: returnValue = IncomingMessages.invoke(message); hasReturnValue = true; break; case IncomingMessages.MSG_EVENTADD: IncomingMessages.eventAdd(message); break; case IncomingMessages.MSG_EVENTREMOVE: IncomingMessages.eventRemove(message); break; case IncomingMessages.MSG_STATICINVOKE: returnValue = IncomingMessages.staticInvoke(message); hasReturnValue = true; break; case IncomingMessages.MSG_FIELDGET: returnValue = IncomingMessages.fieldGet(message); hasReturnValue = true; break; case IncomingMessages.MSG_STATICFIELDGET: returnValue = IncomingMessages.staticFieldGet(message); hasReturnValue = true; break; case IncomingMessages.MSG_GETINSTANCE: instance = IncomingMessages.getInstance(message, activity, _webView); handle = Handle.fromJSONObject(message.getJSONObject(1)); handle.register(instance); break; case IncomingMessages.MSG_NAVIGATE: IncomingMessages.navigate((View) Handle.deserialize(message.getJSONObject(1)), activity); break; case IncomingMessages.MSG_FIELDSET: IncomingMessages.fieldSet(message); break; case IncomingMessages.MSG_PRIVATEFIELDGET: returnValue = IncomingMessages.privateFieldGet(message); hasReturnValue = true; break; default: throw new RuntimeException("Unknown message type: " + messageType); } } if (numMessages == 1 && hasReturnValue) { // This is a single (non-batched) invoke with a return value // (or a field get). // Send it. // TODO: Need to handle arrays of primitives/objects as well if (Utils.isBoxedNumberOrString(returnValue) || returnValue == null) { // Send the primitive value JSONArray primitive = new JSONArray(); primitive.put(returnValue); callbackContext.success(primitive); } else { // Send the object as a handle // Use existing handle if this object already has one Handle handle = Handle.fromObject(returnValue); if (handle == null) { handle = new Handle(); handle.register(returnValue); } callbackContext.success(handle.toJSONObject()); } } else { callbackContext.success(); } } catch (Exception ex) { android.util.Log.d("Ace", "Caught exception: " + exceptionWithStackTrace(ex)); callbackContext.error(exceptionWithStackTrace(ex)); } }; }; activity.runOnUiThread(runnable); }
From source file:com.liferay.mobile.android.v62.blogsentry.BlogsEntryService.java
public Integer getGroupEntriesCount(long groupId, int status) throws Exception { JSONObject _command = new JSONObject(); try {//from w w w . j av a 2s .c om JSONObject _params = new JSONObject(); _params.put("groupId", groupId); _params.put("status", status); _command.put("/blogsentry/get-group-entries-count", _params); } catch (JSONException _je) { throw new Exception(_je); } JSONArray _result = session.invoke(_command); if (_result == null) { return null; } return _result.getInt(0); }
From source file:com.liferay.mobile.android.v62.blogsentry.BlogsEntryService.java
public Integer getGroupEntriesCount(long groupId, long displayDate, int status) throws Exception { JSONObject _command = new JSONObject(); try {//from w ww . j a v a 2s .co m JSONObject _params = new JSONObject(); _params.put("groupId", groupId); _params.put("displayDate", displayDate); _params.put("status", status); _command.put("/blogsentry/get-group-entries-count", _params); } catch (JSONException _je) { throw new Exception(_je); } JSONArray _result = session.invoke(_command); if (_result == null) { return null; } return _result.getInt(0); }
From source file:com.phonegap.Notification.java
/** * Executes the request and returns PluginResult. * /*from w ww .j av a 2 s . co m*/ * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("beep")) { this.beep(args.getLong(0)); } else if (action.equals("vibrate")) { this.vibrate(args.getLong(0)); } else if (action.equals("alert")) { this.alert(args.getString(0), args.getString(1), args.getString(2), callbackId); PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); r.setKeepCallback(true); return r; } else if (action.equals("confirm")) { this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackId); PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT); r.setKeepCallback(true); return r; } else if (action.equals("activityStart")) { this.activityStart(args.getString(0), args.getString(1)); } else if (action.equals("activityStop")) { this.activityStop(); } else if (action.equals("progressStart")) { this.progressStart(args.getString(0), args.getString(1)); } else if (action.equals("progressValue")) { this.progressValue(args.getInt(0)); } else if (action.equals("progressStop")) { this.progressStop(); } return new PluginResult(status, result); } catch (JSONException e) { return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
From source file:com.shearosario.tothepathandback.DisplayDirectionsActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_directions); getActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent();/*www . j a v a 2 s . co m*/ /*if(intent.hasExtra("origin")) { double[] temp = intent.getDoubleArrayExtra("origin"); origin = new LatLng (temp[0], temp[1]); } if (intent.hasExtra("destination")) { double[] temp = intent.getDoubleArrayExtra("destination"); destination = new LatLng (temp[0], temp[1]); }*/ String linkCollection = null; String nodeCollection = null; String points = null; if (intent.hasExtra("GuidanceLinkCollection")) linkCollection = intent.getStringExtra("GuidanceLinkCollection"); if (intent.hasExtra("GuidanceNodeCollection")) nodeCollection = intent.getStringExtra("GuidanceNodeCollection"); if (intent.hasExtra("shapePoints")) points = intent.getStringExtra("shapePoints"); gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.directionsView)).getMap(); gMap.setMyLocationEnabled(false); gMap.setBuildingsEnabled(false); gMap.getUiSettings().setZoomControlsEnabled(false); TextView textView = (TextView) findViewById(R.id.osm_guidance); textView.setText(Html.fromHtml("Data provided by OpenStreetMap contributors " + "<a href=\"http://www.openstreetmap.org/copyright\">License</a>")); textView.setMovementMethod(LinkMovementMethod.getInstance()); textView = (TextView) findViewById(R.id.guidance_text); textView.setText( Html.fromHtml("Guidance Courtesy of " + "<a href=\"http://www.mapquest.com\">MapQuest</a>")); textView.setMovementMethod(LinkMovementMethod.getInstance()); PolylineOptions rectOptions = new PolylineOptions(); markers = new ArrayList<Marker>(); try { JSONArray jGuidanceLinkCollection = new JSONArray(linkCollection); JSONArray jGuidanceNodeCollection = new JSONArray(nodeCollection); JSONArray jShapePoints = new JSONArray(points); int lastIndex = 0; for (int i = 0; i < jGuidanceNodeCollection.length(); i++) { JSONObject nodeObject = jGuidanceNodeCollection.getJSONObject(i); JSONArray linkIds = nodeObject.getJSONArray("linkIds"); int linkIndex = 0; if (linkIds.length() != 0) linkIndex = linkIds.getInt(0); else continue; JSONObject linkObject = jGuidanceLinkCollection.getJSONObject(linkIndex); int shapeIndex = linkObject.getInt("shapeIndex"); // The index of a specific shape point is i/2, so multiply by 2 to get the beginning index in shapePoints // evens are lat and odds are lng double lat = jShapePoints.getDouble((shapeIndex * 2)); double lng = jShapePoints.getDouble((shapeIndex * 2) + 1); lastIndex = ((shapeIndex * 2) + 1); if (i == 0) { Marker temp = gMap .addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Origin")); markers.add(temp); } else if (nodeObject.isNull("infoCollection") == false) { Marker temp = gMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)) .title(nodeObject.getJSONArray("infoCollection").getString(0))); markers.add(temp); } } for (int i = 0; i < lastIndex; i++) { double lat = jShapePoints.getDouble(i); i++; double lng = jShapePoints.getDouble(i); rectOptions.add(new LatLng(lat, lng)); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } gMap.addPolyline(rectOptions); markersIndex = 0; gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(markersIndex).getPosition(), 17)); markers.get(markersIndex).showInfoWindow(); gMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker arg0) { if (arg0 != null) { for (int i = 0; i < markers.size(); i++) { if (markers.get(i).equals(arg0)) { markersIndex = i; break; } } if (markersIndex == 0) { findViewById(R.id.button_nextStep).setEnabled(true); findViewById(R.id.button_previousStep).setEnabled(false); } else if (markersIndex == (markers.size() - 1)) { findViewById(R.id.button_nextStep).setEnabled(false); findViewById(R.id.button_previousStep).setEnabled(true); } else { findViewById(R.id.button_nextStep).setEnabled(true); findViewById(R.id.button_previousStep).setEnabled(true); } gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(arg0.getPosition(), 17)); arg0.showInfoWindow(); return true; } return false; } }); }
From source file:com.jennifer.ui.chart.grid.RangeGrid.java
private void checkValueFormat(JSONArray ticks) { int doubleCount = 0; for (int i = 0, len = ticks.length(); i < len; i++) { if (ticks.getDouble(i) != ticks.getInt(i)) doubleCount++;//w w w . j a v a2 s . c om } if (!options.has("format")) { if (doubleCount > 0) { options.put("format", "###.##"); } else { options.put("format", "###"); } } }
From source file:yunpeng.cordova.media.AudioHandler.java
/** * Executes the request and returns PluginResult. * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback context used when calling back into JavaScript. * @return A PluginResult object with a status and message. *//* w w w . j a v a2s .c o m*/ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { CordovaResourceApi resourceApi = webView.getResourceApi(); PluginResult.Status status = PluginResult.Status.OK; String result = ""; if (action.equals("startRecordingAudio")) { String target = args.getString(1); String fileUriStr; try { Uri targetUri = resourceApi.remapUri(Uri.parse(target)); fileUriStr = targetUri.toString(); } catch (IllegalArgumentException e) { fileUriStr = target; } this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr)); } else if (action.equals("stopRecordingAudio")) { this.stopRecordingAudio(args.getString(0)); } else if (action.equals("startPlayingAudio")) { String target = args.getString(1); String fileUriStr; try { Uri targetUri = resourceApi.remapUri(Uri.parse(target)); fileUriStr = targetUri.toString(); } catch (IllegalArgumentException e) { fileUriStr = target; } this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr)); } else if (action.equals("seekToAudio")) { this.seekToAudio(args.getString(0), args.getInt(1)); } else if (action.equals("pausePlayingAudio")) { this.pausePlayingAudio(args.getString(0)); } else if (action.equals("stopPlayingAudio")) { this.stopPlayingAudio(args.getString(0)); } else if (action.equals("setVolume")) { try { this.setVolume(args.getString(0), Float.parseFloat(args.getString(1))); } catch (NumberFormatException nfe) { //no-op } } else if (action.equals("getCurrentPositionAudio")) { float f = this.getCurrentPositionAudio(args.getString(0)); callbackContext.sendPluginResult(new PluginResult(status, f)); return true; } else if (action.equals("getDurationAudio")) { float f = this.getDurationAudio(args.getString(0), args.getString(1)); callbackContext.sendPluginResult(new PluginResult(status, f)); return true; } else if (action.equals("create")) { String id = args.getString(0); String src = FileHelper.stripFileProtocol(args.getString(1)); getOrCreatePlayer(id, src); } else if (action.equals("release")) { boolean b = this.release(args.getString(0)); callbackContext.sendPluginResult(new PluginResult(status, b)); return true; } else if (action.equals("messageChannel")) { messageChannel = callbackContext; return true; } else { // Unrecognized action. return false; } callbackContext.sendPluginResult(new PluginResult(status, result)); return true; }
From source file:com.remobile.camera.CameraLauncher.java
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. *//*ww w . j a va 2s . co m*/ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; if (action.equals("takePicture")) { int srcType = CAMERA; int destType = FILE_URI; this.saveToPhotoAlbum = false; this.targetHeight = 0; this.targetWidth = 0; this.encodingType = JPEG; this.mediaType = PICTURE; this.mQuality = 80; this.mQuality = args.getInt(0); destType = args.getInt(1); srcType = args.getInt(2); this.targetWidth = args.getInt(3); this.targetHeight = args.getInt(4); this.encodingType = args.getInt(5); this.mediaType = args.getInt(6); this.allowEdit = args.getBoolean(7); this.correctOrientation = args.getBoolean(8); this.saveToPhotoAlbum = args.getBoolean(9); // If the user specifies a 0 or smaller width/height // make it -1 so later comparisons succeed if (this.targetWidth < 1) { this.targetWidth = -1; } if (this.targetHeight < 1) { this.targetHeight = -1; } try { if (srcType == CAMERA) { this.takePicture(destType, encodingType); } else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { this.getImage(srcType, destType, encodingType); } } catch (IllegalArgumentException e) { callbackContext.error("Illegal Argument Exception"); PluginResult r = new PluginResult(PluginResult.Status.ERROR); callbackContext.sendPluginResult(r); return true; } return true; } return false; }
From source file:com.intel.xdk.notification.Notification.java
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback context used when calling back into JavaScript. * @return True when the action was valid, false otherwise. *//* w w w . j ava 2 s .c o m*/ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("alert")) { this.alert(args.getString(0), args.getString(1), args.getString(2)); } else if (action.equals("confirm")) { this.confirm(args.getString(0), args.getString(1), args.getString(2), args.getString(3), args.getString(4)); } else if (action.equals("vibrate")) { this.vibrate(); } else if (action.equals("beep")) { this.beep(args.getInt(0)); } else if (action.equals("showBusyIndicator")) { this.showBusyIndicator(); } else if (action.equals("hideBusyIndicator")) { this.hideBusyIndicator(); } else { return false; } // All actions are async. //callbackContext.success(); return true; }
From source file:com.graphhopper.http.GraphHopperWeb.java
@Override public GHResponse route(GHRequest request) { StopWatch sw = new StopWatch().start(); double took = 0; try {//from www . j av a2s . co m String places = ""; for (GHPoint p : request.getPoints()) { places += "point=" + p.lat + "," + p.lon + "&"; } String url = serviceUrl + "?" + places + "&type=json" + "&points_encoded=" + pointsEncoded + "&min_path_precision=" + request.getHint("douglas.minprecision", 1) + "&algo=" + request.getAlgorithm() + "&locale=" + request.getLocale().toString() + "&elevation=" + withElevation; if (!request.getVehicle().isEmpty()) url += "&vehicle=" + request.getVehicle(); if (!key.isEmpty()) url += "&key=" + key; String str = downloader.downloadAsString(url); JSONObject json = new JSONObject(str); GHResponse res = new GHResponse(); if (json.getJSONObject("info").has("errors")) { JSONArray errors = json.getJSONObject("info").getJSONArray("errors"); for (int i = 0; i < errors.length(); i++) { JSONObject error = errors.getJSONObject(i); String exClass = error.getString("details"); String exMessage = error.getString("message"); if (exClass.equals(UnsupportedOperationException.class.getName())) { res.addError(new UnsupportedOperationException(exMessage)); } else if (exClass.equals(IllegalStateException.class.getName())) { res.addError(new IllegalStateException(exMessage)); } else if (exClass.equals(RuntimeException.class.getName())) { res.addError(new RuntimeException(exMessage)); } else if (exClass.equals(IllegalArgumentException.class.getName())) { res.addError(new IllegalArgumentException(exMessage)); } else { res.addError(new Exception(exClass + " " + exMessage)); } } return res; } else { took = json.getJSONObject("info").getDouble("took"); JSONArray paths = json.getJSONArray("paths"); JSONObject firstPath = paths.getJSONObject(0); double distance = firstPath.getDouble("distance"); int time = firstPath.getInt("time"); PointList pointList; if (pointsEncoded) { String pointStr = firstPath.getString("points"); pointList = WebHelper.decodePolyline(pointStr, 100, withElevation); } else { JSONArray coords = firstPath.getJSONObject("points").getJSONArray("coordinates"); pointList = new PointList(coords.length(), withElevation); for (int i = 0; i < coords.length(); i++) { JSONArray arr = coords.getJSONArray(i); double lon = arr.getDouble(0); double lat = arr.getDouble(1); if (withElevation) pointList.add(lat, lon, arr.getDouble(2)); else pointList.add(lat, lon); } } if (instructions) { JSONArray instrArr = firstPath.getJSONArray("instructions"); InstructionList il = new InstructionList(trMap.getWithFallBack(request.getLocale())); for (int instrIndex = 0; instrIndex < instrArr.length(); instrIndex++) { JSONObject jsonObj = instrArr.getJSONObject(instrIndex); double instDist = jsonObj.getDouble("distance"); String text = jsonObj.getString("text"); long instTime = jsonObj.getLong("time"); int sign = jsonObj.getInt("sign"); JSONArray iv = jsonObj.getJSONArray("interval"); int from = iv.getInt(0); int to = iv.getInt(1); PointList instPL = new PointList(to - from, withElevation); for (int j = from; j <= to; j++) { instPL.add(pointList, j); } // TODO way and payment type Instruction instr = new Instruction(sign, text, InstructionAnnotation.EMPTY, instPL) .setDistance(instDist).setTime(instTime); il.add(instr); } res.setInstructions(il); } return res.setPoints(pointList).setDistance(distance).setMillis(time); } } catch (Exception ex) { throw new RuntimeException( "Problem while fetching path " + request.getPoints() + ": " + ex.getMessage(), ex); } finally { logger.debug("Full request took:" + sw.stop().getSeconds() + ", API took:" + took); } }