Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

In this page you can find the example usage for android.app ProgressDialog dismiss.

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.progym.custom.fragments.FoodProgressDailyPieFragment.java

public void setPieData(final Date dateToSetUp, final boolean isLeftIn) {

    final ProgressDialog ringProgressDialog = ProgressDialog.show(getActivity(),
            getResources().getString(R.string.please_wait), getResources().getString(R.string.populating_data),
            true);//w  w w. j  a va 2  s . c  o  m
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                DATE = dateToSetUp;
                totalProtein = 0;
                totalFat = 0;
                totalCarbs = 0;
                totalCallories = 0;
                final String date = Utils.formatDate(DATE, DataBaseUtils.DATE_PATTERN_YYYY_MM_DD);
                List<Ingridient> ingridients = DataBaseUtils.getProductsOnPlate(date);
                if (null != ingridients) {

                    for (Ingridient ingridient : ingridients) {
                        totalProtein += ingridient.protein;
                        totalFat += ingridient.fat;
                        totalCarbs += ingridient.carbohydrates;
                        totalCallories += ingridient.kkal;
                        Utils.log(String.format(
                                "==========prot:%s == carbs:%s == name:%s == fat %s============",
                                ingridient.protein, ingridient.carbohydrates, ingridient.name, ingridient.fat));
                    }

                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            twCurrentDay.setText(Utils.formatDate(dateToSetUp, "EEEE") + " - "
                                    + Utils.formatDate(dateToSetUp, "dd") + " of "
                                    + Utils.formatDate(dateToSetUp, "MMM"));

                        }
                    });

                    setUpPieChart(totalProtein, totalFat, totalCarbs, isLeftIn);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ringProgressDialog.dismiss();
        }
    }).start();
}

From source file:fm.smart.r1.CreateExampleActivity.java

public void onClick(View v) {
    EditText exampleInput = (EditText) findViewById(R.id.create_example_sentence);
    EditText translationInput = (EditText) findViewById(R.id.create_example_translation);
    EditText exampleTransliterationInput = (EditText) findViewById(R.id.sentence_transliteration);
    EditText translationTransliterationInput = (EditText) findViewById(R.id.translation_transliteration);
    final String example = exampleInput.getText().toString();
    final String translation = translationInput.getText().toString();
    if (TextUtils.isEmpty(example) || TextUtils.isEmpty(translation)) {
        Toast t = Toast.makeText(this, "Example and translation are required fields", 150);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();/*from  w  w w. j  a va2  s  .  c o m*/
    } else {
        final String example_language_code = Utils.LANGUAGE_MAP.get(example_language);
        final String translation_language_code = Utils.LANGUAGE_MAP.get(translation_language);
        final String example_transliteration = exampleTransliterationInput.getText().toString();
        final String translation_transliteration = translationTransliterationInput.getText().toString();

        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // avoid
            // navigation
            // back to this?
            LoginActivity.return_to = CreateExampleActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("goal_id", goal_id);
            LoginActivity.params.put("item_id", item_id);
            LoginActivity.params.put("example", example);
            LoginActivity.params.put("translation", translation);
            LoginActivity.params.put("example_language", example_language);
            LoginActivity.params.put("translation_language", translation_language);
            LoginActivity.params.put("example_transliteration", example_transliteration);
            LoginActivity.params.put("translation_transliteration", translation_transliteration);
            startActivity(intent);
        } else {

            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Creating Example ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread create_example = new Thread() {
                public void run() {
                    // TODO make this interruptable .../*if
                    // (!this.isInterrupted())*/
                    try {
                        // TODO failures here could derail all ...
                        CreateExampleActivity.add_item_goal_result = new AddItemResult(
                                Main.lookup.addItemToGoal(Main.transport, goal_id, item_id, null));

                        Result result = null;
                        try {
                            result = Main.lookup.createExample(Main.transport, translation,
                                    translation_language_code, translation, null, null, null);
                            JSONObject json = new JSONObject(result.http_response);
                            String text = json.getString("text");
                            String translation_id = json.getString("id");
                            result = Main.lookup.createExample(Main.transport, example, example_language_code,
                                    example_transliteration, translation_id, item_id, goal_id);
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        CreateExampleActivity.create_example_result = new CreateExampleResult(result);

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    myOtherProgressDialog.dismiss();

                }
            };
            myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    create_example.interrupt();
                }
            });
            OnCancelListener ocl = new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    create_example.interrupt();
                }
            };
            myOtherProgressDialog.setOnCancelListener(ocl);
            myOtherProgressDialog.show();
            create_example.start();
        }
    }
}

From source file:nl.eduvpn.app.fragment.HomeFragment.java

/**
 * Downloads the key pair if no cached one found. After that it downloads the profile and connects to it.
 *
 * @param instance      The VPN provider.
 * @param discoveredAPI The discovered API.
 * @param profile       The profile to download.
 *//*  w w w.j a  va 2  s  .c o  m*/
