I use paypal integration using android paypal sdk, and i use this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
I got error like this request failed with server response:
{"name":"TRANSACTION_REFUSED","message":"The request was refused.{0}","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#TRANSACTION_REFUSED","debug_id":"f1123aecd0ece"}
05-15 13:36:53.530: E/PayPalService(9581): TRANSACTION_REFUSED
anyone help me
public class PaymentConfermationFragment extends Fragment {
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_SANDBOX;
private static final String CONFIG_CLIENT_ID = "ASdSlRC8iBoCu6ehg59npQXZfhfhfhfhfhl6xQVx0IcYKCCUrZNfcdTBI0zdYCroY1ONz";
private static final String CONFIG_RECEIVER_EMAIL = "xyz#gmail.com";
private FragmentManager mFragmentManager;
private TextView frind_name, amount;
private ImageView frind_img;
private GiftekFriend giftekFriend;
private ArrayList<GiftekProduct> productList;
private View mLoadingCover;
private View mPaymentOK;
long price = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_payment_confirmation, container, false);
frind_img = (ImageView) rootView.findViewById(R.id.friend_img);
frind_name = (TextView) rootView.findViewById(R.id.friend_name);
mLoadingCover = rootView.findViewById(R.id.loading_cover);
mPaymentOK = rootView.findViewById(R.id.payment_ok);
amount = (TextView) rootView.findViewById(R.id.amount);
((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Payment");
giftekFriend = AppData.getInstance().getGiftekFriend();
if (giftekFriend != null) {
String name = giftekFriend.first_name + " " + giftekFriend.last_name;
frind_name.setText(name);
}
productList = AppData.getInstance().getProductList();
Intent intent = new Intent(this.getActivity(), PayPalService.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
getActivity().startService(intent);
rootView.findViewById(R.id.payment_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
paymentStart();
}
});
new Imageloder().execute();
mFragmentManager = getActivity().getSupportFragmentManager();
return rootView;
}
protected void paymentStart() {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(Integer.parseInt(amount.getText().toString())), "USD", "Giftek Gifts");
Intent intent = new Intent(this.getActivity(), PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
onPaymentSuccess();
if (confirm != null) {
try {
System.out.print(confirm.toJSONObject().toString(4));
Log.i("paymentExample", confirm.toJSONObject().toString(3));
Log.i("paymentExample", confirm.toJSONObject().toString(2));
Log.i("paymentExample", confirm.toJSONObject().toString(1));
Log.i("paymentExample", confirm.toJSONObject().toString(0));
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
onPaymentCancel();
Log.i("paymentExample", "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
onPaymentInvalid();
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}
private void onPaymentInvalid() {
Bundle args = new Bundle();
args.putString("result", "Payment Invalid");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
private void onPaymentCancel() {
Bundle args = new Bundle();
args.putString("result", "Payment Cancel");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
private void onPaymentSuccess() {
Bundle args = new Bundle();
args.putString("result", "Order has been completed successfully.");
mFragmentManager.popBackStack("giftek-process-select-friend", 0);
mFragmentManager.beginTransaction()
.replace(R.id.container, ResultFragment.instantiate(getActivity(), ResultFragment.class.getName(), args))
.addToBackStack("result").commit();
}
#Override
public void onDestroy() {
getActivity().stopService(new Intent(getActivity(), PayPalService.class));
super.onDestroy();
}
Related
I have implemented Barcode Scanner functionality in my application using ZBarScannerView.
I have an activity which contains multiple fragments and on one fragment I have a scan button. By clicking on that button I jump to scan activity where I have implemented the ZBarScannerView code.
When I got the barcode from scan activity I jumped it back to that fragment which contains the barcode click button. And then if I press back from that fragment it shows blank screen. What should I do?
Please Reply
Code for ScanActivity:
public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private static final int REQUEST_CAMERA = 1;
ArrayList<ModelProductDetail> modelProductArticleCodeList;
DatabaseHelper databaseHelper;
String article_code;
ArrayList<ModelUnrecognisedCode> modelUnrecognisedCodeArrayList;
ArrayList<ModelUnrecognisedCode> singleUnrecognisedCheck;
//camera permission is needed.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
databaseHelper = new DatabaseHelper(this);
checkUserPermission();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkUserPermission() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
return;
}
}
loadImage();
}
private void loadImage() {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
}
#Override
public void onResume() {
super.onResume();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.startCamera();
mScannerView.setResultHandler(this);
// Stop camera on pause
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.stopCamera(); // Stop camera on pause
}
}
#Override
public void handleResult(me.dm7.barcodescanner.zbar.Result result) {
String resultCode = result.getContents();
Log.e("TAG", "handleResult: " + resultCode);
mScannerView.stopCamera();
modelProductArticleCodeList = new ArrayList<>();
modelProductArticleCodeList = databaseHelper.getProductByArtCode(resultCode);
if (modelProductArticleCodeList.size() == 0) {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(getApplicationContext().VIBRATOR_SERVICE);
vibrator.vibrate(1000);
singleUnrecognisedCheck = new ArrayList<>();
singleUnrecognisedCheck = databaseHelper.getUnrecognisedByCode(resultCode);
if (singleUnrecognisedCheck.size() == 0) {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("unrecognised_alert", true);
in.putExtra("unrecognised_code", resultCode);
in.putExtra("jump", "1");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "not matched code", Toast.LENGTH_SHORT).show();
} else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("jump", "3");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "Unrecognised code has already been added.", Toast.LENGTH_SHORT).show();
}
} else {
// for (ModelProductDetail modelProductDetail : modelProductArticleCodeList) {
// article_code = modelProductDetail.getArticle_code();
// }
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
public void changeFragments(Fragment fragment) {
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void getDialog() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_unrecognised_code);
d.setCanceledOnTouchOutside(true);
d.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
final EditText etCode = (EditText) d.findViewById(R.id.etCode);
final EditText etrecognisedComment = (EditText) d.findViewById(R.id.etrecognisedComment);
ImageView imgClose = (ImageView) d.findViewById(R.id.imgClose);
ImageButton ibSubmit = (ImageButton) d.findViewById(R.id.ibSubmit);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ModelUnrecognisedCode modelUnrecognisedCode = new ModelUnrecognisedCode();
modelUnrecognisedCode.setUnrecognised_code(etCode.getText().toString());
modelUnrecognisedCode.setUnrecognised_comment(etrecognisedComment.getText().toString());
databaseHelper.addUnrecognisedCode(modelUnrecognisedCode);
// changeFragments(new SearchProductFragment());
modelUnrecognisedCodeArrayList = new ArrayList<>();
modelUnrecognisedCodeArrayList = databaseHelper.getUnrecognisedCode();
Log.e("TAG", "unrecognised code: " + modelUnrecognisedCodeArrayList.size());
d.dismiss();
}
});
d.show();
}
}
I'm assuming After successful barcode scanning you're fetching product data and if data found then you are changing the screen . So change your else statement with this and see if it works
else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
startActivity(in);
finish();
}
I have an app where users can subscribe to membership by paying with their Paypal account. How can I get back a confirmation stating if the user has paid for the subscription or not? Please help me with some code or edit my code. How can i know if a user has already subscribed to membership or has not subscribed? Here is my code.
public class MainActivity extends Activity {
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID = "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
//Intent intent = new Intent(this, PayPalService.class);
//intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
//startService(intent);
findViewById(R.id.order).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
thingToBuy = new PayPalPayment(new BigDecimal("1"), "USD",
"HeadSet", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(MainActivity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(MainActivity.this,
PayPalFuturePaymentActivity.class);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println("Responseeee" + confirm);
Log.i("paymentExample", confirm.toJSONObject().toString());
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed"+confirm.toString(),
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.e("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.e("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
this is my first question on stackoverflow.hope i can find my solutuon .i am integrating paypal in android.my device is showing "payment of this marchent are not allowed(invalid client id).here is my code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID ="my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Rajeev Lochan Sharma")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afcl);
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startService(intent);
ButterKnife.inject(this);
_request3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signup();
new Test().execute(_names.getText().toString(), _placeofbirth.getText().toString(), _timeofbirth.getText().toString()
);
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"quote", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(AfcRequest1Activity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
private class Test extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
//here you can some progress dialog or some view
}
#Override
protected String doInBackground(String... Params) {
String res = "";
try {
byte[] result = null;
String str = "";
HttpClient client;
HttpPost post;
ArrayList<NameValuePair> nameValuePair;
HashMap<String, String> mData;
Iterator<String> it;
HttpResponse response;
StatusLine statusLine;
//here is url api call url
post = new HttpPost("http://astro360horoscope.com/backend/api/form_amc_afc.php");
nameValuePair = new ArrayList<NameValuePair>();
mData = new HashMap<String, String>();
mData.put("username", Params[0]);
mData.put("placeofbirth", Params[1]);
mData.put("timeofbirth", Params[2]);
//for now nothing is there
it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
client = new DefaultHttpClient();
response = client.execute(post);
statusLine = response.getStatusLine();
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "utf-8");
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
//here we get the response if all is correct
res = str;
} else {
res = str;
return res;
}
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(AfcRequest1Activity.this,
PayPalFuturePaymentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
I keep getting a NulPpointerException, when I use the Intent's putExtras() method like shown below. It is in the onClick method where I create an intent and call the register activity class. I use android"s account authentication mechanism. Whenever the signUpTxt Textview is clicked, the app crushes and the error log trace below shows. What am I missing?
Here is my source code
public class LoginActivity extends AccountAuthenticatorActivity {
//.......................................
//..........................................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
actionBar = getSupportActionBar();
actionBar.hide();
mAccountManager = AccountManager.get(getBaseContext());
String accountName = getIntent().getStringExtra(ARG_ACCOUNT_NAME);
mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
if (mAuthTokenType == null)
mAuthTokenType = AccountInfo.AUTHTOKEN_TYPE_FULL_ACCESS;
if (accountName != null) {
accountname = ((EditText) findViewById(R.id.txtAccountPhone));
accountname.setText(accountName);
}
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
signUpTxt = (TextView) findViewById(R.id.txtSignUp);
signUpTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Since there can only be one AuthenticatorActivity, we call the sign up activity, get his results,
// and return them in setAccountAuthenticatorResult(). See finishLogin().
Intent signup = new Intent(getBaseContext(), RegisterActivity.class);
signup.putExtras(getIntent().getExtras());
startActivityForResult(signup, REQ_SIGNUP);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// The sign up activity returned that the user has successfully created an account
if (requestCode == REQ_SIGNUP && resultCode == RESULT_OK) {
finishLogin(data);
} else
super.onActivityResult(requestCode, resultCode, data);
}
public void login() {
final String userName = ((TextView) findViewById(R.id.txtAccountPhone)).getText().toString();
final String userPass = ((TextView) findViewById(R.id.txtAccountPassword)).getText().toString();
final String accountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
new AsyncTask<String, Void, Intent>() {
#Override
protected Intent doInBackground(String... params) {
Log.d("Slime", TAG + "> Started authenticating");
String authtoken = null;
Bundle data = new Bundle();
try {
authtoken = AccountInfo.sServerAuthenticate.userSignIn(userName, userPass, mAuthTokenType);
data.putString(AccountManager.KEY_ACCOUNT_NAME, userName);
data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
data.putString(PARAM_USER_PASS, userPass);
} catch (Exception e) {
data.putString(KEY_ERROR_MESSAGE, e.getMessage());
}
final Intent res = new Intent();
res.putExtras(data);
return res;
}
#Override
protected void onPostExecute(Intent intent) {
if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
} else {
finishLogin(intent);
}
}
}.execute();
}
private void finishLogin(Intent intent) {
Log.d("Slime", TAG + "> finishLogin");
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
Log.d("Slime", TAG + "> finishLogin > addAccountExplicitly");
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, accountPassword, null);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
} else {
Log.d("Slime", TAG + "> finishLogin > setPassword");
mAccountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
}
This is the error Logs from the logcat
06-30 14:53:46.109: E/AndroidRuntime(6015): FATAL EXCEPTION: main
06-30 14:53:46.109: E/AndroidRuntime(6015): java.lang.NullPointerException
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.os.Bundle.putAll(Bundle.java:281)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.content.Intent.putExtras(Intent.java:4828)
06-30 14:53:46.109: E/AndroidRuntime(6015): at com.rowland.slumber.LoginActivity$2.onClick(LoginActivity.java:86)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.view.View.performClick(View.java:2485)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.view.View$PerformClick.run(View.java:9080)
06-30 14:53:46.109: E/AndroidRuntime(6015): at android.os.Handler.handleCallback(Handler.java:587)
Edit, this is line 86
public void onClick(View v) {
// Since there can only be one AuthenticatorActivity, we call the sign up activity, get his results,
// and return them in setAccountAuthenticatorResult(). See finishLogin().
Intent signup = new Intent(getBaseContext(), RegisterActivity.class);
signup.putExtras(getIntent().getExtras()); //LINE 86
startActivityForResult(signup, REQ_SIGNUP);
}
});
}
Iam passing the extras from Authenticator.java which extends AbstractAccountAuthenticator, in the addAccount() method
#Override
public Bundle addAccount(AccountAuthenticatorResponse response,
String accountType, String authTokenType,
String[] requiredFeatures, Bundle options)
throws NetworkErrorException {
Bundle result;
if (hasAccount(mContext)) {
result = new Bundle();
Intent i = new Intent(mContext, LoginActivity.class);
i.putExtra(LoginActivity.ARG_ACCOUNT_TYPE, accountType);
i.putExtra(LoginActivity.ARG_AUTH_TYPE, authTokenType);
i.putExtra(LoginActivity.ARG_IS_ADDING_NEW_ACCOUNT, true);
i.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,response);
result.putParcelable(AccountManager.KEY_INTENT, i);
return result;
}
Based on the API:
Intent.getExtras() returns:
the map of all extras previously added with putExtra(), or null if none have been added
My guess would be that you are not passing in any extras and therefore passing null to the Intent.putExtras() method... Or if you think you are you may be doing so incorrectly.
From
getIntent().getStringExtra(ARG_ACCOUNT_NAME);
I can say thay you have used putStringExtra method, instead of putExtras.
Therefore, when you try getIntent().getExtras it is null.
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "live api";
// when testing in sandbox, this is likely the -facilitator email address.
private static final String CONFIG_RECEIVER_EMAIL = "abc#yahoo.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
startService(intent);
onBuyPressed(null);
}
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = getThingToBuy();
String bookId = getIntent().getStringExtra("BookId");
Intent intent = new Intent(this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
// It's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, bookId);
intent.putExtra(PaymentActivity.EXTRA_SKIP_CREDIT_CARD, false);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
private PayPalPayment getThingToBuy() {
String Price = getIntent().getStringExtra("Price");
String BookName = getIntent().getStringExtra("BookName");
String Currency = getIntent().getStringExtra("CurrencyCode");
return new PayPalPayment(new BigDecimal(Price), Currency, BookName);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}
}
When I want to make payment in PayPal from android, one dialog comes with payment failure and UNAUTHORIZED_PAYMENT. How can I resolve this issue ? I used PayPal Android SDK.