Initialize a Stripe Object in new Android Studio - java

Currently, I am working to create a Stripe payment method in an Android Studio App. This will involve a credit card object which will be stored by Stripe into my Firestore DB. Unfortunately, one of the lines in the tutorial that I have used is outdated since it uses getContext() without a view.
Background on Stripe:
https://www.youtube.com/watch?v=JeyxolsJ3aE
Background on Firestore:
https://firebase.google.com/docs/firestore
Here is the link to the tutorial that I am following:
https://stripe.com/docs/mobile/android
Unfortunately, I have not had much luck finding a tutorial that is knew, uses the same format and does not use getContext().
I have already completed all steps up to inserting the line:
final Stripe stripe = new Stripe(
getContext(),
"pk_test_TYooMQauvdEDq54NiTphI7jx"
);
In my version of Android Studio (3.4.1), it seems getContext() cannot be used without a View (shows up as red). As a result, I have tried to substitute a variety of commands. However, they all produce the same crash with message "Invalid Content Provider: null". I believe that "Content Provider" refers to the Context passed in.
I should mention that the Stripe object is created within an On-Click listener. Further, I know that the "pk_test" key is correct and I have tested other valid ids also to no avail. Further, through tests with commenting out code, I am certain that this is the line producing my error.
My theory is that the context is being rejected by Stripe or Firebase. This is because the Stripe Context is known as a "Stripe Provider" (https://lh3.googleusercontent.com/-ByYW3X0ua38/XQ_kRpmddLI/AAAAAAAAAAI/YfhjxSJ9iO0aJwZ8RtANeCXKXyYglWX1QCK8BGAs/s0/2019-06-23.png)
Some of the commands that I have tried are:
getContext() (not recognized)
getApplicationContext()
getBaseContext()
this
this.getApplicationContext()
ClassName.this.getApplicationContext()
ClassName.this.getBaseContext()
Submit.getContext()
WrappingLayoutView.getContext()
I have also tried to capture the Context in OnCreate above the OnClick listener in a variable.
Since none of these are working, I am rather stuck as to what to do.
Here is my Java Code:
public class AddCardActivity extends AppCompatActivity {
private Button submit;
public Context mContext;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_card);
init();
mContext = this.getApplicationContext();
//Not working
/**View mV=findViewById(R.id.myLView);
mContext=mV.getContext();**/
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Use stripe to add new payment to firestore
//This line causes a crash
Stripe stripe = new Stripe(submit.getContext(),
"pk_test_t6NMvJpXDEZd3eOn5SU4y6DA"
);
// The Card class will normalize the card number
final Card card = Card.create("4242-4242-4242-4242", 12, 2020, "123");
//Update this with more useful error messages
if (card == null) {
Toast.makeText(getApplicationContext(), "Invalid Card!", Toast.LENGTH_LONG).show();
}
card.validateNumber();
card.validateCVC();
stripe.createToken(
card,
new TokenCallback() {
public void onSuccess(#NonNull Token token) {
// Send token to your server
}
public void onError(#NonNull Exception error) {
// Show localized error message
Toast.makeText(getApplicationContext(), "Invalid Card!", Toast.LENGTH_LONG).show();
}
}
);
}
});
}
private void init() {
submit = (Button) findViewById(R.id.addCardActivityButton);
}

Here you go:
Token token = null;
final Card card = new Card(cardNumber, month, year, cvc);
final Stripe stripe = new Stripe(getApplicationContext());
try {
token = stripe.createTokenSynchronous(card, "pk_test_TYooMQauvdEDq54NiTphI7jx");
} catch (StripeException stripeEx) {
errorMessage = stripeEx.getLocalizedMessage();
}

Related

How can I find context and start a new Activity from Android firebase ML-Kit BarcodeScannerProcessor onSuccess

