Example usage for android.os Bundle getInt

List of usage examples for android.os Bundle getInt

Introduction

In this page you can find the example usage for android.os Bundle getInt.

Prototype

public int getInt(String key) 

Source Link

Document

Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.

Usage

From source file:org.thoughtland.xlocation.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;//from   w  ww . ja v  a  2s.c  o m

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        setTitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        setTitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        setTitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        setTitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        setTitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spAdapter.add(getString(R.string.title_default));
    for (int i = 1; i <= 4; i++)
        spAdapter.add(getString(R.string.title_alternate) + " " + i);
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setText(R.string.menu_toggle);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}

From source file:biz.bokhorst.xprivacy.ActivityShare.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check privacy service client
    if (!PrivacyService.checkClient())
        return;//from   ww  w  . j av a  2  s. co  m

    // Get data
    int userId = Util.getUserId(Process.myUid());
    final Bundle extras = getIntent().getExtras();
    final String action = getIntent().getAction();
    final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList)
            : new int[0]);
    final String restrictionName = (extras != null ? extras.getString(cRestriction) : null);
    int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1);
    if (action.equals(ACTION_EXPORT))
        mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null);

    // License check
    if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) {
        if (!Util.isProEnabled() && Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) {
        if (Util.hasProLicense(this) == null) {
            Util.viewUri(this, ActivityMain.cProUri);
            finish();
            return;
        }
    }

    // Registration check
    if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) {
        finish();
        return;
    }

    // Check whether we need a user interface
    if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false))
        mInteractive = true;

    // Set layout
    setContentView(R.layout.sharelist);
    setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar));

    // Reference controls
    final TextView tvDescription = (TextView) findViewById(R.id.tvDescription);
    final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle);
    final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle);
    final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
    RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear);
    RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull);
    RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand);
    RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand);
    final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate);
    final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear);
    final Button btnOk = (Button) findViewById(R.id.btnOk);
    final Button btnCancel = (Button) findViewById(R.id.btnCancel);

    // Set title
    if (action.equals(ACTION_TOGGLE)) {
        mActionId = R.string.menu_toggle;
        getSupportActionBar().setSubtitle(R.string.menu_toggle);
    } else if (action.equals(ACTION_IMPORT)) {
        mActionId = R.string.menu_import;
        getSupportActionBar().setSubtitle(R.string.menu_import);
    } else if (action.equals(ACTION_EXPORT)) {
        mActionId = R.string.menu_export;
        getSupportActionBar().setSubtitle(R.string.menu_export);
    } else if (action.equals(ACTION_FETCH)) {
        mActionId = R.string.menu_fetch;
        getSupportActionBar().setSubtitle(R.string.menu_fetch);
    } else if (action.equals(ACTION_SUBMIT)) {
        mActionId = R.string.menu_submit;
        getSupportActionBar().setSubtitle(R.string.menu_submit);
    } else {
        finish();
        return;
    }

    // Get localized restriction name
    List<String> listRestrictionName = new ArrayList<String>(
            PrivacyManager.getRestrictions(this).navigableKeySet());
    listRestrictionName.add(0, getString(R.string.menu_all));

    // Build restriction adapter
    SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    saRestriction.addAll(listRestrictionName);

    // Setup restriction spinner
    int pos = 0;
    if (restrictionName != null)
        for (String restriction : PrivacyManager.getRestrictions(this).values()) {
            pos++;
            if (restrictionName.equals(restriction))
                break;
        }

    spRestriction.setAdapter(saRestriction);
    spRestriction.setSelection(pos);

    // Build template adapter
    SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
    spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    String defaultName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, "0",
            getString(R.string.title_default));
    spAdapter.add(defaultName);
    for (int i = 1; i <= 4; i++) {
        String alternateName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, Integer.toString(i),
                getString(R.string.title_alternate) + " " + i);
        spAdapter.add(alternateName);
    }
    spTemplate.setAdapter(spAdapter);

    // Build application list
    AppListTask appListTask = new AppListTask();
    appListTask.executeOnExecutor(mExecutor, uids);

    // Import/export filename
    if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) {
        // Check for availability of sharing intent
        Intent file = new Intent(Intent.ACTION_GET_CONTENT);
        file.setType("file/*");
        boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file);

        // Get file name
        if (mFileName == null)
            if (action.equals(ACTION_EXPORT)) {
                String packageName = null;
                if (uids.length == 1)
                    try {
                        ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]);
                        packageName = appInfo.getPackageName().get(0);
                    } catch (Throwable ex) {
                        Util.bug(null, ex);
                    }
                mFileName = getFileName(this, hasIntent, packageName);
            } else
                mFileName = (hasIntent ? null : getFileName(this, false, null));

        if (mFileName == null)
            fileChooser();
        else
            showFileName();

        if (action.equals(ACTION_IMPORT))
            cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_FETCH)) {
        tvDescription.setText(getBaseURL());
        cbClear.setVisibility(View.VISIBLE);

    } else if (action.equals(ACTION_TOGGLE)) {
        tvDescription.setVisibility(View.GONE);
        spRestriction.setVisibility(View.VISIBLE);
        svToggle.setVisibility(View.VISIBLE);

        // Listen for radio button
        rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                btnOk.setEnabled(checkedId >= 0);
                spRestriction.setVisibility(
                        checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE
                                : View.VISIBLE);

                spTemplate.setVisibility(checkedId == R.id.rbTemplateCategory
                        || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet
                        || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE);
            }
        });

        boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
        rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE);
        rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE);

        if (choice == CHOICE_CLEAR)
            rbClear.setChecked(true);
        else if (choice == CHOICE_TEMPLATE)
            rbTemplateFull.setChecked(true);

    } else
        tvDescription.setText(getBaseURL());

    if (mInteractive) {
        // Enable ok
        // (showFileName does this for export/import)
        if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH))
            btnOk.setEnabled(true);

        // Listen for ok
        btnOk.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnOk.setEnabled(false);

                // Toggle
                if (action.equals(ACTION_TOGGLE)) {
                    mRunning = true;
                    for (int i = 0; i < rgToggle.getChildCount(); i++)
                        ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false);
                    int pos = spRestriction.getSelectedItemPosition();
                    String restrictionName = (pos == 0 ? null
                            : (String) PrivacyManager.getRestrictions(ActivityShare.this).values().toArray()[pos
                                    - 1]);
                    new ToggleTask().executeOnExecutor(mExecutor, restrictionName);

                    // Import
                } else if (action.equals(ACTION_IMPORT)) {
                    mRunning = true;
                    cbClear.setEnabled(false);
                    new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked());
                }

                // Export
                else if (action.equals(ACTION_EXPORT)) {
                    mRunning = true;
                    new ExportTask().executeOnExecutor(mExecutor, new File(mFileName));

                    // Fetch
                } else if (action.equals(ACTION_FETCH)) {
                    if (uids.length > 0) {
                        mRunning = true;
                        cbClear.setEnabled(false);
                        new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked());
                    }
                }

                // Submit
                else if (action.equals(ACTION_SUBMIT)) {
                    if (uids.length > 0) {
                        if (uids.length <= cSubmitLimit) {
                            mRunning = true;
                            new SubmitTask().executeOnExecutor(mExecutor);
                        } else {
                            String message = getString(R.string.msg_limit, cSubmitLimit + 1);
                            Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show();
                            btnOk.setEnabled(false);
                        }
                    }
                }
            }
        });

    } else
        btnOk.setEnabled(false);

    // Listen for cancel
    btnCancel.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mRunning) {
                mAbort = true;
                Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show();
            } else
                finish();
        }
    });
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static String buildArguments(final Bundle args) {
    final Set<String> keys = args.keySet();
    final JSONObject json = new JSONObject();
    for (final String key : keys) {
        final Object value = args.get(key);
        if (value == null) {
            continue;
        }//from   w  ww  .  j  av a2  s .  co m
        try {
            if (value instanceof Boolean) {
                json.put(key, args.getBoolean(key));
            } else if (value instanceof Integer) {
                json.put(key, args.getInt(key));
            } else if (value instanceof Long) {
                json.put(key, args.getLong(key));
            } else if (value instanceof String) {
                json.put(key, args.getString(key));
            } else {
                Log.w(LOGTAG, "Unknown type " + (value != null ? value.getClass().getSimpleName() : null)
                        + " in arguments key " + key);
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        }
    }
    return json.toString();
}

From source file:org.elasticdroid.SshConnectorView.java

/**
 * Restore instance state when the activity is reconstructed after a destroy
 * /* w w  w.j  a  v a  2 s  . c  o  m*/
 * This method restores:
 * <ul>
 * <li></li>
 * </ul>
 */
@SuppressWarnings("unchecked")
@Override
public void onRestoreInstanceState(Bundle stateToRestore) {
    //restore alertDialogDisplayed boolean
    alertDialogDisplayed = stateToRestore.getBoolean("alertDialogDisplayed");
    Log.v(this.getClass().getName(), "alertDialogDisplayed = " + alertDialogDisplayed);
    alertDialogMessage = stateToRestore.getString("alertDialogMessage");

    //was a progress dialog being displayed? Restore the answer to this question.
    progressDialogDisplayed = stateToRestore.getBoolean("progressDialogDisplayed");
    Log.v(this.getClass().getName() + ".onRestoreInstanceState",
            "progressDialogDisplayed:" + progressDialogDisplayed);

    /*get the model data back, so that you can inform the model that the activity
     * has come back up. */
    Object retained = getLastNonConfigurationInstance();
    //if there was a model executing when the object was destroyed, retained will be an 
    //instance of SecurityGroupsModel
    if (retained instanceof SecurityGroupsModel) {
        Log.i(TAG + ".onRestoreInstanceState()", "Reclaiming previous " + "background task");
        securityGroupsModel = (SecurityGroupsModel) retained;
        securityGroupsModel.setActivity(this);//tell the model of the new activity created
    } else {
        securityGroupsModel = null;

        Log.v(TAG, "No model object, or model finished before activity " + "was recreated.");

        //now if there is no model anymore, and progressDialogDisplayed is set to true,
        //reset it to false, because the model finished executing before the restart
        if (progressDialogDisplayed) {
            progressDialogDisplayed = false;
        }
    }

    Log.d(TAG, "Restoring open ports data if any");

    try {
        openPorts = (ArrayList<String>) stateToRestore.getSerializable("openPorts");
    } catch (Exception exception) {
        openPorts = null;
    }

    //if we have openPorts data, populate the spinner
    if (openPorts != null) {
        populateSpinner();
        //populate spinner will have set the spinner to port 22
        //or to the first index
        //reposition the selected index
        ((Spinner) findViewById(R.id.sshConnectorPortSpinner))
                .setSelection(stateToRestore.getInt("selectedPortPos"));
    }

    //if the user has entered new username, set that into EditText
    if (stateToRestore.getString("sshUsername") != null) {
        ((EditText) findViewById(R.id.sshConnectorUsernameEditTextView))
                .setText(stateToRestore.getString("sshUsername"));
    }

    //set the pubkey auth checkbox
    ((CheckBox) findViewById(R.id.sshConnectorUsePublicKeyAuth))
            .setChecked(stateToRestore.getBoolean("usePubkeyAuth"));
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * checks intent configuration parameters
 * @param extras//from   w  w  w  .ja va 2s .c  o  m
 */
private void getExtraParameters(Bundle extras) {
    if (extras != null) {
        writeToLog("configurationReceiver.onReceive() extras : " + extras.keySet());

        if (extras != null) {
            appId = extras.getString(UploadConstants.PREF_APPID_KEY);

            if (extras.containsKey(UploadConstants.PREF_API_KEY))
                apiKey = extras.getString(UploadConstants.PREF_API_KEY);

            if (extras.containsKey(UploadConstants.PREF_OPENCELL_UPLOAD_URL_KEY))
                openCellUrl = extras.getString(UploadConstants.PREF_OPENCELL_UPLOAD_URL_KEY);

            if (extras.containsKey(UploadConstants.PREF_OPENCELL_NETWORK_UPLOAD_URL_KEY))
                networksUrl = extras.getString(UploadConstants.PREF_OPENCELL_NETWORK_UPLOAD_URL_KEY);

            testEnvironment = extras.getBoolean(UploadConstants.PREF_TEST_ENVIRONMENT_KEY,
                    UploadConstants.PREF_TEST_ENVIRONMENT);

            if (openCellUrl == null) {
                if (testEnvironment) {
                    openCellUrl = UploadConstants.OPEN_CELL_TEST_UPLOAD_URL;
                } else {
                    openCellUrl = UploadConstants.OPEN_CELL_DEFAULT_UPLOAD_URL;
                }
            }

            if (networksUrl == null) {
                if (testEnvironment) {
                    networksUrl = UploadConstants.OPENCELL_NETWORKS_TEST_UPLOAD_URL;
                } else {
                    networksUrl = UploadConstants.OPENCELL_NETWORKS_UPLOAD_URL;
                }
            }

            if (extras.containsKey(UploadConstants.PREF_NEW_DATA_CHECK_INTERVAL_KEY))
                newDataCheckInterval = extras.getLong(UploadConstants.PREF_NEW_DATA_CHECK_INTERVAL_KEY);

            if (newDataCheckInterval < UploadConstants.NEW_DATA_CHECK_INTERVAL_LONG_DEFAULT)
                newDataCheckInterval = UploadConstants.NEW_DATA_CHECK_INTERVAL_LONG_DEFAULT;

            if (extras.containsKey(UploadConstants.PREF_ONLY_WIFI_UPLOAD_KEY))
                wifiOnly = extras.getBoolean(UploadConstants.PREF_ONLY_WIFI_UPLOAD_KEY);

            // check if the maxLogFileSize parameter is provided through intent         
            if (extras.containsKey(UploadConstants.PREFKEY_MAX_LOG_SIZE_INT)) {
                maxLogFileSize = extras.getInt(UploadConstants.PREFKEY_MAX_LOG_SIZE_INT);

                mLibContext.getLogService().setMaxLogFileSize(maxLogFileSize);
            }

            // check if the logToFileEnabled parameter is provided through intent         
            if (extras.containsKey(UploadConstants.PREFKEY_LOG_TO_FILE)) {
                logToFileEnabled = extras.getBoolean(UploadConstants.PREFKEY_LOG_TO_FILE);

                mLibContext.getLogService().setFileLoggingEnabled(logToFileEnabled);
            }
        }

        writeToLog("onConfigurationReceiver ()");
        writeToLog("apiKey = " + apiKey);
        writeToLog("openCellUrl = " + openCellUrl);
        writeToLog("networks url = " + networksUrl);
        writeToLog("newDataCheckInterval = " + newDataCheckInterval);
        writeToLog("wifiOnly = " + wifiOnly);
        writeToLog("testEnvironment = " + testEnvironment);
    }
}

From source file:org.anhonesteffort.flock.SubscriptionGoogleFragment.java

private void handleRefreshDaysTillCharge() {
    if (recurringTask != null)
        return;/*  www.java 2 s .  c  o  m*/

    recurringTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleRefreshDaysTillCharge");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();

            if (subscriptionActivity.billingService == null) {
                Log.e(TAG, "billing service is null");
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
                return result;
            }

            try {

                Bundle ownedItems = subscriptionActivity.billingService.getPurchases(3,
                        SubscriptionGoogleFragment.class.getPackage().getName(), PRODUCT_TYPE_SUBSCRIPTION,
                        null);

                ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                for (int i = 0; i < purchaseDataList.size(); ++i) {
                    JSONObject productObject = new JSONObject(purchaseDataList.get(i));
                    if (productObject.getString("productId").equals(SKU_YEARLY_SUBSCRIPTION)) {
                        long purchaseTime = productObject.getLong("purchaseTime");
                        long msSincePurchase = new Date().getTime() - purchaseTime;
                        if (msSincePurchase < 0)
                            msSincePurchase = 0;

                        daysTillNextCharge = 365 - (msSincePurchase / 1000 / 60 / 60 / 24);
                        if (daysTillNextCharge < 0)
                            daysTillNextCharge = 0;
                    }
                }

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (RemoteException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            } catch (JSONException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            recurringTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS)
                handleUpdateUi();
            else
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
        }
    }.execute();
}

From source file:com.example.alvarpao.popularmovies.MovieGridFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

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

    // The adapter is initialized with an empty array if state wasn't restore on rotation, if
    // it was, the array of movies already has the saved data.
    //Toast.makeText(getActivity(), "mMovies size restored: " + mMovies.size(), Toast.LENGTH_SHORT).show();
    mMovieAdapter = new MovieAdapter(getActivity(), mMovies);
    mMoviesGridView = (GridView) rootView.findViewById(R.id.movies_grid);
    mMoviesGridView.setDrawSelectorOnTop(true);
    mMoviesGridView.setAdapter(mMovieAdapter);
    mMoviesGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            // This will force to draw the selector on top of the poster for the selected movie
            view.setSelected(true);/* ww w.  j  a  v a2s  . c om*/
            mSelectedMovie = position;
            // A selection occurred as opposed to selecting the first visible item by default
            // so the details fragment is not empty in the two-pane layout.
            mSelectionOccurred = true;
            //Toast.makeText(getActivity(), "Selected Movie: " +
            // ((Movie) mMoviesGridView.getItemAtPosition(position)).getOriginalTitle(),
            // Toast.LENGTH_SHORT).show();
            Movie movie = mMovieAdapter.getItem(position);
            // A movie has been selected so the MainActivity has to be notified to take
            // appropriate action
            ((Callback) getActivity()).onItemSelected(movie);
        }
    });

    // Handles pagination for movie grid, except in the case the sort option is "Favorites",
    // since we don't need pagination in that case
    mMoviesGridView.setOnScrollListener(this);

    // If a rotation occurred, restore the selected movie (either selected by the user or
    // "selected" by default (first visible movie before rotation))
    // The restore of the details fragment with this selected after rotation is handled in the
    // onCreateOptionsMenu() method which is called after onCreateView()
    if (savedInstanceState != null && savedInstanceState.containsKey((SELECTED_MOVIE)))
        mSelectedMovie = savedInstanceState.getInt(SELECTED_MOVIE);

    return rootView;
}

