Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

In this page you can find the example usage for org.json JSONObject optInt.

Prototype

public int optInt(String key, int defaultValue) 

Source Link

Document

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number.

Usage

From source file:com.mparticle.internal.ConfigManager.java

public synchronized void updateConfig(JSONObject responseJSON, boolean persistJson) throws JSONException {
    SharedPreferences.Editor editor = mPreferences.edit();
    if (persistJson) {
        saveConfigJson(responseJSON);//from w  w w.jav  a  2  s. c  o  m
    }

    if (responseJSON.has(KEY_UNHANDLED_EXCEPTIONS)) {
        mLogUnhandledExceptions = responseJSON.getString(KEY_UNHANDLED_EXCEPTIONS);
    }

    if (responseJSON.has(KEY_PUSH_MESSAGES)) {
        sPushKeys = responseJSON.getJSONArray(KEY_PUSH_MESSAGES);
        editor.putString(KEY_PUSH_MESSAGES, sPushKeys.toString());
    }

    mRampValue = responseJSON.optInt(KEY_RAMP, -1);

    if (responseJSON.has(KEY_OPT_OUT)) {
        mSendOoEvents = responseJSON.getBoolean(KEY_OPT_OUT);
    } else {
        mSendOoEvents = false;
    }

    if (responseJSON.has(ProviderPersistence.KEY_PERSISTENCE)) {
        setProviderPersistence(new ProviderPersistence(responseJSON, mContext));
    } else {
        setProviderPersistence(null);
    }

    mSessionTimeoutInterval = responseJSON.optInt(KEY_SESSION_TIMEOUT, -1);
    mUploadInterval = responseJSON.optInt(KEY_UPLOAD_INTERVAL, -1);

    mTriggerMessageMatches = null;
    mTriggerMessageHashes = null;
    if (responseJSON.has(KEY_TRIGGER_ITEMS)) {
        try {
            JSONObject items = responseJSON.getJSONObject(KEY_TRIGGER_ITEMS);
            if (items.has(KEY_MESSAGE_MATCHES)) {
                mTriggerMessageMatches = items.getJSONArray(KEY_MESSAGE_MATCHES);
            }
            if (items.has(KEY_TRIGGER_ITEM_HASHES)) {
                mTriggerMessageHashes = items.getJSONArray(KEY_TRIGGER_ITEM_HASHES);
            }
        } catch (JSONException jse) {

        }

    }

    if (responseJSON.has(KEY_INFLUENCE_OPEN)) {
        mInfluenceOpenTimeout = responseJSON.getLong(KEY_INFLUENCE_OPEN) * 60 * 1000;
    } else {
        mInfluenceOpenTimeout = 30 * 60 * 1000;
    }

    mRestrictAAIDfromLAT = responseJSON.optBoolean(KEY_AAID_LAT, true);
    mIncludeSessionHistory = responseJSON.optBoolean(KEY_INCLUDE_SESSION_HISTORY, true);
    if (responseJSON.has(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED)) {
        MParticle.setDevicePerformanceMetricsDisabled(
                responseJSON.optBoolean(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED, false));
    }

    editor.apply();
    applyConfig();

    MParticle.getInstance().getKitManager().updateKits(responseJSON.optJSONArray(KEY_EMBEDDED_KITS));
}