I am using the quickstart-android code provided by google but after many attempts I cam unable to find a context that is not returning null. The BarcodeScannerProcessor is not itself an Activity, so I have attempted to create an instance of the LivePreviewActivity and use that as the context in the intent, but it's null.
The goal is to once a valid barcode is recognized I want to open a new activity that allows a user to verify value and on the push of a button call a webservice to post the barcode to a database via API. I am having a hard time finding a valid context and the app is crashing when it trys to execute the Intent.
Starting at line 97-107:
https://github.com/jamiekeefer/quickstart-android/blob/master/mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/java/barcodescanning/BarcodeScanningProcessor.java
for (int i = 0; i < barcodes.size(); ++i) {
FirebaseVisionBarcode barcode = barcodes.get(i);
BarcodeGraphic barcodeGraphic = new BarcodeGraphic(graphicOverlay, barcode);
graphicOverlay.add(barcodeGraphic);
System.out.println(barcode.getRawValue());
if (!barcode.getRawValue().equals("") ) {
System.out.println("Got the number:" + barcode.getRawValue() + " Context: " + mContext); //OLD SCHOOL DEBUG OUTPUT
//enter code to start activity
Intent intent = new Intent(mContext, SendScannedBarcode.class);
String message = scannedBarcode;
intent.putExtra(EXTRA_MESSAGE, message);
mContext.startActivity(intent);
}
}
You can back up in the repo to see the instance of the LivePreviewActivity where I trying to get context.
I have tried a number of things and read about Context, Views and Activities and basically have completely confused myself. The only tuts I can find are using Kotlin, which is not helping clarify things.
I appreacite any help in indentifying or contruting a valid Intent from this Context. Thank you.
So I am assuming that in your LivePreviewActivity you are creating an object of the class BarcodeScanningProcessor. What you can do is change the constructor in the BarcodeScanningProcessor class to accept a context and then you pass in your LivePreviewActivity's context.
This is what the code should look like:
In BarcodeScanningProcessor:
public BarcodeScanningProcessor(Context context) {
// Note that if you know which format of barcode your app is dealing with, detection will be
// faster to specify the supported barcode formats one by one, e.g.
// new FirebaseVisionBarcodeDetectorOptions.Builder()
// .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
// .build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector();
this.mContext = context;
}
Then in LivePreviewActivity:
In the particular case of your activity you would do:
case BARCODE_DETECTION:
Log.i(TAG, "Using Barcode Detector Processor");
cameraSource.setMachineLearningFrameProcessor(new BarcodeScanningProcessor(getApplicationContext()));
break;
Or if you just wanted to create an object of the class you could do:
BarcodeScanningProcessor bsp = new BarcodeScanningProcessor(getApplicationContext());
This should now give your BarcodeScanningProcessor class the context of your activity. Now, in BarcodeScanningProcessor, mContext should not be null and will have the context of your activity. I hope this answers your question.
try this create Application class
import android.app.Application;
public class MyApplication extends Application {
static MyApplication instance;
#Override
public void onCreate() {
super.onCreate();
instance=this;
}
public static MyApplication getInstance() {
return instance;
}
}
Register in manifest file
<application
..
android:name="com.yourpackage.MyApplication"
..>
.
.
.
</application>
start activity using this MyApplication.
Intent intent = new Intent(MyApplication.getInstance(), SendScannedBarcode.class);
String message = scannedBarcode;
intent.putExtra(EXTRA_MESSAGE, message);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyApplication. getInstance().startActivity(intent);
Another way of handling the issue is create new constructor of BarcodeScanningProcessor which takes interface call back and once processing is done pass back result to caller.
public interface BarcodeUpdateListener {
#UiThread
void onBarcodeDetected(Barcode barcode);
}
private BarcodeUpdateListener callback;
public BarcodeScanningProcessor(BarcodeUpdateListener callback){
this.callback = callback;
detector = FirebaseVision.getInstance().getVisionBarcodeDetector();
}
Once you get the result pass result to caller
callback.onBarcodeDetected(<Barcode>)
You can get the context from graphicOverlay:
Context context = graphicOverlay.getContext();

How to get icc authentication?

