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.dcy.psychology.ChatActivity.java

/**
 * ????//from www .j a  va  2 s .c om
 * 
 * @param username
 */
private void addUserToBlacklist(final String username) {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setMessage(getString(R.string.Is_moved_into_blacklist));
    pd.setCanceledOnTouchOutside(false);
    pd.show();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                EMContactManager.getInstance().addUserToBlackList(username, false);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), R.string.Move_into_blacklist_success, 0).show();
                    }
                });
            } catch (EaseMobException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(), R.string.Move_into_blacklist_failure, 0).show();
                    }
                });
            }
        }
    }).start();
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

private void onPinEntered() {

    final String pin = mEnterPinEditText.getText().toString();
    // Validate pin code
    if (!RegexPatterns.PIN.matcher(pin).matches()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity2.this);
        builder.setMessage(R.string.registration_invalid_pin);
        builder.setPositiveButton(R.string.rogerthat, null);
        AlertDialog dialog = builder.create();
        dialog.show();//from w  ww. j  a  v  a2s  . c  o m
        return;
    }
    // Make call to Rogerthat webfarm
    final ProgressDialog progressDialog = new ProgressDialog(RegistrationActivity2.this);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog
            .setMessage(getString(R.string.registration_activating_account, getString(R.string.app_name)));
    progressDialog.setCancelable(false);
    progressDialog.show();
    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.UI();
            progressDialog.dismiss();
            AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity2.this);
            builder.setMessage(R.string.registration_sending_pin_error);
            builder.setPositiveButton(R.string.rogerthat, null);
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    };
    final String email = mWiz.getEmail();
    final String timestamp = "" + mWiz.getTimestamp();
    final String registrationId = mWiz.getRegistrationId();
    final String deviceId = mWiz.getDeviceId();

    mWorkerHandler.post(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "2";
            String pinSignature = Security.sha256(version + " " + email + " " + timestamp + " " + deviceId + " "
                    + registrationId + " " + pin + CloudConstants.REGISTRATION_PIN_SIGNATURE);

            HttpPost httppost = new HttpPost(CloudConstants.REGISTRATION_PIN_URL);
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("pin_code", pin));
                nameValuePairs.add(new BasicNameValuePair("pin_signature", pinSignature));
                nameValuePairs.add(new BasicNameValuePair("request_id", UUID.randomUUID().toString()));
                nameValuePairs.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));
                nameValuePairs.add(
                        new BasicNameValuePair("use_xmpp_kick", CloudConstants.USE_XMPP_KICK_CHANNEL + ""));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", mGCMRegistrationId));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = mHttpClient.execute(httppost);
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                if (statusCode != 200 || entity == null) {
                    mUIHandler.post(showErrorDialog);
                    return;
                }
                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) org.json.simple.JSONValue
                        .parse(new InputStreamReader(entity.getContent()));
                if ("success".equals(responseMap.get("result"))) {

                    JSONObject account = (JSONObject) responseMap.get("account");
                    final RegistrationInfo info = new RegistrationInfo(email,
                            new Credentials((String) account.get("account"), (String) account.get("password")));

                    mAgeAndGenderSet = (Boolean) responseMap.get("age_and_gender_set");
                    mUIHandler.post(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            T.UI();
                            hideNotification();
                            tryConnect(progressDialog, 1, getString(R.string.registration_establish_connection,
                                    email, getString(R.string.app_name)) + " ", info);
                        }
                    });
                } else {

                    final long attempts_left = (Long) responseMap.get("attempts_left");
                    mUIHandler.post(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            T.UI();
                            progressDialog.dismiss();
                            if (attempts_left > 0) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(
                                        RegistrationActivity2.this);
                                builder.setMessage(getString(R.string.registration_incorrect_pin, email));
                                builder.setTitle(getString(R.string.registration_incorrect_pin_dialog_title));
                                builder.setPositiveButton(R.string.rogerthat, null);
                                AlertDialog dialog = builder.create();
                                dialog.show();
                                mEnterPinEditText.setText("");
                            } else {
                                hideNotification();
                                new AlertDialog.Builder(RegistrationActivity2.this)
                                        .setMessage(getString(R.string.registration_no_attempts_left))
                                        .setCancelable(true).setPositiveButton(R.string.try_again, null)
                                        .create().show();
                                mWiz.reInit();
                                mWiz.goBackToPrevious();
                                return;
                            }
                        }
                    });

                }
            } catch (Exception e) {
                L.d(e);
                mUIHandler.post(showErrorDialog);
            }
        }
    });

}

