List of usage examples for org.json JSONArray getString
public String getString(int index) throws JSONException
From source file:de.kp.ames.web.core.json.JsonUtil.java
/** * A helper method to convert a JSON (String) array * into a String array/*from www . j ava 2 s .co m*/ * * @param jArray * @return * @throws JSONException */ public static ArrayList<String> getStringArray(JSONArray jArray) throws JSONException { /* * Convert JSON array into String representation */ ArrayList<String> array = new ArrayList<String>(); for (int i = 0; i < jArray.length(); i++) { array.add(jArray.getString(i)); } return array; }
From source file:com.connectsdk.cordova.ConnectSDKCordova.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try {/* w ww .j a v a 2 s . c o m*/ if ("sendCommand".equals(action)) { ConnectableDeviceWrapper deviceWrapper = getDeviceWrapper(args.getString(0)); String commandId = args.getString(1); String ifaceName = args.getString(2); String methodName = args.getString(3); JSONObject methodArgs = args.getJSONObject(4); boolean subscribe = args.getBoolean(5); deviceWrapper.sendCommand(commandId, ifaceName, methodName, methodArgs, subscribe, callbackContext); return true; } else if ("cancelCommand".equals(action)) { ConnectableDeviceWrapper deviceWrapper = getDeviceWrapper(args.getString(0)); String commandId = args.getString(1); deviceWrapper.cancelCommand(commandId); callbackContext.success(); return true; } else if ("startDiscovery".equals(action)) { startDiscovery(args, callbackContext); return true; } else if ("stopDiscovery".equals(action)) { stopDiscovery(args, callbackContext); return true; } else if ("setDiscoveryConfig".equals(action)) { setDiscoveryConfig(args, callbackContext); return true; } else if ("pickDevice".equals(action)) { pickDevice(args, callbackContext); return true; } else if ("setDeviceListener".equals(action)) { ConnectableDeviceWrapper deviceWrapper = getDeviceWrapper(args.getString(0)); deviceWrapper.setCallbackContext(callbackContext); return true; } else if ("connectDevice".equals(action)) { ConnectableDeviceWrapper deviceWrapper = getDeviceWrapper(args.getString(0)); deviceWrapper.setCallbackContext(callbackContext); deviceWrapper.connect(); return true; } else if ("disconnectDevice".equals(action)) { ConnectableDeviceWrapper deviceWrapper = getDeviceWrapper(args.getString(0)); deviceWrapper.disconnect(); return true; } else if ("acquireWrappedObject".equals(action)) { String objectId = args.getString(0); JSObjectWrapper wrapper = objectWrappers.get(objectId); if (wrapper != null) { wrapper.setCallbackContext(callbackContext); } return true; } else if ("releaseWrappedObject".equals(action)) { String objectId = args.getString(0); JSObjectWrapper wrapper = objectWrappers.get(objectId); if (wrapper != null) { wrapper.setCallbackContext(null); removeObjectWrapper(wrapper); } return true; } } catch (NoSuchDeviceException e) { callbackContext.error("no such device"); return true; } catch (JSONException e) { Log.d(LOG_TAG, "exception while handling " + action, e); callbackContext.error(e.toString()); return true; } Log.w(LOG_TAG, "no handler for exec action " + action); return false; }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.CiliaRestHelper.java
public static String[] getChainsList(PlatformID platformID) throws CiliaException { List<String> retval = new ArrayList<String>(); JSONObject js = string2json(HttpHelper.get(platformID, "/cilia")); try {/*w w w .j a va2s . c o m*/ JSONArray chains = js.getJSONArray("chains"); for (int i = 0; i < chains.length(); i++) retval.add(chains.getString(i)); } catch (JSONException e) { String message = "Error while parsing JSON message"; throw new CiliaException(message, e); } return retval.toArray(new String[0]); }
From source file:curt.android.result.supplement.BookResultInfoRetriever.java
@Override void retrieveSupplementalInfo() throws IOException, InterruptedException { String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON); if (contents.length() == 0) { return;/*from www. ja v a2 s .co m*/ } String title; String pages; Collection<String> authors = null; try { JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue(); JSONArray items = topLevel.optJSONArray("items"); if (items == null || items.isNull(0)) { return; } JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo"); if (volumeInfo == null) { return; } title = volumeInfo.optString("title"); pages = volumeInfo.optString("pageCount"); JSONArray authorsArray = volumeInfo.optJSONArray("authors"); if (authorsArray != null && !authorsArray.isNull(0)) { authors = new ArrayList<String>(); for (int i = 0; i < authorsArray.length(); i++) { authors.add(authorsArray.getString(i)); } } } catch (JSONException e) { throw new IOException(e.toString()); } Collection<String> newTexts = new ArrayList<String>(); if (title != null && title.length() > 0) { newTexts.add(title); } if (authors != null && !authors.isEmpty()) { boolean first = true; StringBuilder authorsText = new StringBuilder(); for (String author : authors) { if (first) { first = false; } else { authorsText.append(", "); } authorsText.append(author); } newTexts.add(authorsText.toString()); } if (pages != null && pages.length() > 0) { newTexts.add(pages + "pp."); } String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q="; append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn); }
From source file:de.dakror.virtualhub.data.Tags.java
public Tags(JSONArray arr) throws JSONException { for (int i = 0; i < arr.length(); i++) tags.add(arr.getString(i)); }
From source file:org.marietjedroid.connect.MarietjeMessenger.java
/** * Sends a request and handles the response * //from w ww . jav a 2 s. co m * @param list * @throws MarietjeException */ private void doRequest(List<JSONObject> list) throws MarietjeException { if (list != null) list = new ArrayList<JSONObject>(list); else list = new ArrayList<JSONObject>(); HttpClient httpClient = new DefaultHttpClient(); if (this.token == null) { throw new IllegalStateException("token is null"); } JSONArray json = new JSONArray(); json.put(token); for (JSONObject m : list) json.put(m); HttpGet hp = null; try { System.out.println("JSON: " + json.toString()); String url = String.format("http://%s:%s%s?m=%s", host, port, path, URLEncoder.encode(json.toString(), "UTF-8")); System.out.println("url: " + url); hp = new HttpGet(url); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StringBuilder sb = new StringBuilder(); try { HttpResponse r = httpClient.execute(hp); InputStreamReader is = new InputStreamReader(r.getEntity().getContent()); BufferedReader br = new BufferedReader(is); String line; while ((line = br.readLine()) != null) { System.out.println("response: " + line); sb.append(line); } } catch (IOException e) { MarietjeException tr = new MarietjeException("Connection stuk!" + e.getMessage()); this.exception = tr; throw tr; } JSONArray d = null; try { d = new JSONArray(new JSONTokener(sb.toString())); } catch (JSONException e) { throw (exception = new MarietjeException("Ja, JSON kapot!")); } if (d == null || d.length() != 3) throw (exception = new MarietjeException("Unexpected length of response list")); String token = null; JSONArray msgs = null; try { token = d.getString(0); msgs = d.getJSONArray(1); // JSONArray stream = d.getJSONArray(2); } catch (JSONException e) { throw (exception = new MarietjeException("unexpected format of response list")); } synchronized (this.outSemaphore) { String oldToken = this.token; this.token = token; if (oldToken == null) { this.outSemaphore.release(); } } for (int i = 0; i < msgs.length(); i++) { try { System.out.println("adding msg to queue"); synchronized (queueMessageIn) { this.queueMessageIn.add(msgs.getJSONObject(i)); } this.messageInSemaphore.release(); } catch (JSONException e) { System.err.println("ontvangen json kapot"); e.printStackTrace(); } } // TODO Streams left out. }
From source file:census.couchdroid.CouchDocument.java
/** * A list of the revision numbers that this document has. If this hasn't been * populated with a "full=true" query, then the database will be re-queried * @return/*from w ww . j a v a 2 s .c o m*/ */ public String[] getRevisions() throws IOException { String[] revs = null; if (!object.has("_revs")) { populateRevisions(); } //System.out.println(object); JSONArray ar = null; try { ar = object.getJSONObject(REVISION_HISTORY_PROP).getJSONArray("ids"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ar != null) { revs = new String[ar.length()]; for (int i = 0; i < ar.length(); i++) { try { revs[i] = ar.getString(i); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return revs; }
From source file:com.adobe.phonegap.contentsync.Sync.java
@Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("sync")) { sync(args, callbackContext);//from w w w . ja va 2 s .c om return true; } else if (action.equals("download")) { final String source = args.getString(0); // Production String outputDirectory = cordova.getActivity().getCacheDir().getAbsolutePath(); // Testing //String outputDirectory = cordova.getActivity().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); String filename = source.substring(source.lastIndexOf("/") + 1, source.length()); final File target = new File(outputDirectory, filename); // @TODO we need these final JSONObject headers = new JSONObject(); final CallbackContext finalContext = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { if (download(source, target, headers, createProgressEvent("download"), finalContext, false)) { JSONObject retval = new JSONObject(); try { retval.put("archiveURL", target.getAbsolutePath()); } catch (JSONException e) { // never happens } finalContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, retval)); } } }); return true; } else if (action.equals("unzip")) { String tempPath = args.getString(0); if (tempPath.startsWith("file://")) { tempPath = tempPath.substring(7); } final File source = new File(tempPath); final String target = args.getString(1); final CallbackContext finalContext = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { unzipSync(source, target, createProgressEvent("unzip"), finalContext); finalContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } }); return true; } else if (action.equals("cancel")) { ProgressEvent progress = activeRequests.get(args.getString(0)); if (progress != null) { progress.setAborted(true); } } return false; }
From source file:com.adobe.phonegap.contentsync.Sync.java
private void sync(final JSONArray args, final CallbackContext callbackContext) throws JSONException { // get args/*w ww. ja va2s. co m*/ final String src = args.getString(0); final String id = args.getString(1); final JSONObject headers; if (args.optJSONObject(3) != null) { headers = args.optJSONObject(3); } else { headers = new JSONObject(); } final boolean copyCordovaAssets; final boolean copyRootApp = args.getBoolean(5); final boolean trustEveryone = args.getBoolean(7); if (copyRootApp) { copyCordovaAssets = true; } else { copyCordovaAssets = args.getBoolean(4); } final String manifestFile = args.getString(8); Log.d(LOG_TAG, "sync called with id = " + id + " and src = " + src + "!"); final ProgressEvent progress = createProgressEvent(id); /** * need to clear cache or Android won't pick up on the replaced * content */ cordova.getActivity().runOnUiThread(new Runnable() { public void run() { webView.clearCache(true); } }); cordova.getThreadPool().execute(new Runnable() { public void run() { synchronized (progress) { if (progress.isAborted()) { return; } } String outputDirectory = getOutputDirectory(id); // Check to see if we should just return the cached version String type = args.optString(2, TYPE_REPLACE); Log.d(LOG_TAG, "type = " + type); File dir = new File(outputDirectory); Log.d(LOG_TAG, "dir = " + dir.exists()); if (type.equals(TYPE_LOCAL) && !dir.exists()) { if ("null".equals(src) && (copyRootApp || copyCordovaAssets)) { if (copyRootApp) { copyRootApp(outputDirectory, manifestFile); } if (copyCordovaAssets) { copyCordovaAssets(outputDirectory); } } else { type = TYPE_REPLACE; } } if (!dir.exists()) { dir.mkdirs(); } if (!type.equals(TYPE_LOCAL)) { // download file if (download(src, createDownloadFileLocation(id), headers, progress, callbackContext, trustEveryone)) { // update progress with zip file File targetFile = progress.getTargetFile(); Log.d(LOG_TAG, "downloaded = " + targetFile.getAbsolutePath()); // Backup existing directory File backup = backupExistingDirectory(outputDirectory, type, dir); // @TODO: Do we do this even when type is local? if (copyRootApp) { copyRootApp(outputDirectory, manifestFile); } boolean win = false; if (isZipFile(targetFile)) { win = unzipSync(targetFile, outputDirectory, progress, callbackContext); } else { // copy file to ID win = targetFile.renameTo(new File(outputDirectory)); progress.setLoaded(1); progress.setTotal(1); progress.setStatus(STATUS_EXTRACTING); progress.updatePercentage(); } // delete temp file targetFile.delete(); if (copyCordovaAssets) { copyCordovaAssets(outputDirectory); } if (win) { // success, remove backup removeFolder(backup); } else { // failure, revert backup removeFolder(dir); backup.renameTo(dir); } } else { return; } } // complete synchronized (activeRequests) { activeRequests.remove(id); } // Send last progress event progress.setStatus(STATUS_COMPLETE); updateProgress(callbackContext, progress); // Send completion message try { JSONObject result = new JSONObject(); result.put(PROP_LOCAL_PATH, outputDirectory); result.put(PROP_CACHED, type.equals(TYPE_LOCAL)); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result)); } catch (JSONException e) { // never happens } } }); }
From source file:com.adobe.phonegap.contentsync.Sync.java
private void copyRootAppByManifest(String outputDirectory, String manifestFile, boolean wwwExists) throws IOException, JSONException { File fp = new File(outputDirectory); if (!fp.exists()) { fp.mkdirs();//w w w. j av a2 s. c o m } InputStream is = cordova.getActivity().getAssets().open("www/" + manifestFile); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); JSONObject obj = new JSONObject(new String(buffer, "UTF-8")); JSONArray files = obj.getJSONArray("files"); for (int i = 0; i < files.length(); i++) { Log.d(LOG_TAG, "file = " + files.getString(i)); copyAssetFile(outputDirectory, "www/" + files.getString(i), wwwExists); } }