List of usage examples for org.json JSONArray getDouble
public double getDouble(int index) throws JSONException
From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java
/** * Called when JS sends the message./*from w w w . ja v a 2s .c om*/ * * @param bridge * Receiver instance. * @param code * The code name. This looks like the name of function. * @param message * The message. This looks like the argument of function. This is * usually expressed as JSON. */ @Override public void onArriveMessage(JSBridge bridge, String code, String message) { if (code == null) { } else if (code.equals("onLoad")) { this.mMaptypeList = new ArrayList<ValueText<String>>(); this.mLoaded = true; // executes queued commands. this.execute(null); JSONArray json = null; try { json = new JSONArray(message); } catch (JSONException e) { e.printStackTrace(); } if (json != null) { for (int n = 0; n < json.length(); n++) { JSONObject one = null; try { one = json.getJSONObject(n); } catch (JSONException e) { e.printStackTrace(); } if (one != null) { String id = null, name = null; try { id = one.getString("id"); name = one.getString("name"); } catch (JSONException e) { e.printStackTrace(); } if (id != null && name != null) { this.mMaptypeList.add(new ValueText<String>(id, name)); } } } } // restores map state (2013/08/07) if (this.mInternalMapState != null) { this.restoreMapState(this.mInternalMapState.id, this.mInternalMapState.lon, this.mInternalMapState.lat, this.mInternalMapState.z); this.mInternalMapState = null; } // request to create menu items. this.invalidateOptionsMenuIfPossible(); } else if (code.equals("getCurrentMapState")) { if (message == null || !(message.length() > 0)) { // DOES NOTHING } else { try { JSONObject json = new JSONObject(message); this.mInternalMapState = new MapState(); this.mInternalMapState.id = json.getString("id"); this.mInternalMapState.lat = json.getDouble("lat"); this.mInternalMapState.lon = json.getDouble("lon"); this.mInternalMapState.z = json.getInt("z"); } catch (JSONException e) { e.printStackTrace(); } } this.mWaitingForgetCurrentMapState = false; } else if (code.equals("getCurrentZoomState")) { if (message == null) { // DOES NOTHING } else { try { JSONObject json = new JSONObject(message); this.mZoomState = new ZoomState(); this.mZoomState.minzoom = json.getInt("minzoom"); this.mZoomState.maxzoom = json.getInt("maxzoom"); this.mZoomState.currentzoom = json.getInt("currentzoom"); } catch (JSONException e) { e.printStackTrace(); } this.mWaitingForgetCurrentZoomState = false; } } else if (code.equals("alert")) { // shows alert text. (new AlertDialog.Builder(this)).setTitle(this.getTitle()).setMessage(message != null ? message : "") .setCancelable(true).setPositiveButton(android.R.string.ok, null).show(); } }
From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java
@Override public List<Double> getConditionalProbabilities(String authorizationToken, String modelUrn, List<String> phrases) { try {// w w w . j a v a2 s .c o m List<Double> probabilities = new ArrayList<Double>(); NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder( NgramServiceApiUrls.GET_CONDITIONAL_PROBABILITIES_URL); String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn) .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl(); JSONArray array = new JSONArray( convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200))); for (int i = 0; i < array.length(); i++) { probabilities.add(array.getDouble(i)); } return probabilities; } catch (Exception e) { throw new NgramServiceException("An error occurred while getting conditional probabilities.", e); } }
From source file:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java
@Override public List<Double> getProbabilities(String authorizationToken, String modelUrn, List<String> phrases) { try {// w w w. j av a2 s . co m List<Double> probabilities = new ArrayList<Double>(); NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder( NgramServiceApiUrls.GET_PROBABILITIES_URL); String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn) .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl(); JSONArray array = new JSONArray( convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200))); for (int i = 0; i < array.length(); i++) { probabilities.add(array.getDouble(i)); } return probabilities; } catch (Exception e) { throw new NgramServiceException("An error occurred while getting probabilities.", e); } }
From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java
PointOfInterest fromPoint(JSONObject point) throws JSONException { String type = point.getString("type"); double lat;/*from ww w . j av a2 s .c om*/ double lng; if (type.equals("Point")) { JSONArray coords = point.getJSONArray("coordinates"); lng = coords.getDouble(0); lat = coords.getDouble(1); } else { throw new IllegalArgumentException(); } return new PoiBuilder(0, lat, lng, this.category).build(); }
From source file:com.pansapiens.occyd.JSONdecoder.java
/** * Abstract utility class for parsing JSON objects (as strings) and * returning Java objects./*from w ww .ja va 2 s. c om*/ */ public static ArrayList<Post> json2postArray(String json_txt) throws JSONException { /** * Takes an appropriate JSON format string, returned as a response * by the server to a search query, returns an ArrayList * of Post objects. */ ArrayList<Post> post_results = new ArrayList(); if (json_txt != null) { // http://code.google.com/android/reference/org/json/JSONObject.html JSONTokener jsontok = new JSONTokener(json_txt); JSONObject json; String geohash = null; String[] tags = null; // TODO: read these from the JSON too //String key = null; //String user = null; //String desc = null; //URL link = null; // see: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html //Date date = null; // parse "2008-12-31 03:22:23.350798" format date with: // (could have an issue with to many millisecond places SSSSSS .... may need to truncate) // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // Date date = dateformat.parse(dateString); float lat, lon; json = new JSONObject(jsontok); // catch any error codes in the returned json String result = json.getString("result"); if (!result.equals("done")) { return post_results; } // unpack the json into Post objects, add them to the result list JSONArray posts = json.getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONObject p = posts.getJSONObject(i); geohash = (String) p.get("geohash"); JSONArray coordinates = p.getJSONArray("coordinates"); lat = (float) coordinates.getDouble(0); lon = (float) coordinates.getDouble(1); JSONArray t = p.getJSONArray("tags"); tags = new String[t.length()]; for (int j = 0; j < t.length(); j++) { tags[j] = t.getString(j); } Post post = new Post(lat, lon, geohash, tags); post_results.add(post); } } return post_results; }
From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java
private IGeometry decodeGeometry(JSONObject object) throws JSONException { IGeometry geom = null;//from www .j a v a 2 s . c o m LineString[] lineStrings; if (object.get("type").equals("MultiLineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); int size = coordinates.length(); lineStrings = new LineString[size]; LineString l; for (int i = 0; i < size; i++) { JSONArray lineStrCoord = coordinates.getJSONArray(i); double[][] coords = this.decodeLineStringCoords(lineStrCoord); l = new LineString(coords[0], coords[1]); lineStrings[i] = l; } geom = new MultiLineString(lineStrings); } else if (object.get("type").equals("LineString")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new LineString(coords[0], coords[1]); } else if (object.get("type").equals("Point")) { JSONArray coordinates = object.getJSONArray("coordinates"); geom = new Point(coordinates.getDouble(0), coordinates.getDouble(1)); } else if (object.get("type").equals("Polygon")) { JSONArray coordinates = object.getJSONArray("coordinates"); double[][] coords = this.decodeLineStringCoords(coordinates); geom = new Polygon(coords[0], coords[1]); } return geom; }
From source file:fr.bmartel.android.fadecandy.model.FadecandyColor.java
public FadecandyColor(JSONObject color) { try {/*w w w.j av a 2s . c om*/ if (color.has(Constants.CONFIG_GAMMA) && color.has(Constants.CONFIG_WHITEPOINT)) { mGamma = (float) color.getDouble(Constants.CONFIG_GAMMA); JSONArray whitepoints = color.getJSONArray(Constants.CONFIG_WHITEPOINT); for (int i = 0; i < whitepoints.length(); i++) { mWhitepoints.add((float) whitepoints.getDouble(i)); } } } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.wikitude.phonegap.WikitudePlugin.java
@Override public boolean execute(final String action, final JSONArray args, final CallbackContext callContext) { /* hide architect-view -> destroy and remove from activity */ if (WikitudePlugin.ACTION_CLOSE.equals(action)) { if (this.architectView != null) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override/*from www . j a va 2s . c o m*/ public void run() { removeArchitectView(); } }); callContext.success(action + ": architectView is present"); } else { callContext.error(action + ": architectView is not present"); } return true; } /* return success only if view is opened (no matter if visible or not) */ if (WikitudePlugin.ACTION_STATE_ISOPEN.equals(action)) { if (this.architectView != null) { callContext.success(action + ": architectView is present"); } else { callContext.error(action + ": architectView is not present"); } return true; } /* return success only if view is opened (no matter if visible or not) */ if (WikitudePlugin.ACTION_IS_DEVICE_SUPPORTED.equals(action)) { if (ArchitectView.isDeviceSupported(this.cordova.getActivity()) && hasNeonSupport()) { callContext.success(action + ": this device is ARchitect-ready"); } else { callContext.error(action + action + ":Sorry, this device is NOT ARchitect-ready"); } return true; } if (WikitudePlugin.ACTION_CAPTURE_SCREEN.equals(action)) { if (architectView != null) { int captureMode = ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW; try { captureMode = (args.getBoolean(0)) ? ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM_AND_WEBVIEW : ArchitectView.CaptureScreenCallback.CAPTURE_MODE_CAM; } catch (Exception e) { // unexpected error; } architectView.captureScreen(captureMode, new CaptureScreenCallback() { @Override public void onScreenCaptured(Bitmap screenCapture) { try { // final File imageDirectory = cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); final File imageDirectory = Environment.getExternalStorageDirectory(); if (imageDirectory == null) { callContext.error("External storage not available"); } final File screenCaptureFile = new File(imageDirectory, System.currentTimeMillis() + ".jpg"); if (screenCaptureFile.exists()) { screenCaptureFile.delete(); } final FileOutputStream out = new FileOutputStream(screenCaptureFile); screenCapture.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { final String absoluteCaptureImagePath = screenCaptureFile.getAbsolutePath(); callContext.success(absoluteCaptureImagePath); // in case you want to sent the pic to other applications, uncomment these lines (for future use) // final Intent share = new Intent(Intent.ACTION_SEND); // share.setType("image/jpg"); // share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(screenCaptureFile)); // final String chooserTitle = "Share Snaphot"; // cordova.getActivity().startActivity(Intent.createChooser(share, chooserTitle)); } }); } catch (Exception e) { callContext.error(e.getMessage()); } } }); return true; } } /* life-cycle's RESUME */ if (WikitudePlugin.ACTION_ON_RESUME.equals(action)) { if (this.architectView != null) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { WikitudePlugin.this.architectView.onResume(); callContext.success(action + ": architectView is present"); locationProvider.onResume(); } }); // callContext.success( action + ": architectView is present" ); } else { callContext.error(action + ": architectView is not present"); } return true; } /* life-cycle's PAUSE */ if (WikitudePlugin.ACTION_ON_PAUSE.equals(action)) { if (architectView != null) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { WikitudePlugin.this.architectView.onPause(); locationProvider.onPause(); } }); callContext.success(action + ": architectView is present"); } else { callContext.error(action + ": architectView is not present"); } return true; } /* set visibility to "visible", return error if view is null */ if (WikitudePlugin.ACTION_SHOW.equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (architectView != null) { architectView.setVisibility(View.VISIBLE); callContext.success(action + ": architectView is present"); } else { callContext.error(action + ": architectView is not present"); } } }); return true; } /* set visibility to "invisible", return error if view is null */ if (WikitudePlugin.ACTION_HIDE.equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (architectView != null) { architectView.setVisibility(View.INVISIBLE); callContext.success(action + ": architectView is present"); } else { callContext.error(action + ": architectView is not present"); } } }); return true; } /* define call-back for url-invocations */ if (WikitudePlugin.ACTION_ON_URLINVOKE.equals(action)) { this.urlInvokeCallback = callContext; final PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, action + ": registered callback"); result.setKeepCallback(true); callContext.sendPluginResult(result); return true; } /* location update */ if (WikitudePlugin.ACTION_SET_LOCATION.equals(action)) { if (this.architectView != null) { try { final double lat = args.getDouble(0); final double lon = args.getDouble(1); float alt = Float.MIN_VALUE; try { alt = (float) args.getDouble(2); } catch (Exception e) { // invalid altitude -> ignore it } final float altitude = alt; Double acc = null; try { acc = args.getDouble(3); } catch (Exception e) { // invalid accuracy -> ignore it } final Double accuracy = acc; if (this.cordova != null && this.cordova.getActivity() != null) { cordova.getActivity().runOnUiThread( // this.cordova.getThreadPool().execute( new Runnable() { @Override public void run() { if (accuracy != null) { WikitudePlugin.this.architectView.setLocation(lat, lon, altitude, accuracy.floatValue()); } else { WikitudePlugin.this.architectView.setLocation(lat, lon, altitude); } } }); } } catch (Exception e) { callContext.error( action + ": exception thrown, " + e != null ? e.getMessage() : "(exception is NULL)"); return true; } callContext.success(action + ": updated location"); return true; } else { /* return error if there is no architect-view active*/ callContext.error(action + ": architectView is not present"); } return true; } if (WikitudePlugin.ACTION_CALL_JAVASCRIPT.equals(action)) { String logMsg = null; try { final String callJS = args.getString(0); logMsg = callJS; this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (architectView != null) { WikitudePlugin.this.architectView.callJavascript(callJS); } else { callContext.error(action + ": architectView is not present"); } } }); } catch (JSONException je) { callContext.error( action + ": exception thrown, " + je != null ? je.getMessage() : "(exception is NULL)"); return true; } callContext.success(action + ": called js, '" + logMsg + "'"); return true; } /* initial set-up, show ArchitectView full-screen in current screen/activity */ if (WikitudePlugin.ACTION_OPEN.equals(action)) { this.openCallback = callContext; PluginResult result = null; try { final String apiKey = args.getString(0); final String filePath = args.getString(1); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { WikitudePlugin.this.addArchitectView(apiKey, filePath); /* call success method once architectView was added successfully */ if (openCallback != null) { PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); openCallback.sendPluginResult(result); } } catch (Exception e) { /* in case "addArchitectView" threw an exception -> notify callback method asynchronously */ openCallback.error(e != null ? e.getMessage() : "Exception is 'null'"); } } }); } catch (Exception e) { result = new PluginResult(PluginResult.Status.ERROR, action + ": exception thown, " + e != null ? e.getMessage() : "(exception is NULL)"); result.setKeepCallback(false); callContext.sendPluginResult(result); return true; } /* adding architect-view is done in separate thread, ensure to setKeepCallback so one can call success-method properly later on */ result = new PluginResult(PluginResult.Status.NO_RESULT, action + ": no result required, just registered callback-method"); result.setKeepCallback(true); callContext.sendPluginResult(result); return true; } /* fall-back return value */ callContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "no such action: " + action)); return false; }
From source file:com.kevinquan.android.utils.JSONUtils.java
/** * Retrieve a double stored at the provided index from the provided JSON array * @param obj The JSON array to retrieve from * @param index The index to retrieve the double from * @return the double stored at the index, or the default value if the index doesn't exist *//* ww w . ja v a 2s. c o m*/ public static double safeGetDoubleFromArray(JSONArray obj, int index, double defaultValue) { if (obj != null && obj.length() > index) { try { return obj.getDouble(index); } catch (JSONException e) { Log.w(TAG, "Could not get string from JSONArray from at index " + index, e); } } return defaultValue; }
From source file:com.doylestowncoder.plugin.mobileaccessibility.MobileAccessibility.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try {/*w ww . java 2 s .c o m*/ if (action.equals("isScreenReaderRunning")) { isScreenReaderRunning(callbackContext); return true; } else if (action.equals("isClosedCaptioningEnabled")) { isClosedCaptioningEnabled(callbackContext); return true; } else if (action.equals("isTouchExplorationEnabled")) { isTouchExplorationEnabled(callbackContext); return true; } else if (action.equals("postNotification")) { if (args.length() > 1) { String string = args.getString(1); if (!string.isEmpty()) { announceForAccessibility(string, callbackContext); } } return true; } else if (action.equals("getTextZoom")) { getTextZoom(callbackContext); return true; } else if (action.equals("setTextZoom")) { if (args.length() > 0) { double textZoom = args.getDouble(0); if (textZoom > 0) { setTextZoom(textZoom, callbackContext); } } return true; } else if (action.equals("updateTextZoom")) { updateTextZoom(callbackContext); return true; } else if (action.equals("start")) { start(callbackContext); return true; } else if (action.equals("stop")) { stop(); return true; } } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }