Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

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

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

From source file:export.UploadManager.java

protected void doListWorkout(final Uploader uploader) {
    final ProgressDialog copySpinner = mSpinner;

    copySpinner.setMessage("Listing from " + uploader.getName());
    final ArrayList<Pair<String, String>> list = new ArrayList<Pair<String, String>>();

    new AsyncTask<Uploader, String, Uploader.Status>() {

        @Override/*from  w  w  w  . ja  v  a 2  s . c  o  m*/
        protected Uploader.Status doInBackground(Uploader... params) {
            try {
                return params[0].listWorkouts(list);
            } catch (Exception ex) {
                ex.printStackTrace();
                return Uploader.Status.ERROR;
            }
        }

        @Override
        protected void onPostExecute(Uploader.Status result) {
            switch (result) {
            case CANCEL:
            case ERROR:
            case INCORRECT_USAGE:
            case SKIP:
                break;
            case OK:
                for (Pair<String, String> w : list) {
                    workoutRef.add(new WorkoutRef(uploader.getName(), w.first, w.second));
                }
                break;
            case NEED_AUTH:
                handleAuth(new Callback() {
                    @Override
                    public void run(String uploaderName, export.Uploader.Status status) {
                        switch (status) {
                        case CANCEL:
                        case SKIP:
                        case ERROR:
                        case INCORRECT_USAGE:
                        case NEED_AUTH: // should be handled inside
                                        // connect "loop"
                            nextListWorkout();
                            break;
                        case OK:
                            doListWorkout(uploader);
                            break;
                        }
                    }
                }, uploader, result.authMethod);
                return;
            }
            nextListWorkout();
        }
    }.execute(uploader);
}

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

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

private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override//  w w w. j  a va 2s.  c  om
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regId = gcm.register(Config.GOOGLE_PROJECT_ID);
                Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
                msg = "Device registered, registration ID=" + regId;

                storeRegistrationId(context, regId);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                Log.d("RegisterActivity", "Error: " + msg);
            }
            Log.d("RegisterActivity", "AsyncTask completed: " + msg);
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            Toast.makeText(getApplicationContext(), "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                    .show();
        }
    }.execute(null, null, null);
}

From source file:com.music.mybarr.activities.ExampleActivity.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();//from ww  w  .  j av a 2  s. com
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                albumArt.setImageBitmap(artwork);
            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName,
            track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

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

@Override
protected void onListItemClick(ListView list, View view, final int position, long id) {
    super.onListItemClick(list, view, position, id);
    final String sid = mComments.get(position).get(Statuses.SID);
    final String liked = mComments.get(position).get(getString(R.string.like));
    // wait for previous attempts to finish
    if ((liked.length() > 0) && !liked.equals(getString(R.string.loading))) {
        // parse comment body, as in StatusDialog.java
        Matcher m = Sonet.getLinksMatcher(mComments.get(position).get(Statuses.MESSAGE));
        int count = 0;
        while (m.find()) {
            count++;// ww  w .  j  ava  2 s.co m
        }
        // like comments, the first comment is the post itself
        switch (mService) {
        case TWITTER:
            // retweet
            items = new String[count + 1];
            items[0] = getString(R.string.retweet);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                SonetOAuth sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken,
                                        mSecret);
                                HttpPost httpPost = new HttpPost(
                                        String.format(TWITTER_RETWEET, TWITTER_BASE_URL, sid));
                                // resolve Error 417 Expectation by Twitter
                                httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                        false);
                                return SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                setCommentStatus(0, getString(R.string.retweet));
                                (Toast.makeText(SonetComments.this,
                                        mServiceName + " "
                                                + getString(
                                                        response != null ? R.string.success : R.string.failure),
                                        Toast.LENGTH_LONG)).show();
                            }
                        };
                        setCommentStatus(0, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case FACEBOOK:
            items = new String[count + 1];
            items[0] = getString(
                    mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                            ? R.string.like
                            : R.string.unlike);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                if (liked.equals(getString(R.string.like))) {
                                    return SonetHttpClient.httpResponse(mHttpClient,
                                            new HttpPost(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, sid,
                                                    Saccess_token, mToken)));
                                } else {
                                    HttpDelete httpDelete = new HttpDelete(String.format(FACEBOOK_LIKES,
                                            FACEBOOK_BASE_URL, sid, Saccess_token, mToken));
                                    httpDelete.setHeader("Content-Length", "0");
                                    return SonetHttpClient.httpResponse(mHttpClient, httpDelete);
                                }
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                if (response != null) {
                                    setCommentStatus(position,
                                            getString(liked.equals(getString(R.string.like)) ? R.string.unlike
                                                    : R.string.like));
                                    (Toast.makeText(SonetComments.this,
                                            mServiceName + " " + getString(R.string.success),
                                            Toast.LENGTH_LONG)).show();
                                } else {
                                    setCommentStatus(position,
                                            getString(liked.equals(getString(R.string.like)) ? R.string.like
                                                    : R.string.unlike));
                                    (Toast.makeText(SonetComments.this,
                                            mServiceName + " " + getString(R.string.failure),
                                            Toast.LENGTH_LONG)).show();
                                }
                            }
                        };
                        setCommentStatus(position, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case LINKEDIN:
            if (position == 0) {
                items = new String[count + 1];
                items[0] = getString(
                        mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                                ? R.string.like
                                : R.string.unlike);
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                                        @Override
                                        protected String doInBackground(String... arg0) {
                                            SonetOAuth sonetOAuth = new SonetOAuth(LINKEDIN_KEY,
                                                    LINKEDIN_SECRET, mToken, mSecret);
                                            HttpPut httpPut = new HttpPut(
                                                    String.format(LINKEDIN_IS_LIKED, LINKEDIN_BASE_URL, mSid));
                                            httpPut.addHeader(
                                                    new BasicHeader("Content-Type", "application/xml"));
                                            try {
                                                httpPut.setEntity(new StringEntity(
                                                        String.format(LINKEDIN_LIKE_BODY, Boolean.toString(
                                                                liked.equals(getString(R.string.like))))));
                                                return SonetHttpClient.httpResponse(mHttpClient,
                                                        sonetOAuth.getSignedRequest(httpPut));
                                            } catch (UnsupportedEncodingException e) {
                                                Log.e(TAG, e.toString());
                                            }
                                            return null;
                                        }

                                        @Override
                                        protected void onPostExecute(String response) {
                                            if (response != null) {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.unlike
                                                                : R.string.like));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.success),
                                                        Toast.LENGTH_LONG)).show();
                                            } else {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.like
                                                                : R.string.unlike));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.failure),
                                                        Toast.LENGTH_LONG)).show();
                                            }
                                        }
                                    };
                                    setCommentStatus(position, getString(R.string.loading));
                                    asyncTask.execute();
                                } else {
                                    if ((which < items.length) && (items[which] != null))
                                        // open link
                                        startActivity(new Intent(Intent.ACTION_VIEW)
                                                .setData(Uri.parse(items[which])));
                                    else
                                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                                Toast.LENGTH_LONG)).show();
                                }
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            } else {
                // no like option here
                items = new String[count];
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ((which < items.length) && (items[which] != null))
                                    // open link
                                    startActivity(
                                            new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                                else
                                    (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                            Toast.LENGTH_LONG)).show();
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            }
            break;
        case IDENTICA:
            // retweet
            items = new String[count + 1];
            items[0] = getString(R.string.repeat);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                SonetOAuth sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken,
                                        mSecret);
                                HttpPost httpPost = new HttpPost(
                                        String.format(IDENTICA_RETWEET, IDENTICA_BASE_URL, sid));
                                // resolve Error 417 Expectation by Twitter
                                httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                        false);
                                return SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                setCommentStatus(0, getString(R.string.repeat));
                                (Toast.makeText(SonetComments.this,
                                        mServiceName + " "
                                                + getString(
                                                        response != null ? R.string.success : R.string.failure),
                                        Toast.LENGTH_LONG)).show();
                            }
                        };
                        setCommentStatus(0, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case GOOGLEPLUS:
            //TODO:
            // plus1
            items = new String[count];
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if ((which < items.length) && (items[which] != null))
                        // open link
                        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                    else
                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                Toast.LENGTH_LONG)).show();
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case CHATTER:
            if (position == 0) {
                items = new String[count + 1];
                items[0] = getString(
                        mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                                ? R.string.like
                                : R.string.unlike);
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                                        @Override
                                        protected String doInBackground(String... arg0) {
                                            HttpUriRequest httpRequest;
                                            if (liked.equals(getString(R.string.like))) {
                                                httpRequest = new HttpPost(String.format(CHATTER_URL_LIKES,
                                                        mChatterInstance, mSid));
                                            } else {
                                                httpRequest = new HttpDelete(String.format(CHATTER_URL_LIKE,
                                                        mChatterInstance, mChatterLikeId));
                                            }
                                            httpRequest.setHeader("Authorization", "OAuth " + mChatterToken);
                                            return SonetHttpClient.httpResponse(mHttpClient, httpRequest);
                                        }

                                        @Override
                                        protected void onPostExecute(String response) {
                                            if (response != null) {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.unlike
                                                                : R.string.like));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.success),
                                                        Toast.LENGTH_LONG)).show();
                                            } else {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.like
                                                                : R.string.unlike));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.failure),
                                                        Toast.LENGTH_LONG)).show();
                                            }
                                        }
                                    };
                                    setCommentStatus(position, getString(R.string.loading));
                                    asyncTask.execute();
                                } else {
                                    if ((which < items.length) && (items[which] != null))
                                        // open link
                                        startActivity(new Intent(Intent.ACTION_VIEW)
                                                .setData(Uri.parse(items[which])));
                                    else
                                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                                Toast.LENGTH_LONG)).show();
                                }
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            } else {
                // no like option here
                items = new String[count];
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ((which < items.length) && (items[which] != null))
                                    // open link
                                    startActivity(
                                            new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                                else
                                    (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                            Toast.LENGTH_LONG)).show();
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            }
            break;
        }
    }
}

From source file:com.cloverstudio.spika.CameraCropActivity.java

protected void onPhotoTaken(String path) {

    String fileName = Uri.parse(path).getLastPathSegment();
    mFilePath = CameraCropActivity.this.getExternalCacheDir() + "/" + fileName;

    if (!path.equals(mFilePath)) {
        copy(new File(path), new File(mFilePath));
    }//w w  w . ja va2s  .  c om

    new AsyncTask<String, Void, byte[]>() {
        boolean loadingFailed = false;

        @Override
        protected byte[] doInBackground(String... params) {
            try {

                if (params == null)
                    return null;

                File f = new File(params[0]);
                ExifInterface exif = new ExifInterface(f.getPath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL);

                int angle = 0;

                if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                    angle = 90;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                    angle = 180;
                } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                    angle = 270;
                }

                Matrix mat = new Matrix();
                mat.postRotate(angle);

                BitmapFactory.Options optionsMeta = new BitmapFactory.Options();
                optionsMeta.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(f.getAbsolutePath(), optionsMeta);

                BitmapFactory.Options options = new BitmapFactory.Options();

                options.inSampleSize = BitmapManagement.calculateInSampleSize(optionsMeta, 640, 640);
                options.inPurgeable = true;
                options.inInputShareable = true;
                mBitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
                mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), mat,
                        true);
                _scaleBitmap();
                return null;
            } catch (Exception ex) {
                loadingFailed = true;
                finish();
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);

            if (null != mBitmap) {
                mImageView.setImageBitmap(mBitmap);
                mImageView.setScaleType(ScaleType.MATRIX);
                translateMatrix.setTranslate(-(mBitmap.getWidth() - crop_container_size) / 2f,
                        -(mBitmap.getHeight() - crop_container_size) / 2f);
                mImageView.setImageMatrix(translateMatrix);

                matrix = translateMatrix;

            }

        }
    }.execute(mFilePath);

}

From source file:com.facebook.internal.Utility.java