private void _downloadKeyPairIfNeeded(@NonNull final Instance instance,
        @NonNull final DiscoveredAPI discoveredAPI, @NonNull final Profile profile,
        @NonNull final AuthState authState) {
    // First we create a keypair, if there is no saved one yet.
    SavedKeyPair savedKeyPair = _historyService.getSavedKeyPairForInstance(instance);
    int dialogMessageRes = savedKeyPair != null ? R.string.vpn_profile_checking_certificate
            : R.string.vpn_profile_creating_keypair;
    ProgressDialog progressDialog = ProgressDialog.show(getContext(), getString(R.string.progress_dialog_title),
            getString(dialogMessageRes), true, false);
    _currentDialog = progressDialog;
    if (savedKeyPair != null) {
        _checkCertificateValidity(instance, discoveredAPI, savedKeyPair, profile, authState, progressDialog);
        return;
    }

    String requestData = "display_name=eduVPN";
    try {
        requestData = "display_name=" + URLEncoder.encode(BuildConfig.CERTIFICATE_DISPLAY_NAME, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // unable to encode the display name, use default
    }

    String createKeyPairEndpoint = discoveredAPI.getCreateKeyPairEndpoint();
    _apiService.postResource(createKeyPairEndpoint, requestData, authState, new APIService.Callback<String>() {

        @Override
        public void onSuccess(String keyPairJson) {
            try {
                KeyPair keyPair = _serializerService.deserializeKeyPair(new JSONObject(keyPairJson));
                Log.i(TAG, "Created key pair, is it successful: " + keyPair.isOK());
                // Save it for later
                SavedKeyPair savedKeyPair = new SavedKeyPair(instance, keyPair);
                _historyService.storeSavedKeyPair(savedKeyPair);
                _downloadProfileWithKeyPair(instance, discoveredAPI, savedKeyPair, profile, authState,
                        progressDialog);
            } catch (Exception ex) {
                progressDialog.dismiss();
                if (getActivity() != null) {
                    _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title,
                            getString(R.string.error_parsing_keypair, ex.getMessage()));
                }
                Log.e(TAG, "Unable to parse keypair data", ex);
            }
        }

        @Override
        public void onError(String errorMessage) {
            progressDialog.dismiss();
            _currentDialog = ErrorDialog.show(getContext(), R.string.error_dialog_title,
                    getString(R.string.error_creating_keypair, errorMessage));
            Log.e(TAG, "Error creating keypair: " + errorMessage);
        }
    });
}

From source file:com.piusvelte.sonet.StatusDialog.java

@Override
public void onClick(final DialogInterface dialog, int which) {
    switch (which) {
    case COMMENT:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST) {
                if (mSid != null)
                    startActivity(new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse(String.format(PINTEREST_PIN, mSid))));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            } else
                startActivity(Sonet.getPackageIntent(this, SonetComments.class).setData(mData));
        } else/*from ww w . j av a  2  s .  com*/
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        dialog.cancel();
        finish();
        break;
    case POST:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            else
                startActivity(Sonet.getPackageIntent(this, SonetCreatePost.class).setData(Uri
                        .withAppendedPath(Accounts.getContentUri(StatusDialog.this), Long.toString(mAccount))));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // no account, dialog to select one
                        // don't limit accounts to the widget
                        Cursor c = StatusDialog.this.getContentResolver().query(
                                Accounts.getContentUri(StatusDialog.this),
                                new String[] { Accounts._ID, ACCOUNTS_QUERY }, null, null, null);
                        if (c.moveToFirst()) {
                            int iid = c.getColumnIndex(Accounts._ID),
                                    iusername = c.getColumnIndex(Accounts.USERNAME), i = 0;
                            final long[] accountIndexes = new long[c.getCount()];
                            final String[] accounts = new String[c.getCount()];
                            while (!c.isAfterLast()) {
                                long id = c.getLong(iid);
                                accountIndexes[i] = id;
                                accounts[i++] = c.getString(iusername);
                                c.moveToNext();
                            }
                            arg0.cancel();
                            mDialog = (new AlertDialog.Builder(StatusDialog.this)).setTitle(R.string.accounts)
                                    .setSingleChoiceItems(accounts, -1, new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int which) {
                                            startActivity(Sonet
                                                    .getPackageIntent(StatusDialog.this, SonetCreatePost.class)
                                                    .setData(Uri.withAppendedPath(
                                                            Accounts.getContentUri(StatusDialog.this),
                                                            Long.toString(accountIndexes[which]))));
                                            arg0.cancel();
                                        }
                                    }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                                        @Override
                                        public void onCancel(DialogInterface arg0) {
                                            dialog.cancel();
                                        }
                                    }).create();
                            mDialog.show();
                        } else {
                            (Toast.makeText(StatusDialog.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                            dialog.cancel();
                        }
                        c.close();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case SETTINGS:
        if (mAppWidgetId != -1) {
            startActivity(Sonet.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(Sonet.getPackageIntent(StatusDialog.this, ManageAccounts.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[arg1]));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case NOTIFICATIONS:
        startActivity(Sonet.getPackageIntent(this, SonetNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Sonet.getPackageIntent(this, SonetService.class).setAction(ACTION_REFRESH)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId }));
            dialog.cancel();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                                        new int[] { mAppWidgetIds[arg1] }));
                        arg0.cancel();
                        finish();
                    }
                }).setPositiveButton(R.string.refreshallwidgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        // refresh all
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Sonet.getPackageIntent(StatusDialog.this, SonetService.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, mAppWidgetIds));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                dialog.cancel();
                finish();
            }
        }
        break;
    case PROFILE:
        Cursor account;
        final AsyncTask<String, Void, String> asyncTask;
        // get the resources
        switch (mService) {
        case TWITTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY,
                                BuildConfig.TWITTER_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                                        .parse(String.format(TWITTER_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FACEBOOK:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpGet(String.format(FACEBOOK_USER, FACEBOOK_BASE_URL, mEsid,
                                        Saccess_token, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getString("link"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        case MYSPACE:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY,
                                BuildConfig.MYSPACE_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(MYSPACE_USER, MYSPACE_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getJSONObject("person")
                                                .getString("profileUrl"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FOURSQUARE:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(FOURSQUARE_URL_PROFILE, mEsid))));
            finish();
            break;
        case LINKEDIN:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                BuildConfig.LINKEDIN_SECRET, arg0[0], arg0[1]);
                        HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_USER, mEsid));
                        for (String[] header : LINKEDIN_HEADERS)
                            httpGet.setHeader(header[0], header[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(httpGet));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        (new JSONObject(response)).getJSONObject("siteStandardProfileRequest")
                                                .getString("url").replaceAll("\\\\", ""))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case IDENTICA:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                BuildConfig.IDENTICA_SECRET, arg0[0], arg0[1]);
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()),
                                sonetOAuth.getSignedRequest(
                                        new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        String.format(IDENTICA_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case GOOGLEPLUS:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(GOOGLEPLUS_PROFILE, mEsid))));
            finish();
            break;
        case PINTEREST:
            if (mEsid != null)
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse(String.format(PINTEREST_PROFILE, mEsid))));
            else
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            finish();
            break;
        case CHATTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        // need to get an instance
                        return SonetHttpClient.httpResponse(
                                SonetHttpClient.getThreadSafeClient(getApplicationContext()), new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url")) {
                                    startActivity(new Intent(Intent.ACTION_VIEW)
                                            .setData(Uri.parse(jobj.getString("instance_url") + "/" + mEsid)));
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        }
        break;
    default:
        if ((itemsData != null) && (which < itemsData.length) && (itemsData[which] != null))
            // open link
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(itemsData[which])));
        else
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        finish();
        break;
    }
}

From source file:com.uraroji.garage.android.arrraycopybench.MainActivity.java