From source file:com.gongpingjia.carplay.activity.chat.ChatActivity.java

protected void onChatRoomViewCreation() {
    // findViewById(R.id.container_to_group).setVisibility(View.GONE);

    final ProgressDialog pd = ProgressDialog.show(this, "", "Joining......");
    EMChatManager.getInstance().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

        @Override//from www.  j  av a  2  s. c  o m
        public void onSuccess(EMChatRoom value) {
            // TODO Auto-generated method stub
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                    room = EMChatManager.getInstance().getChatRoom(toChatUsername);
                    if (room != null) {
                        setTitle(room.getName());
                    } else {
                        setTitle(toChatUsername);
                    }
                    EMLog.d(TAG, "join room success : " + room.getName());

                    onConversationInit();

                    onListViewCreation();
                }
            });
        }

        @Override
        public void onError(final int error, String errorMsg) {
            // TODO Auto-generated method stub
            EMLog.d(TAG, "join room failure : " + error);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                }
            });
            finish();
        }
    });
}

From source file:org.symptomcheck.capstone.ui.CheckInFlowActivityOld.java

private void executeCheckInSaving(final CheckIn checkIn) {
    final ProgressDialog ringProgressDialog = ProgressDialog.show(this, "Please wait ...",
            "Check-In submission in progress ...", true);
    ringProgressDialog.setCancelable(true);
    new Thread(new Runnable() { //TODO#BPR_8 Check-In saving performed in a background Thread
        @Override//from   w w  w.j a v a  2 s.  c  o m
        public void run() {
            try {
                final boolean checkinRes = saveCheckIn(checkIn);
                Thread.sleep(3000);
                progressBarHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (checkinRes) {
                            //re-schedule the next check-in
                            SymptomAlarmRequest.get().setAlarm(getApplicationContext(),
                                    SymptomAlarmRequest.AlarmRequestedType.ALARM_CHECK_IN_REMINDER, false);
                            SyncUtils.TriggerRefreshPartialCloud(ActiveContract.SYNC_CHECK_IN);
                            finish();
                            Toast.makeText(getApplicationContext(), "Check-In Submitted Correctly",
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Check-In Submission ERROR!!!",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                });
            } catch (Exception ignored) {
            }
            ringProgressDialog.dismiss();
        }
    }).start();
}

From source file:com.huison.DriverAssistant_Web.util.LoginHelper.java

public static void register(final BaseActivity activity, final String username, final String phone,
        final String password, final String tjrphone, final String yzm) {
    UmengEventSender.sendEvent(activity, UmengEventTypes.register);
    final ProgressDialog pd = new ProgressDialog(activity);
    pd.setMessage("...");
    pd.setCanceledOnTouchOutside(false);
    pd.setCancelable(false);/* w w w.ja v a 2 s .c o  m*/
    pd.show();
    /*
     * Map<String, String> map = new HashMap<String, String>();
     * map.put("sessionkey", BaseActivity.getSESSIONKEY());
     * map.put("userid", username); map.put("mob", phone);
     * map.put("passwork", password); map.put("version",
     * activity.getVersionName()); map.put("imei",
     * DeviceUniqueIdentifier.getIMEIorMEID(activity)); map.put("imsi",
     * DeviceUniqueIdentifier.getIMSI(activity)); map.put("mac",
     * DeviceUniqueIdentifier.getMacAddress(activity)); map.put("channel",
     * getChannel(activity)); map.put("referee", tjrphone); map.put("Lng", ;
     * map.put("Lat", HomeActivity.gps_jdHomeActivity.gps_wd));
     * map.put("Code", yzm);
     */
    AsyncHttpClient client = activity.getAsyncHttpClient();
    RequestParams params = new RequestParams();
    /*
     * params.put("action", REGISTER_ACTION); params.put("xml",
     * BaseActivity.getXML(map));
     */
    try {
        JSONObject p = new JSONObject();
        p.put("mobile", phone);
        p.put("password", password);
        p.put("method", "register");
        p.put("version", activity.getVersionName());
        p.put("devicetype", "android");
        p.put("channel", getChannel(activity));
        p.put("imei", DeviceUniqueIdentifier.getIMEIorMEID(activity));
        p.put("imsi", "android" + DeviceUniqueIdentifier.getIMSI(activity));
        p.put("lat", Env.latitude);
        p.put("lng", Env.longitude);
        p.put("mac", DeviceUniqueIdentifier.getMacAddress(activity));
        p.put("referee", tjrphone);
        p.put("username", username);
        p.put("code", yzm);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 
        String time = formatter.format(curDate);
        p.put("time", time);
        Log.v("JSON", p.toString());
        String data = Util.DesJiaMi(p.toString(), "czxms520");
        params.put("data", data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() {
        @Override
        public void onDispatchSuccess(int statusCode, Header[] headers, String result) {
            Log.v("", "1");
            pd.dismiss();
            try {
                result = Util.decrypt(result, "czxms520");
                Log.v("JSON", result);
                JSONObject jo = new JSONObject(result);
                String code = jo.getString("code");
                /*
                 * boolean registerFlag = getJSONValueAsString(jo, "code")
                 * .equals("0");
                 */
                String msg = getJSONValueAsString(jo, "message");
                if (code.equals("0")) {
                    String data = jo.getString("data");
                    jo = new JSONObject(data);
                    /*
                     * registerFlag = getJSONValueAsString(jo, "logincode")
                     * .equals("0");
                     */
                    // msg = getJSONValueAsString(jo, "loginmessage");
                    /*
                     * String passwordMD5 = getJSONValueAsString( jo,
                     * "pass");
                     */
                    /*
                     * //  String breakRuleRemind =
                     * getJSONValueAsString( jo, "wzxx"); //  String
                     * changeLicenseRemind = getJSONValueAsString( jo,
                     * "hzxx"); //  String examineRemind =
                     * getJSONValueAsString(jo, "nsxx");
                     */
                    // vip
                    /*
                     * boolean isVip = getJSONValueAsString(jo, "Vip")
                     * .equals("true"); //  String
                     * blackPointUpdateTime = getJSONValueAsString( jo,
                     * "wzhdtime"); //  String toolUpdateTime =
                     * getJSONValueAsString( jo, "sygjtime"); // 
                     * String favorUpdateTime = getJSONValueAsString( jo,
                     * "yhtime");
                     */
                    /*
                     * boolean isVip = getJSONValueAsString(jo, "Vip")
                     * .equals("true");
                     */
                    // 
                    String loginTime = getJSONValueAsString(jo, "LastLogin");
                    // 
                    String lastLoginTime = getJSONValueAsString(jo, "LastLogin");
                    // SESSIONKEY
                    /*
                     * String sessionKey = getJSONValueAsString( jo,
                     * "sessionkey");
                     */
                    String urlHead = getJSONValueAsString(jo, "PhotoUrl");
                    String photoUrl = getJSONValueAsString(jo, "PhotoUrl");
                    String phone = getJSONValueAsString(jo, "Mobile");
                    Boolean vip = false;
                    if (String.valueOf(jo.getInt("Vip")).equals("1")) {
                        vip = true;
                    } else {
                        vip = false;
                    }
                    Log.v("VIP", String.valueOf(vip));
                    activity.markLogin(phone, phone, password, true, "", loginTime, lastLoginTime, vip);
                    if (!photoUrl.equals("")) {
                        // 
                        String finalHeadUrl = URLDecoder.decode(photoUrl, "utf-8");
                        BaseActivity.setUserHeadUrl(finalHeadUrl);
                        BaseActivity.setUserHeadDrawable(null);
                    } else {
                        BaseActivity.setUserHeadUrl("");
                        BaseActivity.setUserHeadDrawable(null);
                    }
                    try {
                        pd.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sendMsg(ConfigActivity.thiz, 0);
                    activity.finish();
                } else {
                    activity.showMessageBox(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                // activity.markLogout();
                // sendMsg(activity,1);
                activity.showMessageBox(activity.getText(R.string.server404));
                Log.e("register error", Log.getStackTraceString(e));
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                activity.showMessageBox("");
            }
        }

        @Override
        public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable,
                BaseBinaryResponse jsonResponse) {
            Log.v("C", "1");
            pd.dismiss();
            activity.showMessageBox(activity.getText(R.string.server404));
        }

        @Override
        public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) {
            pd.dismiss();
            Log.v("A", "1");
        }
    });
    Log.v("B", "1");
    TimeCounter.countTime(activity, pd);
}

From source file:com.grass.caishi.cc.activity.main.MainActivity.java

void logout() {
    final ProgressDialog pd = new ProgressDialog(MainActivity.this);
    String st = "...";
    pd.setMessage(st);//from ww w.j a v a2 s .c om
    pd.setCanceledOnTouchOutside(false);
    pd.show();
    DemoHXSDKHelper.getInstance().logout(true, new EMCallBack() {
        @Override
        public void onSuccess() {
            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    pd.dismiss();
                    // ??
                    MainActivity.this.finish();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            });
        }

        @Override
        public void onProgress(int progress, String status) {

        }

        @Override
        public void onError(int code, String message) {
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //
                    pd.dismiss();
                    Toast.makeText(MainActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                }
            });
        }
    });
}