From source file:org.anhonesteffort.flock.SubscriptionStripeFragment.java

private void handleVerifyCardAndPutToServer() {
    if (asyncTask != null)
        return;//  w  w w. j a va  2s.c om

    asyncTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleVerifyCardAndPutToServer()");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        private String handleGetStripeCardTokenId(String cardNumber, String cardExpiration, String cardCVC)
                throws StripeException {
            String[] expiration = cardExpiration.split("/");
            Integer expirationMonth = Integer.valueOf(expiration[0]);
            Integer expirationYear;

            if (expiration[1].length() == 4)
                expirationYear = Integer.valueOf(expiration[1]);
            else
                expirationYear = Integer.valueOf(expiration[1]) + 2000;

            java.util.Map<String, Object> cardParams = new HashMap<String, Object>();
            java.util.Map<String, Object> tokenParams = new HashMap<String, Object>();

            cardParams.put("number", cardNumber.replace(" ", ""));
            cardParams.put("exp_month", expirationMonth);
            cardParams.put("exp_year", expirationYear);
            cardParams.put("cvc", cardCVC);

            tokenParams.put("card", cardParams);

            return Token.create(tokenParams, OwsRegistration.STRIPE_PUBLIC_KEY).getId();
        }

        private void handlePutStripeTokenToServer(String stripeTokenId)
                throws IOException, RegistrationApiException, CardException {
            RegistrationApi registrationApi = new RegistrationApi(subscriptionActivity);
            registrationApi.setStripeCard(subscriptionActivity.davAccount, stripeTokenId);
        }

        private void handleUpdateSubscriptionStore(String cardNumber, String cardExpiration)
                throws JsonProcessingException {
            String cardNoSpaces = cardNumber.replace(" ", "");
            String lastFour = cardNoSpaces.substring(cardNoSpaces.length() - 4);

            FlockCardInformation cardInformation = new FlockCardInformation(
                    subscriptionActivity.davAccount.getUserId(), lastFour, cardExpiration);

            StripePlan newStripePlan = new StripePlan(subscriptionActivity.davAccount.getUserId(), "nope");

            AccountStore.setLastChargeFailed(subscriptionActivity, false);
            AccountStore.setSubscriptionPlan(subscriptionActivity, newStripePlan);
            AccountStore.setAutoRenew(subscriptionActivity, true);
            AccountStore.setCardInformation(subscriptionActivity, Optional.of(cardInformation));
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();
            String cardNumber = ((TextView) subscriptionActivity.findViewById(R.id.card_number)).getText()
                    .toString();
            String cardExpiration = ((TextView) subscriptionActivity.findViewById(R.id.card_expiration))
                    .getText().toString();
            String cardCVC = ((TextView) subscriptionActivity.findViewById(R.id.card_cvc)).getText().toString();

            if (StringUtils.isEmpty(cardNumber) || cardNumber.contains("*")) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_NUMBER_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardExpiration) || cardExpiration.split("/").length != 2) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_EXPIRATION_INVALID);
                return result;
            }

            if (StringUtils.isEmpty(cardCVC) || cardCVC.length() < 1) {
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CARD_CVC_INVALID);
                return result;
            }

            try {

                String stripeTokenId = handleGetStripeCardTokenId(cardNumber, cardExpiration, cardCVC);
                handlePutStripeTokenToServer(stripeTokenId);
                handleUpdateSubscriptionStore(cardNumber, cardExpiration);

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (CardException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (StripeException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (RegistrationApiException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (JsonProcessingException e) {
                ErrorToaster.handleBundleError(e, result);
            } catch (IOException e) {
                ErrorToaster.handleBundleError(e, result);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            asyncTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS) {
                Toast.makeText(subscriptionActivity, R.string.card_verified_and_saved, Toast.LENGTH_LONG)
                        .show();
                handleUpdateUi();
            }

            else {
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
                handleUpdateUi();
            }
        }
    }.execute();
}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
public void run() {
    // take the String from the TopicActivity
    Bundle extras = getIntent().getExtras();
    Category = extras.getString(CATEGORY_INTENT_VAR);

    // Make sure we have updated the data source
    NewSumUiActivity.setDataSource(this);

    // Get user sources
    String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

    // get Topics from TopicActivity (avoid multiple server calls)
    TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this);

    // Also get Topic Titles, to display to adapter
    final String[] saTopicTitles = new String[tiTopics.length];
    // Also get Topic IDs
    final String[] saTopicIDs = new String[tiTopics.length];
    // Also get Dates, in order to show in summary title
    final String[] saTopicDates = new String[tiTopics.length];
    // DeHTML titles
    for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) {
        // update Titles Array
        saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString();
        // update IDs Array
        saTopicIDs[iCnt] = tiTopics[iCnt].getID();
        // update Date Array
        saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale());
    }//from  w w  w.j a v  a2 s.c o  m
    // get the value of the TopicIDs list size (to use in swipe)
    saTopicIDsLength = saTopicIDs.length;
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTopicTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // Get active topic
    int iTopicNum;
    // If we have returned from a pause
    if (iPrvSelectedItem >= 0)
        // use previous selection before pause
        iTopicNum = iPrvSelectedItem;
    // else
    else
        // use selection from topic page
        iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR);
    final int num = iTopicNum;

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            spinner.setAdapter(adapter);

            // Scroll view init
            final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
            final String[] saTopicTitlesArg = saTopicTitles;
            final String[] saTopicIDsArg = saTopicIDs;
            final String[] SaTopicDatesArg = saTopicDates;

            // Add selection event
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // Changing summary
                    loading = true;
                    showWaitingDialog();
                    // Update visibility of rating bar
                    final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
                    rb.setRating(0.0f);
                    rb.setVisibility(View.VISIBLE);
                    final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
                    rateLbl.setVisibility(View.VISIBLE);
                    scroll.scrollTo(0, 0);

                    String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

                    String[] saTopicIDs = saTopicIDsArg;

                    // track summary views per category and topic title
                    if (getAnalyticsPref()) {
                        EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category,
                                saTopicTitlesArg[arg2], 0l);
                    }

                    if (sCustomCategory.trim().length() > 0) {
                        if (Category.equals(sCustomCategory)) {
                            Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this);
                            String sCustomCategoryURL = ctxCur.getResources()
                                    .getString(R.string.custom_category_url);
                            // Check if specific element needs to be read
                            String sElementID = ctxCur.getResources()
                                    .getString(R.string.custom_category_elementId);
                            // If an element needs to be selected
                            if (sElementID.trim().length() > 0) {
                                try {
                                    // Check if specific element needs to be read
                                    String sViewOriginalPage = ctxCur.getResources()
                                            .getString(R.string.custom_category_visit_source);
                                    // Init text by a link to the original page
                                    sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage
                                            + "</a></p>";
                                    // Get document
                                    Document doc = Jsoup.connect(sCustomCategoryURL).get();
                                    // If a table
                                    Element eCur = doc.getElementById(sElementID);
                                    if (eCur.tagName().equalsIgnoreCase("table")) {
                                        // Get table rows
                                        Elements eRows = eCur.select("tr");

                                        // For each row
                                        StringBuffer sTextBuf = new StringBuffer();
                                        for (Element eCurRow : eRows) {
                                            // Append content
                                            // TODO: Use HTML if possible. Now problematic (crashes when we click on link)
                                            sTextBuf.append("<p>" + eCurRow.text() + "</p>");
                                        }
                                        // Return as string
                                        sText = sText + sTextBuf.toString();
                                    } else
                                        // else get text
                                        sText = eCur.text();

                                } catch (IOException e) {
                                    // Show unavailable text
                                    sText = ctxCur.getResources()
                                            .getString(R.string.custom_category_unavailable);
                                    e.printStackTrace();
                                }

                            } else
                                sText = Utils.getFromHttp(sCustomCategoryURL, false);
                        }

                    } else {
                        // call getSummary with (sTopicID, sUserSources). Use "All" for
                        // all Sources
                        String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
                        // check if Summary exists, otherwise display message
                        if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT
                            // WORK. Updated: Probably OK
                            nothingFound = true;
                            AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this);
                            al.setMessage(R.string.shouldReloadSummaries);
                            al.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // Reset cache
                                    CacheController.clearCache();
                                    // Restart main activity
                                    startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                }
                            });
                            al.setCancelable(false);
                            al.show();
                            // Return to home activity
                            loading = false;
                            return;
                        }
                        // Generate Summary text for normal categories
                        sText = generateSummaryText(Summary, ViewActivity.this);
                        pText = generatesummarypost(Summary, ViewActivity.this);
                    }

                    // Update HTML
                    tx.setText(Html.fromHtml(sText));
                    // Allow links to be followed into browser
                    tx.setMovementMethod(LinkMovementMethod.getInstance());
                    // Also Add Date to Topic Title inside Summary
                    title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]);

                    // Update size
                    updateTextSize();

                    // Update visited topics
                    TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);
                    // Done
                    loading = false;
                    closeWaitingDialog();
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                }

            });

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Get active topic
                    spinner.setSelection(num);
                }
            });

        }
    });

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showHelpDialog();
        }
    });

    closeWaitingDialog();
}