Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

In this page you can find the example usage for org.json JSONArray getString.

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:com.googlecode.gmaps4jsf.services.ReverseGeocoderServiceImpl.java

private void getPlaceMarkPrimaryInformation(PlaceMark placeMark, JSONObject placeMarkPrimaryData) {

    // Address//from  w  w  w  .j  a  va2  s.  c om
    try {
        placeMark.setAddress((String) placeMarkPrimaryData.get(ComponentConstants.FORMATTED_ADDRESS_LABEL));
    } catch (JSONException exception) {
        System.err.println("Unable to get the place mark address");
    }

    // Postal code
    try {
        JSONArray results = (JSONArray) placeMarkPrimaryData
                .getJSONArray(ComponentConstants.ADDRESS_COMPONENT_LABEL);

        for (int i = 0; i < results.length(); ++i) {
            JSONObject jsonObject = results.getJSONObject(i);

            String shortName = jsonObject.getString("short_name");
            JSONArray types = jsonObject.getJSONArray("types");

            for (int j = 0; j < types.length(); ++j) {
                String attribute = types.getString(j);

                if ("postal_code".equals(attribute)) {
                    placeMark.setPostalCodeNumber(shortName);
                    break;
                }
            }
        }

    } catch (JSONException exception) {
        System.err.println("Unable to get the place mark address");
    }
}

