List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java
public static String geocode(Context context, double latitude, double longitude) { String addressString = String.format("%.4f, %.4f", latitude, longitude); try {/*from w w w . ja va 2 s . c o m*/ String apiKey = Global.getApiKey(context); String server = Global.getApiUrl(context); String url = server + "/api/osm/location?apiKey=" + apiKey + "&location=" + latitude + "&location=" + longitude; String response = WebReporter.getHttpURLResponse(url, false); JSONObject json = null; JSONArray jsonArray = null; if (response == null) return addressString; try { jsonArray = new JSONArray(response); } catch (JSONException e) { return addressString; } try { for (int i = 0; i < jsonArray.length(); i++) { json = jsonArray.getJSONObject(i); if (json.has("error")) { String error = json.getString("error"); return null; } else { addressString = ""; json = json.getJSONObject("address"); String number = ""; if (json.has("house_number")) { number = json.getString("house_number"); addressString += number + " "; } String road = json.getString("road"); addressString += road;// + suburb; return addressString; } } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception e) { } return addressString; }
From source file:org.openmrs.mobile.listeners.visit.FindVisitsByPatientUUIDListener.java
@Override public void onResponse(JSONObject response) { mLogger.d(response.toString());//from ww w . j av a 2s . co m try { JSONArray visitResultJSON = response.getJSONArray(BaseManager.RESULTS_KEY); if (visitResultJSON.length() > 0) { for (int i = 0; i < visitResultJSON.length(); i++) { Visit visit = VisitMapper.map(visitResultJSON.getJSONObject(i)); long visitId = visitDAO.getVisitsIDByUUID(visit.getUuid()); if (visitId > 0) { visitDAO.updateVisit(visit, visitId, mPatientID); } else { visitDAO.saveVisit(visit, mPatientID); } } } } catch (JSONException e) { mErrorOccurred = true; mLogger.d(e.toString()); } finally { updateData(); } }
From source file:com.theaigames.game.warlight2.MapCreator.java
/** * @param mapString : string that represents the map to be created * @return : a Map object to use in the game *//*from w w w.j av a 2 s .co m*/ public static Map createMap(String mapString) { Map map = new Map(); //parse the map string try { JSONObject jsonMap = new JSONObject(mapString); // create SuperRegion objects JSONArray superRegions = jsonMap.getJSONArray("SuperRegions"); for (int i = 0; i < superRegions.length(); i++) { JSONObject jsonSuperRegion = superRegions.getJSONObject(i); map.add(new SuperRegion(jsonSuperRegion.getInt("id"), jsonSuperRegion.getInt("bonus"))); } // create Region object JSONArray regions = jsonMap.getJSONArray("Regions"); for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); SuperRegion superRegion = map.getSuperRegion(jsonRegion.getInt("superRegion")); map.add(new Region(jsonRegion.getInt("id"), superRegion)); } // add the Regions' neighbors for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); Region region = map.getRegion(jsonRegion.getInt("id")); JSONArray neighbors = jsonRegion.getJSONArray("neighbors"); for (int j = 0; j < neighbors.length(); j++) { Region neighbor = map.getRegion(neighbors.getInt(j)); region.addNeighbor(neighbor); } } } catch (JSONException e) { System.err.println("JSON: Can't parse map string: " + e); } map.sort(); return map; }
From source file:com.google.samples.apps.friendlyping.gcm.MyGcmListenerService.java
private ArrayList<Pinger> getPingers(Bundle data) throws JSONException { final JSONArray clients = new JSONArray(data.getString("clients")); ArrayList<Pinger> pingers = new ArrayList<>(clients.length()); for (int i = 0; i < clients.length(); i++) { JSONObject jsonPinger = clients.getJSONObject(i); pingers.add(Pinger.fromJson(jsonPinger)); }/*from w ww .j a v a2s.com*/ return pingers; }
From source file:org.b3log.rhythm.repository.impl.UserRepositoryImpl.java
@Override public JSONObject getByEmail(final String email) throws RepositoryException { final Query query = new Query().setPageCount(1); query.setFilter(new PropertyFilter(User.USER_EMAIL, FilterOperator.EQUAL, email.toLowerCase().trim())); try {/*from w w w.j av a 2s . co m*/ final JSONObject result = get(query); final JSONArray array = result.getJSONArray(Keys.RESULTS); if (0 == array.length()) { return null; } return array.getJSONObject(0); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); throw new RepositoryException(e); } }
From source file:com.example.pyrkesa.shwc.OngoingNotificationListenerService.java
@Override public void onDataChanged(DataEventBuffer dataEvents) { final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); final String ACTION_DEMAND = "ACTION_DEMAND"; String EXTRA_CMD = "EXTRA_CMD"; dataEvents.close();//from w w w . jav a2s. c om if (!mGoogleApiClient.isConnected()) { ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS); if (!connectionResult.isSuccess()) { Log.e(TAG, "Service failed to connect to GoogleApiClient."); return; } } for (DataEvent event : events) { if (event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (PATH.equals(path)) { // Get the data out of the event DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); //final String title = dataMapItem.getDataMap().getString(KEY_TITLE); final String room_devices = dataMapItem.getDataMap().getString(KEY_ROOM_DEVICES); final String room_name = dataMapItem.getDataMap().getString(KEY_ROOM_NAME); // Asset asset = dataMapItem.getDataMap().getAsset(KEY_BACKGROUND); try { JSONObject roomJSON = new JSONObject(room_devices); JSONArray devicesArray = roomJSON.getJSONArray("devices"); String firstPageText = "quipements :"; ArrayList<Device> devicess = new ArrayList<Device>(); for (int i = 0; i < devicesArray.length(); i++) { JSONObject d = devicesArray.getJSONObject(i); Device device = new Device(d.getString("id"), d.getString("name"), d.getInt("type"), d.getString("status")); String Newline = System.getProperty("line.separator"); firstPageText += Newline; firstPageText += device.name; devicess.add(device); } if (firstPageText.equalsIgnoreCase("quipements :")) { firstPageText = "Aucun quipement"; } Bitmap background = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg_distance); NotificationCompat.WearableExtender notifExtender = new NotificationCompat.WearableExtender(); for (Device d : devicess) { try { notifExtender.addAction(d.getAction(OngoingNotificationListenerService.this)); } catch (Exception e) { Log.e("Erreur get Action :", e.getMessage()); } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle("Pice : " + roomJSON.getString("name")) .setContentText(firstPageText).setSmallIcon(R.drawable.mini_logo) .extend(notifExtender.setBackground(background)).setOngoing(true); // Build the notification and show it NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } catch (Throwable t) { Log.e("JSON_WEAR_SHWC", "Could not parse malformed JSON: " + room_devices + t.getMessage()); } } else { Log.d(TAG, "Unrecognized path: " + path); } } } }
From source file:com.example.wmgps.MainActivity.java
/** Called when the user clicks the Send button */ public void sendMessage(View view) { /*Intent intent = new Intent(this, DisplayMessageActivity.class); EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent);*///from w w w. java 2 s . com /*EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); TextView output = (TextView) findViewById(R.id.welcome); output.setText(message);*/ /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL)); startActivity(browserIntent); */ TextView hiddenText = (TextView) findViewById(R.id.Hidden11); if (Misc.isNullTrimmedString(hiddenText.getText().toString())) { TextView output = (TextView) findViewById(R.id.welcome1); boolean without_connection = true; Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed String response = Misc.EMPTY_STRING; String welcome1String = "*******************Connected*************************"; try { response = new RetrieveFeedTask().execute(new String[] {}).get(); } catch (Exception e) { response = Misc.EMPTY_STRING; Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } if (Misc.isNullTrimmedString(response)) { // welcome1String = "***Loading Static, couldn't connect***"; response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"}," + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10," + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true}," + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"}," + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"}," + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]" + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}"; } StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING); int currentOutputTag = R.id.Hidden1; int currentInputTag = R.id.edit_message; // Renderer::decodeConfig() if (!Misc.isNullTrimmedString(response)) { try { JSONObject jsonObj = new JSONObject(response); for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) { String name = (String) iterator.next(); JSONObject jsonObj1 = jsonObj.getJSONObject(name); for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) { String name1 = (String) iterator1.next(); if ("elements".equals(name1)) { JSONArray jsonArr = jsonObj1.getJSONArray(name1); boolean userName = false; boolean password = false; for (int i = 0; i < jsonArr.length(); i++) { JSONObject temp = jsonArr.getJSONObject(i); String initialValue = null; String initialName = null; String initialLabel = null; if (!temp.isNull("name") && temp.getString("name").equals("j_password")) { initialName = "j_password"; } else if (!temp.isNull("name") && temp.getString("name").equals("j_username")) { initialName = "j_username"; } for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) { String tempName = (String) iterator2.next(); String tempValue = (String) temp.getString(tempName); if (tempName.equals("type")) { if (tempValue.equals("label") || tempValue.equals("entry")) { initialLabel = tempValue; } } else if (tempName.equals("value")) { initialValue = tempValue; } /* if(tempName.equals("label")) { if(Misc.isNullTrimmedString(initialValue)) initialLabel = tempName; else { typeAndValueOfTag.put("output",initialValue); initialValue = Misc.EMPTY_STRING; continue; } } else if(tempName.equals("value")) { if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel)) { initialValue = tempValue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label")) { typeAndValueOfTag.put("output",tempValue); initialValue = Misc.EMPTY_STRING; continue; } else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry")) { if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name")) typeAndValueOfTag.put("input",tempValue); else initialValue = tempValue; } } else if(tempName.equals("entry")) { if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel)) { initialName = tempName; } else typeAndValueOfTag.put("input",initialValue); finalEncodedString.append(" " + tempName + " " + tempValue + " ----- "); }*/ } if (initialLabel != null) { if (initialLabel.equals("label")) { if (initialValue.equals(" User ID: ")) { TextView output1 = (TextView) findViewById(R.id.userNameText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = true; password = false; } else if (initialValue.equals("Password: ")) { TextView output1 = (TextView) findViewById(R.id.passwordText); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); password = true; userName = false; } else { TextView output1 = (TextView) findViewById(currentOutputTag++); output1.setText(initialValue); output1.setVisibility(View.VISIBLE); userName = false; password = false; } } else if (initialLabel.equals("entry")) { if ("j_password".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.passwordEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter password"); } } else if ("j_username".equals(initialName)) { EditText input = ((EditText) findViewById(R.id.userNameEdit)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter username"); } } else { EditText input = ((EditText) findViewById(currentInputTag++)); input.setVisibility(View.VISIBLE); if (Misc.isNullTrimmedString(initialValue)) { input.setText(""); input.setHint("Please enter value"); } else input.setText(initialValue); } } } /*if(initialLabel != null) { List<String> listOfValues; if(typeAndValueOfTag.containsKey(initialLabel)) { listOfValues = typeAndValueOfTag.get(initialLabel); listOfValues.add(initialValue); } typeAndValueOfTag.put(initialLabel,initialValue); }*/ } } else { // Here, just the URL would get processed. So don't use. // output.setText(" " + name + " " + jsonObj1.getString(name1)); } } } TextView welcome1 = (TextView) findViewById(R.id.welcome1); welcome1.setText(welcome1String); // processUIDisplay(typeAndValueOfTag); /*if(finalEncodedString.length() == 0) finalEncodedString.append("Could not process"); output.setText(finalEncodedString.toString()); TextView output2 = (TextView) findViewById(R.id.Hidden1); output2.setText("Hidden one is enabled"); output2.setVisibility(View.VISIBLE);*/ } catch (JSONException e) { Log.e("Exception ", e.getMessage()); Log.e("Exception ", e.getLocalizedMessage()); Log.e("Exception ", e.getStackTrace().toString()); } } hiddenText.setText("validated user"); /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"}, {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "}, {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10, "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true}, {"type":"break"},{"type":"label","value":"Password: "}, {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false}, {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"}, {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}] ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/ } else { List outputList = verifyUser(); if (!Misc.isNullList(outputList)) { String sessionId = (String) outputList.get(0); String userType = (String) outputList.get(1); Intent intent = new Intent(this, MenuActivity.class); if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType) && Integer.parseInt(sessionId) > 0) { if (userType.equals(Constants.WORKER)) { MenuActivity.sessionId = Misc.EMPTY_STRING; TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.WORKER); intent.putExtra(Constants.SESSION_ID, sessionId); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText(Misc.EMPTY_STRING); error.setVisibility(View.GONE); intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR); intent.putExtra(Constants.SESSION_ID, sessionId); } } // goto Maps screen // Get the message from the intent startActivity(intent); } else { TextView error = (TextView) findViewById(R.id.ErrorText); error.setText("Invalid Username/Password"); error.setVisibility(View.VISIBLE); } } return; }
From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.PebbleReceiver.java
@Override public void onReceive(Context context, Intent intent) { Prefs prefs = GBApplication.getPrefs(); if ("never".equals(prefs.getString("notification_mode_pebblemsg", "when_screen_off"))) { return;/*from ww w . ja va 2s . c om*/ } if ("when_screen_off".equals(prefs.getString("notification_mode_pebblemsg", "when_screen_off"))) { PowerManager powermanager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (powermanager.isScreenOn()) { return; } } String messageType = intent.getStringExtra("messageType"); if (!messageType.equals("PEBBLE_ALERT")) { LOG.info("non PEBBLE_ALERT message type not supported"); return; } if (!intent.hasExtra("notificationData")) { LOG.info("missing notificationData extra"); return; } NotificationSpec notificationSpec = new NotificationSpec(); notificationSpec.id = -1; String notificationData = intent.getStringExtra("notificationData"); try { JSONArray notificationJSON = new JSONArray(notificationData); notificationSpec.title = notificationJSON.getJSONObject(0).getString("title"); notificationSpec.body = notificationJSON.getJSONObject(0).getString("body"); } catch (JSONException e) { e.printStackTrace(); return; } if (notificationSpec.title != null) { notificationSpec.type = NotificationType.UNKNOWN; String sender = intent.getStringExtra("sender"); if ("Conversations".equals(sender)) { notificationSpec.type = NotificationType.CONVERSATIONS; } else if ("OsmAnd".equals(sender)) { notificationSpec.type = NotificationType.GENERIC_NAVIGATION; } GBApplication.deviceService().onNotification(notificationSpec); } }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Transform an array of JSON Objects into a {@link List} of DTOs. * * @param <T> The object type contained with in the array * * @param jsonArray The {@link JSONArray} to convert * @param objectMapper The {@link Mapper} to use to process the JSON objects * * @return List of DTOs/*from w ww .j av a2s. c o m*/ */ protected <T extends Object> List<T> parseArray(final JSONArray jsonArray, final Mapper<JSONObject, T> objectMapper) { final List<T> arrayContents = new ArrayList<>(); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { final JSONObject element = jsonArray.getJSONObject(i); if (element != null) { arrayContents.add(objectMapper.map(element)); } } } return arrayContents; }
From source file:com.streaming.sweetplayer.fragment.ArtistFragment.java
private void getSongsList(ArrayList<HashMap<String, String>> parseList, String url) { JSONParser jsonParser = new JSONParser(); JSONArray jsonArray; try {/*from w w w .j a va 2s.c o m*/ JSONObject json = jsonParser.getJSONFromUrl(url); if (json != null) { jsonArray = json.getJSONArray(mJsonItem); int array_length = jsonArray.length(); if (isSongsView) { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ARTIST, jsonObject.getString(Config.ARTIST)); map.put(Config.NAME, jsonObject.getString(Config.SONG)); map.put(Config.MP3, jsonObject.getString(Config.MP3)); map.put(Config.DURATION, jsonObject.getString(Config.DURATION)); map.put(Config.URL, jsonObject.getString(Config.URL)); map.put(Config.IMAGE, mImageForDB); parseList.add(map); } } else { for (int i = 0; i < array_length; i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject jsonObject = jsonArray.getJSONObject(i); map.put(Config.ID, jsonObject.getString(Config.ID)); map.put(Config.ALBUM, jsonObject.getString(Config.ALBUM)); map.put(Config.SONGS_ITEM, jsonObject.getString(Config.SONGS_ITEM)); map.put(Config.IMAGE, jsonObject.getString(Config.IMAGE)); map.put(Config.URL, jsonObject.getString(Config.URL)); parseList.add(map); } } } } catch (JSONException e) { e.printStackTrace(); } }