public static void loadAppSettingsAsync(final Context context, final String applicationId) {
    if (Utility.isNullOrEmpty(applicationId) || fetchedAppSettings.containsKey(applicationId)
            || initialAppSettingsLoadTask != null) {
        return;/*from   ww  w  .j a  va  2  s .c  o  m*/
    }

    final String settingsKey = String.format(APP_SETTINGS_PREFS_KEY_FORMAT, applicationId);

    initialAppSettingsLoadTask = new AsyncTask<Void, Void, GraphObject>() {
        @Override
        protected GraphObject doInBackground(Void... params) {
            return getAppSettingsQueryResponse(applicationId);
        }

        @Override
        protected void onPostExecute(GraphObject result) {
            if (result != null) {
                JSONObject resultJSON = result.getInnerJSONObject();
                parseAppSettingsFromJSON(applicationId, resultJSON);

                SharedPreferences sharedPrefs = context.getSharedPreferences(APP_SETTINGS_PREFS_STORE,
                        Context.MODE_PRIVATE);
                sharedPrefs.edit().putString(settingsKey, resultJSON.toString()).apply();
            }

            initialAppSettingsLoadTask = null;
        }
    };
    initialAppSettingsLoadTask.execute((Void[]) null);

    // Also see if we had a cached copy and use that immediately.
    SharedPreferences sharedPrefs = context.getSharedPreferences(APP_SETTINGS_PREFS_STORE,
            Context.MODE_PRIVATE);
    String settingsJSONString = sharedPrefs.getString(settingsKey, null);
    if (!isNullOrEmpty(settingsJSONString)) {
        JSONObject settingsJSON = null;
        try {
            settingsJSON = new JSONObject(settingsJSONString);
        } catch (JSONException je) {
            logd(LOG_TAG, je);
        }
        if (settingsJSON != null) {
            parseAppSettingsFromJSON(applicationId, settingsJSON);
        }
    }
}

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