From source file:com.baroq.pico.google.PlayServices.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {

    try {//  ww  w. ja v  a 2  s  .c o m
        if (!ACTION_SETUP.equals(action) && !ACTION_SIGNIN.equals(action)
                && (null == mHelper || !mHelper.isConnected())) {
            callbackContext.error("Please setup and signin to use PlayServices plugin");
            return false;
        }
        if (ACTION_SETUP.equals(action)) {
            int l = data.length();
            if (0 == l) {
                callbackContext.error("Expecting at least 1 parameter for action: " + action);
                return false;
            }
            clientTypes = data.getInt(0);
            String[] extraScopes = new String[l - 1];
            for (int i = 1; i < l; i++) {
                extraScopes[i - 1] = data.getString(i);
            }
            setup(clientTypes, extraScopes, callbackContext);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_SIGNIN.equals(action)) {
            mHelper.beginUserInitiatedSignIn();
            callbackContext.success();
        } else if (ACTION_SIGNOUT.equals(action)) {
            signout();
            callbackContext.success();
        } else if (ACTION_AS_MAX_KEYS.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxNumKeys());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_MAX_SIZE.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxStateSize());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_DEL.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().deleteState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_LIST.equals(action)) {
            mHelper.getAppStateClient().listStates(this);
            callbackContext.success();
        } else if (ACTION_AS_LOAD.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().loadState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_RESOLVE.equals(action)) {
            int key = data.getInt(0);
            String resolvedVersion = data.getString(1);
            String value = data.getString(2);
            mHelper.getAppStateClient().resolveState(this, key, resolvedVersion, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateState(key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE_NOW.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateStateImmediate(this, key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_ACHIEVEMENTS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAchievementsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARDS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAllLeaderboardsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARD.equals(action)) {
            String id = data.getString(0);
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getLeaderboardIntent(id), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievement(id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievementImmediate(this, id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_ACHIEVEMENTS.equals(action)) {
            boolean forceReload = data.getBoolean(0);
            mHelper.getGamesClient().loadAchievements(this, forceReload);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_GAME.equals(action)) {
            mHelper.getGamesClient().loadGame(this);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_LEADERBOARD_METADATA.equals(action)) {
            if (1 == data.length()) {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getBoolean(0));
            } else {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getString(0), data.getBoolean(1));
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_MORE_SCORES.equals(action)) {
            if (null == scoreBuffer) {
                callbackContext.error("Get a leaderboard fist before calling: " + action);
                return false;
            }
            int maxResults = data.getInt(0);
            int pageDirection = data.getInt(0);
            mHelper.getGamesClient().loadMoreScores(this, scoreBuffer, maxResults, pageDirection);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER.equals(action)) {
            String playerId = data.getString(0);
            mHelper.getGamesClient().loadPlayer(this, playerId);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER_CENTERED_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_TOP_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievementImmediate(this, id);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScore(leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE_NOW.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScoreImmediate(this, leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievementImmediate(this, id);
            callbackContext.success();
        } else {
            callbackContext.error("Unknown action: " + action);
            return false;
        }
    } catch (JSONException ex) {
        callbackContext.error(ex.getMessage());
        return false;
    }

    return true;
}

From source file:com.projectgoth.mywebrtcdemo.RoomParametersFetcher.java

private void roomHttpResponseParse(String response) {
    Log.d(TAG, "Room response: " + response);
    try {//from ww w  .jav  a  2s . com
        LinkedList<IceCandidate> iceCandidates = null;
        SessionDescription offerSdp = null;
        JSONObject roomJson = new JSONObject(response);

        String result = roomJson.getString("result");
        if (!result.equals("SUCCESS")) {
            events.onSignalingParametersError("Room response error: " + result);
            return;
        }
        response = roomJson.getString("params");
        roomJson = new JSONObject(response);
        String roomId = roomJson.getString("room_id");
        String clientId = roomJson.getString("client_id");
        String wssUrl = roomJson.getString("wss_url");
        String wssPostUrl = roomJson.getString("wss_post_url");
        boolean initiator = (roomJson.getBoolean("is_initiator"));
        if (!initiator) {
            iceCandidates = new LinkedList<IceCandidate>();
            String messagesString = roomJson.getString("messages");
            JSONArray messages = new JSONArray(messagesString);
            for (int i = 0; i < messages.length(); ++i) {
                String messageString = messages.getString(i);
                JSONObject message = new JSONObject(messageString);
                String messageType = message.getString("type");
                Log.d(TAG, "GAE->C #" + i + " : " + messageString);
                if (messageType.equals("offer")) {
                    offerSdp = new SessionDescription(SessionDescription.Type.fromCanonicalForm(messageType),
                            message.getString("sdp"));
                } else if (messageType.equals("candidate")) {
                    IceCandidate candidate = new IceCandidate(message.getString("id"), message.getInt("label"),
                            message.getString("candidate"));
                    iceCandidates.add(candidate);
                } else {
                    Log.e(TAG, "Unknown message: " + messageString);
                }
            }
        }
        Log.d(TAG, "RoomId: " + roomId + ". ClientId: " + clientId);
        Log.d(TAG, "Initiator: " + initiator);
        Log.d(TAG, "WSS url: " + wssUrl);
        Log.d(TAG, "WSS POST url: " + wssPostUrl);

        LinkedList<PeerConnection.IceServer> iceServers = iceServersFromPCConfigJSON(
                roomJson.getString("pc_config"));
        boolean isTurnPresent = false;
        for (PeerConnection.IceServer server : iceServers) {
            Log.d(TAG, "IceServer: " + server);
            if (server.uri.startsWith("turn:")) {
                isTurnPresent = true;
                break;
            }
        }
        // Request TURN servers.
        if (!isTurnPresent) {
            LinkedList<PeerConnection.IceServer> turnServers = requestTurnServers(
                    roomJson.getString("turn_url"));
            for (PeerConnection.IceServer turnServer : turnServers) {
                Log.d(TAG, "TurnServer: " + turnServer);
                iceServers.add(turnServer);
            }
        }

        SignalingParameters params = new SignalingParameters(iceServers, initiator, clientId, wssUrl,
                wssPostUrl, offerSdp, iceCandidates);
        events.onSignalingParametersReady(params);
    } catch (JSONException e) {
        events.onSignalingParametersError("Room JSON parsing error: " + e.toString());
    } catch (IOException e) {
        events.onSignalingParametersError("Room IO error: " + e.toString());
    }
}

From source file:com.projectgoth.mywebrtcdemo.RoomParametersFetcher.java

private LinkedList<PeerConnection.IceServer> requestTurnServers(String url) throws IOException, JSONException {
    LinkedList<PeerConnection.IceServer> turnServers = new LinkedList<PeerConnection.IceServer>();
    Log.d(TAG, "Request TURN from: " + url);
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS);
    connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS);
    int responseCode = connection.getResponseCode();
    if (responseCode != 200) {
        throw new IOException("Non-200 response when requesting TURN server from " + url + " : "
                + connection.getHeaderField(null));
    }/*  w w w . ja va  2  s .  c  o  m*/
    InputStream responseStream = connection.getInputStream();
    String response = drainStream(responseStream);
    connection.disconnect();
    Log.d(TAG, "TURN response: " + response);
    JSONObject responseJSON = new JSONObject(response);
    String username = responseJSON.getString("username");
    String password = responseJSON.getString("password");
    JSONArray turnUris = responseJSON.getJSONArray("uris");
    for (int i = 0; i < turnUris.length(); i++) {
        String uri = turnUris.getString(i);
        turnServers.add(new PeerConnection.IceServer(uri, username, password));
    }
    return turnServers;
}

From source file:it.bradipao.berengar.DbTool.java

public static int json2table(SQLiteDatabase mDB, JSONObject jsonTable) {

    // vars//from w w  w  .j  a va 2 s .c  o  m
    JSONArray jsonRows = new JSONArray();
    JSONArray jsonColsName = new JSONArray();
    JSONArray jsonCols = null;
    ContentValues cv = null;

    int iRes = 0;
    try {
        // init database transaction
        mDB.beginTransaction();
        // fetch table name and drop if exists
        String sTableName = jsonTable.getString("table_name");
        mDB.execSQL("DROP TABLE IF EXISTS " + sTableName);
        if (GOLOG)
            Log.d(LOGTAG, "TABLE NAME : " + sTableName);
        // fetch and execute create sql
        String sTableSql = jsonTable.getString("table_sql");
        mDB.execSQL(sTableSql);
        // fetch columns name
        jsonColsName = jsonTable.getJSONArray("cols_name");
        // fetch rows array
        jsonRows = jsonTable.getJSONArray("rows");
        // iterate through rows
        for (int i = 0; i < jsonRows.length(); i++) {
            // fetch columns
            jsonCols = jsonRows.getJSONArray(i);
            // perform insert
            cv = new ContentValues();
            for (int j = 0; j < jsonCols.length(); j++)
                cv.put(jsonColsName.getString(j), jsonCols.getString(j));
            mDB.insert(sTableName, null, cv);
            if (GOLOG)
                Log.d(LOGTAG, "INSERT IN " + sTableName + " ID=" + jsonCols.getString(0));
        }
        iRes++;
        // set transaction successful
        mDB.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(LOGTAG, "error in json2table", e);
    } finally {
        // end transaction, commit if successful else rollback
        mDB.endTransaction();
    }

    return iRes;
}

From source file:org.kavaproject.kavatouch.internal.JSONDeviceConfiguration.java

public JSONDeviceConfiguration(Resources resources, int id) {
    InputStream jsonStream = resources.openRawResource(id);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int ctr;//from   w w w .  ja  v a  2  s. co  m
    try {
        ctr = jsonStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = jsonStream.read();
        }
        jsonStream.close();
    } catch (IOException e) {
        throw new Error(e);
    }
    try {
        JSONObject jConfiguration = new JSONObject(byteArrayOutputStream.toString());
        flipYAxis = jConfiguration.getBoolean("flipYAxis");
        useIPadTheme = jConfiguration.getBoolean("useIPadTheme");
        JSONArray jDeviceModifiers = jConfiguration.getJSONArray("deviceModifiers");
        for (int i = 0; i < jDeviceModifiers.length(); i++) {
            deviceModifiers.add(jDeviceModifiers.getString(i));
        }
        JSONArray jImageScaleModifiers = jConfiguration.getJSONArray("imageScaleModifiers");
        for (int i = 0; i < jImageScaleModifiers.length(); i++) {
            imageScaleModifiers.add(ImageScaleModifier.createFromJSON(jImageScaleModifiers.getJSONObject(i)));
        }
        double scale = jConfiguration.optDouble("scale");
        if (Double.isNaN(scale)) {
            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
            this.scale = displayMetrics.density;
        } else {
            this.scale = (float) scale;
        }
    } catch (JSONException e) {
        throw new Error(e);
    }
}

From source file:com.intellisol.plugin.Wallpaper.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {/*from   w  w  w .ja  va  2 s  .c om*/
        // get path from argument
        String path = args.getString(0);

        // get context (Android)
        Context ctxt = cordova.getActivity().getBaseContext();
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(ctxt);

        // get image file
        InputStream bitmapIn = cordova.getActivity().getAssets().open(path);
        Bitmap bitmap = BitmapFactory.decodeStream(bitmapIn);

        // set wallpaper
        wallpaperManager.setBitmap(bitmap);

    } catch (JSONException e) {
        // log error
        Log.d("Wallpaper", e.toString());
        return false;
    } catch (Exception e) {
        // log error
        Log.d("Wallpaper", e.toString());
        return false;
    }
    return true;
}

