Example usage for android.content Intent setFlags

List of usage examples for android.content Intent setFlags

Introduction

In this page you can find the example usage for android.content Intent setFlags.

Prototype

public @NonNull Intent setFlags(@Flags int flags) 

Source Link

Document

Set special flags controlling how this intent is handled.

Usage

From source file:com.tt.jobtracker.MainActivity.java

@Override
public void onBackPressed() {
    if (Shared.onbackpress == true) {
        if (back_pressed + 2000 > System.currentTimeMillis()) {
            //    super.onBackPressed();
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);/*from  w w  w.ja  v a  2  s .c  o m*/
        } else {
            Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
            back_pressed = System.currentTimeMillis();
        }
    } else {
        super.onBackPressed();
    }
}

From source file:com.bonsai.btcreceive.WalletService.java

private void showStatusNotification() {
    // In this sample, we'll use the same text for the ticker and
    // the expanded notification
    CharSequence started_txt = getText(R.string.wallet_service_started);
    CharSequence info_txt = getText(R.string.wallet_service_info);

    Notification note = new Notification(R.drawable.ic_stat_notify, started_txt, System.currentTimeMillis());

    Intent intent = new Intent(this, MainActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

    // Set the info for the views that show in the notification panel.
    note.setLatestEventInfo(this, getText(R.string.wallet_service_label), info_txt, contentIntent);

    note.flags |= Notification.FLAG_NO_CLEAR;

    startForeground(NOTIFICATION, note);
}

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

private void LoadMoreTracks() {
    if (accessToken == null || accessTokenSecret == null) {
        Log.i(TAG, "Anonymous user! No more tracks to play.");

        // Notify the user we're out of tracks
        Toast.makeText(this, getString(R.string.no_more_tracks), Toast.LENGTH_LONG).show();

        // Then helpfully point them to the market to go install Rdio ;)
        Intent installRdioIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("market://search?q=pname:com.rdio.android.ui"));
        installRdioIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(installRdioIntent);

        finish();//from w ww  .j  av  a2  s  . c  o m
        return;
    }

    showGetCollectionDialog();
    List<NameValuePair> args = new LinkedList<NameValuePair>();
    args.add(new BasicNameValuePair("keys", collectionKey));
    args.add(new BasicNameValuePair("count", "50"));
    rdio.apiCall("get", args, new RdioApiCallback() {
        @Override
        public void onApiFailure(String methodName, Exception e) {
            dismissGetCollectionDialog();
            Log.e(TAG, methodName + " failed: ", e);
        }

        @Override
        public void onApiSuccess(JSONObject result) {
            try {
                result = result.getJSONObject("result");
                result = result.getJSONObject(collectionKey);
                List<Track> trackKeys = new LinkedList<Track>();
                JSONArray tracks = result.getJSONArray("tracks");
                for (int i = 0; i < tracks.length(); i++) {
                    JSONObject trackObject = tracks.getJSONObject(i);
                    String key = trackObject.getString("key");
                    String name = trackObject.getString("name");
                    String artist = trackObject.getString("artist");
                    String album = trackObject.getString("album");
                    String albumArt = trackObject.getString("icon");
                    Log.d(TAG, "Found track: " + key + " => " + trackObject.getString("name"));
                    trackKeys.add(new Track(key, name, artist, album, albumArt));
                }
                if (trackKeys.size() > 1)
                    trackQueue.addAll(trackKeys);
                dismissGetCollectionDialog();

                next(true);

            } catch (Exception e) {
                dismissGetCollectionDialog();
                Log.e(TAG, "Failed to handle JSONObject: ", e);
            }
        }
    });
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

int interact(final String message, final int titleId) {
    /* prepare the MTMDecision blocker object */
    MTMDecision choice = new MTMDecision();
    final int myId = createDecisionId(choice);

    masterHandler.post(new Runnable() {
        public void run() {
            Intent ni = new Intent(master, MemorizingActivity.class);
            ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
            ni.putExtra(DECISION_INTENT_ID, myId);
            ni.putExtra(DECISION_INTENT_CERT, message);
            ni.putExtra(DECISION_TITLE_ID, titleId);

            // we try to directly start the activity and fall back to
            // making a notification
            try {
                getUI().startActivity(ni);
            } catch (Exception e) {
                LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
            }//from  w  ww.j av a  2s .  c om
        }
    });

    LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
    try {
        synchronized (choice) {
            choice.wait();
        }
    } catch (InterruptedException e) {
        LOGGER.log(Level.FINER, "InterruptedException", e);
    }
    LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
    return choice.state;
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Abre o anexo pela URI do arquivo anexado para visualizao.
 * @param mUri/*www  .  j a  v  a  2s . com*/
 */
private void abrirAnexo(Uri mUri) {
    String extension = FilenameUtils.getExtension(AndroidFileUtils.getPath(AnexoCadastroActivity.this, mUri));
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        MimeTypeMap mime = MimeTypeMap.getSingleton();

        String type = mime.getMimeTypeFromExtension(extension);

        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(mUri, type);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(intent);

    } catch (ActivityNotFoundException e) {
        new ErrorAlert(AnexoCadastroActivity.this, getResources().getString(R.string.app_name),
                "No foi encontrado nenhum aplicativo nesse aparelho que suporte abrir a extenso '"
                        + extension
                        + "', entre em contato com a equipe de Suporte para resolver esse problema.").show();
    } catch (Exception e) {
        new ErrorAlert(AnexoCadastroActivity.this, getResources().getString(R.string.app_name),
                "No foi possvel abrir o anexo " + anexo.getId() + ". " + e.getMessage()).show();
        e.printStackTrace();
    }
}

From source file:com.raceyourself.android.samsung.ProviderService.java

private void launchWebBrowser(String uri) {
    Log.i(TAG, "Launching browser for URI: " + uri);
    Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(myIntent);/*from   www .j  a  v  a 2 s  . co  m*/
}

From source file:com.android.providers.downloads.DownloadInfo.java

void notifyPauseDueToSize(boolean isWifiRequired) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(getAllDownloadsUri());
    intent.setClassName(SizeLimitActivity.class.getPackage().getName(), SizeLimitActivity.class.getName());
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(EXTRA_IS_WIFI_REQUIRED, isWifiRequired);
    /// M: Modify to support CU customization
    intent.putExtra(SHOW_DIALOG_REASON, 0);
    mContext.startActivity(intent);// w w w.  jav a  2  s .  c o  m
}

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

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // this should be called once image has been chosen by user
    // using requestCode to pass item id - haven't worked out any other way
    // to do it/*from w  w  w .ja  v a  2s  . c  o  m*/
    // if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
        // TODO check if user is logged in
        if (LoginActivity.isNotLoggedIn(this)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setClassName(this, LoginActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            // avoid navigation back to this?
            LoginActivity.return_to = ItemActivity.class.getName();
            LoginActivity.params = new HashMap<String, String>();
            LoginActivity.params.put("item_id", (String) item.getId());
            startActivity(intent);
            // TODO in this case forcing the user to rechoose the image
            // seems a little
            // rude - should probably auto-submit here ...
        } else {
            // Bundle extras = data.getExtras();
            // String sentence_id = (String) extras.get("sentence_id");
            final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
            myOtherProgressDialog.setTitle("Please Wait ...");
            myOtherProgressDialog.setMessage("Uploading image ...");
            myOtherProgressDialog.setIndeterminate(true);
            myOtherProgressDialog.setCancelable(true);

            final Thread add_image = new Thread() {
                public void run() {
                    // TODO needs to check for interruptibility

                    String sentence_id = Integer.toString(requestCode);
                    Uri selectedImage = data.getData();
                    // Bitmap bitmap = Media.getBitmap(getContentResolver(),
                    // selectedImage);
                    // ByteArrayOutputStream bytes = new
                    // ByteArrayOutputStream();
                    // bitmap.compress(Bitmap.CompressFormat.JPEG, 40,
                    // bytes);
                    // ByteArrayInputStream fileInputStream = new
                    // ByteArrayInputStream(
                    // bytes.toByteArray());

                    // TODO Might have to save to file system first to get
                    // this
                    // to work,
                    // argh!
                    // could think of it as saving to cache ...

                    // add image to sentence
                    FileInputStream is = null;
                    FileOutputStream os = null;
                    File file = null;
                    ContentResolver resolver = getContentResolver();
                    try {
                        Bitmap bitmap = Media.getBitmap(getContentResolver(), selectedImage);
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
                        // ByteArrayInputStream bais = new
                        // ByteArrayInputStream(bytes.toByteArray());

                        // FileDescriptor fd =
                        // resolver.openFileDescriptor(selectedImage,
                        // "r").getFileDescriptor();
                        // is = new FileInputStream(fd);

                        String filename = "test.jpg";
                        File dir = ItemActivity.this.getDir("images", MODE_WORLD_READABLE);
                        file = new File(dir, filename);
                        os = new FileOutputStream(file);

                        // while (bais.available() > 0) {
                        // / os.write(bais.read());
                        // }
                        os.write(bytes.toByteArray());

                        os.close();

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (os != null) {
                            try {
                                os.close();
                            } catch (IOException e) {
                            }
                        }
                        if (is != null) {
                            try {
                                is.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    // File file = new
                    // File(Uri.decode(selectedImage.toString()));

                    // ensure item is in users default list

                    ItemActivity.add_item_result = new AddItemResult(Main.lookup.addItemToGoal(Main.transport,
                            Main.default_study_goal_id, item.getId(), null));

                    Result result = ItemActivity.add_item_result;

                    if (ItemActivity.add_item_result.success()
                            || ItemActivity.add_item_result.alreadyInList()) {

                        // ensure sentence is in users default goal

                        ItemActivity.add_sentence_goal_result = new AddSentenceResult(
                                Main.lookup.addSentenceToGoal(Main.transport, Main.default_study_goal_id,
                                        item.getId(), sentence_id, null));

                        result = ItemActivity.add_sentence_goal_result;
                        if (ItemActivity.add_sentence_goal_result.success()) {

                            String media_entity = "http://test.com/test.jpg";
                            String author = "tansaku";
                            String author_url = "http://smart.fm/users/tansaku";
                            Log.d("DEBUG-IMAGE-URI", selectedImage.toString());
                            ItemActivity.add_image_result = addImage(file, media_entity, author, author_url,
                                    "1", sentence_id, (String) item.getId(), Main.default_study_goal_id);
                            result = ItemActivity.add_image_result;
                        }
                    }
                    final Result display = result;
                    myOtherProgressDialog.dismiss();
                    ItemActivity.this.runOnUiThread(new Thread() {
                        public void run() {
                            final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                            dialog.setTitle(display.getTitle());
                            dialog.setMessage(display.getMessage());
                            dialog.setButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    if (ItemActivity.add_image_result != null
                                            && ItemActivity.add_image_result.success()) {
                                        ItemListActivity.loadItem(ItemActivity.this, item.getId().toString());
                                    }
                                }
                            });

                            dialog.show();
                        }
                    });

                }

            };

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

        }
    }
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

