Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *//*  www .j  ava2  s. c  om*/
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

From source file:com.habzy.syncontacts.platform.User.java

/**
 * Creates and returns an instance of the user from the provided JSON data.
 * // ww  w .j av a2 s  .  co  m
 * @param user The JSONObject containing user data
 * @return user The new instance of Voiper user created from the JSON data.
 */
public static User valueOf(JSONObject user) {
    try {
        final String userName = user.getString("u");
        final String firstName = user.has("f") ? user.getString("f") : null;
        final String lastName = user.has("l") ? user.getString("l") : null;
        final String cellPhone = user.has("m") ? user.getString("m") : null;
        final String officePhone = user.has("o") ? user.getString("o") : null;
        final String homePhone = user.has("h") ? user.getString("h") : null;
        final String email = user.has("e") ? user.getString("e") : null;
        final boolean deleted = user.has("d") ? user.getBoolean("d") : false;
        final int userId = user.getInt("i");
        return new User(userName, firstName, lastName, cellPhone, officePhone, homePhone, email, deleted,
                userId);
    } catch (final Exception ex) {
        Log.i("User", "Error parsing JSON user object" + ex.toString());

    }
    return null;

}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }//from  w  ww  .  j  av a 2s.c o m
    // FIXME: until core fixes the annotation for architecture let's assume it's nullable
    String cacheName = "productsALL";
    if (architecture != null) {
        cacheName = "products" + architecture.name();
    }
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName,
            VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
    Iterable<VirtualMachineProduct> products = cache.get(ctx);

    if (products == null) {
        List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();

        try {
            InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");

            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject productSet = arr.getJSONObject(i);
                    String cloud, providerName;

                    if (productSet.has("cloud")) {
                        cloud = productSet.getString("cloud");
                    } else {
                        continue;
                    }
                    if (productSet.has("provider")) {
                        providerName = productSet.getString("provider");
                    } else {
                        continue;
                    }
                    if (!productSet.has("products")) {
                        continue;
                    }
                    if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) {
                        toCache = productSet;
                    }
                    if (providerName.equalsIgnoreCase(getProvider().getProviderName())
                            && cloud.equalsIgnoreCase(getProvider().getCloudName())) {
                        toCache = productSet;
                        break;
                    }
                }
                if (toCache == null) {
                    logger.warn("No products were defined");
                    return Collections.emptyList();
                }
                JSONArray plist = toCache.getJSONArray("products");

                for (int i = 0; i < plist.length(); i++) {
                    JSONObject product = plist.getJSONObject(i);
                    boolean supported = false;

                    if (architecture != null) {
                        if (product.has("architectures")) {
                            JSONArray architectures = product.getJSONArray("architectures");

                            for (int j = 0; j < architectures.length(); j++) {
                                String a = architectures.getString(j);

                                if (architecture.name().equals(a)) {
                                    supported = true;
                                    break;
                                }
                            }
                        }
                        if (!supported) {
                            continue;
                        }
                    }
                    if (product.has("excludesRegions")) {
                        JSONArray regions = product.getJSONArray("excludesRegions");

                        for (int j = 0; j < regions.length(); j++) {
                            String r = regions.getString(j);

                            if (r.equals(ctx.getRegionId())) {
                                supported = false;
                                break;
                            }
                        }
                    }
                    if (!supported) {
                        continue;
                    }
                    VirtualMachineProduct prd = toProduct(product);

                    if (prd != null) {
                        if (options != null) {
                            if (options.matches(prd)) {
                                list.add(prd);
                            }
                        } else {
                            list.add(prd);
                        }
                    }

                }

            } else {
                logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
            }
            input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
            if (input != null) {
                ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
                TreeSet<String> discard = new TreeSet<String>();
                boolean discardAll = false;

                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject listing = arr.getJSONObject(i);
                    String cloud, providerName, endpoint = null;

                    if (listing.has("cloud")) {
                        cloud = listing.getString("cloud");
                    } else {
                        continue;
                    }
                    if (listing.has("provider")) {
                        providerName = listing.getString("provider");
                    } else {
                        continue;
                    }
                    if (listing.has("endpoint")) {
                        endpoint = listing.getString("endpoint");
                    }
                    if (!cloud.equals(getProvider().getCloudName())
                            || !providerName.equals(getProvider().getProviderName())) {
                        continue;
                    }
                    if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) {
                        toCache = listing;
                        break;
                    }
                    if (endpoint == null && toCache == null) {
                        toCache = listing;
                    }
                }
                if (toCache != null) {
                    if (toCache.has("discardDefaults")) {
                        discardAll = toCache.getBoolean("discardDefaults");
                    }
                    if (toCache.has("discard")) {
                        JSONArray dlist = toCache.getJSONArray("discard");

                        for (int i = 0; i < dlist.length(); i++) {
                            discard.add(dlist.getString(i));
                        }
                    }
                    if (toCache.has("products")) {
                        JSONArray plist = toCache.getJSONArray("products");

                        for (int i = 0; i < plist.length(); i++) {
                            JSONObject product = plist.getJSONObject(i);
                            boolean supported = false;
                            if (architecture != null) {

                                if (product.has("architectures")) {
                                    JSONArray architectures = product.getJSONArray("architectures");

                                    for (int j = 0; j < architectures.length(); j++) {
                                        String a = architectures.getString(j);

                                        if (architecture.name().equals(a)) {
                                            supported = true;
                                            break;
                                        }
                                    }
                                }
                                if (!supported) {
                                    continue;
                                }
                            }
                            if (product.has("excludesRegions")) {
                                JSONArray regions = product.getJSONArray("excludesRegions");

                                for (int j = 0; j < regions.length(); j++) {
                                    String r = regions.getString(j);

                                    if (r.equals(ctx.getRegionId())) {
                                        supported = false;
                                        break;
                                    }
                                }
                            }
                            if (!supported) {
                                continue;
                            }
                            VirtualMachineProduct prd = toProduct(product);

                            if (prd != null) {
                                customList.add(prd);
                            }
                        }
                    }
                    if (!discardAll) {
                        for (VirtualMachineProduct product : list) {
                            if (!discard.contains(product.getProviderProductId())) {
                                customList.add(product);
                            }
                        }
                    }
                    list = customList;
                }
            }
            products = list;
            cache.put(ctx, products);

        } catch (IOException e) {
            throw new InternalException(e);
        } catch (JSONException e) {
            throw new InternalException(e);
        }
    }
    return products;
}

