Example usage for android.os AsyncTask cancel

List of usage examples for android.os AsyncTask cancel

Introduction

In this page you can find the example usage for android.os AsyncTask cancel.

Prototype

public final boolean cancel(boolean mayInterruptIfRunning) 

Source Link

Document

Attempts to cancel execution of this task.

Usage

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);//from   w w w. j a va 2 s .  c  om
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.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);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

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//from  w  w  w  . ja  v a 2  s  .  co  m
            (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;
    }
}

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 a v  a2s .  c o  m
            (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.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/*from w w  w  .j  av  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(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:im.vector.fragments.VectorSettingsPreferencesFragment.java

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

    final Context appContext = getActivity().getApplicationContext();

    // retrieve the arguments
    Bundle args = getArguments();//from w w  w  .ja v  a2 s  .  com
    String matrixId = args.getString(ARG_MATRIX_ID);
    mSession = Matrix.getInstance(appContext).getSession(matrixId);

    // sanity checks
    if ((null == mSession) || !mSession.isAlive()) {
        getActivity().finish();
        return;
    }

    // define the layout
    addPreferencesFromResource(R.xml.vector_settings_preferences);

    if (null == mPushesRuleByResourceId) {
        mPushesRuleByResourceId = new HashMap<>();

        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_ALL_NOTIF_PREFERENCE_KEY,
                BingRule.RULE_ID_DISABLE_ALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_ENABLE_THIS_DEVICE_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_TURN_SCREEN_ON_PREFERENCE_KEY, DUMMY_RULE);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_DISPLAY_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_DISPLAY_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CONTAINING_MY_USER_NAME_PREFERENCE_KEY,
                BingRule.RULE_ID_CONTAIN_USER_NAME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_ONE_TO_ONE_PREFERENCE_KEY,
                BingRule.RULE_ID_ONE_TO_ONE_ROOM);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_IN_GROUP_CHAT_PREFERENCE_KEY,
                BingRule.RULE_ID_ALL_OTHER_MESSAGES_ROOMS);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_INVITED_TO_ROOM_PREFERENCE_KEY,
                BingRule.RULE_ID_INVITE_ME);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_CALL_INVITATIONS_PREFERENCE_KEY,
                BingRule.RULE_ID_CALL);
        mPushesRuleByResourceId.put(PreferencesManager.SETTINGS_MESSAGES_SENT_BY_BOT_PREFERENCE_KEY,
                BingRule.RULE_ID_SUPPRESS_BOTS_NOTIFICATIONS);
    }

    UserAvatarPreference avatarPreference = (UserAvatarPreference) findPreference(
            PreferencesManager.SETTINGS_PROFILE_PICTURE_PREFERENCE_KEY);
    avatarPreference.setSession(mSession);
    avatarPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onUpdateAvatarClick();
            return false;
        }
    });

    EditTextPreference passwordPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CHANGE_PASSWORD_PREFERENCE_KEY);
    passwordPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            onPasswordUpdateClick();
            return false;
        }
    });

    EditTextPreference notificationRingTonePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_RINGTONE_SELECTION_PREFERENCE_KEY);
    notificationRingTonePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);

            if (null != PreferencesManager.getNotificationRingTone(getActivity())) {
                intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
                        PreferencesManager.getNotificationRingTone(getActivity()));
            }
            getActivity().startActivityForResult(intent, REQUEST_NOTIFICATION_RINGTONE);
            return false;
        }
    });
    refreshNotificationRingTone();

    EditTextPreference notificationPrivacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATION_PRIVACY_PREFERENCE_KEY);
    if (notificationPrivacyPreference != null) {
        notificationPrivacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(NotificationPrivacyActivity.getIntent(getActivity()));
                return true;
            }
        });
        refreshNotificationPrivacy();
    }

    // application version
    VectorCustomActionEditTextPreference versionTextPreference = (VectorCustomActionEditTextPreference) findPreference(
            PreferencesManager.SETTINGS_VERSION_PREFERENCE_KEY);
    if (null != versionTextPreference) {
        versionTextPreference.setSummary(VectorUtils.getApplicationVersion(appContext));

        versionTextPreference.setOnPreferenceLongClickListener(
                new VectorCustomActionEditTextPreference.OnPreferenceLongClickListener() {
                    @Override
                    public boolean onPreferenceLongClick(Preference preference) {
                        VectorUtils.copyToClipboard(appContext, VectorUtils.getApplicationVersion(appContext));
                        return true;
                    }
                });
    }

    // olm version
    EditTextPreference olmTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_OLM_VERSION_PREFERENCE_KEY);
    if (null != olmTextPreference) {
        olmTextPreference.setSummary(
                Matrix.getInstance(appContext).getDefaultSession().getCryptoVersion(appContext, false));
    }

    // user account
    EditTextPreference accountIdTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_LOGGED_IN_PREFERENCE_KEY);
    if (null != accountIdTextPreference) {
        accountIdTextPreference.setSummary(mSession.getMyUserId());
    }

    // home server
    EditTextPreference homeServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_HOME_SERVER_PREFERENCE_KEY);
    if (null != homeServerTextPreference) {
        homeServerTextPreference.setSummary(mSession.getHomeServerConfig().getHomeserverUri().toString());
    }

    // identity server
    EditTextPreference identityServerTextPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_IDENTITY_SERVER_PREFERENCE_KEY);
    if (null != identityServerTextPreference) {
        identityServerTextPreference
                .setSummary(mSession.getHomeServerConfig().getIdentityServerUri().toString());
    }

    // terms & conditions
    EditTextPreference termConditionsPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_APP_TERM_CONDITIONS_PREFERENCE_KEY);

    if (null != termConditionsPreference) {
        termConditionsPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppTac();
                return false;
            }
        });
    }

    // Themes
    ListPreference themePreference = (ListPreference) findPreference(ThemeUtils.APPLICATION_THEME_KEY);

    if (null != themePreference) {
        themePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                if (newValue instanceof String) {
                    VectorApp.updateApplicationTheme((String) newValue);
                    getActivity().startActivity(getActivity().getIntent());
                    getActivity().finish();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    // privacy policy
    EditTextPreference privacyPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_PRIVACY_POLICY_PREFERENCE_KEY);

    if (null != privacyPreference) {
        privacyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppPrivacyPolicy();
                return false;
            }
        });
    }

    // third party notice
    EditTextPreference thirdPartyNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_THIRD_PARTY_NOTICES_PREFERENCE_KEY);

    if (null != thirdPartyNotices) {
        thirdPartyNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayThirdPartyLicenses();
                return false;
            }
        });
    }

    // copyright
    EditTextPreference copyrightNotices = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_COPYRIGHT_PREFERENCE_KEY);

    if (null != copyrightNotices) {
        copyrightNotices.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                VectorUtils.displayAppCopyright();
                return false;
            }
        });
    }

    // update keep medias period
    final EditTextPreference keepMediaPeriodPreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_MEDIA_SAVING_PERIOD_KEY);

    if (null != keepMediaPeriodPreference) {
        keepMediaPeriodPreference
                .setSummary(PreferencesManager.getSelectedMediasSavingPeriodString(getActivity()));

        keepMediaPeriodPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                new AlertDialog.Builder(getActivity())
                        .setSingleChoiceItems(PreferencesManager.getMediasSavingItemsChoicesList(getActivity()),
                                PreferencesManager.getSelectedMediasSavingPeriod(getActivity()),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int n) {
                                        PreferencesManager.setSelectedMediasSavingPeriod(getActivity(), n);
                                        d.cancel();

                                        keepMediaPeriodPreference.setSummary(PreferencesManager
                                                .getSelectedMediasSavingPeriodString(getActivity()));
                                    }
                                })
                        .show();
                return false;
            }
        });
    }

    // clear medias cache
    final EditTextPreference clearMediaCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_MEDIA_CACHE_PREFERENCE_KEY);

    if (null != clearMediaCachePreference) {
        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearMediaCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearMediaCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();

                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        mSession.getMediasCache().clear();
                        Glide.get(getActivity()).clearDiskCache();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        hideLoadingView();

                        MXMediasCache.getCachesSize(getActivity(), new SimpleApiCallback<Long>() {
                            @Override
                            public void onSuccess(Long size) {
                                clearMediaCachePreference.setSummary(
                                        android.text.format.Formatter.formatFileSize(getActivity(), size));
                            }
                        });
                    }
                };

                try {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## mSession.getMediasCache().clear() failed " + e.getMessage());
                    task.cancel(true);
                    hideLoadingView();
                }
                return false;
            }
        });
    }

    // clear cache
    final EditTextPreference clearCachePreference = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_CLEAR_CACHE_PREFERENCE_KEY);

    if (null != clearCachePreference) {
        MXSession.getApplicationSizeCaches(getActivity(), new SimpleApiCallback<Long>() {
            @Override
            public void onSuccess(Long size) {
                if (null != getActivity()) {
                    clearCachePreference
                            .setSummary(android.text.format.Formatter.formatFileSize(getActivity(), size));
                }
            }
        });

        clearCachePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                displayLoadingView();
                Matrix.getInstance(appContext).reloadSessions(appContext);
                return false;
            }
        });
    }

    final EditTextPreference displaynamePref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DISPLAY_NAME_PREFERENCE_KEY);
    displaynamePref.setSummary(mSession.getMyUser().displayname);
    displaynamePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            onDisplayNameClick((null == newValue) ? null : ((String) newValue).trim());
            return false;
        }
    });

    final VectorSwitchPreference urlPreviewPreference = (VectorSwitchPreference) findPreference(
            PreferencesManager.SETTINGS_SHOW_URL_PREVIEW_KEY);
    urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());

    urlPreviewPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            if ((null != newValue) && ((boolean) newValue != mSession.isURLPreviewEnabled())) {
                displayLoadingView();
                mSession.setURLPreviewStatus((boolean) newValue, new ApiCallback<Void>() {
                    @Override
                    public void onSuccess(Void info) {
                        urlPreviewPreference.setChecked(mSession.isURLPreviewEnabled());
                        hideLoadingView();
                    }

                    private void onError(String errorMessage) {
                        if (null != getActivity()) {
                            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                        }
                        onSuccess(null);
                    }

                    @Override
                    public void onNetworkError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onMatrixError(MatrixError e) {
                        onError(e.getLocalizedMessage());
                    }

                    @Override
                    public void onUnexpectedError(Exception e) {
                        onError(e.getLocalizedMessage());
                    }
                });
            }

            return false;
        }
    });

    // push rules
    for (String resourceText : mPushesRuleByResourceId.keySet()) {
        final Preference preference = findPreference(resourceText);

        if (null != preference) {
            if (preference instanceof CheckBoxPreference) {
                preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
                        // on some old android APIs,
                        // the callback is called even if there is no user interaction
                        // so the value will be checked to ensure there is really no update.
                        onPushRuleClick(preference.getKey(), (boolean) newValueAsVoid);
                        return true;
                    }
                });
            } else if (preference instanceof BingRulePreference) {
                final BingRulePreference bingRulePreference = (BingRulePreference) preference;
                bingRulePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        new AlertDialog.Builder(getActivity()).setSingleChoiceItems(
                                bingRulePreference.getBingRuleStatuses(),
                                bingRulePreference.getRuleStatusIndex(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface d, int index) {
                                        BingRule rule = bingRulePreference.createRule(index);
                                        d.cancel();

                                        if (null != rule) {
                                            displayLoadingView();
                                            mSession.getDataHandler().getBingRulesManager().updateRule(
                                                    bingRulePreference.getRule(), rule,
                                                    new BingRulesManager.onBingRuleUpdateListener() {
                                                        private void onDone() {
                                                            refreshDisplay();
                                                            hideLoadingView();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateSuccess() {
                                                            onDone();
                                                        }

                                                        @Override
                                                        public void onBingRuleUpdateFailure(
                                                                String errorMessage) {
                                                            if (null != getActivity()) {
                                                                Toast.makeText(getActivity(), errorMessage,
                                                                        Toast.LENGTH_SHORT).show();
                                                            }
                                                            onDone();
                                                        }
                                                    });
                                        }
                                    }
                                }).show();
                        return true;
                    }
                });
            }
        }
    }

    // background sync tuning settings
    // these settings are useless and hidden if the app is registered to the GCM push service
    final GcmRegistrationManager gcmMgr = Matrix.getInstance(appContext).getSharedGCMRegistrationManager();
    if (gcmMgr.useGCM() && gcmMgr.hasRegistrationToken()) {
        // Hide the section
        PreferenceScreen preferenceScreen = getPreferenceScreen();
        PreferenceCategory backgroundSyncCategory = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_PREFERENCE_KEY);
        PreferenceCategory backgroundSyncDivider = (PreferenceCategory) findPreference(
                PreferencesManager.SETTINGS_BACKGROUND_SYNC_DIVIDER_PREFERENCE_KEY);

        preferenceScreen.removePreference(backgroundSyncDivider);
        preferenceScreen.removePreference(backgroundSyncCategory);
    } else {
        mSyncRequestTimeoutPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_TIMEOUT_PREFERENCE_KEY);
        mSyncRequestDelayPreference = (EditTextPreference) findPreference(
                PreferencesManager.SETTINGS_SET_SYNC_DELAY_PREFERENCE_KEY);
        final CheckBoxPreference useBackgroundSyncPref = (CheckBoxPreference) findPreference(
                PreferencesManager.SETTINGS_ENABLE_BACKGROUND_SYNC_PREFERENCE_KEY);

        if (null != useBackgroundSyncPref) {

            final GcmRegistrationManager.ThirdPartyRegistrationListener listener = new GcmRegistrationManager.ThirdPartyRegistrationListener() {

                @Override
                public void onThirdPartyRegistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyRegistrationFailed() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistered() {
                    hideLoadingView();
                }

                @Override
                public void onThirdPartyUnregistrationFailed() {
                    hideLoadingView();
                }
            };

            if (null != useBackgroundSyncPref) {
                useBackgroundSyncPref.setChecked(gcmMgr.isBackgroundSyncAllowed());

                useBackgroundSyncPref
                        .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                            @Override
                            public boolean onPreferenceChange(Preference preference, Object aNewValue) {
                                final boolean newValue = (boolean) aNewValue;

                                if (newValue != gcmMgr.isBackgroundSyncAllowed()) {
                                    gcmMgr.setBackgroundSyncAllowed(newValue);
                                }

                                displayLoadingView();

                                Matrix.getInstance(VectorSettingsPreferencesFragment.this.getActivity())
                                        .getSharedGCMRegistrationManager().forceSessionsRegistration(listener);

                                return true;
                            }
                        });
            }
        }
    }

    mUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_USER_SETTINGS_PREFERENCE_KEY);
    mContactSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CONTACT_PREFERENCE_KEYS);
    mPushersSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGETS_PREFERENCE_KEY);
    mPushersSettingsDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_NOTIFICATIONS_TARGET_DIVIDER_PREFERENCE_KEY);
    mIgnoredUserSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORED_USERS_PREFERENCE_KEY);
    mIgnoredUserSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_IGNORE_USERS_DIVIDER_PREFERENCE_KEY);
    mDevicesListSettingsCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_LIST_PREFERENCE_KEY);
    mDevicesListSettingsCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_DEVICES_DIVIDER_PREFERENCE_KEY);
    mCryptographyCategory = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_PREFERENCE_KEY);
    mCryptographyCategoryDivider = (PreferenceCategory) findPreference(
            PreferencesManager.SETTINGS_CRYPTOGRAPHY_DIVIDER_PREFERENCE_KEY);
    mLabsCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_LABS_PREFERENCE_KEY);
    mGroupsFlairCategory = (PreferenceCategory) findPreference(PreferencesManager.SETTINGS_GROUPS_FLAIR_KEY);

    // preference to start the App info screen, to facilitate App permissions access
    Preference applicationInfoLInkPref = findPreference(APP_INFO_LINK_PREFERENCE_KEY);
    applicationInfoLInkPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (null != getActivity()) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromParts("package", appContext.getPackageName(), null);
                intent.setData(uri);
                getActivity().getApplicationContext().startActivity(intent);
            }

            return true;
        }
    });

    // Contacts
    setContactsPreferences();

    // user interface preferences
    setUserInterfacePreferences();

    final CheckBoxPreference useCryptoPref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_PREFERENCE_KEY);
    final Preference cryptoIsEnabledPref = findPreference(
            PreferencesManager.SETTINGS_ROOM_SETTINGS_LABS_END_TO_END_IS_ACTIVE_PREFERENCE_KEY);

    cryptoIsEnabledPref.setEnabled(false);

    if (!mSession.isCryptoEnabled()) {
        useCryptoPref.setChecked(false);
        mLabsCategory.removePreference(cryptoIsEnabledPref);
    } else {
        mLabsCategory.removePreference(useCryptoPref);
    }

    useCryptoPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValueAsVoid) {
            if (TextUtils.isEmpty(mSession.getCredentials().deviceId)) {
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.room_settings_labs_end_to_end_warnings)
                        .setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                CommonActivityUtils.logout(getActivity());

                            }
                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                dialog.dismiss();
                                useCryptoPref.setChecked(false);
                            }
                        }).create().show();
            } else {
                boolean newValue = (boolean) newValueAsVoid;

                if (mSession.isCryptoEnabled() != newValue) {
                    displayLoadingView();

                    mSession.enableCrypto(newValue, new ApiCallback<Void>() {
                        private void refresh() {
                            if (null != getActivity()) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        hideLoadingView();
                                        useCryptoPref.setChecked(mSession.isCryptoEnabled());

                                        if (mSession.isCryptoEnabled()) {
                                            mLabsCategory.removePreference(useCryptoPref);
                                            mLabsCategory.addPreference(cryptoIsEnabledPref);
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onSuccess(Void info) {
                            useCryptoPref.setEnabled(false);
                            refresh();
                        }

                        @Override
                        public void onNetworkError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onMatrixError(MatrixError e) {
                            useCryptoPref.setChecked(false);
                        }

                        @Override
                        public void onUnexpectedError(Exception e) {
                            useCryptoPref.setChecked(false);
                        }
                    });
                }
            }

            return true;
        }
    });

    // SaveMode Managment
    final CheckBoxPreference dataSaveModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_DATA_SAVE_MODE_PREFERENCE_KEY);
    dataSaveModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            List<MXSession> sessions = Matrix.getMXSessions(getActivity());
            for (MXSession session : sessions) {
                session.setUseDataSaveMode((boolean) newValue);
            }

            return true;
        }
    });

    // Analytics tracking managment
    final CheckBoxPreference useAnalyticsModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_ANALYTICS_KEY);

    // On if the analytics tracking is activated
    useAnalyticsModePref.setChecked(PreferencesManager.useAnalytics(appContext));

    useAnalyticsModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseAnalytics(appContext, (boolean) newValue);
            return true;
        }
    });

    // Rageshake Managment
    final CheckBoxPreference useRageShakeModePref = (CheckBoxPreference) findPreference(
            PreferencesManager.SETTINGS_USE_RAGE_SHAKE_KEY);
    final boolean mIsUsedRageShake = PreferencesManager.useRageshake(appContext);

    useRageShakeModePref.setChecked(mIsUsedRageShake);

    useRageShakeModePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            PreferencesManager.setUseRageshake(appContext, (boolean) newValue);
            return true;
        }
    });

    // deactivate account
    EditTextPreference deactivateAccountPref = (EditTextPreference) findPreference(
            PreferencesManager.SETTINGS_DEACTIVATE_ACCOUNT_KEY);

    if (null != deactivateAccountPref) {
        deactivateAccountPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                startActivity(DeactivateAccountActivity.Companion.getIntent(getActivity()));

                return false;
            }
        });
    }

    addButtons();
    refreshPushersList();
    refreshEmailsList();
    refreshPhoneNumbersList();
    refreshIgnoredUsersList();
    refreshDevicesList();
    refreshGroupFlairsList();
}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

private void startNavigationTask(String id) {

    if (!NetworkUtils.isOnline(this)) {
        Toast.makeText(this, "No connection available!", Toast.LENGTH_SHORT).show();
        return;//ww w  .  j av  a2 s  . com
    }

    // show the info window for the destination marker
    Marker marker = visiblePois.getMarkerFromPoisModel(id);
    if (marker != null) {
        marker.showInfoWindow();
    }

    final BuildingModel b = userData.getSelectedBuilding();
    final String floor = userData.getSelectedFloorNumber();

    class Status {
        Boolean task1 = false;
        Boolean task2 = false;
    }
    final Status status = new Status();

    final ProgressDialog dialog;
    dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setTitle("Plotting navigation");
    dialog.setMessage("Please be patient...");
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(false);

    GeoPoint entrance = null;
    GeoPoint pos = userData.getPositionWifi();
    if (pos == null) {
        // Find The nearest building entrance from the destination poi
        PoisModel _entrance = null;
        PoisModel dest = mAnyplaceCache.getPoisMap().get(id);
        double min = Double.MAX_VALUE;
        String currentFloor = userData.getSelectedFloorNumber();
        for (PoisModel pm : mAnyplaceCache.getPoisMap().values()) {
            if (pm.floor_number.equalsIgnoreCase(currentFloor) && pm.is_building_entrance) {
                double distance = Math.abs(pm.lat() - dest.lat()) + Math.abs(pm.lng() - dest.lng());
                if (min > distance) {
                    _entrance = pm;
                    min = distance;
                }
            }
        }

        if (_entrance != null) {
            entrance = new GeoPoint(_entrance.lat(), _entrance.lng());
        } else {
            Toast.makeText(this, "No entrance found!", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    final GeoPoint entrancef = entrance;

    // Does not run if entrance==null or is near the building
    final AsyncTask<Void, Void, String> async1f = new NavDirectionsTask(
            new NavDirectionsTask.NavDirectionsListener() {

                @Override
                public void onNavDirectionsSuccess(String result, List<LatLng> points) {
                    onNavDirectionsAboart();

                    if (!points.isEmpty()) {
                        // points.add(new LatLng(entrancef.dlat, entrancef.dlon));
                        pathLineOutsideOptions = new PolylineOptions().addAll(points).width(10).color(Color.RED)
                                .zIndex(100.0f);
                        pathLineOutside = mMap.addPolyline(pathLineOutsideOptions);
                    }
                }

                @Override
                public void onNavDirectionsErrorOrCancel(String result) {
                    onNavDirectionsAboart();
                    // display the error cause
                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onNavDirectionsAboart() {
                    status.task1 = true;
                    if (status.task1 && status.task2)
                        dialog.dismiss();
                    else {
                        // First task executed calls this
                        clearLastNavigationInfo();
                    }
                }

            }, userData.getLocationGPSorIP(), entrance);

    // start the navigation task
    final AsyncTask<Void, Void, String> async2f = new NavRouteTask(new NavRouteTask.NavRouteListener() {
        @Override
        public void onNavRouteSuccess(String result, List<PoisNav> points) {
            onNavDirectionsAboart();

            // set the navigation building and new points
            userData.setNavBuilding(b);
            userData.setNavPois(points);

            // handle drawing of the points
            handlePathDrawing(points);
        }

        @Override
        public void onNavRouteErrorOrCancel(String result) {
            onNavDirectionsAboart();
            // display the error cause
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
        }

        public void onNavDirectionsAboart() {
            status.task2 = true;
            if (status.task1 && status.task2)
                dialog.dismiss();
            else {
                // First task executed calls this
                clearLastNavigationInfo();
            }
        }
    }, this, id, (pos == null) ? entrancef : pos, floor);

    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            async1f.cancel(true);
            async2f.cancel(true);
        }
    });
    dialog.show();
    async1f.execute();
    async2f.execute();
}

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

protected void loadFriends() {
    mFriends.clear();// w w w.  j a v  a 2  s .  co m
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = sonetCrypto.Decrypt(account.getString(0));
                mSecret = sonetCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    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(mAccountId);
}

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

protected void loadFriends() {
    mFriends.clear();//from   w w  w.  ja v a 2  s  . c  om
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = myfeedleCrypto.Decrypt(account.getString(0));
                mSecret = myfeedleCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    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(mAccountId);
}

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

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override//from w w  w  . ja  va  2s.  c  o  m
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                SonetOAuth sonetOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH,
                            FACEBOOK_BASE_URL, mLat, mLong, Saccess_token,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(
                            FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show();
            }
        }

    };
    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();
}

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

private void setLocation(final long accountId) {
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {

        int serviceId;

        @Override//  w  w  w .j av a 2  s . c  o  m
        protected String doInBackground(Void... none) {
            Cursor account = getContentResolver().query(Accounts.getContentUri(SonetCreatePost.this),
                    new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SERVICE, Accounts.SECRET },
                    Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
            if (account.moveToFirst()) {
                SonetOAuth sonetOAuth;
                serviceId = account.getInt(account.getColumnIndex(Accounts.SERVICE));
                switch (serviceId) {
                case TWITTER:
                    // anonymous requests are rate limited to 150 per hour
                    // authenticated requests are rate limited to 350 per hour, so authenticate this!
                    sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))),
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.SECRET))));
                    return SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(
                            new HttpGet(String.format(TWITTER_SEARCH, TWITTER_BASE_URL, mLat, mLong))));
                case FACEBOOK:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(FACEBOOK_SEARCH,
                            FACEBOOK_BASE_URL, mLat, mLong, Saccess_token,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                case FOURSQUARE:
                    return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(String.format(
                            FOURSQUARE_SEARCH, FOURSQUARE_BASE_URL, mLat, mLong,
                            mSonetCrypto.Decrypt(account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                }
            }
            account.close();
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            if (response != null) {
                switch (serviceId) {
                case TWITTER:
                    try {
                        JSONArray places = new JSONObject(response).getJSONObject(Sresult)
                                .getJSONArray(Splaces);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sfull_name);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FACEBOOK:
                    try {
                        JSONArray places = new JSONObject(response).getJSONArray(Sdata);
                        final String placesNames[] = new String[places.length()];
                        final String placesIds[] = new String[places.length()];
                        for (int i = 0, i2 = places.length(); i < i2; i++) {
                            JSONObject place = places.getJSONObject(i);
                            placesNames[i] = place.getString(Sname);
                            placesIds[i] = place.getString(Sid);
                        }
                        mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                .setSingleChoiceItems(placesNames, -1, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mAccountsLocation.put(accountId, placesIds[which]);
                                        dialog.dismiss();
                                    }
                                }).setNegativeButton(android.R.string.cancel,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        })
                                .create();
                        mDialog.show();
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                case FOURSQUARE:
                    try {
                        JSONArray groups = new JSONObject(response).getJSONObject(Sresponse)
                                .getJSONArray(Sgroups);
                        for (int g = 0, g2 = groups.length(); g < g2; g++) {
                            JSONObject group = groups.getJSONObject(g);
                            if (group.getString(Sname).equals(SNearby)) {
                                JSONArray places = group.getJSONArray(Sitems);
                                final String placesNames[] = new String[places.length()];
                                final String placesIds[] = new String[places.length()];
                                for (int i = 0, i2 = places.length(); i < i2; i++) {
                                    JSONObject place = places.getJSONObject(i);
                                    placesNames[i] = place.getString(Sname);
                                    placesIds[i] = place.getString(Sid);
                                }
                                mDialog = (new AlertDialog.Builder(SonetCreatePost.this))
                                        .setSingleChoiceItems(placesNames, -1,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        mAccountsLocation.put(accountId, placesIds[which]);
                                                        dialog.dismiss();
                                                    }
                                                })
                                        .setNegativeButton(android.R.string.cancel,
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .create();
                                mDialog.show();
                                break;
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                    break;
                }
            } else {
                (Toast.makeText(SonetCreatePost.this, getString(R.string.failure), Toast.LENGTH_LONG)).show();
            }
        }

    };
    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();
}