public void getTwitterSystemAccount(final String networkUserName, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;/* w  w  w  . ja va  2 s.  co m*/
            final JSONObject json = new JSONObject();
            final JSONObject account = new JSONObject();

            final Account[] twitterAccounts = accountManager
                    .getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        if (twitterAccounts[i].name.equals(networkUserName)) {
                            account.put("userName", twitterAccounts[i].name);

                            final Account twitterAccount = twitterAccounts[i];

                            accountManager.getAuthToken(twitterAccount, "com.twitter.android.oauth.token", null,
                                    false, new AccountManagerCallback<Bundle>() {
                                        @Override
                                        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                                            try {
                                                Bundle bundle = accountManagerFuture.getResult();

                                                if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                                    Intent intent = bundle
                                                            .getParcelable(AccountManager.KEY_INTENT);

                                                    //clear the new task flag just in case, since a result is expected
                                                    int flags = intent.getFlags();
                                                    flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                    intent.setFlags(flags);

                                                    requestedTwitterAccountName = networkUserName;

                                                    cordova.getActivity().startActivityForResult(intent,
                                                            TWITTER_OAUTH_REQUEST);
                                                } else {
                                                    account.put("oauth_token",
                                                            bundle.getString(AccountManager.KEY_AUTHTOKEN));

                                                    accountManager.getAuthToken(twitterAccount,
                                                            "com.twitter.android.oauth.token.secret", null,
                                                            false, new AccountManagerCallback<Bundle>() {
                                                                @Override
                                                                public void run(
                                                                        AccountManagerFuture<Bundle> accountManagerFuture) {
                                                                    try {
                                                                        Bundle bundle = accountManagerFuture
                                                                                .getResult();

                                                                        if (bundle.containsKey(
                                                                                AccountManager.KEY_INTENT)) {
                                                                            Intent intent = bundle
                                                                                    .getParcelable(
                                                                                            AccountManager.KEY_INTENT);

                                                                            //clear the new task flag just in case, since a result is expected
                                                                            int flags = intent.getFlags();
                                                                            flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                                            intent.setFlags(flags);

                                                                            requestedTwitterAccountName = networkUserName;

                                                                            cordova.getActivity()
                                                                                    .startActivityForResult(
                                                                                            intent,
                                                                                            TWITTER_OAUTH_REQUEST);
                                                                        } else {
                                                                            account.put("oauth_token_secret",
                                                                                    bundle.getString(
                                                                                            AccountManager.KEY_AUTHTOKEN));

                                                                            json.put("data", account);

                                                                            Log.v(TAG, "Account data: "
                                                                                    + json.toString());

                                                                            PluginResult pluginResult = new PluginResult(
                                                                                    PluginResult.Status.OK,
                                                                                    json);
                                                                            pluginResult.setKeepCallback(true);
                                                                            callbackContext.sendPluginResult(
                                                                                    pluginResult);
                                                                        }

                                                                    } catch (Exception e) {
                                                                        PluginResult pluginResult = new PluginResult(
                                                                                PluginResult.Status.ERROR,
                                                                                e.getLocalizedMessage());
                                                                        pluginResult.setKeepCallback(true);
                                                                        callbackContext
                                                                                .sendPluginResult(pluginResult);
                                                                    }
                                                                }
                                                            }, null);
                                                }

                                            } catch (Exception e) {
                                                PluginResult pluginResult = new PluginResult(
                                                        PluginResult.Status.ERROR, e.getLocalizedMessage());
                                                pluginResult.setKeepCallback(true);
                                                callbackContext.sendPluginResult(pluginResult);
                                            }
                                        }
                                    }, null);
                        }
                    }
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        }
    });
}