private void startBench() {
    mResultTextView.setText("");

    final String arrayTypeStr = mArrayTypeSpinner.getSelectedItem().toString();
    final int arrayLength = Integer.parseInt(mArrayLengthSpinner.getSelectedItem().toString());
    final int benchTimes = Integer.parseInt(mBenchTimesSpinner.getSelectedItem().toString());

    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage(getString(R.string.benchmarking));
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setCancelable(false);/*from   w w  w . j  av  a  2  s  .co m*/
    dialog.show();

    final Handler handler = new Handler();

    if (arrayTypeStr.equals("byte")) {
        final byte[] src = new byte[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = (byte) i;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                benchResult = copyNative(src, benchTimes);
                showResult("native", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("short")) {
        final short[] src = new short[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = (short) i;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                benchResult = copyNative(src, benchTimes);
                showResult("native", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("int")) {
        final int[] src = new int[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = (int) i;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                benchResult = copyNative(src, benchTimes);
                showResult("native", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("long")) {
        final long[] src = new long[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = (long) i;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                benchResult = copyNative(src, benchTimes);
                showResult("native", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("double")) {
        final double[] src = new double[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = (double) i;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                benchResult = copyNative(src, benchTimes);
                showResult("native", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("Object")) {
        final Object[] src = new Object[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = new Object();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("Byte")) {
        final Byte[] src = new Byte[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = new Byte((byte) i);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("Integer")) {
        final Integer[] src = new Integer[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = new Integer((int) i);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("Long")) {
        final Long[] src = new Long[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = new Long((long) i);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else if (arrayTypeStr.equals("Double")) {
        final Double[] src = new Double[arrayLength];
        for (int i = 0; i < src.length; ++i) {
            src[i] = new Double((double) i);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BenchResult benchResult = null;

                benchResult = copyClone(src, benchTimes);
                showResult("clone", benchResult, handler);

                benchResult = copyArraycopy(src, benchTimes);
                showResult("System.arraycopy", benchResult, handler);

                benchResult = copyArraysCopyOf(src, benchTimes);
                showResult("Arrays.copyOf", benchResult, handler);

                benchResult = copyForLoop(src, benchTimes);
                showResult("for loop", benchResult, handler);

                dialog.dismiss();
            }
        }).start();
    } else {
        dialog.dismiss();
    }
}

From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java

private void getInfoFromXML() {

    //Show a progress dialog while reading XML
    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);/* ww  w.  j a  v a  2 s  . co m*/

            try {

                //Log.d("EMD - ","About to parse");

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                //Log.d("EMD - ","Done Parsing");

                statuscode = myXMLHandler.statuscode;
                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                genre = myXMLHandler.genre;
                genreId = myXMLHandler.genreId;
                labelId = myXMLHandler.labelId;
                label = myXMLHandler.label;
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                imageURL = myXMLHandler.imageURL;
                artist = myXMLHandler.artist;
                artistId = myXMLHandler.artistId;

                //Log.d("EMD - ","Set genre etc..");

                numberOfTracks = myXMLHandler.nItems;
                trackNames = myXMLHandler.tracks;
                //sampleAddresses = myXMLHandler.sampleAddress;
                //sampleExists = myXMLHandler.sampleExists;
                //vSamplesExist = myXMLHandler.samplesExist;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {
                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_album_info);
                    }
                });

            }

            //Remove Progress Dialog
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            handlerDoneLoading.sendEmptyMessage(0);
        }
    };
    t3.start();
}

From source file:com.shafiq.myfeedle.core.StatusDialog.java

@Override
public void onClick(final DialogInterface dialog, int which) {
    switch (which) {
    case COMMENT:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST) {
                if (mSid != null)
                    startActivity(new Intent(Intent.ACTION_VIEW)
                            .setData(Uri.parse(String.format(PINTEREST_PIN, mSid))));
                else
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            } else
                startActivity(Myfeedle.getPackageIntent(this, MyfeedleComments.class).setData(mData));
        } else/*  ww  w .  j a  v a  2  s.  c  om*/
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        dialog.cancel();
        finish();
        break;
    case POST:
        if (mAppWidgetId != -1) {
            if (mService == GOOGLEPLUS)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://plus.google.com")));
            else if (mService == PINTEREST)
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            else
                startActivity(Myfeedle.getPackageIntent(this, MyfeedleCreatePost.class).setData(Uri
                        .withAppendedPath(Accounts.getContentUri(StatusDialog.this), Long.toString(mAccount))));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // no account, dialog to select one
                        // don't limit accounts to the widget
                        Cursor c = StatusDialog.this.getContentResolver().query(
                                Accounts.getContentUri(StatusDialog.this),
                                new String[] { Accounts._ID, ACCOUNTS_QUERY }, null, null, null);
                        if (c.moveToFirst()) {
                            int iid = c.getColumnIndex(Accounts._ID),
                                    iusername = c.getColumnIndex(Accounts.USERNAME), i = 0;
                            final long[] accountIndexes = new long[c.getCount()];
                            final String[] accounts = new String[c.getCount()];
                            while (!c.isAfterLast()) {
                                long id = c.getLong(iid);
                                accountIndexes[i] = id;
                                accounts[i++] = c.getString(iusername);
                                c.moveToNext();
                            }
                            arg0.cancel();
                            mDialog = (new AlertDialog.Builder(StatusDialog.this)).setTitle(R.string.accounts)
                                    .setSingleChoiceItems(accounts, -1, new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int which) {
                                            startActivity(Myfeedle
                                                    .getPackageIntent(StatusDialog.this,
                                                            MyfeedleCreatePost.class)
                                                    .setData(Uri.withAppendedPath(
                                                            Accounts.getContentUri(StatusDialog.this),
                                                            Long.toString(accountIndexes[which]))));
                                            arg0.cancel();
                                        }
                                    }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                                        @Override
                                        public void onCancel(DialogInterface arg0) {
                                            dialog.cancel();
                                        }
                                    }).create();
                            mDialog.show();
                        } else {
                            (Toast.makeText(StatusDialog.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                            dialog.cancel();
                        }
                        c.close();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case SETTINGS:
        if (mAppWidgetId != -1) {
            startActivity(Myfeedle.getPackageIntent(this, ManageAccounts.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId));
            dialog.cancel();
            finish();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        startActivity(Myfeedle.getPackageIntent(StatusDialog.this, ManageAccounts.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[arg1]));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
                dialog.cancel();
                finish();
            }
        }
        break;
    case NOTIFICATIONS:
        startActivity(Myfeedle.getPackageIntent(this, MyfeedleNotifications.class));
        dialog.cancel();
        finish();
        break;
    case REFRESH:
        if (mAppWidgetId != -1) {
            (Toast.makeText(getApplicationContext(), getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
            startService(Myfeedle.getPackageIntent(this, MyfeedleService.class).setAction(ACTION_REFRESH)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId }));
            dialog.cancel();
        } else {
            // no widget sent in, dialog to select one
            String[] widgets = getAllWidgets();
            if (widgets.length > 0) {
                mDialog = (new AlertDialog.Builder(this)).setItems(widgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Myfeedle.getPackageIntent(StatusDialog.this, MyfeedleService.class)
                                .setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
                                        new int[] { mAppWidgetIds[arg1] }));
                        arg0.cancel();
                        finish();
                    }
                }).setPositiveButton(R.string.refreshallwidgets, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int which) {
                        // refresh all
                        (Toast.makeText(StatusDialog.this.getApplicationContext(),
                                getString(R.string.refreshing), Toast.LENGTH_LONG)).show();
                        startService(Myfeedle.getPackageIntent(StatusDialog.this, MyfeedleService.class)
                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, mAppWidgetIds));
                        arg0.cancel();
                        finish();
                    }
                }).setCancelable(true).setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        dialog.cancel();
                        finish();
                    }
                }).create();
                mDialog.show();
            } else {
                dialog.cancel();
                finish();
            }
        }
        break;
    case PROFILE:
        Cursor account;
        final AsyncTask<String, Void, String> asyncTask;
        // get the resources
        switch (mService) {
        case TWITTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.getSignedRequest(
                                        new HttpGet(String.format(TWITTER_USER, TWITTER_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                                        .parse(String.format(TWITTER_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FACEBOOK:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpGet(String.format(FACEBOOK_USER, FACEBOOK_BASE_URL, mEsid,
                                        Saccess_token, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getString("link"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        case MYSPACE:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.getSignedRequest(
                                        new HttpGet(String.format(MYSPACE_USER, MYSPACE_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW)
                                        .setData(Uri.parse((new JSONObject(response)).getJSONObject("person")
                                                .getString("profileUrl"))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case FOURSQUARE:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(FOURSQUARE_URL_PROFILE, mEsid))));
            finish();
            break;
        case LINKEDIN:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, arg0[0],
                                arg0[1]);
                        HttpGet httpGet = new HttpGet(String.format(LINKEDIN_URL_USER, mEsid));
                        for (String[] header : LINKEDIN_HEADERS)
                            httpGet.setHeader(header[0], header[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.getSignedRequest(httpGet));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        (new JSONObject(response)).getJSONObject("siteStandardProfileRequest")
                                                .getString("url").replaceAll("\\\\", ""))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case IDENTICA:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        MyfeedleOAuth myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, arg0[0],
                                arg0[1]);
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                myfeedleOAuth.getSignedRequest(
                                        new HttpGet(String.format(IDENTICA_USER, IDENTICA_BASE_URL, mEsid))));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject user = new JSONObject(response);
                                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                                        String.format(IDENTICA_PROFILE, user.getString("screen_name")))));
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
            }
            account.close();
            break;
        case GOOGLEPLUS:
            startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(String.format(GOOGLEPLUS_PROFILE, mEsid))));
            finish();
            break;
        case PINTEREST:
            if (mEsid != null)
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse(String.format(PINTEREST_PROFILE, mEsid))));
            else
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://pinterest.com")));
            finish();
            break;
        case CHATTER:
            account = this.getContentResolver().query(Accounts.getContentUri(StatusDialog.this),
                    new String[] { Accounts._ID, Accounts.TOKEN }, Accounts._ID + "=?",
                    new String[] { Long.toString(mAccount) }, null);
            if (account.moveToFirst()) {
                final ProgressDialog loadingDialog = new ProgressDialog(this);
                asyncTask = new AsyncTask<String, Void, String>() {
                    @Override
                    protected String doInBackground(String... arg0) {
                        // need to get an instance
                        return MyfeedleHttpClient.httpResponse(
                                MyfeedleHttpClient.getThreadSafeClient(getApplicationContext()),
                                new HttpPost(String.format(CHATTER_URL_ACCESS, CHATTER_KEY, arg0[0])));
                    }

                    @Override
                    protected void onPostExecute(String response) {
                        if (loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        if (response != null) {
                            try {
                                JSONObject jobj = new JSONObject(response);
                                if (jobj.has("instance_url")) {
                                    startActivity(new Intent(Intent.ACTION_VIEW)
                                            .setData(Uri.parse(jobj.getString("instance_url") + "/" + mEsid)));
                                }
                            } catch (JSONException e) {
                                Log.e(TAG, e.toString());
                                onErrorExit(mServiceName);
                            }
                        } else {
                            onErrorExit(mServiceName);
                        }
                        finish();
                    }
                };
                loadingDialog.setMessage(getString(R.string.loading));
                loadingDialog.setCancelable(true);
                loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!asyncTask.isCancelled())
                            asyncTask.cancel(true);
                    }
                });
                loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        });
                loadingDialog.show();
                asyncTask.execute(
                        mMyfeedleCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))));
            }
            account.close();
            break;
        }
        break;
    default:
        if ((itemsData != null) && (which < itemsData.length) && (itemsData[which] != null))
            // open link
            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(itemsData[which])));
        else
            (Toast.makeText(this, getString(R.string.error_status), Toast.LENGTH_LONG)).show();
        finish();
        break;
    }
}

