I used PayPal SDK before in my regular apps. Here are the steps I take in a normal activity
a) on activity’s onCreate I make a new thread to init the PayPal library
b) if the init goes well, I create a PayPal button and add it in one of my layouts
c) on PayPal button’s onClick I start a new activity for result where the user makes the payment
d) on activity’s onActivityResult I check if payment was successfully and save the info
This worked well so far but things get messy when I try to use the same approach on a fragment. My fragment has a layout with 2 EditTexts and a LinearLayout that will host the Paypal button
So far I did it like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = (MainActivity) getActivity();
View view = inflater.inflate(R.layout.fragment_layout, container, false);
libraryInitializationThread = new Thread() {
@Override
public void run() {
initLibrary();
// The library is initialized so let's create our CheckoutButton and update the UI.
if (PayPal.getInstance().isLibraryInitialized()) {
hRefresh.sendEmptyMessage(INITIALIZE_SUCCESS);
} else {
hRefresh.sendEmptyMessage(INITIALIZE_FAILURE);
}
}
};
libraryInitializationThread.start();
}
private void initLibrary() {
PayPal pp = PayPal.getInstance();
if (pp == null) {
pp = PayPal.initWithAppID(context, getString(R.string.paypal_sandbox_id), PayPal.ENV_SANDBOX);
pp.setLanguage("en_US"); // Sets the language for the library.
pp.setDynamicAmountCalculationEnabled(false);
}
}
So far, on pp = PayPal.initWithAppID I get this error:
java.lang.IllegalStateException: Fragment FragmentPayPal{415f43f8} not attached to Activity
Now my questions are:
-
where and how should I init the paypal library ?
-
from my fragment, can I start an activity for result and catch onActivityResult ?
Thank you.
Actually the approach I used in the end was, simply, init paypal library before adding the fragment, in my main hosting activity. In this way it works just fine.