From source file:de.ub0r.android.callmeter.ui.prefs.Preferences.java

/**
 * Export data.//  w w  w . ja  v a2s.co m
 * 
 * @param descr
 *            description of the exported rule set
 * @param fn
 *            one of the predefined file names from {@link DataProvider}.
 */
private void exportData(final String descr, final String fn) {
    if (descr == null) {
        final EditText et = new EditText(this);
        Builder builder = new Builder(this);
        builder.setView(et);
        builder.setCancelable(true);
        builder.setTitle(R.string.export_rules_descr);
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                Preferences.this.exportData(et.getText().toString(), fn);
            }
        });
        builder.show();
    } else {
        final ProgressDialog d = new ProgressDialog(this);
        d.setIndeterminate(true);
        d.setMessage(this.getString(R.string.export_progr));
        d.setCancelable(false);
        d.show();

        // run task in background
        final AsyncTask<Void, Void, String> task = // .
                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(final Void... params) {
                        if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                            return DataProvider.backupRuleSet(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                            return DataProvider.backupLogs(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                            return DataProvider.backupNumGroups(Preferences.this, descr);
                        } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                            return DataProvider.backupHourGroups(Preferences.this, descr);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final String result) {
                        Log.d(TAG, "export:\n" + result);
                        System.out.println("\n" + result);
                        d.dismiss();
                        if (result != null && result.length() > 0) {
                            Uri uri = null;
                            int resChooser = -1;
                            if (fn.equals(DataProvider.EXPORT_RULESET_FILE)) {
                                uri = DataProvider.EXPORT_RULESET_URI;
                                resChooser = R.string.export_rules_;
                            } else if (fn.equals(DataProvider.EXPORT_LOGS_FILE)) {
                                uri = DataProvider.EXPORT_LOGS_URI;
                                resChooser = R.string.export_logs_;
                            } else if (fn.equals(DataProvider.EXPORT_NUMGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_NUMGROUPS_URI;
                                resChooser = R.string.export_numgroups_;
                            } else if (fn.equals(DataProvider.EXPORT_HOURGROUPS_FILE)) {
                                uri = DataProvider.EXPORT_HOURGROUPS_URI;
                                resChooser = R.string.export_hourgroups_;
                            }
                            final Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType(DataProvider.EXPORT_MIMETYPE);
                            intent.putExtra(Intent.EXTRA_STREAM, uri);
                            intent.putExtra(Intent.EXTRA_SUBJECT, // .
                                    "Call Meter 3G export");
                            intent.addCategory(Intent.CATEGORY_DEFAULT);

                            try {
                                final File d = Environment.getExternalStorageDirectory();
                                final File f = new File(d, DataProvider.PACKAGE + File.separator + fn);
                                f.mkdirs();
                                if (f.exists()) {
                                    f.delete();
                                }
                                f.createNewFile();
                                FileWriter fw = new FileWriter(f);
                                fw.append(result);
                                fw.close();
                                // call an exporting app with the uri to the
                                // preferences
                                Preferences.this.startActivity(
                                        Intent.createChooser(intent, Preferences.this.getString(resChooser)));
                            } catch (IOException e) {
                                Log.e(TAG, "error writing export file", e);
                                Toast.makeText(Preferences.this, R.string.err_export_write, Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    }
                };
        task.execute((Void) null);
    }
}

From source file:cn.yunluosoft.tonglou.activity.ChatActivity.java

protected void onChatRoomViewCreation() {
    // findViewById(R.id.container_to_group).setVisibility(View.GONE);

    final ProgressDialog pd = ProgressDialog.show(this, "", "Joining......");
    EMChatManager.getInstance().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

        @Override// w  w  w . ja v  a2 s .  co  m
        public void onSuccess(EMChatRoom value) {
            // TODO Auto-generated method stub
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                    room = EMChatManager.getInstance().getChatRoom(toChatUsername);
                    if (room != null) {
                        ((TextView) findViewById(R.id.title_title)).setText(room.getName());
                    } else {
                        ((TextView) findViewById(R.id.title_title)).setText(toChatUsername);
                    }
                    EMLog.d(TAG, "join room success : " + room.getName());

                    onConversationInit();

                    onListViewCreation();
                }
            });
        }

        @Override
        public void onError(final int error, String errorMsg) {
            // TODO Auto-generated method stub
            EMLog.d(TAG, "join room failure : " + error);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                }
            });
            finish();
        }
    });
}