From source file:com.freecast.LudoCast.MainActivity.java

private void setupCastListener() {

    mCastConsumer = new VideoCastConsumerImpl() {

        @Override//from www  .  j  a va  2 s  . c  o  m
        public void onApplicationConnected(ApplicationMetadata appMetadata, String sessionId,
                boolean wasLaunched) {

            System.out.println("onApplicationConnected message = " + sessionId);

            Toast.makeText(MainActivity.this, "Device is Ready to Start Game!!!", Toast.LENGTH_SHORT).show();

            mAppConnected = true;
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onConnected() {

            System.out.println("MainActivity onConnected ");
            Createbnt.setText("Connecting");

        }

        @Override
        public void onDisconnected() {

            System.out.println("onDisconnected message ");

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onFailed(int resourceId, int statusCode) {

            System.out.println("onFailed message = " + statusCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onApplicationDisconnected(int errorCode) {

            System.out.println("onApplicationDisconnected message = " + errorCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public boolean onApplicationConnectionFailed(int errorCode) {

            System.out.println("onApplicationConnectionFailed message = " + errorCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

            return true;
        }

        @Override
        public void onDataMessageReceived(String message) {

            JSONObject obj = null;
            try {
                obj = new JSONObject(message);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            String command = null;
            try {
                command = obj.getString("command");
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (command.equals("connect_reply")) {
                boolean ret = false;
                try {
                    ret = obj.getBoolean("ret");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if (ret == false) {
                    String reason = null;
                    try {
                        reason = obj.getString("error");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.d(TAG, "error info: " + reason);
                    Toast.makeText(MainActivity.this, "Fail to connect Ludo Server !!!!", Toast.LENGTH_SHORT)
                            .show();

                } else {
                    connectstatus = true;
                    CreateConfigGame(message);
                }

            }

            try {
                protocol.parseMessage(message);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("MainActivity receiver message = " + message);
        }

        @Override
        public void onConnectionSuspended(int cause) {
            Log.d(TAG, "onConnectionSuspended() was called with cause: " + cause);
            com.freecast.LudoCast.Utils.showToast(MainActivity.this, R.string.connection_temp_lost);
        }

        @Override
        public void onConnectivityRecovered() {
            com.freecast.LudoCast.Utils.showToast(MainActivity.this, R.string.connection_recovered);
        }

        @Override
        public void onCastDeviceDetected(final RouteInfo info) {
            if (!CastPreference.isFtuShown(MainActivity.this)) {
                CastPreference.setFtuShown(MainActivity.this);

                Log.d(TAG, "Route is visible: " + info);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (mediaRouteMenuItem.isVisible()) {
                            Log.d(TAG, "Cast Icon is visible: " + info.getName());
                        }
                    }
                }, 1000);
            }
        }
    };

}

From source file:com.nextgis.firereporter.SettingsSupport.java

public SettingsSupport(Context context, PreferenceScreen screen) {
    this.screen = screen;
    this.context = context;

    // Load the preferences from an XML resource
    //addPreferencesFromResource(R.xml.preferences);

    mSendDataIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_INTERVAL);
    if (mSendDataIntervalPref != null) {
        int index = mSendDataIntervalPref.findIndexOfValue(mSendDataIntervalPref.getValue());
        if (index >= 0) {
            mSendDataIntervalPref.setSummary(mSendDataIntervalPref.getEntries()[index]);
        } else {//from ww w .j a v a2  s.com
            mSendDataIntervalPref.setSummary((String) mSendDataIntervalPref.getValue());
        }
    }

    mSaveBattPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE);
    if (mSaveBattPref != null)
        mSaveBattPref.setSummary(mSaveBattPref.isChecked() ? R.string.stOn : R.string.stOff);

    mNotifyLEDPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_LED);
    if (mNotifyLEDPref != null)
        mNotifyLEDPref.setSummary(mNotifyLEDPref.isChecked() ? R.string.stOn : R.string.stOff);

    mPlaySoundPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_SOUND);
    if (mPlaySoundPref != null)
        mPlaySoundPref.setSummary(mPlaySoundPref.isChecked() ? R.string.stOn : R.string.stOff);

    mVibroPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_VIBRO);
    if (mVibroPref != null)
        mVibroPref.setSummary(mVibroPref.isChecked() ? R.string.stOn : R.string.stOff);

    mRowCountPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_ROW_COUNT);
    if (mRowCountPref != null)
        mRowCountPref.setSummary((String) mRowCountPref.getText());

    mFireSearchRadiusPref = (EditTextPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_FIRE_SEARCH_RADIUS);
    if (mFireSearchRadiusPref != null)
        mFireSearchRadiusPref
                .setSummary((String) mFireSearchRadiusPref.getText() + " " + context.getString(R.string.km));

    mDayIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL);
    if (mDayIntervalPref != null) {
        int index = mDayIntervalPref.findIndexOfValue(mDayIntervalPref.getValue());
        if (index >= 0) {
            mDayIntervalPref.setSummary(mDayIntervalPref.getEntries()[index]);
        } else {
            mDayIntervalPref.setSummary((String) mDayIntervalPref.getValue());
        }
    }

    mSearchCurrentDatePref = (CheckBoxPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_SEARCH_CURR_DAY);
    if (mSearchCurrentDatePref != null)
        mSearchCurrentDatePref.setSummary(mSearchCurrentDatePref.isChecked() ? R.string.stSearchCurrentDayOn
                : R.string.stSearchCurrentDayOff);

    mNasaServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA);
    if (mNasaServerPref != null)
        mNasaServerPref.setSummary((String) mNasaServerPref.getText());
    mNasaServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_USER);
    if (mNasaServerUserPref != null)
        mNasaServerUserPref.setSummary((String) mNasaServerUserPref.getText());

    mUserServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER);
    if (mUserServerPref != null)
        mUserServerPref.setSummary((String) mUserServerPref.getText());
    mUserServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_USER);
    if (mUserServerUserPref != null)
        mUserServerUserPref.setSummary((String) mUserServerUserPref.getText());

    mScanServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_USER);
    if (mScanServerUserPref != null)
        mScanServerUserPref.setSummary((String) mScanServerUserPref.getText());

    mNasaServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_PASS);
    mUserServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_PASS);
    mScanServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_PASS);

    final Preference checkNasaConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_NASA_CHECK_CONN);
    final Preference checkUserConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_USER_CHECK_CONN);
    final Preference checkScanConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_CHECK_CONN);

    mReturnHandler = new Handler() {
        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            Bundle resultData = msg.getData();

            boolean bHaveErr = resultData.getBoolean(GetFiresService.ERROR);
            int nType = resultData.getInt(GetFiresService.SOURCE);
            if (bHaveErr) {
                Toast.makeText(SettingsSupport.this.context, resultData.getString(GetFiresService.ERR_MSG),
                        Toast.LENGTH_LONG).show();
                if (nType == 1) {//user
                    checkUserConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 2) {//nasa
                    checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 3) {//scanex
                    checkScanConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                }
            } else {

                String sData = resultData.getString(GetFiresService.JSON);
                if (nType == 1) {//user
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkUserConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkUserConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkUserConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 2) {//nasa
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkNasaConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkNasaConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 3) {//scanex
                    if (sData.length() == 0) {
                        String sMsg = "Connect failed";
                        Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                        checkScanConnPref.setSummary(R.string.stConnectionFailed);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                    } else {
                        checkScanConnPref.setSummary(R.string.stConnectionSucceeded);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_navigation_accept);

                        new HttpGetter(SettingsSupport.this.context, 4,
                                SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler,
                                true).execute(
                                        "http://fires.kosmosnimki.ru/SAPI/Account/Get/?CallBackName="
                                                + GetFiresService.USER_ID,
                                        sData);
                    }
                } else if (nType == 4) {//scanex detailes
                    try {
                        String sSubData = GetFiresService.removeJsonT(sData);
                        JSONObject rootobj = new JSONObject(sSubData);
                        String sStatus = rootobj.getString("Status");
                        if (sStatus.equals("OK")) {
                            JSONObject resobj = rootobj.getJSONObject("Result");
                            String sName = "";
                            if (!resobj.isNull("FullName"))
                                sName = resobj.getString("FullName");
                            String sPhone = "";
                            if (!resobj.isNull("Phone"))
                                sPhone = resobj.getString("Phone");
                            //add properties
                            if (sPhone.length() > 0) {
                                Preference PhonePref = new Preference(SettingsSupport.this.context);
                                PhonePref.setTitle(R.string.stScanexServerUserPhone);
                                PhonePref.setSummary(sPhone);
                                PhonePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(PhonePref);
                            }

                            if (sName.length() > 0) {
                                Preference NamePref = new Preference(SettingsSupport.this.context);
                                NamePref.setTitle(R.string.stScanexServerUserFullName);
                                NamePref.setSummary(sName);
                                NamePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(NamePref);
                            }

                        } else {
                            Toast.makeText(SettingsSupport.this.context, rootobj.getString("ErrorInfo"),
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
            }
        };
    };

    if (checkNasaConnPref != null)
        checkNasaConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mNasaServerPref.getText() + "?function=test_conn_nasa&user="
                        + mNasaServerUserPref.getText() + "&pass=" + mNasaServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 2,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkUserConnPref != null)
        checkUserConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mUserServerPref.getText() + "?function=test_conn_user&user="
                        + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 1,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkScanConnPref != null)
        checkScanConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //String sURL = mUserServerPref.getText() + "?function=test_conn_nasa&user=" + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new ScanexHttpLogin(SettingsSupport.this.context, 3,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(mScanServerUserPref.getText(), mScanServerPassPref.getText());
                return true;
            }
        });
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