I found some interesting methods in telephonyManager class like turning mobile data off/on but when trying to use them it obviously throws me security exception.("No carrier privilege"). I Googled it, but didn't find any helpful solution.
Because it's carrier privilege I thought it may be possible to get its permission by telephonyManager.getIccAuthentication(int appType, int authType, String data) but I'm having problems with input parameters because I can't figure out what should I pass in to make it work.
From documentation to the first parameter would pass TelephonyManager.APPTYPE_SIM or/and TelephonyManager.APPTYPE_USIM depending on if it has big meaning in using setDataEnabled(boolean).
If I would pass TelephonyManager.APPTYPE_SIM as a first argument I think I should passed TelephonyManager.AUTHTYPE_EAP_SIM as a second argument (correct me if I'm wrong) and vice versa, when TelephonyManager.APPTYPE_USIM as first so TelephonyManager.AUTHTYPE_EAP_AKA as second one.
And then there is the third argument. There must be encoded Base64 to string. I found in TelephonyProvider this line of code:
String base64Challenge = Base64.encodeToString(byteParam, Base64.NO_WRAP); where byteParam is an input byte from another method which is being preceding by thousands other methods. If I pass "" as third parameter to getIccAuthentication method I get again securityException (it's obviously, wrong param) but it throws me lack of getIccSimChallengeResponse. I'm afraid of it may be infinite loop of methods, but maybe someone has any idea or help me to break this through?
My sample code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonPanel);
button.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
try {
Process p = Runtime.getRuntime().exec("su");
tel();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void tel(){
// String base64Challenge = Base64.encodeToString(,
Base64.NO_WRAP);
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
boolean isCarrier = telephonyManager.hasCarrierPrivileges();
String authentication =
telephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
TelephonyManager.AUTHTYPE_EAP_SIM, "");
Log.v(TAG, authentication);
if (isCarrier) {
Log.v(TAG, "privs granted");
telephonyManager.setDataEnabled(false);
} else {
Log.v(TAG, "no privilegies");
}
}
}
From the docs:
Requires Permission: READ_PRIVILEGED_PHONE_STATE or that the calling
app has carrier privileges (see hasCarrierPrivileges()).
The first of those requires you to be installed as a privileged system app (requires root or owning system certificate). The second requires your UID to be the carrier's. Without that no combo of parameters will work.

Trying to add google maps to a Vaadin view

I'm trying to use the Vaadin GoogleMaps plugin on our web application to show a small window with Google maps. I have this:
private GoogleMap googleMap;
private LatLon mapMarkerlatLon;
private GoogleMapMarker googleMapMarker;
private final String apiKey = "https://maps.googleapis.com/maps/api/js?key=<ourKey>=initMap";
#Override
public void enter(ViewChangeEvent event) {
//googleMap = new GoogleMap(apiKey, null, null);
//As suggested:
googleMap = new GoogleMap(apiKey, null, "english");
mapMarkerlatLon = new LatLon(0,0);
googleMap.setCenter(mapMarkerlatLon);
googleMapMarker = new GoogleMapMarker("Tal", mapMarkerlatLon, false);
googleMap.addMarker(googleMapMarker);
initializeViewContent();
}
A bit further down my class..
protected CssLayout initializeViewContent() {
CssLayout sideBarLayout = new CssLayout();
sideBarLayout.addStyleName("sidebar");
/* ... */
sideBarLayout.addComponent(googleMap);
return sideBarLayout;
}
There's more stuff around the class,but basically this is the "important" bit. When I load the page, I got this:
More or less, translated to english, it says "An error occured. This webpage did not load Google Maps correctly. Discover the technical details on the Javascript console."
EDITED: Firfeox Console is as empyt as my knowledge of this topic.
Chrome's console is telling me about a missing keyMapError.
I've tried changin the key format to:
{ourKey}
{ourKey}=initMap
key={ourKey}=initMap
And, well, I'm getting tired of playing with combinatory. The key works, as it was given to me with a small demo that works flawlessly.
What I'm doing wrong?

1 of the 3 callback weakreferences goes to null in the asynctask (Android)