@Override
protected void onListItemClick(ListView list, View view, final int position, long id) {
    super.onListItemClick(list, view, position, id);
    final String sid = mComments.get(position).get(Statuses.SID);
    final String liked = mComments.get(position).get(getString(R.string.like));
    // wait for previous attempts to finish
    if ((liked.length() > 0) && !liked.equals(getString(R.string.loading))) {
        // parse comment body, as in StatusDialog.java
        Matcher m = Sonet.getLinksMatcher(mComments.get(position).get(Statuses.MESSAGE));
        int count = 0;
        while (m.find()) {
            count++;/*from w  ww .j a  v a 2s  .c om*/
        }
        // like comments, the first comment is the post itself
        switch (mService) {
        case TWITTER:
            // retweet
            items = new String[count + 1];
            items[0] = getString(R.string.retweet);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY,
                                        BuildConfig.TWITTER_SECRET, mToken, mSecret);
                                HttpPost httpPost = new HttpPost(
                                        String.format(TWITTER_RETWEET, TWITTER_BASE_URL, sid));
                                // resolve Error 417 Expectation by Twitter
                                httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                        false);
                                return SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                setCommentStatus(0, getString(R.string.retweet));
                                (Toast.makeText(SonetComments.this,
                                        mServiceName + " "
                                                + getString(
                                                        response != null ? R.string.success : R.string.failure),
                                        Toast.LENGTH_LONG)).show();
                            }
                        };
                        setCommentStatus(0, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case FACEBOOK:
            items = new String[count + 1];
            items[0] = getString(
                    mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                            ? R.string.like
                            : R.string.unlike);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                if (liked.equals(getString(R.string.like))) {
                                    return SonetHttpClient.httpResponse(mHttpClient,
                                            new HttpPost(String.format(FACEBOOK_LIKES, FACEBOOK_BASE_URL, sid,
                                                    Saccess_token, mToken)));
                                } else {
                                    HttpDelete httpDelete = new HttpDelete(String.format(FACEBOOK_LIKES,
                                            FACEBOOK_BASE_URL, sid, Saccess_token, mToken));
                                    httpDelete.setHeader("Content-Length", "0");
                                    return SonetHttpClient.httpResponse(mHttpClient, httpDelete);
                                }
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                if (response != null) {
                                    setCommentStatus(position,
                                            getString(liked.equals(getString(R.string.like)) ? R.string.unlike
                                                    : R.string.like));
                                    (Toast.makeText(SonetComments.this,
                                            mServiceName + " " + getString(R.string.success),
                                            Toast.LENGTH_LONG)).show();
                                } else {
                                    setCommentStatus(position,
                                            getString(liked.equals(getString(R.string.like)) ? R.string.like
                                                    : R.string.unlike));
                                    (Toast.makeText(SonetComments.this,
                                            mServiceName + " " + getString(R.string.failure),
                                            Toast.LENGTH_LONG)).show();
                                }
                            }
                        };
                        setCommentStatus(position, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case LINKEDIN:
            if (position == 0) {
                items = new String[count + 1];
                items[0] = getString(
                        mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                                ? R.string.like
                                : R.string.unlike);
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                                        @Override
                                        protected String doInBackground(String... arg0) {
                                            SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                                    BuildConfig.LINKEDIN_SECRET, mToken, mSecret);
                                            HttpPut httpPut = new HttpPut(
                                                    String.format(LINKEDIN_IS_LIKED, LINKEDIN_BASE_URL, mSid));
                                            httpPut.addHeader(
                                                    new BasicHeader("Content-Type", "application/xml"));
                                            try {
                                                httpPut.setEntity(new StringEntity(
                                                        String.format(LINKEDIN_LIKE_BODY, Boolean.toString(
                                                                liked.equals(getString(R.string.like))))));
                                                return SonetHttpClient.httpResponse(mHttpClient,
                                                        sonetOAuth.getSignedRequest(httpPut));
                                            } catch (UnsupportedEncodingException e) {
                                                Log.e(TAG, e.toString());
                                            }
                                            return null;
                                        }

                                        @Override
                                        protected void onPostExecute(String response) {
                                            if (response != null) {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.unlike
                                                                : R.string.like));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.success),
                                                        Toast.LENGTH_LONG)).show();
                                            } else {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.like
                                                                : R.string.unlike));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.failure),
                                                        Toast.LENGTH_LONG)).show();
                                            }
                                        }
                                    };
                                    setCommentStatus(position, getString(R.string.loading));
                                    asyncTask.execute();
                                } else {
                                    if ((which < items.length) && (items[which] != null))
                                        // open link
                                        startActivity(new Intent(Intent.ACTION_VIEW)
                                                .setData(Uri.parse(items[which])));
                                    else
                                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                                Toast.LENGTH_LONG)).show();
                                }
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            } else {
                // no like option here
                items = new String[count];
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ((which < items.length) && (items[which] != null))
                                    // open link
                                    startActivity(
                                            new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                                else
                                    (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                            Toast.LENGTH_LONG)).show();
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            }
            break;
        case IDENTICA:
            // retweet
            items = new String[count + 1];
            items[0] = getString(R.string.repeat);
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                            @Override
                            protected String doInBackground(String... arg0) {
                                SonetOAuth sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                        BuildConfig.IDENTICA_SECRET, mToken, mSecret);
                                HttpPost httpPost = new HttpPost(
                                        String.format(IDENTICA_RETWEET, IDENTICA_BASE_URL, sid));
                                // resolve Error 417 Expectation by Twitter
                                httpPost.getParams().setBooleanParameter("http.protocol.expect-continue",
                                        false);
                                return SonetHttpClient.httpResponse(mHttpClient,
                                        sonetOAuth.getSignedRequest(httpPost));
                            }

                            @Override
                            protected void onPostExecute(String response) {
                                setCommentStatus(0, getString(R.string.repeat));
                                (Toast.makeText(SonetComments.this,
                                        mServiceName + " "
                                                + getString(
                                                        response != null ? R.string.success : R.string.failure),
                                        Toast.LENGTH_LONG)).show();
                            }
                        };
                        setCommentStatus(0, getString(R.string.loading));
                        asyncTask.execute();
                    } else {
                        if ((which < items.length) && (items[which] != null))
                            // open link
                            startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                        else
                            (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                    Toast.LENGTH_LONG)).show();
                    }
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case GOOGLEPLUS:
            //TODO:
            // plus1
            items = new String[count];
            count = 1;
            m.reset();
            while (m.find()) {
                items[count++] = m.group();
            }
            mDialog = (new AlertDialog.Builder(this)).setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if ((which < items.length) && (items[which] != null))
                        // open link
                        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                    else
                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                Toast.LENGTH_LONG)).show();
                }
            }).setCancelable(true).setOnCancelListener(this).create();
            mDialog.show();
            break;
        case CHATTER:
            if (position == 0) {
                items = new String[count + 1];
                items[0] = getString(
                        mComments.get(position).get(getString(R.string.like)) == getString(R.string.like)
                                ? R.string.like
                                : R.string.unlike);
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                                        @Override
                                        protected String doInBackground(String... arg0) {
                                            HttpUriRequest httpRequest;
                                            if (liked.equals(getString(R.string.like))) {
                                                httpRequest = new HttpPost(String.format(CHATTER_URL_LIKES,
                                                        mChatterInstance, mSid));
                                            } else {
                                                httpRequest = new HttpDelete(String.format(CHATTER_URL_LIKE,
                                                        mChatterInstance, mChatterLikeId));
                                            }
                                            httpRequest.setHeader("Authorization", "OAuth " + mChatterToken);
                                            return SonetHttpClient.httpResponse(mHttpClient, httpRequest);
                                        }

                                        @Override
                                        protected void onPostExecute(String response) {
                                            if (response != null) {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.unlike
                                                                : R.string.like));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.success),
                                                        Toast.LENGTH_LONG)).show();
                                            } else {
                                                setCommentStatus(position,
                                                        getString(liked.equals(getString(R.string.like))
                                                                ? R.string.like
                                                                : R.string.unlike));
                                                (Toast.makeText(SonetComments.this,
                                                        mServiceName + " " + getString(R.string.failure),
                                                        Toast.LENGTH_LONG)).show();
                                            }
                                        }
                                    };
                                    setCommentStatus(position, getString(R.string.loading));
                                    asyncTask.execute();
                                } else {
                                    if ((which < items.length) && (items[which] != null))
                                        // open link
                                        startActivity(new Intent(Intent.ACTION_VIEW)
                                                .setData(Uri.parse(items[which])));
                                    else
                                        (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                                Toast.LENGTH_LONG)).show();
                                }
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            } else {
                // no like option here
                items = new String[count];
                count = 1;
                m.reset();
                while (m.find()) {
                    items[count++] = m.group();
                }
                mDialog = (new AlertDialog.Builder(this))
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if ((which < items.length) && (items[which] != null))
                                    // open link
                                    startActivity(
                                            new Intent(Intent.ACTION_VIEW).setData(Uri.parse(items[which])));
                                else
                                    (Toast.makeText(SonetComments.this, getString(R.string.error_status),
                                            Toast.LENGTH_LONG)).show();
                            }
                        }).setCancelable(true).setOnCancelListener(this).create();
                mDialog.show();
            }
            break;
        }
    }
}

