List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.google.android.apps.body.LayersLoader.java
/** Synchronously loads a single layer. */ private Render.DrawGroup[] load(Context context, int layerResource) { // TODO(thakis): this method is kinda ugly. // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion // needs to happen at load time. The utf8 stuff is clever, but mostly overhead // for local files. // Timers for different loading phases. float jsonReadS = 0; float jsonParseS = 0; float textureS = 0; float fileReadS = 0; float fileDecodeS = 0; float colorBufferS = 0; Render.DrawGroup[] drawGroups = null; long jsonReadStartNS = System.nanoTime(); JSONObject object = loadJsonResource(context, layerResource); jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f; long jsonParseStartNS = System.nanoTime(); Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>(); try {// w ww . ja v a 2 s . c o m JSONArray dataDrawGroups = object.getJSONArray("draw_groups"); drawGroups = new Render.DrawGroup[dataDrawGroups.length()]; for (int i = 0; i < drawGroups.length; ++i) { if (mCancelled) return null; JSONObject drawGroup = dataDrawGroups.getJSONObject(i); drawGroups[i] = new Render.DrawGroup(); if (drawGroup.has("texture")) drawGroups[i].texture = drawGroup.getString("texture"); else if (drawGroup.has("diffuse_color")) { JSONArray color = drawGroup.getJSONArray("diffuse_color"); drawGroups[i].diffuseColor = new float[3]; for (int j = 0; j < 3; ++j) drawGroups[i].diffuseColor[j] = (float) color.getDouble(j); } JSONArray draws = drawGroup.getJSONArray("draws"); drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length()); for (int j = 0; j < draws.length(); ++j) { JSONObject jsonDraw = draws.getJSONObject(j); Render.Draw draw = new Render.Draw(); draw.geometry = jsonDraw.getString("geometry"); draw.offset = jsonDraw.getJSONArray("range").getInt(0); draw.count = jsonDraw.getJSONArray("range").getInt(1); drawGroups[i].draws.add(draw); } long textureReadStartNS = System.nanoTime(); loadTexture(mContext, drawGroups[i]); textureS += (System.nanoTime() - textureReadStartNS) / 1e9f; String indices = drawGroup.getString("indices"); FP.FPEntry indicesFP = FP.get(indices); if (toBeLoaded.get(indicesFP.file) == null) toBeLoaded.put(indicesFP.file, new ArrayList<Loader>()); toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP)); String attribs = drawGroup.getString("attribs"); FP.FPEntry attribsFP = FP.get(attribs); if (toBeLoaded.get(attribsFP.file) == null) toBeLoaded.put(attribsFP.file, new ArrayList<Loader>()); toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP)); drawGroups[i].numIndices = drawGroup.getInt("numIndices"); } } catch (JSONException e) { Log.e("Body", e.toString()); } jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS; for (int resource : toBeLoaded.keySet()) { if (mCancelled) return null; long fileReadStartNS = System.nanoTime(); char[] data = new char[0]; InputStream is = mContext.getResources().openRawResource(resource); try { // Comment from the ApiDemo content/ReadAsset.java in the Android SDK: // "We guarantee that the available method returns the total // size of the asset... of course, this does mean that a single // asset can't be more than 2 gigs." data = new char[is.available()]; Reader in = new InputStreamReader(is, "UTF-8"); in.read(data, 0, data.length); } catch (UnsupportedEncodingException e) { Log.e("Body", e.toString()); } catch (IOException e) { Log.e("Body", e.toString()); } finally { try { is.close(); } catch (IOException e) { Log.e("Body", e.toString()); } } fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f; long fileDecodeStartNS = System.nanoTime(); for (Loader l : toBeLoaded.get(resource)) { if (mCancelled) return null; l.load(data); } fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f; } long colorBufferStartNS = System.nanoTime(); for (Render.DrawGroup drawGroup : drawGroups) { if (mCancelled) return null; createColorBuffer(drawGroup); } colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f; Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS); return drawGroups; }
From source file:com.acrutiapps.browser.tasks.HistoryBookmarksImportTask.java
private String readAsJSON(File file) { List<ContentValues> insertValues = null; try {/*from ww w.ja v a 2 s .c o m*/ insertValues = new ArrayList<ContentValues>(); publishProgress(1, 0, 0); FileInputStream fis = new FileInputStream(file); StringBuilder sb = new StringBuilder(); String line; BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } } JSONObject data = new JSONObject(sb.toString()); Map<Long, Folder> folders = new HashMap<Long, Folder>(); if (data.has("folders")) { JSONArray foldersArray = data.getJSONArray("folders"); int progress = 0; int total = foldersArray.length(); for (int i = 0; i < foldersArray.length(); i++) { publishProgress(3, progress, total); JSONObject folder = foldersArray.getJSONObject(i); long id = folder.getLong("id"); long parentId = folder.getLong("parentId"); String title = URLDecoder.decode(folder.getString("title"), "UTF-8"); ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.TITLE, title); values.put(BookmarksProvider.Columns.BOOKMARK, 0); values.put(BookmarksProvider.Columns.IS_FOLDER, 1); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, -1); Uri insertionUri = mContext.getContentResolver().insert(BookmarksProvider.BOOKMARKS_URI, values); String insertionString = insertionUri.toString(); // Get the new id for the current folder. long insertionId = -1; try { insertionId = Long .parseLong(insertionString.substring(insertionString.lastIndexOf('/') + 1)); } catch (NumberFormatException e) { insertionId = -1; } // Keep a relation between the id of the folder in the export file, its parent id (in the export file), and its new id. folders.put(id, new Folder(insertionId, parentId)); progress++; } publishProgress(4, 0, 0); // Correct folders parent ids. if (!folders.isEmpty()) { for (Folder folder : folders.values()) { // For each folder previously inserted, check if it had a parent folder in the export file. long oldParentId = folder.getOldParentId(); if (oldParentId != -1) { // Get the parent folder by its old Id, key of folders map. Folder parentFolder = folders.get(oldParentId); if (parentFolder != null) { ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); String whereClause = BookmarksProvider.Columns._ID + " = " + folder.getNewId(); mContext.getContentResolver().update(BookmarksProvider.BOOKMARKS_URI, values, whereClause, null); } } } } } if (data.has("bookmarks")) { JSONArray bookmarksArray = data.getJSONArray("bookmarks"); int progress = 0; int total = bookmarksArray.length(); for (int i = 0; i < bookmarksArray.length(); i++) { publishProgress(5, progress, total); JSONObject bookmark = bookmarksArray.getJSONObject(i); long folderId = bookmark.getLong("folderId"); Folder parentFolder = null; if (folderId != -1) { parentFolder = folders.get(folderId); } String title = URLDecoder.decode(bookmark.getString("title"), "UTF-8"); String url = URLDecoder.decode(bookmark.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, bookmark.getInt("visits"), bookmark.getLong("visitedDate"), bookmark.getLong("creationDate"), 1); if (parentFolder != null) { values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); } insertValues.add(values); progress++; } } if (data.has("history")) { JSONArray historyArray = data.getJSONArray("history"); int progress = 0; int total = historyArray.length(); for (int i = 0; i < historyArray.length(); i++) { publishProgress(6, progress, total); JSONObject history = historyArray.getJSONObject(i); String title = URLDecoder.decode(history.getString("title"), "UTF-8"); String url = URLDecoder.decode(history.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, history.getInt("visits"), history.getLong("visitedDate"), 0, 0); insertValues.add(values); progress++; } } } catch (FileNotFoundException e) { e.printStackTrace(); return e.getMessage(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } if (insertValues != null) { publishProgress(7, 0, 0); mContext.getContentResolver().bulkInsert(BookmarksProvider.BOOKMARKS_URI, insertValues.toArray(new ContentValues[insertValues.size()])); } return null; }
From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java
/** * The implementation of all the possible requests is here * -> "sounds": returns a list of available sounds on the phone * -> "screen": returns the screen state (whether the app. is on the foreground or not) * -> "play": plays a sound on the phone * -> "set": update Spydroid's configuration * -> "get": returns Spydroid's configuration (framerate, bitrate...) * -> "state": returns a JSON containing information about the state of the application * -> "battery": returns an approximation of the battery level on the phone * -> "buzz": makes the phone buuz //from w ww. j ava 2 s . c o m * -> "volume": sets or gets the volume * @throws JSONException * @throws IllegalAccessException * @throws IllegalArgumentException **/ static private void exec(JSONObject object, StringBuilder response) throws JSONException, IllegalArgumentException, IllegalAccessException { SpydroidApplication application = SpydroidApplication.getInstance(); Context context = application.getApplicationContext(); String action = object.getString("action"); // Returns a list of available sounds on the phone if (action.equals("sounds")) { Field[] raws = R.raw.class.getFields(); response.append("["); for (int i = 0; i < raws.length - 1; i++) { response.append("\"" + raws[i].getName() + "\","); } response.append("\"" + raws[raws.length - 1].getName() + "\"]"); } // Returns the screen state (whether the app. is on the foreground or not) else if (action.equals("screen")) { response.append(application.applicationForeground ? "\"1\"" : "\"0\""); } // Plays a sound on the phone else if (action.equals("play")) { Field[] raws = R.raw.class.getFields(); for (int i = 0; i < raws.length; i++) { if (raws[i].getName().equals(object.getString("name"))) { mSoundPool.load(application, raws[i].getInt(null), 0); } } response.append("[]"); } // Returns Spydroid's configuration (framerate, bitrate...) else if (action.equals("get")) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ","); response.append("\"audioEncoder\":\"" + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\","); response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ","); response.append("\"videoEncoder\":\"" + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\","); response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x" + application.videoQuality.resY + "\","); response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\","); response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}"); } // Update Spydroid's configuration else if (action.equals("set")) { final JSONObject settings = object.getJSONObject("settings"); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final Editor editor = prefs.edit(); editor.putBoolean("stream_video", settings.getBoolean("stream_video")); application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality")); editor.putInt("video_resX", application.videoQuality.resX); editor.putInt("video_resY", application.videoQuality.resY); editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate)); editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000)); editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1"); editor.putBoolean("stream_audio", settings.getBoolean("stream_audio")); editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5"); editor.commit(); response.append("[]"); } // Returns a JSON containing information about the state of the application else if (action.equals("state")) { Exception exception = application.lastCaughtException; response.append("{"); if (exception != null) { // Used to display the message on the user interface String lastError = exception.getMessage(); // Useful to display additional information to the user depending on the error StackTraceElement[] stack = exception.getStackTrace(); StringBuilder builder = new StringBuilder( exception.getClass().getName() + " : " + lastError + "||"); for (int i = 0; i < stack.length; i++) builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " (" + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||"); response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\","); response.append("\"lastStackTrace\":\"" + builder.toString() + "\","); } response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\""); response.append("}"); } else if (action.equals("clear")) { application.lastCaughtException = null; response.append("[]"); } // Returns an approximation of the battery level else if (action.equals("battery")) { response.append("\"" + application.batteryLevel + "\""); } // Makes the phone vibrates for 300ms else if (action.equals("buzz")) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(300); response.append("[]"); } // Sets or gets the system's volume else if (action.equals("volume")) { AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (object.has("set")) { audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); response.append("[]"); } else { int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC); response.append("{\"max\":" + max + ",\"current\":" + current + "}"); } } }
From source file:io.riddles.lightriders.game.state.LightridersStateDeserializer.java
private LightridersState visitState(JSONObject stateJson, LightridersState previousState) throws JSONException { int roundNumber = stateJson.getInt("round"); return null;//w w w . j a va2 s . com }
From source file:com.github.koraktor.steamcondenser.community.WebApi.java
/** * Fetches JSON data from Steam Web API using the specified interface, * method and version. Additional parameters are supplied via HTTP GET. * * @param apiInterface The Web API interface to call, e.g. * <code>ISteamUser</code> * @param method The Web API method to call, e.g. * <code>GetPlayerSummaries</code> * @param params Additional parameters to supply via HTTP GET * @param version The API method version to use * @return Data is returned as a <code>JSONObject</code> * @throws JSONException In case of misformatted JSON data * @throws WebApiException In case of any request failure *//* ww w . ja v a 2s . co m*/ public static JSONObject getJSONData(String apiInterface, String method, int version, Map<String, Object> params) throws JSONException, WebApiException { String data = getJSON(apiInterface, method, version, params); JSONObject result = new JSONObject(data).getJSONObject("result"); if (result.getInt("status") != 1) { throw new WebApiException(WebApiException.Cause.STATUS_BAD, result.getInt("status"), result.getString("statusDetail")); } return result; }
From source file:com.example.android.directboot.alarms.Alarm.java
/** * Parses a Json string to an {@link Alarm} instance. * * @param string The String representation of an alarm * @return an instance of {@link Alarm}// ww w . j a va2 s . co m */ public static Alarm fromJson(String string) { JSONObject jsonObject; Alarm alarm = new Alarm(); try { jsonObject = new JSONObject(string); alarm.id = jsonObject.getInt("id"); alarm.month = jsonObject.getInt("month"); alarm.date = jsonObject.getInt("date"); alarm.hour = jsonObject.getInt("hour"); alarm.minute = jsonObject.getInt("minute"); } catch (JSONException e) { throw new IllegalArgumentException("Failed to parse the String: " + string); } return alarm; }
From source file:com.domuslink.elements.Alias.java
public Alias(JSONObject jsonElement) throws Exception { super();/*www . j a va 2 s. co m*/ setState(0); setDimLevel(0); try { setLabel(jsonElement.getString("label")); setAliasMapElement(new AliasMap(jsonElement.getJSONObject("aliasMapElement"))); if (!this.aliasMapElement.getElementType().contentEquals("Scene")) { setHouseCode(jsonElement.getString("houseCode")); setDevices(jsonElement.getString("devices")); setModuleType(jsonElement.getString("moduleType")); setModuleOptions(jsonElement.getString("moduleOptions")); setElementType(jsonElement.getString("elementType")); setElementLine(jsonElement.getString("elementLine")); setLineNum(jsonElement.getInt("lineNum")); setArrayNum(jsonElement.getInt("arrayNum")); setEnabled(jsonElement.getBoolean("enabled")); this.isScene = false; if (devices.indexOf(",") > 0 || devices.indexOf("-") > 0) this.isMultiAlias = true; else this.isMultiAlias = false; } else { this.isScene = true; this.isMultiAlias = false; } } catch (Exception e) { Log.e(TAG, "Error getting alias from JSONObject", e); throw e; } }
From source file:es.rocapal.wtl.api.WTLManager.java
private Response parseResponse(String jsonResponse) { JSONObject json; if (jsonResponse == null) return null; try {/* w w w.j a v a 2s. c o m*/ json = new JSONObject(jsonResponse); if (json.has(CODE_KEY) && json.has(MSG_KEY)) return new Response(json.getInt(CODE_KEY), json.getString(MSG_KEY)); else return null; } catch (JSONException e) { Log.e(TAG, e.getMessage()); return null; } }
From source file:org.protorabbit.json.DefaultSerializer.java
@SuppressWarnings("unchecked") void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) { Object param = null;/*from w w w .java 2 s . c om*/ Throwable ex = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().equals(name)) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length == 1 && jo.has(key)) { Class<?> tparam = paramTypes[0]; boolean allowNull = false; try { if (jo.isNull(key)) { // do nothing because param is already null : lets us not null on other types } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) { param = new Long(jo.getLong(key)); } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) { param = new Double(jo.getDouble(key)); } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) { param = new Integer(jo.getInt(key)); } else if (String.class.isAssignableFrom(tparam)) { param = jo.getString(key); } else if (Enum.class.isAssignableFrom(tparam)) { param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key)); } else if (Boolean.class.isAssignableFrom(tparam)) { param = new Boolean(jo.getBoolean(key)); } else if (jo.isNull(key)) { param = null; allowNull = true; } else if (Collection.class.isAssignableFrom(tparam)) { if (m.getGenericParameterTypes().length > 0) { Type t = m.getGenericParameterTypes()[0]; if (t instanceof ParameterizedType) { ParameterizedType tv = (ParameterizedType) t; if (tv.getActualTypeArguments().length > 0 && tv.getActualTypeArguments()[0] == String.class) { List<String> ls = new ArrayList<String>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { ls.add(ja.getString(j)); } } param = ls; } else if (tv.getActualTypeArguments().length == 1) { ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0]; Class itemClass = (Class) type.getRawType(); if (itemClass == Map.class && type.getActualTypeArguments().length == 2 && type.getActualTypeArguments()[0] == String.class && type.getActualTypeArguments()[1] == Object.class) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject mo = ja.getJSONObject(j); Iterator<String> keys = mo.keys(); while (keys.hasNext()) { String okey = keys.next(); Object ovalue = null; // make sure we don't get JSONObject$Null if (!mo.isNull(okey)) { ovalue = mo.get(okey); } map.put(okey, ovalue); } ls.add(map); } } param = ls; } else { getLogger().warning( "Don't know how to handle Collection of type : " + itemClass); } } else { getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0]); } } } } else { getLogger().warning( "Unable to serialize " + key + " : Don't know how to handle " + tparam); } } catch (JSONException e) { e.printStackTrace(); } if (param != null || allowNull) { try { if (m != null) { Object[] args = { param }; m.invoke(targetObject, args); ex = null; break; } } catch (SecurityException e) { ex = e; } catch (IllegalArgumentException e) { ex = e; } catch (IllegalAccessException e) { ex = e; } catch (InvocationTargetException e) { ex = e; } } } } } if (ex != null) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } }
From source file:org.gdg.bari.entities.TableTurn.java
static public TableTurn unpersist(byte[] byteArray) { if (byteArray == null) { Log.d(TAG, "Empty array---possible bug."); return new TableTurn(); }//from w w w. j a v a 2 s .c o m String st = null; try { st = new String(byteArray, "UTF-16"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); return null; } Log.d(TAG, "====UNPERSIST \n" + st); TableTurn retVal = new TableTurn(); try { JSONObject obj = new JSONObject(st); if (obj.has("data")) { retVal.data = obj.getString("data"); } if (obj.has("turnCounter")) { retVal.turnCounter = obj.getInt("turnCounter"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retVal; }