From source file:com.dubsar_dictionary.Dubsar.model.DailyWord.java

@Override
public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    int id = response.getInt(0);
    String name = response.getString(1);
    String pos = response.getString(2);
    int freqCnt = response.getInt(3);
    String inflections = response.getString(4);

    mWord = new Word(id, name, pos);

    mWord.setFreqCnt(freqCnt);/*from w  w  w .j  av a  2 s . c o  m*/
    mWord.setInflections(inflections);

    mExpirationMillis = response.getLong(5) * 1000;
}

From source file:io.rapidpro.androidchannel.json.JSON.java

public String[] getStringArray(String key) {
    try {//  w  w  w . j  av a  2  s  . com
        JSONArray array = m_o.getJSONArray(key);
        String[] strArray = new String[array.length()];
        for (int i = 0; i < strArray.length; i++) {
            strArray[i] = array.getString(i);
        }
        return strArray;
    } catch (Throwable t) {
        throw new JSONException(t);
    }
}

From source file:io.rapidpro.androidchannel.json.JSON.java

public String[] getStringArrayOpt(String key) {
    try {//from  w w w.j a  v a2 s. c  om
        JSONArray array = m_o.optJSONArray(key);
        if (array != null) {
            String[] strArray = new String[array.length()];
            for (int i = 0; i < strArray.length; i++) {
                strArray[i] = array.getString(i);
            }
            return strArray;
        }
        return null;
    } catch (Throwable t) {
        throw new JSONException(t);
    }
}