From source file:projekt.substratum.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    startService(new Intent(this, ThemeService.class));

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from   w  w  w .  j ava  2 s .c  o m
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(false);

    AccountHeader header = new AccountHeaderBuilder().withActivity(this)
            .withHeaderBackground(R.drawable.material_drawer_header_background).withProfileImagesVisible(false)
            .withSelectionListEnabledForSingleProfile(false).addProfiles(new ProfileDrawerItem()
                    .withName(getString(R.string.drawer_name)).withEmail(BuildConfig.VERSION_NAME))
            .withCurrentProfileHiddenInList(true).build();

    final LibsSupportFragment fragment = new LibsBuilder().supportFragment();

    if (References.checkOMS()) {
        drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(header)
                .withSavedInstance(savedInstanceState).withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.nav_home)
                                .withIcon(R.drawable.nav_theme_packs),
                        new PrimaryDrawerItem().withName(R.string.nav_overlays)
                                .withIcon(R.drawable.nav_overlays),
                        new PrimaryDrawerItem().withName(R.string.nav_bootanim)
                                .withIcon(R.drawable.nav_bootanim),
                        new PrimaryDrawerItem().withName(R.string.nav_fonts).withIcon(R.drawable.nav_fonts),
                        new PrimaryDrawerItem().withName(R.string.nav_sounds).withIcon(R.drawable.nav_sounds),
                        new SectionDrawerItem().withName(R.string.nav_section_header_utilities),
                        new PrimaryDrawerItem().withName(R.string.nav_overlay_manager)
                                .withIcon(R.drawable.nav_overlay_manager),
                        new PrimaryDrawerItem().withName(R.string.nav_manage).withIcon(R.drawable.nav_manage),
                        new PrimaryDrawerItem().withName(R.string.nav_priorities)
                                .withIcon(R.drawable.nav_drawer_priorities),
                        new PrimaryDrawerItem().withName(R.string.nav_backup_restore)
                                .withIcon(R.drawable.nav_drawer_profiles),
                        new SectionDrawerItem().withName(R.string.nav_section_header_more),
                        new SecondaryDrawerItem().withName(R.string.nav_troubleshooting)
                                .withIcon(R.drawable.nav_troubleshooting),
                        new SecondaryDrawerItem().withName(R.string.nav_team)
                                .withIcon(R.drawable.nav_drawer_team),
                        new SecondaryDrawerItem().withName(getString(R.string.nav_opensource))
                                .withIcon(R.drawable.nav_drawer_licenses),
                        new SecondaryDrawerItem().withName(R.string.nav_settings)
                                .withIcon(R.drawable.nav_drawer_settings))
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        if (drawerItem != null) {
                            switch (position) {
                            case 1:
                                if (drawerSelected != position) {
                                    switchFragment(((References.checkOMS()) ? getString(R.string.app_name)
                                            : getString(R.string.legacy_app_name)), "HomeFragment");
                                    drawerSelected = 1;
                                }
                                break;
                            case 2:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_overlays), "OverlaysFragment");
                                    drawerSelected = 2;
                                }
                                break;
                            case 3:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_bootanim), "BootAnimationsFragment");
                                    drawerSelected = 3;
                                }
                                break;
                            case 4:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_fonts), "FontsFragment");
                                    drawerSelected = 4;
                                }
                                break;
                            case 5:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_sounds), "SoundsFragment");
                                    drawerSelected = 5;
                                }
                                break;
                            case 7:
                                switchFragment(getString(R.string.nav_overlay_manager),
                                        "AdvancedManagerFragment");
                                drawerSelected = 7;
                                break;
                            case 8:
                                switchFragment(getString(R.string.nav_manage), "ManageFragment");
                                drawerSelected = 8;
                                break;
                            case 9:
                                switchFragment(getString(R.string.nav_priorities), "PriorityLoaderFragment");
                                drawerSelected = 9;
                                break;
                            case 10:
                                switchFragment(getString(R.string.nav_backup_restore), "ProfileFragment");
                                drawerSelected = 10;
                                break;
                            case 12:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_troubleshooting),
                                            "TroubleshootingFragment");
                                    drawerSelected = 12;
                                }
                                break;
                            case 13:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_team), "TeamFragment");
                                    drawerSelected = 13;
                                }
                                break;
                            case 14:
                                switchFragmentToLicenses(getString(R.string.nav_opensource), fragment);
                                drawerSelected = 14;
                                break;
                            case 15:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_settings), "SettingsFragment");
                                    drawerSelected = 15;
                                }
                                break;
                            }
                        }
                        return false;
                    }
                }).withSelectedItem(1).withSelectedItemByPosition(1).build();
    } else {
        drawer = new DrawerBuilder().withActivity(this).withToolbar(toolbar).withAccountHeader(header)
                .withSavedInstance(savedInstanceState).withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(
                        new PrimaryDrawerItem().withName(R.string.nav_home)
                                .withIcon(R.drawable.nav_theme_packs),
                        new PrimaryDrawerItem().withName(R.string.nav_overlays)
                                .withIcon(R.drawable.nav_overlays),
                        new PrimaryDrawerItem().withName(R.string.nav_sounds).withIcon(R.drawable.nav_sounds),

                        new SectionDrawerItem().withName(R.string.nav_section_header_utilities),
                        new PrimaryDrawerItem().withName(R.string.nav_overlay_manager)
                                .withIcon(R.drawable.nav_overlay_manager),
                        new PrimaryDrawerItem().withName(R.string.nav_manage).withIcon(R.drawable.nav_manage),
                        new PrimaryDrawerItem().withName(R.string.nav_backup_restore)
                                .withIcon(R.drawable.nav_drawer_profiles),

                        new SectionDrawerItem().withName(R.string.nav_section_header_more),
                        new SecondaryDrawerItem().withName(R.string.nav_troubleshooting)
                                .withIcon(R.drawable.nav_troubleshooting),
                        new SecondaryDrawerItem().withName(R.string.nav_team)
                                .withIcon(R.drawable.nav_drawer_team),
                        new SecondaryDrawerItem().withName(getString(R.string.nav_opensource))
                                .withIcon(R.drawable.nav_drawer_licenses),
                        new SecondaryDrawerItem().withName(R.string.nav_settings)
                                .withIcon(R.drawable.nav_drawer_settings))
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        if (drawerItem != null) {
                            switch (position) {
                            case 1:
                                if (drawerSelected != position) {
                                    switchFragment(((References.checkOMS()) ? getString(R.string.app_name)
                                            : getString(R.string.legacy_app_name)), "HomeFragment");
                                    drawerSelected = 1;
                                }
                                break;
                            case 2:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_overlays), "OverlaysFragment");
                                    drawerSelected = 2;
                                }
                                break;
                            case 3:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_sounds), "SoundsFragment");
                                    drawerSelected = 3;
                                }
                                break;
                            case 5:
                                switchFragment(getString(R.string.nav_overlay_manager),
                                        "AdvancedManagerFragment");
                                drawerSelected = 5;
                                break;
                            case 6:
                                switchFragment(getString(R.string.nav_manage), "ManageFragment");
                                drawerSelected = 6;
                                break;
                            case 7:
                                switchFragment(getString(R.string.nav_backup_restore), "ProfileFragment");
                                drawerSelected = 7;
                                break;
                            case 9:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_troubleshooting),
                                            "TroubleshootingFragment");
                                    drawerSelected = 10;
                                }
                                break;
                            case 10:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_team), "TeamFragment");
                                    drawerSelected = 10;
                                }
                                break;
                            case 11:
                                switchFragmentToLicenses(getString(R.string.nav_opensource), fragment);
                                drawerSelected = 11;
                                break;
                            case 12:
                                if (drawerSelected != position) {
                                    switchFragment(getString(R.string.nav_settings), "SettingsFragment");
                                    drawerSelected = 12;
                                }
                                break;
                            }
                        }
                        return false;
                    }
                }).withSelectedItem(1).withSelectedItemByPosition(1).build();
    }
    if (!Root.requestRootAccess()) {
        final ProgressDialog mProgressDialog = new ProgressDialog(this,
                R.style.SubstratumBuilder_ActivityTheme);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        mProgressDialog.setContentView(R.layout.root_rejected_loader);

        final float radius = 5;
        final View decorView = getWindow().getDecorView();
        final View rootView = decorView.findViewById(android.R.id.content);
        final Drawable windowBackground = decorView.getBackground();

        BlurView blurView = (BlurView) mProgressDialog.findViewById(R.id.blurView);

        blurView.setupWith(rootView).windowBackground(windowBackground)
                .blurAlgorithm(new RenderScriptBlur(this, true)).blurRadius(radius);

        final TextView textView = (TextView) mProgressDialog.findViewById(R.id.timer);
        CountDownTimer Count = new CountDownTimer(5000, 1000) {
            public void onTick(long millisUntilFinished) {
                if ((millisUntilFinished / 1000) > 1) {
                    textView.setText(String.format(getString(R.string.root_rejected_timer_plural),
                            (millisUntilFinished / 1000) + ""));
                } else {
                    textView.setText(String.format(getString(R.string.root_rejected_timer_singular),
                            (millisUntilFinished / 1000) + ""));
                }

            }

            public void onFinish() {
                mProgressDialog.dismiss();
                finish();
            }
        };
        Count.start();
    }

    permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    permissionCheck2 = ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.READ_PHONE_STATE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.System.canWrite(getApplicationContext())) {
            Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Log.d("SubstratumLogger", "Substratum was granted " + "'android.permission.WRITE_SETTINGS' "
                    + "permissions for system runtime code execution.");
        }
    }

    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
        // permission already granted, allow the program to continue running
        File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File cacheDirectory = new File(getCacheDir(), "/SubstratumBuilder/");
        if (!cacheDirectory.exists()) {
            cacheDirectory.mkdirs();
        }
        if (permissionCheck2 == PackageManager.PERMISSION_GRANTED) {
            // permission already granted, allow the program to continue running
            // Set the first option to start at app boot
            drawer.setSelectionAtPosition(1);
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_PHONE_STATE },
                    PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }
    } else {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }

    // Now, let's grab root on the helper
    Intent rootIntent = new Intent(Intent.ACTION_MAIN);
    rootIntent.setAction("masquerade.substratum.INITIALIZE");
    try {
        startActivity(rootIntent);
    } catch (RuntimeException re) {
        // Exception: At this point, Masquerade is not installed at all.
    }

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    if (References.checkOMS()) {
        if (!prefs.getBoolean("substratum_oms", true)) {
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/.substratum/");
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/substratum/");
            File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }
    } else {
        if (prefs.getBoolean("substratum_oms", true)) {
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/.substratum/");
            Root.runCommand(
                    "rm -r " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/substratum/");
            File directory = new File(Environment.getExternalStorageDirectory(), "/.substratum/");
            if (!directory.exists()) {
                directory.mkdirs();
            }
        }
    }

    printFCMtoken();
}