From source file:de.alosdev.android.customerschoice.CustomersChoice.java

private void persistVariants(final Context context) {
    if (lifeTime == LifeTime.Persistent) {
        new AsyncTask<Void, Void, Void>() {
            @Override/*from  ww w.j a v a2 s .co m*/
            protected Void doInBackground(Void... params) {
                final Editor editor = getPreferences(context).edit();
                final HashSet<String> variantNames = new HashSet<String>();
                for (Variant variant : variants.values()) {
                    variantNames.add(variant.name);
                    editor.putInt(getPreferencesKey(FIELD_VARIANTS, variant.name), variant.currentVariant);
                }
                editor.putStringSet(getPreferencesKey(KEY_VARIANTS, ""), variantNames);
                editor.commit();
                log.d(TAG, "persisted Variant");
                return null;
            }
        }.execute();
    }
}

From source file:com.androidquery.simplefeed.activity.PostActivity.java

private void photoPost() {

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override/*from   w ww  . j  ava  2s.co m*/
        protected Void doInBackground(Void... params) {

            try {
                String id = getSelected();
                photoPost(id, getMessage(), photo);
            } catch (Exception e) {
                AQUtility.report(e);
                failed();
            }
            return null;
        }
    };

    task.execute();

    finish(R.string.pending_upload, false, null, null);

}