private boolean handleCallback(String callback, JSONObject data) {
    switch (callback) {
    case Cobalt.JSCallbackOnBackButtonPressed:
        try {//from   w  ww  .  java 2s.  c  om
            onBackPressed(data.getBoolean(Cobalt.kJSValue));
            return true;
        } catch (JSONException exception) {
            if (Cobalt.DEBUG)
                Log.e(Cobalt.TAG, TAG + " - handleCallback: JSONException");
            exception.printStackTrace();
            return false;
        }
    case Cobalt.JSCallbackPullToRefreshDidRefresh:
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                onPullToRefreshDidRefresh();
            }
        });
        return true;
    case Cobalt.JSCallbackInfiniteScrollDidRefresh:
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                onInfiniteScrollDidRefresh();
            }
        });
        return true;
    default:
        return onUnhandledCallback(callback, data);
    }
}

From source file:se.frostyelk.cordova.amazon.ads.AmazonAds.java

private PluginResult executeCreateInterstitialAd(JSONObject options, final CallbackContext callbackContext) {
    if (options.has(OPTION_INTERSTITIAL_AD_ID)) {
        interstitialAdId = options.optString(OPTION_INTERSTITIAL_AD_ID);
    } else {// w  w w. ja  v  a 2  s .  com
        return new PluginResult(Status.ERROR, "Option " + OPTION_INTERSTITIAL_AD_ID + " is missing");
    }

    if (options.has(OPTION_IS_TESTING)) {
        try {
            isTesting = options.getBoolean(OPTION_IS_TESTING);
        } catch (JSONException e) {
            return new PluginResult(Status.ERROR, "Value of option " + OPTION_IS_TESTING + " is wrong");
        }
    }

    if (options.has(OPTION_DEBUG)) {
        try {
            AdRegistration.enableLogging(options.getBoolean(OPTION_DEBUG));
        } catch (JSONException e) {
            return new PluginResult(Status.ERROR, "Value of option " + OPTION_DEBUG + " is wrong");
        }
    } else {
        AdRegistration.enableLogging(false);
    }

    if (callbackContext == null) {
        return new PluginResult(Status.ERROR, "Callback function is missing");
    }

    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {

            if (interstitialAd == null) {
                interstitialAd = new InterstitialAd(cordova.getActivity());
                interstitialAd.setListener(new AmazonInterstitialAdListener());
            }

            AdRegistration.enableTesting(isTesting);

            try {
                AdRegistration.setAppKey(interstitialAdId);
            } catch (final IllegalArgumentException e) {
                callbackContext.error("Value of " + OPTION_INTERSTITIAL_AD_ID + " is wrong");
                return;
            }

            if (interstitialAd.loadAd()) {
                if (callbackContext != null) {
                    callbackContext.success();
                }
            } else {
                if (callbackContext != null) {
                    callbackContext.error("Failed to create Ad");
                }
            }
        }
    });

    return null;
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {/*from   ww w  . java  2  s .  co m*/
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}