From source file:com.microsoft.live.sample.skydrive.SkyDriveActivity.java

@Override
protected Dialog onCreateDialog(final int id, final Bundle bundle) {
    Dialog dialog = null;/*from  w ww .  j  av a  2  s.  com*/
    switch (id) {
    case DIALOG_DOWNLOAD_ID: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Download").setMessage("This file will be downloaded to the sdcard.")
                .setPositiveButton("OK", new Dialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final ProgressDialog progressDialog = new ProgressDialog(SkyDriveActivity.this);
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setMessage("Downloading...");
                        progressDialog.setCancelable(true);
                        progressDialog.show();

                        String fileId = bundle.getString(JsonKeys.ID);
                        String name = bundle.getString(JsonKeys.NAME);

                        File file = new File(Environment.getExternalStorageDirectory(), name);

                        final LiveDownloadOperation operation = mClient.downloadAsync(fileId + "/content", file,
                                new LiveDownloadOperationListener() {
                                    @Override
                                    public void onDownloadProgress(int totalBytes, int bytesRemaining,
                                            LiveDownloadOperation operation) {
                                        int percentCompleted = computePrecentCompleted(totalBytes,
                                                bytesRemaining);

                                        progressDialog.setProgress(percentCompleted);
                                    }

                                    @Override
                                    public void onDownloadFailed(LiveOperationException exception,
                                            LiveDownloadOperation operation) {
                                        progressDialog.dismiss();
                                        showToast(exception.getMessage());
                                    }

                                    @Override
                                    public void onDownloadCompleted(LiveDownloadOperation operation) {
                                        progressDialog.dismiss();
                                        showToast("File downloaded.");
                                    }
                                });

                        progressDialog.setOnCancelListener(new OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                operation.cancel();
                            }
                        });
                    }
                }).setNegativeButton("Cancel", new Dialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        dialog = builder.create();
        break;
    }
    }

    if (dialog != null) {
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                removeDialog(id);
            }
        });
    }

    return dialog;
}