Intro to me and my application school project
Hi,
iam pretty new with android and for some school project iam building an application where users can configure regions to recieve alerts from. The app need also make it posible to recieve alerts around the current location of the app user.
The app gets its info from a xml feed and sorts the data by the configured regions. The workflow is 1. to get the alerts which are in the configured regions. 2. When gps alerts are enabled the app need to get the location and when it is known it needs to do the first step again but this time the gps region is included. (i need to optimize this proces LATER)
(questions bellow)
intro to my app and problem
I'm using a asynctask in my application to download some xml feed. When the asynctask is ready i need to call 3 places for do something with the result.
1 class saves the result in the local database (alertmanager)
2 fragments (in a tabview) needs to show the results (1 in a map an one in a listview)
Now i use weakreferences for giving the call back "references" to the asynctask. in the onPostExecute() i use theWeakReference.get().updateMethod(result); for updating the class/fragments.
The alertmanager (the class who needs to recieve the updates) also calls a gps manager in the same method where it calls the asynctask to get the gps location. When i comment out (in my case with a if) the line what calls the gps manager the weak reference of the alertmanager will go to null in the asynctask between the constructor (all references are filled) and the doInBackground (the alertmanager reference is null, the other 2 still filled) which results in a crashing app.
When i dont comment out the if the app works fine.....
Alertmanager information
This is the method in the alertmanager who calls the async task. The references are filled on this place.
public void GetAlerts(List<WeakReference<e_Alerts>> callbackReferences, Context context) {
//Update the alerts in the listview and mapview with the local alerts.
List<Alert> localAlerts = internalDc.GetAllAlerts();
try {
for (WeakReference<e_Alerts> callback : callbackReferences) {
callback.get().UpdateAlerts(localAlerts);
}
} catch (Exception e) {
Log.e("AlertManager", e.getMessage());
}
//If connected to the internet then update the local db and the views
if (isConnectingToInternet(context)) {
WeakReference<e_Alerts> wr = new WeakReference<e_Alerts>(this);
callbackReferences.add(wr);
// Update the alerts where no location is needed for so the user has a quick result
externalDc.getAlerts(callbackReferences, areaManager.GetActiveAreas(false));
// If gps region is enabled then find the phones location and update the alerts
if (areaManager.GetGpsArea().IsActive()) {
new GpsManager(this.context, this, callbackReferences);
}
}
}
The GpsManager extends the LocationListener:
public class GpsManager extends Service implements LocationListener {
The listener is implemented by the Alertmanager
// This method is caled by the GPS Manager when the GPS location is changed
#Override
public void OnLocationChanged(Location location, List<WeakReference<e_Alerts>> references) {Area gpsArea = areaManager.GetGpsArea();
gpsArea.SetLocation(location);
areaManager.SaveArea(gpsArea);
externalDc.getAlerts(references, areaManager.GetActiveAreas(true));
}
Asynctask information
This are the asynctask methods:
Asynctask constructor:
Here the list callbackReferences contains 3 weakrefrences and all of them are filled (2x fragment reference 1x alertmanager reference)
public At_allAlerts(List<WeakReference<e_Alerts>> callbackReferences, List<Area> areas) {
this.mCallbackReferences = callbackReferences;
this.mAreas = areas;
}
doInBackground code:
The XmlDownloader: Downloads an xml feed an parses the xml to objects with a library
The AlertConverter: converts the xml object to the object i use in my app
Both classes can work without the asynctask class and don't use the references.
#Override
protected String doInBackground(String... inputUrl) {
Log.i("At_allAlerts", "Asynctask for downloading and parsing mAlerts is started");
try {
//Downloads the alert XMLs from the internet and parses it to xmlAlerts
this.mAlerts = new XmlDownloader().DownloadAlerts(inputUrl);
// Filters the mXml mAlerts so only the mAlerts where the enduser is interessed in will remain
this.mAlerts = filterAlerts(this.mAlerts);
// Converts the remaining xmlAlerts to Alerts;
this.mResult = new AlertConverter().Convert(this.mAlerts);
}catch (Exception e) {
Log.e("At_allAlerts",e.getMessage());
}
return null;
}
The onPostExecute method:
When the programm comes in this method the this.references.get(2) reference (alertmanager reference) = null, the other 2 references are still filed
#Override
protected void onPostExecute(String xml){
for (WeakReference<e_Alerts> reference : activityWeakReferences)
{
reference.get().UpdateAlerts(this.result);
}
}
filterAlerts Method:
private List<Item> filterAlerts(List<Item> alerts) {
List<Item> filteredXmlAlerts = new ArrayList<>();
for (Item alert : alerts)
{
Location alertLocation = new Location("");
alertLocation.setLatitude(alert.getGeometries().get(0).getLocations().get(0).getLat());
alertLocation.setLongitude(alert.getGeometries().get(0).getLocations().get(0).getLng());
for(Area area : this.mAreas)
{
if (area.IsOrganization() && alert.getCountryCode().toLowerCase().equals(area.getOrganizationcode().toLowerCase())){
filteredXmlAlerts.add(alert);
break;
}
else if(!area.IsOrganization() && isAlertInRegion(alertLocation, area)) {
filteredXmlAlerts.add(alert);
break;
}
}
}
return filteredXmlAlerts;
}
My Question(s)
I think Weakreference are the right way for giving references to asynctask is this correct or do i need to give it as an other object? (class or object or whatever?).
Why goes my reference to null? and only one of the 3? and only when i dont use the gps location class? and how to solve this?
I read something about the garbage collector what can be the cause of this problem, is this true and when yes how can i solve this?
It would be fine when the answere are simple to understand since android is pretty new for me.

how to retrieve info from datastore using google app engine and display it in a list view on an android app using java?

I am trying to make an android app that retrieves info from google app engine datastore and display it as a listview in the android app..can anyone help me out with some code or explain what exactly needs to be done for this purpose? i have already made modifications on the server side to store data on the datastore..what i dont know is how to get that data onto the android app..i am using eclipse indigo and language is java
EDIT : I am putting my code that i am using to retrieve a set of strings from datastore and put it in a list view...the code is gonna look all haywire but i request you to bear with me and explain how exactly to write it..presently the application is force-closing whenever i get to the page where this list of retrieved strings is supposed to be displayed...
public class Display extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] title;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaylayout);
MyRequestFactory factory = (MyRequestFactory)Util.getRequestFactory(Display.this,MyRequestFactory.class);
FebfourthRequest febfourthRequest = factory.febfourthRequest();
final List<TrialDBProxy> list= new ArrayList<TrialDBProxy>();
febfourthRequest.queryTrialDBs().fire(new Receiver<List<TrialDBProxy>>()
{
#Override
public void onSuccess(List<TrialDBProxy> arg0) {
// TODO Auto-generated method stub
list.addAll(arg0);
}
});
for(int i=0;i<list.size();i++)
{
title[i] = list.get(i).getMessage();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++)
{
rd = new RowData(i,title[i]);
data.add(rd);
}
int[] to = new int[] { R.id.text1, R.id.text2 };
#SuppressWarnings("deprecation")
Cursor mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.displaylayout,mCursor,title,to);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
private class RowData
{
protected int mId;
protected String mTitle;
RowData(int id,String title)
{
mId=id;
mTitle = title;
}
#Override
public String toString()
{
return mId+" "+mTitle;
}
} '
NOTE : TrialDB is the file that contains all my fields that i want to store on the datastore.
displaylayout is the xml file where i have created a listview.
i am guessing the main part where i have to put code for displaying stuff is in the onCreate() method.
PLEASE HELP !
This is already a very good starting point for learning both Google App Engine and Android Development.
I may write the steps to follow:
Write a Google App Engine application which reads data from datastore and gives as JSON. You can use GAE web framework, or maybe Django. After doing that, you will have a url which gives you your data in your browser.
Write a hello world application for Android. This step gives you an opportunity to understand and setup Android development environment.
Write an Android app which uses a listview with static data.
Extend your Android app with calling a single simple url from web, then print it on your screen.
Extend your application via calling your Google App Engine application url inside your app. Now you have your datastore data in your app.
Populate your listview with your data.

Categories