List of usage examples for org.json JSONArray toString
public String toString()
From source file:com.phonegap.DroidGap.java
/** * Load the url into the webview./*from w w w . j a v a2 s .c o m*/ * * @param url */ public void loadUrl(final String url) { System.out.println("loadUrl(" + url + ")"); this.url = url; int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i); } else { this.baseUrl = this.url; } System.out.println("url=" + url + " baseUrl=" + baseUrl); mydialog = ProgressDialog.show(this, "su...", "Loading", true); // Load URL on UI thread final DroidGap me = this; this.runOnUiThread(new Runnable() { public void run() { // Handle activity parameters me.handleActivityParameters(); // Initialize callback server me.callbackServer.init(url); // If loadingDialog, then show the App loading dialog String loading = me.getStringProperty("loadingDialog", null); if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma + 1); } else { title = ""; message = loading; } } JSONArray parm = new JSONArray(); parm.put(title); parm.put(message); me.pluginManager.exec("Notification", "activityStart", null, parm.toString(), false); } // Create a timeout timer for loadUrl final int currentLoadUrlTimeout = me.loadUrlTimeout; Runnable runnable = new Runnable() { public void run() { try { synchronized (this) { wait(me.loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.appView.stopLoading(); me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url); } } }; Thread thread = new Thread(runnable); thread.start(); me.appView.loadUrl(url); } }); }
From source file:com.imos.sample.pi.PythonTemperatureSensor.java
public void pythonTemperatureSensor() { try {// w w w .j a v a 2 s . c om String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4"; int count = 0; JSONArray array = new JSONArray(); int dayOfMonth = 0; cal.setTime(new Date()); dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); while (true) { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line); } String result = output.toString(), tempStr; double temp, humid; if (result != null && !result.trim().isEmpty()) { tempStr = result.substring(result.indexOf("Humid")); result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1); temp = Double.parseDouble(result); result = tempStr; result = result.substring(result.indexOf("=") + 1, result.indexOf("%")); humid = Double.parseDouble(result); JSONObject data = new JSONObject(); data.put("temp", temp); data.put("humid", humid); data.put("time", new Date().getTime()); array.put(data); } Thread.sleep(60000); count++; if (count == 60) { cal.setTime(new Date()); StringBuilder builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); builder.append("-"); builder.append(cal.get(Calendar.HOUR_OF_DAY)); builder.append("_"); builder.append(cal.get(Calendar.MINUTE)); String name = builder.toString(); Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name); try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) { writer.append(array.toString()); } catch (IOException ex) { } System.out.println(builder.toString()); count = 0; array = new JSONArray(); if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) { builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); String dirName = builder.toString(); File newDir = new File("./" + dirName); newDir.mkdir(); File files = new File("./"); for (File file : files.listFiles()) { if (file.getName().endsWith(".json")) { file.renameTo(new File("./" + dirName + File.separator + file.getName())); } } dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); } } } } catch (IOException | InterruptedException ex) { Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.mirasense.scanditsdk.plugin.FullScreenPickerActivity.java
private Bundle bundleForScanResult(ScanSession session) { Bundle bundle = new Bundle(); if (mLegacyMode) { Barcode code = session.getNewlyRecognizedCodes().get(0); bundle.putString("barcode", code.getData()); bundle.putString("symbology", Code.symbologyToString(code.getSymbology(), code.isGs1DataCarrier())); return bundle; }//from w w w .ja v a2 s .c om JSONArray eventArgs = Marshal.createEventArgs(ScanditSDK.DID_SCAN_EVENT, ResultRelay.jsonForSession(session)); bundle.putString("jsonString", eventArgs.toString()); return bundle; }
From source file:com.mirasense.scanditsdk.plugin.FullScreenPickerActivity.java
private Bundle manualSearchResultsToBundle(String entry) { Bundle bundle = new Bundle(); if (mLegacyMode) { bundle.putString("barcode", entry.trim()); bundle.putString("symbology", "UNKNOWN"); } else {/*from w w w.ja v a2s . co m*/ JSONArray args = Marshal.createEventArgs(ScanditSDK.DID_MANUAL_SEARCH_EVENT, entry); bundle.putString("jsonString", args.toString()); } // no need to wait for result bundle.putBoolean("waitForResult", false); return bundle; }
From source file:com.mirasense.scanditsdk.plugin.FullScreenPickerActivity.java
@Override public void pickerEnteredState(BarcodePickerWithSearchBar picker, int newState) { // don't produce events in legacy mode. They would be interpreted as scan events. if (mLegacyMode) return;/*from w w w . j av a 2 s.com*/ Bundle resultBundle = new Bundle(); JSONArray didStopArgs = Marshal.createEventArgs(ScanditSDK.DID_CHANGE_STATE_EVENT, newState); resultBundle.putString("jsonString", didStopArgs.toString()); resultBundle.putBoolean("waitForResult", false); ResultRelay.relayResult(resultBundle); }
From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertAllData(String data) { JSONObject jsonArray = null;//from www .j a va 2 s.c o m JSONArray weatherArray = null; JSONArray surfArray = null; try { jsonArray = new JSONObject(data); weatherArray = jsonArray.getJSONArray("weather"); surfArray = jsonArray.getJSONArray("surf"); } catch (Exception e) { System.err.println("couldn't parse JSON"); return false; } SQLiteDatabase db = this.getWritableDatabase(); int err_count = 0; /* Insert weather data */ db.beginTransaction(); Boolean weatherSuccess = insertWeatherData(weatherArray.toString(), db); if (!weatherSuccess) { err_count++; System.err.println("Error storing weather"); db.endTransaction(); } else { db.setTransactionSuccessful(); db.endTransaction(); } /* Insert surf data - using transactions to help performance */ db.beginTransaction(); Boolean surfSuccess = insertSurfData(surfArray.toString(), db); if (!surfSuccess) { err_count++; System.err.println("Error storing surf"); db.endTransaction(); } else { db.setTransactionSuccessful(); db.endTransaction(); } if (err_count > 0) { db.endTransaction(); return false; } return true; }
From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java
private String[] jsonArrayToStringArray(JSONArray jsonArray) { return jsonArray.toString().substring(1, jsonArray.toString().length() - 1).replaceAll("\"", "").split(","); }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
public ICalTask(ActionManager actionManager, String providerId, JSONObject json) { this.actionManager = actionManager; this.providerId = providerId; this.event = new VEvent(); String id;/*from w ww .ja va2 s. c om*/ if (json.has("id")) { id = json.getString("id"); } else { id = UUID.randomUUID().toString(); } event.getProperties().add(new Uid(id)); event.getProperties().add(new Summary(json.getString("name"))); try { if (json.has("conditions")) { JSONArray conditions = json.getJSONArray("conditions"); if (conditions.length() == 1) { JSONObject jc = conditions.getJSONObject(0); if (jc.has("start") && !jc.isNull("start")) { event.getProperties().add(new DtStart(jc.getString("start"))); } if (jc.has("recurrence") && !jc.isNull("recurrence")) { event.getProperties().add(new RRule(jc.getString("recurrence"))); } if (jc.has("sunOffset") && !jc.isNull("sunOffset")) { event.getProperties().add(new XProperty(PROP_SUN_OFFSET, jc.getString("sunOffset"))); } } else { throw new HobsonRuntimeException("ICalTasks only support one condition"); } } } catch (ParseException e) { throw new HobsonRuntimeException("Error parsing recurrence rule", e); } try { if (json.has("actions")) { JSONArray actions = json.getJSONArray("actions"); event.getProperties().add(new Comment(actions.toString())); for (int i = 0; i < actions.length(); i++) { addActionRef(actions.getJSONObject(i)); } } } catch (Exception e) { throw new HobsonRuntimeException("Error parsing actions", e); } }
From source file:com.phonegap.Storage.java
/** * Process query results.// w w w. j a v a 2 s . co m * * @param cur Cursor into query results * @param tx_id Transaction id */ public void processResults(Cursor cur, String tx_id) { String result = "[]"; // If query result has rows if (cur.moveToFirst()) { JSONArray fullresult = new JSONArray(); String key = ""; String value = ""; int colCount = cur.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = cur.getColumnName(i); value = cur.getString(i); row.put(key, value); } fullresult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (cur.moveToNext()); result = fullresult.toString(); } // Let JavaScript know that there are no more rows this.sendJavascript("droiddb.completeQuery('" + tx_id + "', " + result + ");"); }
From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java
private WebViewClient createWebViewClientThatHandlesFileLinksForCharts() { WebViewClient webViewClient = new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url);//from ww w . ja va2s . c o m if (uri.getScheme().startsWith("http")) { return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues. } String inputIdStr = uri.getQueryParameter("inputId"); if (inputIdStr == null) { return true; } long inputId = Long.parseLong(inputIdStr); JSONArray results = new JSONArray(); for (Event event : experiment.getEvents()) { JSONArray eventJson = new JSONArray(); DateTime responseTime = event.getResponseTime(); if (responseTime == null) { continue; // missed signal; } eventJson.put(responseTime.getMillis()); // in this case we are looking for one input from the responses that we are charting. for (Output response : event.getResponses()) { if (response.getInputServerId() == inputId) { Input inputById = experiment.getInputById(inputId); if (!inputById.isInvisible() && inputById.isNumeric()) { eventJson.put(response.getDisplayOfAnswer(inputById)); results.put(eventJson); continue; } } } } env.put("data", results.toString()); env.put("inputId", inputIdStr); view.loadUrl(stripQuery(url)); return true; } }; return webViewClient; }