From source file:samples.piggate.com.piggateCompleteExample.buyOfferActivity.java

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

    //Set action bar fields
    getSupportActionBar().setTitle(PiggateUser.getEmail());
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    //Views/*from w ww.  j a  va 2 s .c  o  m*/
    EditCardNumber = (EditText) findViewById(R.id.cardNumber);
    EditCVC = (EditText) findViewById(R.id.CVC);
    SpinnerYear = (Spinner) findViewById(R.id.spinerYear);
    SpinnerMonth = (Spinner) findViewById(R.id.spinerMonth);
    validate = (Button) findViewById(R.id.buttonValidate);
    buttonBuy = (Button) findViewById(R.id.buttonBuy);
    buttonCancel = (Button) findViewById(R.id.buttonCancel);
    headerLayout = (LinearLayout) findViewById(R.id.headerLayout);
    cardlayout = (LinearLayout) findViewById(R.id.cardlayout);
    buylayout = (LinearLayout) findViewById(R.id.buyLayout);
    image = (SmartImageView) findViewById(R.id.offerImage2);

    //Animations
    slidetoLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidetoleft);
    slidetoRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidetoright);
    slidefromRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidefromright);
    slidefromLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slidefromleft);

    //Validation Error AlertDialog
    errorDialog = new AlertDialog.Builder(buyOfferActivity.this).create();
    errorDialog.setTitle("Validation error");
    errorDialog.setMessage("The credit card is not valid");
    errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    //Network Error AlertDialog
    networkDialog = new AlertDialog.Builder(this).create();
    networkDialog.setTitle("Network error");
    networkDialog.setMessage("Network is not working");
    networkDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    image.setImageUrl(getIntent().getExtras().getString("offerImgURL")); //Set the offer image from URL
    //(Provisional) set the default fields of the credit card
    EditCardNumber.setText("4242424242424242");
    EditCVC.setText("123");

    piggate = new Piggate(this); //Initialize Piggate Object

    //OnClick listener for the validate button
    validate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Validate the credit card with Stripe
            if (checkInternetConnection() == true) {
                // Credit card for testing: ("4242-4242-4242-4242", 12, 2016, "123")
                if (piggate.validateCard(EditCardNumber.getText().toString(),
                        Integer.parseInt(SpinnerMonth.getSelectedItem().toString()),
                        Integer.parseInt(SpinnerYear.getSelectedItem().toString()),
                        EditCVC.getText().toString(), "pk_test_BN86VnxiMBHkZtzPmpykc56g", //Stripe test. Will be returned by requests in next release
                        buyOfferActivity.this, "Validating", "Wait while the credit card is validated")) {
                    openBuyLayout();
                } else
                    errorDialog.show();
            } else {
                networkDialog.show();
            }
        }
    });

    //OnClick listener for the buy button
    buttonBuy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Do the buy request to the server
            RequestParams params = new RequestParams();
            //Get the latest credit card Stripe token, amount to pay, type of coin and ID
            params.put("stripeToken", piggate.get_creditCards().get(piggate.get_creditCards().size() - 1)
                    .getTokenID().toString());
            params.put("amount", getIntent().getExtras().getString("offerPrice"));
            params.put("offerID", getIntent().getExtras().getString("offerID"));
            params.put("currency", getIntent().getExtras().getString("offerCurrency"));

            //Loading payment ProgressDialog
            loadingDialog = ProgressDialog.show(v.getContext(), "Payment", "Wait while the payment is finished",
                    true);

            //Do the buy request to the server (The server do the payment with Stripe)
            piggate.RequestBuy(params).setListenerRequest(new Piggate.PiggateCallBack() {

                //onComplete method for JSONObject
                @Override
                public void onComplete(int statusCode, Header[] headers, String msg, JSONObject data) {
                    loadingDialog.dismiss();

                    //Go back to the offer list passing the offer attributes (to exchange)
                    Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class);
                    slideactivity.putExtra("offerID", getIntent().getExtras().getString("offerID"));
                    slideactivity.putExtra("offerName", getIntent().getExtras().getString("offerName"));
                    slideactivity.putExtra("offerDescription",
                            getIntent().getExtras().getString("offerDescription"));
                    slideactivity.putExtra("payment", true);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(),
                            R.anim.slidefromleft, R.anim.slidetoright).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }

                //onError method for JSONObject
                @Override
                public void onError(int statusCode, Header[] headers, String msg, JSONObject data) {

                    //Show an error and go back to the credit card
                    loadingDialog.dismiss();
                    //Go back to the offer list with the variable payment set to false (payment error)
                    Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class);
                    slideactivity.putExtra("payment", false);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(),
                            R.anim.slidefromleft, R.anim.slidetoright).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }

                //onComplete method for JSONArray
                @Override
                public void onComplete(int statusCode, Header[] headers, String msg, JSONArray data) {
                    loadingDialog.dismiss();

                    //Go back to the offer list passing the offer attributes (to exchange)
                    Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class);
                    slideactivity.putExtra("offerID", getIntent().getExtras().getString("offerID"));
                    slideactivity.putExtra("offerName", getIntent().getExtras().getString("offerName"));
                    slideactivity.putExtra("offerDescription",
                            getIntent().getExtras().getString("offerDescription"));
                    slideactivity.putExtra("payment", true);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(),
                            R.anim.slidefromleft, R.anim.slidetoright).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }

                //onError method for JSONArray (Show an error and go back to the credit card)
                @Override
                public void onError(int statusCode, Header[] headers, String msg, JSONArray data) {

                    //Show an error and go back to the credit card
                    loadingDialog.dismiss();
                    //Go back to the offer list with the variable payment set to false (payment error)
                    Intent slideactivity = new Intent(buyOfferActivity.this, Activity_Logged.class);
                    slideactivity.putExtra("payment", false);
                    slideactivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(),
                            R.anim.slidefromleft, R.anim.slidetoright).toBundle();
                    startActivity(slideactivity, bndlanimation);
                }
            }).exec();
        }
    });

    //OnClick listener for the cancel button (Go back to the credit card)
    buttonCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            closeBuyLayout();
        }
    });
}