From source file:com.mikecorrigan.trainscorekeeper.FragmentButton.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.vc(VERBOSE, TAG, "onCreateView: inflater=" + inflater + ", container=" + container
            + ", savedInstanceState=" + Utils.bundleToString(savedInstanceState));

    View rootView = inflater.inflate(R.layout.fragment_button, container, false);

    Bundle args = getArguments();//from w  w w. jav a 2  s. c om
    if (args == null) {
        Log.e(TAG, "onCreateView: missing arguments");
        return rootView;
    }

    // The activity must support a standard OnClickListener.
    final MainActivity mainActivity = (MainActivity) getActivity();
    final Context context = mainActivity;

    players = mainActivity.getPlayers();
    if (players != null) {
        players.addListener(mPlayersListener);
    }

    // final int index = args.getInt(ARG_INDEX);
    final String tabSpec = args.getString(ARG_TAB_SPEC);

    try {
        JSONObject jsonTab = new JSONObject(tabSpec);

        final String tabName = jsonTab.optString(JsonSpec.TAB_NAME, JsonSpec.DEFAULT_TAB_NAME);
        if (!TextUtils.isEmpty(tabName)) {
            TextView tv = (TextView) rootView.findViewById(R.id.text_view_name);
            tv.setText(tabName);
        }

        tabLayout = (LinearLayout) rootView;

        JSONArray jsonSections = jsonTab.getJSONArray(JsonSpec.SECTIONS_KEY);
        for (int i = 0; i < jsonSections.length(); i++) {
            JSONObject jsonSection = jsonSections.getJSONObject(i);

            LinearLayout sectionLayout = new LinearLayout(context);
            sectionLayout.setOrientation(LinearLayout.VERTICAL);
            tabLayout.addView(sectionLayout);

            // If a section is named, label it.
            final String sectionName = jsonSection.optString(JsonSpec.SECTION_NAME,
                    JsonSpec.DEFAULT_SECTION_NAME);
            if (!TextUtils.isEmpty(sectionName)) {
                TextView textView = new TextView(context);
                textView.setText(sectionName);
                sectionLayout.addView(textView);
            }

            int numColumns = jsonSection.optInt(JsonSpec.SECTION_COLUMNS, JsonSpec.DEFAULT_SECTION_COLUMNS);

            List<View> buttonViews = new LinkedList<View>();

            JSONArray buttons = jsonSection.getJSONArray(JsonSpec.BUTTONS_KEY);
            for (int k = 0; k < buttons.length(); k++) {
                JSONObject jsonButton = buttons.getJSONObject(k);

                ScoreButton buttonView = new ScoreButton(context);
                buttonView.setButtonSpec(jsonButton);
                buttonView.setOnClickListener(mainActivity.getScoreClickListener());

                // Add the button to the section.
                buttonViews.add(buttonView);
            }

            GridView gridView = new GridView(context);
            gridView.setNumColumns(numColumns);
            gridView.setAdapter(new ViewAdapter(context, buttonViews));
            sectionLayout.addView(gridView);
        }
    } catch (JSONException e) {
        Log.th(TAG, e, "onCreateView: failed to parse JSON");
    }

    updateUi();

    return rootView;
}

From source file:com.linkedin.platform.errors.ApiErrorResponse.java

public static ApiErrorResponse build(JSONObject jsonErr) throws JSONException {
    return new ApiErrorResponse(jsonErr, jsonErr.optInt(ERROR_CODE, -1), jsonErr.optString(MESSAGE),
            jsonErr.optString(REQUEST_ID), jsonErr.optInt(STATUS, -1), jsonErr.optLong(TIMESTAMP, 0));
}

From source file:com.QuarkLabs.BTCeClient.services.CheckTickersService.java