From source file:drusy.ui.panels.SwitchStatePanel.java

public void update(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output,
            "Getting Switch status", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override/*from w w  w  . j  a va  2  s.c o  m*/
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                JSONArray switchStatusArray = obj.getJSONArray("result");

                for (int i = 0; i < switchStatusArray.length(); ++i) {
                    JSONObject switchStatus = switchStatusArray.getJSONObject(i);
                    String status = switchStatus.getString("link");
                    int id = switchStatus.getInt("id");

                    if (status.equals("up")) {
                        JSONArray switchMacArray = switchStatus.getJSONArray("mac_list");
                        JSONObject switchMac = switchMacArray.getJSONObject(i);
                        String hostname = switchMac.getString("hostname");
                        addUsersForSwitchIdAndHostname(id, hostname);
                    }
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch status", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch status", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:drusy.ui.panels.SwitchStatePanel.java

public void addUsersForSwitchIdAndHostname(int id, final String hostname) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_SWITCH_ID.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting Switch information",
            false);/*from  w  w  w . j  a v a  2 s . com*/

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                long txBytes = result.getLong("tx_bytes_rate");
                long rxBytes = result.getLong("rx_bytes_rate");

                addUser("", hostname, txBytes, rxBytes);
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch information", msg);
            }

            setVisible(true);
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch information", ex.getMessage());
        }
    });
}