How to calculate age in Android Application using edit text - android

I am working on an android application that shows bar specials in the area and I want to make sure the only users that are using our app are 21+ years old. I have created a login/registration activity using edit texts and the information typed into the edit texts is sent to a mySQL database.
I have already searched for tutorials on youtube/stack overflow/google for help on this and I have only found datepicker tutorials. I am not sure how I would implement a datepicker tutorial into my project using edit texts.
Here is part of my RegisterActivity.java file that I want to validate the data when the user clicks on register. I have already figured out how to validate email/password but do not know how to add date difference into my code. I have also added my submitForm function that is called....
I am not sure what the output is supposed to look like or how to implement age validation into my project as a I am still fairly new to using Android Studio and I am open to new ideas etc. on how to best implement this into my project.
Here is part of my RegisterActivity.java file that I want to validate the data when the user clicks on register. I have already figured out how to validate email/password but do not know how to add date difference into my code. I have also added my submitForm function that is called....
buttonSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = signupInputEmail.getText().toString();
String password = signupInputPassword.getText().toString();
if (password.length()< 8){
signupInputPassword.setError("Your password must be at least 8 characters");
}else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
signupInputEmail.setError("You must enter a valid email address");
} else {
submitForm();
}
}
});
submitForm()
private void submitForm() {
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
String gender;
if(selectedId == R.id.female_radio_btn)
gender = "Female";
else
gender = "Male";
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
gender,
signup_input_DOB.getText().toString());
}

Looks like you are following a long way to do this task. You can simply use DatePicker (Android Date Picker Official Docs
and set the selection range for the date, set the selected date (by the user) on the TextView. User Interface for handling the click event.
Create Interface.
public interface IOnItemClickListenerCountryStates {
void onAgeClick(String Date);
}

Convert the date of birth on the sign up input from String to Date like this:
String DOB = signup_input_DOB.getText().toString();
Date dateOfBirth=new SimpleDateFormat("dd/MM/yyyy").parse(DOB);
Then pass the date of birth to a method computing for the age:
int age = currentDate.getYear() - dateOfBirth.getYear();

Related

checkedRadioButtonID integer to string in output Kotlin

I have a basic survey app that emails results upon hitting the submit button at the end. In the string that is built it calls the result of the checked radio button to put into the email, but it's showing as an integer instead of the button text.
Currently:
val id = group1.checkedRadioButtonId
returns 213120809 or 2131230810 depending on which response is checked
I've tried to add getString() to it so like so:
val id = group1.checkedRadioButtonId.getString()
but that doesn't seem to do anything. Does anyone know if there's another command I should be using? This is in Kotlin.
There is no property to get selected button text.
You can get it like this
val radioButtonText = when (group1.checkedRadioButtonId) {
R.id.radioButton1 -> radioButton1.text
else -> radioButton2.text
}

Android - Automatically fill text fields of another app

I am implementing an Android app that is responsible for some data exchange with other services such as credentials. I then want to use that information to automatically fill in the input fields of other applications on the device such as Spotify.
Is there any way to fill the input fields of another app, like the username and password to remove the chore for the user to manually input it?
Also I noticed that at least on iOS, Spotify recognizes 1Password to be installed and displays a small icon next to the input fields with which I can fill the fields from the data stored in 1Password - how is this done as it seems to be another solution to my problem?
Thanks in advance
You might want to implement Autofill Service https://developer.android.com/guide/topics/text/autofill-services.html
There is a ready to use sample app which will get you started https://github.com/googlesamples/android-AutofillFramework
Android will invoke onFillRequest() method giving your service a chance to show autofill suggestions. Here is a sample code from above link:
#Override
public void onFillRequest(FillRequest request, CancellationSignal cancellationSignal, FillCallback callback) {
// Get the structure from the request
List<FillContext> context = request.getFillContexts();
AssistStructure structure = context.get(context.size() - 1).getStructure();
// Traverse the structure looking for nodes to fill out.
ParsedStructure parsedStructure = parseStructure(structure);
// Fetch user data that matches the fields.
UserData userData = fetchUserData(parsedStructure);
// Build the presentation of the datasets
RemoteViews usernamePresentation = new RemoteViews(getPackageName(), android.R.layout.simple_list_item_1);
usernamePresentation.setTextViewText(android.R.id.text1, "my_username");
RemoteViews passwordPresentation = new RemoteViews(getPackageName(), android.R.layout.simple_list_item_1);
passwordPresentation.setTextViewText(android.R.id.text1, "Password for my_username");
// Add a dataset to the response
FillResponse fillResponse = new FillResponse.Builder()
.addDataset(new Dataset.Builder()
.setValue(parsedStructure.usernameId,
AutofillValue.forText(userData.username), usernamePresentation)
.setValue(parsedStructure.passwordId,
AutofillValue.forText(userData.password), passwordPresentation)
.build())
.build();
// If there are no errors, call onSuccess() and pass the response
callback.onSuccess(fillResponse);
}
class ParsedStructure {
AutofillId usernameId;
AutofillId passwordId;
}
class UserData {
String username;
String password;
}

How do I retrieve address components from Place API object?

I want my user to be able to pick an address. For my backend, I need to get the following info: street name, number, country and zip code.
I am using PlaceAutocompleteFragment fragment as mentioned here: https://developers.google.com/places/android-api/autocomplete.
When the user has selected a Place, I get the Place object as a result:
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// Here I want to retrieve all the address details, such as
// street name, number, country etc. and send them to my backend
}
#Override
public void onError(Status status) {
//handle Error
}
});
However from the Place object I can only use place.getAddress() to get a "human readable" address line.
The iOs and JS documentations both show that you can retrieve the addressComponents(iOs) or address_components(JS) from the Place object which contains these fields (street, zipcode, etc.). However the Android documentation shows no such method for a Place object for retrieving the addressComponents.
Am I overlooking something? Is it possible that they provide this info fro iOs and JS but not for android? Or am I also maybe missing an ovious alternative?
You need to set the search parameters you want.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS,Place.Field.LAT_LNG));
There is a getAddressComponents() in Place object.
Make sure to add "Place.Field.ADDRESS" in Fields list, onActivityResultresults data will have the components of the place, otherwise it will be null.
List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS,
Place.Field.ADDRESS_COMPONENTS,
Place.Field.LAT_LNG, Place.Field.NAME, Place.Field.UTC_OFFSET);
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY
, fieldList)
.build(context);

