List of usage examples for org.json JSONArray getString
public String getString(int index) throws JSONException
From source file:com.pansapiens.occyd.JSONdecoder.java
/** * Abstract utility class for parsing JSON objects (as strings) and * returning Java objects./* w w w .j a va 2 s .c o m*/ */ 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:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java
/** * Converts a JSON array to from the JSON server response. * /*w w w . j a v a2s. c om*/ * @param columns * The number of columns. * @param rows * The number of rows. * @param dataArray * the input data. * * @return the body content */ private String[][] convertArray(int rows, int columns, JSONArray dataArray) { String[][] resultTable = new String[rows][]; for (int i = 0; i < rows; i++) { JSONArray arr = dataArray.getJSONArray(i); List<String> list = new ArrayList<String>(); if (arr.length() < columns) { throw new ArrayStoreException(i18n.getString("jsonUtil.dataColumnError")); } for (int j = 0; j < columns; j++) { list.add(arr.isNull(j) ? "" : arr.getString(j)); } resultTable[i] = list.toArray(new String[columns]); } return resultTable; }
From source file:fr.pasteque.client.sync.SendProcess.java
private boolean parseCustomer(JSONObject resp) { try {/*from w w w . j a v a2 s. c o m*/ // Were customers properly send ? JSONObject o = resp.getJSONObject("content"); JSONArray ids = o.getJSONArray("saved"); int createdCustomerSize = Data.Customer.createdCustomers.size(); for (int i = 0; i < createdCustomerSize; i++) { String tmpId = Data.Customer.createdCustomers.get(i).getId(); String serverId = ids.getString(i); if (tmpId == null) continue; // Should never happen. // Updating local info for (Customer c : Data.Customer.customers) { if (c.getId().equals(tmpId)) { c.setId(serverId); break; } } for (Ticket t : Data.Session.currentSession(this.ctx).getTickets()) { Customer c = t.getCustomer(); if (c != null && c.getId().equals(tmpId)) { c.setId(serverId); } } for (Receipt r : Data.Receipt.getReceipts(this.ctx)) { Customer c = r.getTicket().getCustomer(); if (c != null && c.getId().equals(tmpId)) { c.setId(serverId); } } Data.Customer.resolvedIds.put(tmpId, serverId); } // Sending Customer completed Data.Customer.createdCustomers.clear(); Data.Customer.save(this.ctx); Data.Session.save(this.ctx); Data.Receipt.save(this.ctx); Log.i(LOG_TAG, "Customer Sync: Saved new local customer ids"); this.sendCustomer = false; this.subprogress = 0; SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE); instance.nextArchive(); return true; } catch (JSONException e) { // Customer not send properly. Log.i(LOG_TAG, "Error while parsing customer result", e); SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED); } catch (IOError e) { Log.i(LOG_TAG, "Could not save customer data in parse customer", e); SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED); } return false; }
From source file:com.cranberrygame.cordova.plugin.ad.admob.Plugin.java
private void setLicenseKey(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { final String email = args.getString(0); final String licenseKey = args.getString(1); Log.d(LOG_TAG, String.format("%s", email)); Log.d(LOG_TAG, String.format("%s", licenseKey)); cordova.getActivity().runOnUiThread(new Runnable() { @Override/*w w w . j a v a2 s. co m*/ public void run() { _setLicenseKey(email, licenseKey); } }); }
From source file:com.cranberrygame.cordova.plugin.ad.admob.Plugin.java
private void setUp(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { //Activity activity=cordova.getActivity(); //webView//from w w w .j a va2 s .c om //args.length() //args.getString(0) //args.getString(1) //args.getInt(0) //args.getInt(1) //args.getBoolean(0) //args.getBoolean(1) //JSONObject json = args.optJSONObject(0); //json.optString("bannerAdUnit") //json.optString("interstitialAdUnit") //JSONObject inJson = json.optJSONObject("inJson"); //final String bannerAdUnit = args.getString(0); //final String interstitialAdUnit = args.getString(1); //final boolean isOverlap = args.getBoolean(2); //final boolean isTest = args.getBoolean(3); //final String[] zoneIds = new String[args.getJSONArray(4).length()]; //for (int i = 0; i < args.getJSONArray(4).length(); i++) { // zoneIds[i] = args.getJSONArray(4).getString(i); //} //Log.d(LOG_TAG, String.format("%s", bannerAdUnit)); //Log.d(LOG_TAG, String.format("%s", interstitialAdUnit)); //Log.d(LOG_TAG, String.format("%b", isOverlap)); //Log.d(LOG_TAG, String.format("%b", isTest)); final String bannerAdUnit = args.getString(0); final String interstitialAdUnit = args.getString(1); final String rewardedVideoAdUnit = args.getString(2); final boolean isOverlap = args.getBoolean(3); final boolean isTest = args.getBoolean(4); Log.d(LOG_TAG, String.format("%s", bannerAdUnit)); Log.d(LOG_TAG, String.format("%s", interstitialAdUnit)); Log.d(LOG_TAG, String.format("%s", rewardedVideoAdUnit)); Log.d(LOG_TAG, String.format("%b", isOverlap)); Log.d(LOG_TAG, String.format("%b", isTest)); callbackContextKeepCallback = callbackContext; if (isOverlap) pluginDelegate = new AdMobOverlap(this); else pluginDelegate = new AdMobSplit(this); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { _setUp(bannerAdUnit, interstitialAdUnit, rewardedVideoAdUnit, isOverlap, isTest); } }); }
From source file:com.cranberrygame.cordova.plugin.ad.admob.Plugin.java
private void showBannerAd(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { final String position = args.getString(0); final String size = args.getString(1); Log.d(LOG_TAG, String.format("%s", position)); Log.d(LOG_TAG, String.format("%s", size)); cordova.getActivity().runOnUiThread(new Runnable() { @Override/* w w w. j a v a 2s. co m*/ public void run() { _showBannerAd(position, size); } }); }
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/* w ww. j a v a 2 s . 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.ichi2.anki2.DeckOptions.java
public static String getSteps(JSONArray a) { StringBuilder sb = new StringBuilder(); try {//from w w w .jav a 2 s . c o m for (int i = 0; i < a.length(); i++) { sb.append(a.getString(i)).append(" "); } } catch (JSONException e) { throw new RuntimeException(e); } return sb.toString().trim(); }
From source file:de.btobastian.javacord.utils.handler.message.MessageBulkDeleteHandler.java
@Override public void handle(JSONObject packet) { JSONArray messageIds = packet.getJSONArray("ids"); for (int i = 0; i < messageIds.length(); i++) { String messageId = messageIds.getString(i); final Message message = api.getMessageById(messageId); if (message == null) { return; // no cached version available }//from w w w. j a va 2s . c om listenerExecutorService.submit(new Runnable() { @Override public void run() { List<MessageDeleteListener> listeners = api.getListeners(MessageDeleteListener.class); synchronized (listeners) { for (MessageDeleteListener listener : listeners) { try { listener.onMessageDelete(api, message); } catch (Throwable t) { logger.warn("Uncaught exception in MessageDeleteListener!", t); } } } } }); } }
From source file:widgets.Graphical_List.java
@SuppressLint("HandlerLeak") public Graphical_List(tracerengine Trac, Activity context, int id, int dev_id, String name, String type, String address, final String state_key, String url, final String usage, int period, int update, int widgetSize, int session_type, final String parameters, String model_id, int place_id, String place_type, SharedPreferences params) { super(context, Trac, id, name, "", usage, widgetSize, session_type, place_id, place_type, mytag, container); this.Tracer = Trac; this.context = context; this.dev_id = dev_id; this.id = id; this.usage = usage; this.address = address; //this.type = type; this.state_key = state_key; this.update = update; this.wname = name; this.url = url; String[] model = model_id.split("\\."); this.type = model[0]; this.place_id = place_id; this.place_type = place_type; this.params = params; packageName = context.getPackageName(); this.myself = this; this.session_type = session_type; this.parameters = parameters; setOnLongClickListener(this); setOnClickListener(this); mytag = "Graphical_List (" + dev_id + ")"; login = params.getString("http_auth_username", null); password = params.getString("http_auth_password", null); //state key//from w w w . ja v a 2 s. c o m state_key_view = new TextView(context); state_key_view.setText(state_key); state_key_view.setTextColor(Color.parseColor("#333333")); //value value = new TextView(context); value.setTextSize(28); value.setTextColor(Color.BLACK); animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(1000); if (with_list) { //Exploit parameters JSONObject jparam = null; String command; JSONArray commandValues = null; try { jparam = new JSONObject(parameters.replaceAll(""", "\"")); command = jparam.getString("command"); commandValues = jparam.getJSONArray("commandValues"); Tracer.e(mytag, "Json command :" + commandValues); } catch (Exception e) { command = ""; commandValues = null; Tracer.e(mytag, "Json command error " + e.toString()); } if (commandValues != null) { if (commandValues.length() > 0) { if (known_values != null) known_values = null; known_values = new String[commandValues.length()]; for (int i = 0; i < commandValues.length(); i++) { try { known_values[i] = commandValues.getString(i); } catch (Exception e) { known_values[i] = "???"; } } } } //list of choices listeChoices = new ListView(context); listItem = new ArrayList<HashMap<String, String>>(); list_usable_choices = new Vector<String>(); for (int i = 0; i < known_values.length; i++) { list_usable_choices.add(getStringResourceByName(known_values[i])); HashMap<String, String> map = new HashMap<String, String>(); map.put("choice", getStringResourceByName(known_values[i])); map.put("cmd_to_send", known_values[i]); listItem.add(map); } SimpleAdapter adapter_map = new SimpleAdapter(getContext(), listItem, R.layout.item_choice, new String[] { "choice", "cmd_to_send" }, new int[] { R.id.choice, R.id.cmd_to_send }); listeChoices.setAdapter(adapter_map); listeChoices.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if ((position < listItem.size()) && (position > -1)) { //process selected command HashMap<String, String> map = new HashMap<String, String>(); map = listItem.get(position); cmd_requested = map.get("cmd_to_send"); Tracer.d(mytag, "command selected at Position = " + position + " Commande = " + cmd_requested); new CommandeThread().execute(); } } }); listeChoices.setScrollingCacheEnabled(false); //feature panel 2 which will contain list of selectable choices featurePan2 = new LinearLayout(context); featurePan2.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); featurePan2.setGravity(Gravity.CENTER_VERTICAL); featurePan2.setPadding(5, 10, 5, 10); featurePan2.addView(listeChoices); } LL_featurePan.addView(value); handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 2) { Toast.makeText(getContext(), "Command Failed", Toast.LENGTH_SHORT).show(); } else if (msg.what == 9999) { //Message from cache engine //state_engine send us a signal to notify value changed if (session == null) return; String loc_Value = session.getValue(); Tracer.d(mytag, "Handler receives a new value <" + loc_Value + ">"); value.setText(getStringResourceByName(loc_Value)); //To have the icon colored as it has no state IV_img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2)); } else if (msg.what == 9998) { // state_engine send us a signal to notify it'll die ! Tracer.d(mytag, "cache engine disappeared ===> Harakiri !"); session = null; realtime = false; removeView(LL_background); myself.setVisibility(GONE); if (container != null) { container.removeView(myself); container.recomputeViewAttributes(myself); } try { finalize(); } catch (Throwable t) { } //kill the handler thread itself } } }; //End of handler //================================================================================ /* * New mechanism to be notified by widgetupdate engine when our value is changed * */ WidgetUpdate cache_engine = WidgetUpdate.getInstance(); if (cache_engine != null) { session = new Entity_client(dev_id, state_key, mytag, handler, session_type); if (tracerengine.get_engine().subscribe(session)) { realtime = true; //we're connected to engine //each time our value change, the engine will call handler handler.sendEmptyMessage(9999); //Force to consider current value in session } } //================================================================================ //updateTimer(); //Don't use anymore cyclic refresh.... }