List of usage examples for org.json JSONArray getString
public String getString(int index) throws JSONException
From source file:fr.pasteque.pos.customers.DataLogicCustomers.java
private List<String> loadTopCustomers() throws BasicException { try {//from w ww . j a v a2s . com ServerLoader loader = new ServerLoader(); ServerLoader.Response r = loader.read("CustomersAPI", "getTop"); if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) { List<String> data = new ArrayList<String>(); JSONArray a = r.getArrayContent(); for (int i = 0; i < a.length(); i++) { data.add(a.getString(i)); } return data; } } catch (Exception e) { throw new BasicException(e); } return null; }
From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java
/****************************************************************************************************************** * ALERT DIALOG//from w ww . j av a 2 s. c o m *****************************************************************************************************************/ private void showAlertDialog(JSONObject data, final String callback) { try { String title = data.optString(Cobalt.kJSAlertTitle); String message = data.optString(Cobalt.kJSMessage); boolean cancelable = data.optBoolean(Cobalt.kJSAlertCancelable, false); JSONArray buttons = data.has(Cobalt.kJSAlertButtons) ? data.getJSONArray(Cobalt.kJSAlertButtons) : new JSONArray(); AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle(title).setMessage(message) .create(); alertDialog.setCancelable(cancelable); if (buttons.length() == 0) { alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callback != null) { try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAlertButtonIndex, 0); sendCallback(callback, data); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException"); exception.printStackTrace(); } } } }); } else { int buttonsLength = Math.min(buttons.length(), 3); for (int i = 0; i < buttonsLength; i++) { int buttonId; switch (i) { case 0: default: buttonId = DialogInterface.BUTTON_NEGATIVE; break; case 1: buttonId = DialogInterface.BUTTON_NEUTRAL; break; case 2: buttonId = DialogInterface.BUTTON_POSITIVE; break; } alertDialog.setButton(buttonId, buttons.getString(i), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callback != null) { int buttonIndex; switch (which) { case DialogInterface.BUTTON_NEGATIVE: default: buttonIndex = 0; break; case DialogInterface.BUTTON_NEUTRAL: buttonIndex = 1; break; case DialogInterface.BUTTON_POSITIVE: buttonIndex = 2; break; } try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAlertButtonIndex, buttonIndex); sendCallback(callback, data); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException"); exception.printStackTrace(); } } } }); } } alertDialog.show(); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - showAlertDialog: JSONException"); exception.printStackTrace(); } }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "executing action: " + action); if (action.equals("abort")) { String objectId = args.getString(0); abort(objectId);//from w w w . ja v a2 s .c o m callbackContext.success(); return true; } else if (action.equals("upload")) { String source = args.getString(0); String target = args.getString(1); upload(source, target, args, callbackContext); return true; } return false; }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { try {//from www .j a v a2s . c om for (Iterator<?> iter = headers.keys(); iter.hasNext();) { String headerKey = iter.next().toString(); JSONArray headerValues = headers.optJSONArray(headerKey); if (headerValues == null) { headerValues = new JSONArray(); headerValues.put(headers.getString(headerKey)); } connection.setRequestProperty(headerKey, headerValues.getString(0)); for (int i = 1; i < headerValues.length(); ++i) { connection.addRequestProperty(headerKey, headerValues.getString(i)); } } } catch (JSONException e1) { // No headers to be manipulated! } }
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * @param callbackContext callback id for optional progress reports * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request *///from w w w. java2 s.c o m private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "upload " + source + " to " + target); // Setup the options final String mimeType = getArgument(args, 4, "image/jpeg"); final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); final boolean trustEveryone = args.optBoolean(6); // Always use chunked mode unless set to false as per API final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); // Look for headers on the params map for backwards compatibility with older Cordova versions. final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); final String objectId = args.getString(9); final String httpMethod = getArgument(args, 10, "POST"); final CordovaResourceApi resourceApi = webView.getResourceApi(); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); Log.d(LOG_TAG, "headers: " + headers); Log.d(LOG_TAG, "objectId: " + objectId); Log.d(LOG_TAG, "httpMethod: " + httpMethod); final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); // Accept a path or a URI for the source. Uri tmpSrc = Uri.parse(source); final Uri sourceUri = resourceApi .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); int uriType = CordovaResourceApi.getUriType(targetUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection conn = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; int totalBytes = 0; int fixedLength = -1; try { // Create return object PSFileUploadResult result = new PSFileUploadResult(); PSFileProgressResult progress = new PSFileProgressResult(); //------------------ CLIENT REQUEST // Open a HTTP connection to the URL based on protocol conn = resourceApi.createHttpConnection(targetUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) conn; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod(httpMethod); conn.setRequestProperty("Content-Type", mimeType); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); if (readResult.length >= 0) { fixedLength = (int) readResult.length; progress.setLengthComputable(true); progress.setTotal(fixedLength); } Log.d(LOG_TAG, "Content Length: " + fixedLength); // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. // http://code.google.com/p/android/issues/detail?id=3164 // It also causes OOM if HTTPS is used, even on newer devices. boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); useChunkedMode = useChunkedMode || (fixedLength == -1); if (useChunkedMode) { conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); // Although setChunkedStreamingMode sets this header, setting it explicitly here works // around an OutOfMemoryException when using https. conn.setRequestProperty("Transfer-Encoding", "chunked"); } else { conn.setFixedLengthStreamingMode(fixedLength); } conn.connect(); OutputStream sendStream = null; try { sendStream = conn.getOutputStream(); synchronized (context) { if (context.aborted) { return; } context.currentOutputStream = sendStream; } //We don't want to change encoding, we just want this to write for all Unicode. // create a buffer of maximum size int bytesAvailable = readResult.inputStream.available(); int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); long prevBytesRead = 0; while (bytesRead > 0) { result.setBytesSent(totalBytes); sendStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (totalBytes > prevBytesRead + 102400) { prevBytesRead = totalBytes; Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); } bytesAvailable = readResult.inputStream.available(); bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); // Send a progress event. progress.setLoaded(totalBytes); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } context.currentOutputStream = null; Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); //------------------ read the SERVER RESPONSE String responseString; int responseCode = conn.getResponseCode(); Log.d(LOG_TAG, "response code: " + responseCode); Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); TrackingInputStream inStream = null; try { inStream = getInputStream(conn); synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inStream; } ByteArrayOutputStream out = new ByteArrayOutputStream( Math.max(1024, conn.getContentLength())); byte[] buffer = new byte[1024]; int bytesRead = 0; // write bytes to file while ((bytesRead = inStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } responseString = out.toString("UTF-8"); } finally { context.currentInputStream = null; safeClose(inStream); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); // send request and retrieve response result.setResponseCode(responseCode); result.setResponse(responseString); context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), t); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (conn != null) { // Revert back to the proper verifier and socket factories // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) conn; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } } }); }
From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java
/** * Called when JS sends the message./* ww w . ja va2s .c o m*/ * * @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<String> getModels() { try {/*from w w w. j a v a2 s .c om*/ List<String> models = new ArrayList<String>(); NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(NgramServiceApiUrls.LOOKUP_URL); String apiUrl = urlBuilder.buildUrl(); JSONArray array = new JSONArray(convertStreamToString(callApiGet(apiUrl))); for (int i = 0; i < array.length(); i++) { models.add(array.getString(i)); } return models; } catch (Exception e) { throw new NgramServiceException("An error occurred while getting models.", e); } }
From source file:com.dubsar_dictionary.Dubsar.model.Sense.java
@Override public void parseData(Object jsonResponse) throws JSONException { JSONArray response = (JSONArray) jsonResponse; JSONArray _word = response.getJSONArray(1); JSONArray _synset = response.getJSONArray(2); int wordId = _word.getInt(0); String wordName = _word.getString(1); String wordPos = _word.getString(2); int synsetId = _synset.getInt(0); mGloss = new String(_synset.getString(1)); setPos(wordPos);//w w w.java2s. com mWord = new Word(wordId, wordName, getPartOfSpeech()); mName = new String(wordName); mSynset = new Synset(synsetId, mGloss, getPartOfSpeech()); mIsWeakWordReference = mIsWeakSynsetReference = false; mWordReference = null; mSynsetReference = null; setLexname(response.getString(3)); getSynset().setLexname(getLexname()); if (!response.isNull(4)) { setMarker(response.getString(4)); } setFreqCnt(response.getInt(5)); JSONArray _synonyms = response.getJSONArray(6); mSynonyms = new ArrayList<Sense>(_synonyms.length()); int j; int senseId; String senseName; for (j = 0; j < _synonyms.length(); ++j) { JSONArray _synonym = _synonyms.getJSONArray(j); senseId = _synonym.getInt(0); senseName = _synonym.getString(1); String marker = null; if (!_synonym.isNull(2)) { marker = _synonym.getString(2); } int freqCnt = _synonym.getInt(3); Sense synonym = new Sense(senseId, senseName, getSynset()); synonym.setMarker(marker); synonym.setFreqCnt(freqCnt); mSynonyms.add(synonym); } JSONArray _verbFrames = response.getJSONArray(7); mVerbFrames = new ArrayList<String>(_verbFrames.length()); for (j = 0; j < _verbFrames.length(); ++j) { String frame = _verbFrames.getString(j); // Replace %s in verb frames with the name of the word // TODO: Make that a bold span. StringBuffer buffer = new StringBuffer(); Formatter formatter = new Formatter(buffer); formatter.format(frame, new Object[] { getName() }); formatter.close(); mVerbFrames.add(buffer.toString()); } JSONArray _samples = response.getJSONArray(8); mSamples = new ArrayList<String>(_samples.length()); for (j = 0; j < _samples.length(); ++j) { mSamples.add(_samples.getString(j)); } parsePointers(response.getJSONArray(9)); }
From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java
private void downloadDatabase(DownloadItem di) throws Exception { String url = di.getAddress(); String jsonString = downloadJSONString(url); JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonDataArray = jsonObject.getJSONArray("data"); List<Item> itemList = new LinkedList<Item>(); for (int i = 0; i < jsonDataArray.length(); i++) { JSONArray jsonItemArray = jsonDataArray.getJSONArray(i); String question = jsonItemArray.getString(0); String answer = jsonItemArray.getString(1); if (question != null && !question.equals("")) { Item item = new Item(); item.setQuestion(question);/*from ww w. ja v a2 s .com*/ item.setAnswer(answer); item.setId(i + 1); itemList.add(item); } } String dbname = di.getTitle() + ".db"; String dbpath = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_dir); DatabaseHelper.createEmptyDatabase(dbpath, dbname); DatabaseHelper dbHelper = new DatabaseHelper(this, dbpath, dbname); dbHelper.insertListItems(itemList); dbHelper.close(); }
From source file:run.ace.IncomingMessages.java
public static Object create(JSONArray message, Activity activity) throws JSONException { String fullTypeName = message.getString(2); Class c = null;//www.j ava2 s . c o m Object instance = null; try { c = Class.forName(fullTypeName); } catch (ClassNotFoundException e) { throw new RuntimeException("Unable to find a class named '" + fullTypeName + "'"); } if (message.length() == 4) { // Parameterized constructor JSONArray constructorArgs = message.getJSONArray(3); Object[] args = Utils.convertJSONArrayToArray(constructorArgs); instance = Utils.invokeConstructorWithBestParameterMatch(c, args); } else { // Default constructor try { // Expect the Context constructor try { instance = c.getConstructor(new Class[] { Context.class }).newInstance(activity); } catch (NoSuchMethodException ex) { // Try the default constructor instead instance = c.getConstructor().newInstance(); } } catch (NoSuchMethodException ex) { throw new RuntimeException(fullTypeName + " does not have a public default constructor, or a public constructor with a single Context parameter"); } catch (InvocationTargetException ex) { throw new RuntimeException( "Error in " + fullTypeName + " constructor: " + ex.getTargetException().toString()); } catch (IllegalAccessException ex) { throw new RuntimeException(fullTypeName + ", or its relevant constructor, isn't public"); } catch (InstantiationException ex) { throw new RuntimeException("Error instantiating " + fullTypeName + ": " + ex.toString()); } } return instance; }