Android If statement not breaking when condition is true - android

In this activity I am creating an account for users. I am using mobsandgeeks.saripaar API for validation features. To allow the activity to work I currently print the errors to an invisible text field, if this textfield has text, the activity does not go onto the next activity (i.e. there is an issue with user input).
I am having a problem with the if statement that checks if the username or email already exists in the database. When condition is true (checked in logs), the account is not created, but the 'Account created' message is still displayed and the application still goes to the next activity.
Any help on this would be much appreciated. Thanks
CreateAccount.java
DatabaseHelper myDb;
private static final String TAG = "CreateAccount";
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#NotEmpty
#Length(min = 3, max = 10)
private EditText etUsername;
#NotEmpty
private EditText etUserAddress;
#NotEmpty
private EditText etFirstName;
#NotEmpty
private EditText etLastName;
#NotEmpty
#Email
private EditText etEmail;
#NotEmpty
#Pattern(regex = "(^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$)")
private EditText etPhone;
#NotEmpty
private EditText etPaypal;
//Valid = abcABC123!
#NotEmpty
#Password(scheme = Password.Scheme.ALPHA_NUMERIC_SYMBOLS)
private EditText etPassword;
#ConfirmPassword
EditText etConfirmPassword;
Button btnCreateAccount;
TextView check;
//https://www.youtube.com/watch?v=rt-8PgncIio
ImageView profileImageView;
Button btnProfilePic;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
ProgressDialog progressBar;
int progressBarStatus;
Handler progressBarHandler = new Handler();
Bitmap thumbnail;
private Validator validator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
myDb = new DatabaseHelper(this);
validator = new Validator(this);
validator.setValidationListener(this);
etUsername = findViewById(R.id.etUsername);
etFirstName = findViewById(R.id.etFirstName);
etLastName = findViewById(R.id.etLastName);
etUserAddress = findViewById(R.id.etAddress);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPasswordLogin);
etConfirmPassword = findViewById(R.id.etConfirmPasswordLogin);
etPhone = findViewById(R.id.etPhoneNo);
etPaypal = findViewById(R.id.etPaypalName);
btnCreateAccount = findViewById(R.id.btnCreateAccount);
check = findViewById(R.id.tvCheck);
btnProfilePic = findViewById(R.id.btnProfilePicture);
profileImageView = findViewById(R.id.imageProfile);
btnProfilePic.setOnClickListener(this);
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
//had to change permissions in the Android Manifest file to allow for camera to be used
if (ContextCompat.checkSelfPermission(CreateAccount.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(CreateAccount.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
} else {
profileImageView.setEnabled(true);
}
createAccount();
}
public void createAccount() {
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validate();
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String email1 = etEmail.getText().toString().trim();
Log.d(TAG, "onClick: email " + email1);
String username = etUsername.getText().toString().trim();
Log.d(TAG, "onClick: username " + username);
boolean emailExists = myDb.checkIfEmailAlreadyExists(email1);
Log.d(TAG, "onClick: emailExists " + emailExists);
boolean usernameExists = myDb.checkIfUsernameAlreadyExists(username);
Log.d(TAG, "onClick: usernameExists " + usernameExists);
//https://stackoverflow.com/questions/6290531/check-if-edittext-is-empty
if (etUsername.getText().toString().matches("") | etFirstName.getText().toString().matches("") | etLastName.getText().toString().matches("")
| etEmail.getText().toString().matches("") | etUserAddress.getText().toString().matches("") | etPassword.getText().toString().matches("")|
etConfirmPassword.getText().toString().matches("") | etPhone.getText().toString().matches("") | etPaypal.getText().toString().matches(""))
{
Toast.makeText(CreateAccount.this, "Please fill empty fields", Toast.LENGTH_LONG).show();
}
else if(check.getText().toString().matches("") == false) {
Toast.makeText(CreateAccount.this, "Please enter correct details", Toast.LENGTH_SHORT).show();
}
else {
if (usernameExists){
Log.d(TAG, "onClick: userExists " + usernameExists);
Toast.makeText(CreateAccount.this, "This username is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (emailExists){
Log.d(TAG, "onClick: emailExists" + emailExists);
Toast.makeText(CreateAccount.this, "This email is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (usernameExists == false | emailExists == false) {
boolean checktext = check.getText().equals("");
// original CRUD video - https://www.youtube.com/watch?v=kDZES1wtKUY&list=PLS1QulWo1RIaRdy16cOzBO5Jr6kEagA07&index=8
boolean isInserted = myDb.insertUserData(etUsername.getText().toString(), etUserAddress.getText().toString(), etFirstName.getText().toString(), etLastName.getText().toString(),
etEmail.getText().toString(), etPassword.getText().toString(), etPhone.getText().toString(),
etPaypal.getText().toString(), data);
if (isInserted == true) {
if (checktext == true) {
onValidationSucceeded();
}
else if (checktext == false){
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
}
});
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
//TextView check = findViewById(R.id.tvCheck);
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
check.setText(errors.toString());
}
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationSucceeded() {
Toast.makeText(CreateAccount.this, "Account Created, Please sign in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CreateAccount.this, Login.class);
startActivity(intent);
}

You have a problem in your condition:
Instead of:
else if (usernameExists == false | emailExists == false)
It should be:
else if (usernameExists == false && emailExists == false)
which means user/email not exist, insert them in DB and navigate to next activity.

Related

android nullpointer exception on hashSet

this is my MainActivity class:
package com.example.alon.a2018_17_12_userloginexhomework;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String USERNAME = "username";
public static final String SP_LOGGED_USER = "spLoggedUser";
public static final String PREFS = "prefs";
public static final int REQUEST_CODE = 123;
public static final String DESTINATION = "destination";
public static final String REGISTERED_USERS_SET = "registeredUsersSet";
EditText etUsername, etPassword;
Button btnLogin, btnSignup;
public static HashMap<String, User> hashMap;
public static SharedPreferences sharedPreferences;
Set<String> registeredUsersSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
checkDestination();
checkForLoggedOrRegisteredUsers();
}
private void checkDestination() {
int destination = getIntent().getIntExtra(DESTINATION, -1);
if (destination == 0)
finish();
}
private void checkForLoggedOrRegisteredUsers() {
String loggedInUser = getSharedPreferences(PREFS, MODE_PRIVATE)
.getString(SP_LOGGED_USER, null);
if (loggedInUser != null){
User user = new User(loggedInUser);
Intent intent = new Intent(this, ActivityUserLoggedIn.class);
intent.putExtra(USERNAME, user.getUsername());
startActivityForResult(intent,REQUEST_CODE);
}
try {
registeredUsersSet = getSharedPreferences(PREFS, MODE_PRIVATE)
.getStringSet(REGISTERED_USERS_SET, null);
}catch (NullPointerException e){
e.printStackTrace();
}
if (registeredUsersSet != null){
for (String s : registeredUsersSet){
User u = new User(s);
hashMap.put(u.getUsername(),u);
}
}
}
private void init() {
registeredUsersSet = new HashSet<>();
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnSignup = findViewById(R.id.btnSignup);
hashMap = new HashMap<>();
sharedPreferences = getSharedPreferences(PREFS,MODE_PRIVATE);
btnLogin.setOnClickListener(this);
btnSignup.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnSignup:
signUp();
break;
case R.id.btnLogin:
login();
break;
}
}
private void login() {
String user = etUsername.getText().toString();
String password = etPassword.getText().toString();
//logic check:
if (user.length() < 1 || password.length() < 1){
Toast.makeText(this,
"user or pass must be above 1 chars",
Toast.LENGTH_SHORT).show();
}
//username check
if (hashMap.containsKey(user)){
//password check:
if (Objects.requireNonNull(hashMap.get(user)).getPassword().equals(password)){
//all checks are okay, logging in:
Intent intent = new Intent(this, ActivityUserLoggedIn.class);
intent.putExtra(USERNAME, user);
sharedPreferences.edit().putString(SP_LOGGED_USER,user).apply();
startActivityForResult(intent, REQUEST_CODE);
} else {
//password error:
Toast.makeText(this,
"password does not match, please retry"
, Toast.LENGTH_SHORT).show();
etPassword.setText("");
}
} else {
//username error:
Toast.makeText(this,
"User does not exists, please try again"
, Toast.LENGTH_SHORT).show();
clearEditTexts();
}
}
private void signUp() {
String user = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (user.length() < 1 || password.length() < 1){
Toast.makeText(this,
"user or pass must be above 1 chars",
Toast.LENGTH_SHORT).show();
} else if (hashMap.containsKey(user)){
Toast.makeText(this,
"user already exists, please choose a different usename",
Toast.LENGTH_SHORT).show();
clearEditTexts();
} else {
User newUser = new User(user,password);
hashMap.put(user,newUser);
registeredUsersSet.add(newUser.toString());
Toast.makeText(this,
"successfully registered used name " + user,
Toast.LENGTH_SHORT).show();
clearEditTexts();
}
}
private void clearEditTexts(){
etUsername.setText("");
etPassword.setText("");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
if (data != null) {
int destination = data.getIntExtra(DESTINATION, -1);
if (destination == 0)
finish();
}
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putStringSet(REGISTERED_USERS_SET, registeredUsersSet).apply();
}
}
every time I click on the sign up button I get NPE on the HashSet object. can anyone point the reason for it? it seems like the HashSet object initialize is way before the click method so I really have no idea why it goes null.
the error I get:
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.Set.add(java.lang.Object)' on a null object reference
at com.example.alon.a2018_17_12_userloginexhomework.MainActivity.signUp(MainActivity.java:144)
In the onCreate method, you call:
init() - > here you initialize your registeredUsersSet
but soon after that, you call:
checkForLoggedOrRegisteredUsers() -> here you initialize again registeredUsersSet, but this time from sharedPreferences, which probably returns null in your case.
(registeredUsersSet = getSharedPreferences(PREFS, MODE_PRIVATE)
.getStringSet(REGISTERED_USERS_SET, null);)
You are missing this:
if (registeredUsersSet ==null)
registeredUsersSet = new HashSet<>();

How to pass a string value from edit text to a button in the same fragment

i have a fragment in that i made a button to collect user mobile number. In the same fragment i have made a button to toast the string value collected from edited text (mobile), I know it's a simple question but i don't know the answer please help me
this is my edit text
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
String mobile = inputMobile.getText().toString();
//DatabaseReference mynum = database.getReference("number");
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
This is my button code
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
this is my whole code of fragment
package com.example.guanzhuli.foody.CartPage.fragment;
public class CheckoutFragment extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
// PayPal Initialization
private static final String TAG = "iCartPayment";
//private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
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 = "AfNfJY2QLMIzxPpAt97YVg4GKJtMa0k8wQICuFcwIdR6bR73oexStWMQfH0nirg-WlFradZHcPnCleZg";
private static final int REQUEST_CODE_PAYMENT = 1;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
// Fragment Component Initialization
private RecyclerView mRecyclerView;
private TextView mTextMobile, mTextTotal, mTextEditAddress, mTextEditMobil;
public static TextView mTextAddress;
private Button mButtonCheckout, mButtonCancel;
public CheckoutFragment() {
// Required empty public constructor
}
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_checkout, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_checkout);
mRecyclerView.setAdapter(new CheckoutAdapter(getContext()));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// initial button
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getContext(),abc, Toast.LENGTH_SHORT).show();
// payOrder();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
mButtonCancel = (Button) view.findViewById(R.id.checkout_cancel);
mButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
}
});
// initial text
mTextMobile = (TextView) view.findViewById(R.id.checkout_mobile);
mTextMobile.setText(SPManipulation.getInstance(getActivity()).getMobile());
mTextAddress = (TextView) view.findViewById(R.id.checkout_address);
mTextAddress.setText(SPManipulation.getInstance(getContext()).getAddress());
mTextTotal = (TextView) view.findViewById(R.id.checkout_total);
mTextEditMobil = (TextView) view.findViewById(R.id.checkout_edit_mobile);
mTextEditMobil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Toast.makeText(getContext(), "Edit Number", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
String mobile = inputMobile.getText().toString();
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton("Cancel", null).show();
}
});
mTextEditAddress = (TextView) view.findViewById(R.id.checkout_edit_addr);
mTextEditAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_location,(ViewGroup) view.findViewById(R.id.dialog_location));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Delivery Location").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputLocation = (EditText) dialog.findViewById(R.id.dialog_et_location);
if (inputLocation.getText().toString().isEmpty()){
return;
}
mTextAddress.setText(inputLocation.getText().toString());
String bbb = inputLocation.getText().toString();
Toast.makeText(getContext(),bbb, Toast.LENGTH_LONG).show();
}
})
.setNeutralButton("Show Map", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent mapAct = new Intent(getActivity(), MapsActivity.class);
startActivity(mapAct);
}
})
.setNegativeButton("Cancel", null)
.show();
}
});
mTextTotal.setText(String.valueOf(ShoppingCartItem.getInstance(getContext()).getPrice() * 1.06 + 1.99));
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == getActivity().RESULT_OK) {
ShoppingCartItem.getInstance(getContext()).placeOrder(mTextAddress.getText().toString(), mTextMobile.getText().toString());
ShoppingCartItem.getInstance(getContext()).clear();
DBManipulation.getInstance(getActivity()).deleteAll();
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
registerOrder();
}
catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
HomePageActivity.cartNumber.setText("0");
getActivity().finish();
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
Toast.makeText(getContext(),"Cancel", Toast.LENGTH_LONG).show();
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().stopService(new Intent(getContext(), PayPalService.class));
}
private void payOrder() {
/*
* PAYMENT_INTENT_SALE will cause the payment to complete immediately.
* Change PAYMENT_INTENT_SALE to
* - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
* - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
* later via calls from your server.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getStuffToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
/*
* See getStuffToBuy(..) for examples of some available payment options.
*/
Intent intent = new Intent(getContext(), PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getStuffToBuy(String paymentIntent) {
//--- include an item list, payment amount details
PayPalItem[] items = new PayPalItem[ShoppingCartItem.getInstance(getContext()).getFoodTypeSize()];
for (int position = 0; position < ShoppingCartItem.getInstance(getContext()).getFoodTypeSize(); position++){
int id = ShoppingCartItem.getInstance(getContext()).getFoodInCart().get(position);
final Food curFood = ShoppingCartItem.getInstance(getContext()).getFoodById(id);
final int curFoodNumber = ShoppingCartItem.getInstance(getContext()).getFoodNumber(curFood);
Log.e("PRICE & NUMBER", "price: " + curFood.getPrice() + ", number: " + curFoodNumber);
items[position] = new PayPalItem("Item No." + curFood.getId(),
curFoodNumber,
new BigDecimal(String.valueOf(curFood.getPrice())),"USD", curFood.getName()
);
}
BigDecimal subtotal = PayPalItem.getItemTotal(items);
BigDecimal shipping = new BigDecimal("1.99");
BigDecimal tax = new BigDecimal("" + ShoppingCartItem.getInstance(getContext()).getPrice() * 0.06);
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(amount, "USD", "Foody Inc.", paymentIntent);
payment.items(items).paymentDetails(paymentDetails);
//--- set other optional fields like invoice_number, custom field, and soft_descriptor
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
private void registerOrder() {
}
}
you have two way
1 : Instead on mobile use this
Toast.makeText(getContext(),inputMobile.getText().toString(), Toast.LENGTH_SHORT).show();
2 : Create global string variable mobile like this
first create global mobile number above on onCreateView()
public String mobileNumber;
then in you button click in dialog init mobileNumber
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
mobileNumber = inputMobile.getText().toString();//THIS LINE CHANGED
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
Now you can use mobileNumber anywhere like in button
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),mobileNumber, Toast.LENGTH_SHORT).show();
}
});
declare a String variable to store the value of the EditText
String mobileNumber = inputMobile.getText().toString();
Create your Toast inside the OnClickListener.
Toast.makeText(getContext, mobileNumber,Toast.LENGTH_LONG).show();