From source file:com.jereksel.rommanager.MainActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    final MainActivity context = this;
    this.context = context;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initializing
    dataList = new ArrayList<DrawerItem>();
    mTitle = mDrawerTitle = getTitle();/*from   ww  w. ja  v  a2  s  .  c  o m*/
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    final ProgressDialog pDialog;

    pDialog = ProgressDialog.show(context, "Downloading/Preparing Data..", "Please wait", true, false);

    final DownloadXML DownloadThread;

    Log.w("TESCIK", "");
    DownloadThread = new DownloadXML(context, false);
    DownloadThread.start();

    new Thread() {
        public void run() {

            dataList = new ArrayList<DrawerItem>();

            dataList.add(new DrawerItem("Status"));

            try {
                DownloadThread.join();
            } catch (InterruptedException e) {
                Toast.makeText(getApplicationContext(), "ERROR" + e.getMessage(), Toast.LENGTH_LONG).show();
            }

            Log.w("START:", "pliki");
            BufferedReader xml;
            StringBuilder total = null;
            try {
                File file = new File(context.getFilesDir(), "rom.xml");
                InputStream inputStream = new FileInputStream(file);
                xml = new BufferedReader(new InputStreamReader(inputStream));
                total = new StringBuilder();
                String line;

                while ((line = xml.readLine()) != null) {
                    total.append(line);
                }
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            XMLParser parser = new XMLParser();
            Document doc = parser.getDomElement(total.toString());
            NodeList nl = doc.getElementsByTagName(KEY_ITEM);

            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);
                NodeList n = e.getElementsByTagName("name");
                dataList.add(new DrawerItem(parser.getElementValue(n.item(0))));
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pDialog.dismiss();
                    CustomDrawerAdapter adapter = new CustomDrawerAdapter(context, R.layout.custom_drawer_item,
                            dataList);
                    mDrawerList.setAdapter(adapter);
                    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

                    if (savedInstanceState == null) {
                        SelectItem(0);
                    }
                }
            });
        }
    }.start();

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to
            // onPrepareOptionsMenu()
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

}