From source file:com.piusvelte.sonet.core.SonetNotifications.java

@Override
public boolean onContextItemSelected(final MenuItem item) {
    if (item.getItemId() == CLEAR) {
        final ProgressDialog loadingDialog = new ProgressDialog(this);
        final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {

            @Override/* www.j  a  va 2  s.  co  m*/
            protected Void doInBackground(Void... arg0) {
                // clear all notifications
                ContentValues values = new ContentValues();
                values.put(Notifications.CLEARED, 1);
                SonetNotifications.this.getContentResolver().update(
                        Notifications.getContentUri(SonetNotifications.this), values, Notifications._ID + "=?",
                        new String[] { Long.toString(((AdapterContextMenuInfo) item.getMenuInfo()).id) });
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                if (loadingDialog.isShowing()) {
                    loadingDialog.dismiss();
                }
                SonetNotifications.this.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();
                    }
                });
        loadingDialog.show();
        asyncTask.execute();
    }
    return super.onContextItemSelected(item);
    // clear
}

From source file:com.piusvelte.sonet.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(Sonet.getPackageIntent(this, SonetComments.class).setData(mData));
        } else//w  w w .  j a  v  a2  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(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(TWITTER_KEY, 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(MYSPACE_KEY, 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(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 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(IDENTICA_KEY, 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, 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;
    }
}