How to do subscription for android app for every one year

#Override
public void onClick(View v) {
payWithPaypal();
}
private void payWithPaypal()
{
PayPalPayment newPayment = new PayPalPayment();
BigDecimal bigDecimal=new BigDecimal(10);
newPayment.setSubtotal(bigDecimal);
newPayment.setCurrencyType(Currency.getInstance(Locale.US));
// newPayment.setRecipient("testandroid366-facilitator#gmail.com");
newPayment.setRecipient("b.umamaheshwar-facilitator#gmail.com ");
newPayment.setMerchantName("Testing Android");
PayPal pp = PayPal.getInstance();
if(pp==null)
pp = PayPal.initWithAppID(this, "APP-80W284XXXXXXXXXX", PayPal.ENV_SANDBOX);
//Call the paypal activity
Intent paypalIntent = pp.checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
}
here i am using paypal to achieve answer for my above question,i am able to make payment. i am planning to make a background service for getting app installed date and for executing paywithpaypal() after one year.i am not getting how to do it,any suggestions please.
You could use a read-only preference value.
Define it like this in the .xml file:
<EditTextPreference
android:summary="Date of your last subscription"
android:defaultValue="N/A"
android:title="Subscription date"
android:key="prefSubscription"
android:enabled="false" />
And use it like this in your code:
PreferenceManager.getDefaultSharedPreferences(this).getString("prefSubscription","");
And then you have to think about the rest of your code. Basically you have two options:
Get the current date via Calendar class then convert both dates to a long value and subtract the difference to see if it's greater than 365 days.
Convert the preference value to date, add another year to it and compare it with the current date.
FYI, you initialize the Calendar object this way:
Calendar myCalendar = Calendar.getInstance();

Dynamically name objects based on EditText input?

I am creating a finance Android app that will open up and ask the user to add an account. (This will always be static on the page.) On the Main activity, it will have an EditText box next to a Button ("Add Account"). When the Button is pressed, I want a new Object created and it will then be stored into an ArrayList. The List of accounts (as they are added) will then be looped below (with corresponding dynamic buttons to edit the account). This is my practice/unfinished code. It is very raw at this point!
String accountName = (Whatever is in EditText Box)
ArrayList<Accounts> accountList = new ArrayList<Accounts>();
int accountListSize = accountList.size();
(Button on Click) {
Account{accountName} = new Account(); // Not sure how to dynamically name
accountList.add({accountName}) // Not sure how to dynamically name
}
// iterate through finance loop
for(int i = 0; i < accountList .size(); i++)
{
// do stuff - Create Dynamicly Edit and Clear Buttons for each account
}
One of the big issues I am trying to overcome is how to name an Object Dynamically?
Am I over-thinking this process overall and making it harder than it should be? I am going to create a class to handle the account specifics. I eventually have to keep the data stored--so maybe should I scrap the Object orientated style and use SQLite? Shared-preferences?
Any code samples would be great, but I am mostly hoping to find the recommend method I should take.
I would recommend to create an Account object that takes the name in the constructor. For example:
public class Account {
private String name;
public Account( String name ) {
this.name = name;
}
// ... other account related methods here...
public String getName() {
return name;
}
}
Then in your code above:
List<Account> accountList = new ArrayList<Account>();
(Button on Click) {
Account anAccount = new Account( accountName ); // accountName taken from text box.
accountList.add( anAccount );
}
Then to loop through the account list:
for( Account account : accountList ) {
String name = account.getName();
// .. do whatever you need to for each account...
}
Once you have this list of Account objects, you can do anything you need to do with them, such as storing in SQLite DB for later, etc...
Hope this helps...

Categories

Resources