When clicking Register button with empty field app crashes with error "NumberFormatException"

my register is working fine, but i want to validate when the fields(EditText) are empty, if i click register the app crashes and if i leave an empty field it crashes too..
public class register extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
builder = new AlertDialog.Builder(register.this);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == 0 || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
} else {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(register.this, login.class);
register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(register.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(register.this);
queue.add(registerRequest);
}
}
});
}
Integer age =null;
if(!etAge.getText().toString().trim().equals(""))
{
age=Integer.parseInt(etAge.getText().toString());
}
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == null || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
return ;
}

Sinch mobile verification Skipping

I have made an app in which first the user verifies its number with the help of sinch verification and then after succesfull verification it goes to the gameactivity but the problem is that every time the user opens the app he or she has to verify again which is a very bad out come.
i dont how o skip the verification process after again opening the app
Main Activity
public class MainActivity extends Activity {
public static final String SMS = "sms";
public static final String FLASHCALL = "flashcall";
public static final String INTENT_PHONENUMBER = "phonenumber";
public static final String INTENT_METHOD = "method";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
phoneNumber.setText(manager.getLine1Number());
}
private void openActivity(String phoneNumber, String method) {
Intent verification = new Intent(this, VerificationActivity.class);
verification.putExtra(INTENT_PHONENUMBER, phoneNumber);
verification.putExtra(INTENT_METHOD, method);
startActivity(verification);
}
private boolean checkInput() {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (phoneNumber.getText().toString().isEmpty()) {
Toast.makeText(this, "Please input a phone number.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void onButtonClicked(View view) {
if (checkInput()) {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (view == findViewById(R.id.smsVerificationButton)) {
openActivity(phoneNumber.getText().toString(), SMS);
} else if (view == findViewById(R.id.callVerificationButton)) {
openActivity(phoneNumber.getText().toString(), FLASHCALL);
}
}
}
}
Verification Activity
public class VerificationActivity extends Activity {
private static final String TAG = Verification.class.getSimpleName();
private final String APPLICATION_KEY = "af23************************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.VISIBLE);
Intent intent = getIntent();
if (intent != null) {
String phoneNumber = intent.getStringExtra(MainActivity.INTENT_PHONENUMBER);
String method = intent.getStringExtra(MainActivity.INTENT_METHOD);
TextView phoneText = (TextView) findViewById(R.id.numberText);
phoneText.setText(phoneNumber);
createVerification(phoneNumber, method);
}
}
void createVerification(String phoneNumber, String method) {
Config config = SinchVerification.config().applicationKey(APPLICATION_KEY).context(getApplicationContext())
.build();
VerificationListener listener = new MyVerificationListener();
Verification verification;
if (method.equalsIgnoreCase(MainActivity.SMS)) {
verification = SinchVerification.createSmsVerification(config, phoneNumber, listener);
} else {
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(R.string.flashcalling);
verification = SinchVerification.createFlashCallVerification(config, phoneNumber, listener);
}
verification.initiate();
}
class MyVerificationListener implements VerificationListener {
#Override
public void onInitiated() {
Log.d(TAG, "Initialized!");
}
#Override
public void onInitiationFailed(Exception exception) {
Log.e(TAG, "Verification initialization failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
#Override
public void onVerified() {
Log.d(TAG, "Verified!");
hideProgress(R.string.verified, true);
}
#Override
public void onVerificationFailed(Exception exception) {
Log.e(TAG, "Verification failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
}
void hideProgress(int message, boolean success) {
if (success) {
ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
checkMark.setVisibility(View.VISIBLE);
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.INVISIBLE);
TextView progressText = (TextView) findViewById(R.id.progressText);
progressText.setVisibility(View.INVISIBLE);
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(message);
}
}
I just want that on re opening verification process should not be again called.
You can use SharedPreferences. add a key to your SharedPreferences object and initialize with value 0. You can do something like below
SharedPrefences prefences = PrefenceManager.getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Now on successfull verification :
preferences.putInt("key",1);
so on next launch check for this key value, if its 1 skip the VerificationActivity and start GameActivtiy i.e
int value = preferences.getInt("key",0);
if(value == 0){
// Verify
}else{
// Skip Verification
}

Email id and phone number not validating

Hi In My application checking validation for email id and phone number but it's not validating both and simply it's saving into database.
I want to check the email id and phone number if it's both correct i want to do next process
Can any one please help me
ContactUs.java
public class ContactUs extends Activity
{
EditText fname1,lname1,mobile1,altmob1,email1,comment1;
String data="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1=(EditText) findViewById(R.id.fname);
lname1=(EditText) findViewById(R.id.lname);
mobile1=(EditText) findViewById(R.id.mobile);
altmob1=(EditText) findViewById(R.id.altno);
email1=(EditText) findViewById(R.id.email);
comment1=(EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String fname = fname1.getText().toString();
String lname = lname1.getText().toString();
String mobile = mobile1.getText().toString();
String altmob = altmob1.getText().toString();
String email = email1.getText().toString();
String comment = comment1.getText().toString();
if(fname.equals(""))
{
fname1.setError( "Please Enter First Name" );
}
else if(lname.equals(""))
{
lname1.setError( "Please Enter Last Name" );
}
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
else if(altmob.equals(""))
{
altmob1.setError( "Please Enter Altenative Mobile No." );
}
else if(email.equals(""))
{
email1.setError( "Please Enter EmailId" );
isValidMail(email);
}
else if(comment.equals(""))
{
comment1.setError( "Please Enter Your Comments here" );
}
else
{
try{
String queryString ="fname="+ fname
+"&lname="+lname+"&mobile="+mobile+ "&altmob="+altmob+"&email="+email+"&comment="+comment;
data = DatabaseUtility.executeQueryPhp("Contactform",queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private boolean isValidMail(String email)
{
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if(!check)
{
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile)
{
boolean check;
if(mobile.length() < 6 || mobile.length() > 13)
{
check = false;
mobile1.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
there are edittext box with property email
android:inputType="textEmailAddress"
in your code
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
it check if email in blank then go to isValidMobile
so use
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile)){
// do somting
}
and similar for email
You are running your valid email check but ignoring the result. As long as you enter some text the call to save will work.
If you incorporate the return values from your is valid check methods, you can stop saving when those calls return false.
e.g.
if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile))
{
mobile1.setError("Not Valid Number");
}
Try this for checking email:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
For telephone number check:
public final static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
And please update your code with as :
public class ContactUs extends Activity {
EditText fname1, lname1, mobile1, altmob1, email1, comment1;
String data = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1 = (EditText) findViewById(R.id.fname);
lname1 = (EditText) findViewById(R.id.lname);
mobile1 = (EditText) findViewById(R.id.mobile);
altmob1 = (EditText) findViewById(R.id.altno);
email1 = (EditText) findViewById(R.id.email);
comment1 = (EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fname = fname1.getText().toString().trim();
String lname = lname1.getText().toString().trim();
String mobile = mobile1.getText().toString().trim();
String altmob = altmob1.getText().toString().trim();
String email = email1.getText().toString().trim();
String comment = comment1.getText().toString().trim();
if (fname.length() != 0) {
if (lname.length() != 0) {
if (mobile.length() != 0 && isValidMobile(mobile)) {
if (altmob.length() != 0 && isValidMobile(altmob)) {
if (email.length() != 0 && isValidMail(email)) {
if (comment.length() != 0) {
try {
String queryString = "fname="
+ fname + "&lname=" + lname
+ "&mobile=" + mobile
+ "&altmob=" + altmob
+ "&email=" + email
+ "&comment=" + comment;
data = DatabaseUtility
.executeQueryPhp(
"Contactform",
queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
comment1.setError("Please Enter Your Comments here");
}
} else {
email1.setError("Please Enter Valid EmailId");
}
} else {
altmob1.setError("Please Enter Altenative Mobile No.");
}
} else {
mobile1.setError("Please Enter valid Mobile No.");
}
} else {
lname1.setError("Please Enter Last Name");
}
} else {
fname1.setError("Please Enter First Name");
}
}
});
}
private boolean isValidMail(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if (!check) {
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile) {
boolean check;
if (mobile.length() < 6 || mobile.length() > 13) {
check = false;
mobile1.setError("Not Valid Number");
} else {
check = true;
}
return check;
}
}

Categories

Resources