@Override
protected void onHandleIntent(Intent intent) {

    SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(this);
    Set<String> x = sh.getStringSet("PairsToDisplay", new HashSet<String>());
    if (x.size() == 0) {
        return;/*w  w  w  .j av a 2 s  .  c o  m*/
    }
    String[] pairs = x.toArray(new String[x.size()]);
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    String url = BASE_URL;
    for (String xx : pairs) {
        url += xx.replace("/", "_").toLowerCase(Locale.US) + "-";
    }
    SimpleRequest reqSim = new SimpleRequest();

    if (networkInfo != null && networkInfo.isConnected()) {
        JSONObject data = null;
        try {
            data = reqSim.makeRequest(url);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (data != null && data.optInt("success", 1) != 0) {

            ArrayList<Ticker> tickers = new ArrayList<>();
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = data.keys(); iterator.hasNext();) {
                String key = iterator.next();
                JSONObject pairData = data.optJSONObject(key);
                Ticker ticker = new Ticker(key);
                ticker.setUpdated(pairData.optLong("updated"));
                ticker.setAvg(pairData.optDouble("avg"));
                ticker.setBuy(pairData.optDouble("buy"));
                ticker.setSell(pairData.optDouble("sell"));
                ticker.setHigh(pairData.optDouble("high"));
                ticker.setLast(pairData.optDouble("last"));
                ticker.setLow(pairData.optDouble("low"));
                ticker.setVol(pairData.optDouble("vol"));
                ticker.setVolCur(pairData.optDouble("vol_cur"));
                tickers.add(ticker);
            }

            String message = checkNotifiers(tickers, TickersStorage.loadLatestData());

            if (message.length() != 0) {
                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        NOTIFICATION_SERVICE);
                NotificationCompat.Builder nb = new NotificationCompat.Builder(this)
                        .setContentTitle(getResources().getString(R.string.app_name))
                        .setSmallIcon(R.drawable.ic_stat_bitcoin_sign)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(message.substring(0, message.length() - 2));
                notificationManager.notify(ConstantHolder.ALARM_NOTIF_ID, nb.build());
            }

            Map<String, Ticker> newData = new HashMap<>();
            for (Ticker ticker : tickers) {
                newData.put(ticker.getPair(), ticker);
            }
            TickersStorage.saveData(newData);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("UpdateTickers"));
        }
    } else {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(CheckTickersService.this, "Unable to fetch data", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

From source file:com.funzio.pure2D.particles.nova.vo.TornadoAnimatorVO.java

public TornadoAnimatorVO(final JSONObject json) throws JSONException {
    super(json);/*from   w  w  w  .  ja  v a 2  s .  c  o  m*/

    dx = NovaVO.getListInt(json, "dx");
    dy = NovaVO.getListInt(json, "dy");
    circle_radius = NovaVO.getListInt(json, "circle_radius");
    circle_num = NovaVO.getListInt(json, "circle_num");
    circle_interpolation = NovaVO.getListString(json, "circle_interpolation");
    circle_multiplier = NovaVO.getListFloat(json, "circle_multiplier");
    circle_ratio = NovaVO.getListFloat(json, "circle_ratio");

    z_enabled = json.optInt("z_enabled", 0) > 0;
}

From source file:com.commontime.plugin.notification.Notification.java

/**
 * Update multiple local notifications./*from w  w  w.  ja  va  2  s .c o  m*/
 *
 * @param updates NotificationWrapper properties including their IDs
 */
private void update(JSONArray updates) {
    for (int i = 0; i < updates.length(); i++) {
        JSONObject update = updates.optJSONObject(i);
        int id = update.optInt("id", 0);

        NotificationWrapper notification = getNotificationMgr().update(id, update, TriggerReceiver.class);

        fireEvent("update", notification);
    }
}

From source file:org.apache.cordova.navigationmenu.NavigationMenu.java

private void appendItem(Menu menu, JSONObject menuItem) {
    try {/*www .  jav a 2 s.co  m*/
        Integer menuId = menuItem.getInt("id");
        Integer order = menuItem.optInt("order", 1);
        String name = menuItem.getString("name");
        menu.add(Menu.NONE, menuId, order, name);
    } catch (JSONException e) {
        this.webView.sendJavascript("console.log('Invalid menu option');");
    }
}

From source file:com.sina.weibo.sdk_lib.openapi.models.FavoriteList.java

public static FavoriteList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*www . j  a  v a 2s . co  m*/

    FavoriteList favorites = new FavoriteList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        favorites.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("favorites");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            favorites.favoriteList = new ArrayList<Favorite>(length);
            for (int ix = 0; ix < length; ix++) {
                favorites.favoriteList.add(Favorite.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return favorites;
}

From source file:com.mikecorrigan.trainscorekeeper.ScoreEvent.java

public ScoreEvent(int playerId, final String playerName, JSONObject jsonButton) {
    this.playerId = playerId;
    this.playerName = playerName;
    this.type = jsonButton.optInt(JsonSpec.BUTTON_TYPE, JsonSpec.DEFAULT_BUTTON_TYPE);
    this.value = jsonButton.optInt(JsonSpec.BUTTON_VALUE, JsonSpec.DEFAULT_BUTTON_VALUE);
    this.history = jsonButton.optString(JsonSpec.BUTTON_HISTORY, JsonSpec.DEFAULT_BUTTON_HISTORY);

    Log.vc(VERBOSE, TAG, "ctor: " + this);
}

From source file:com.mikecorrigan.trainscorekeeper.ScoreEvent.java

public ScoreEvent(JSONObject jsonScoreEvent) {
    this.playerId = jsonScoreEvent.optInt(JsonSpec.SCORE_ID, JsonSpec.DEFAULT_SCORE_ID);
    this.playerName = jsonScoreEvent.optString(JsonSpec.SCORE_NAME, JsonSpec.DEFAULT_SCORE_NAME);
    this.type = jsonScoreEvent.optInt(JsonSpec.SCORE_TYPE, JsonSpec.DEFAULT_SCORE_TYPE);
    this.value = jsonScoreEvent.optInt(JsonSpec.SCORE_VALUE, JsonSpec.DEFAULT_SCORE_VALUE);
    this.history = jsonScoreEvent.optString(JsonSpec.SCORE_HISTORY, JsonSpec.DEFAULT_SCORE_HISTORY);

    Log.vc(VERBOSE, TAG, "ctor: " + this);
}