Updating saved data in Realtime Database using Android Studio - android

I am working on an application which allows a user to register their details, log in with them then fill out a questionnaire, these details will also be saved for later use. Current I have successfully got my user's details on the registration page to save however whenever they fill out the questionnaire their registration details are being overwritten with their answers on the questionnaire. Included below is the code for my questionnaire page.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faqquestions);
setupUIViews();
fAuth =FirebaseAuth.getInstance();
submitfaq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
sendScoreData();
Toast.makeText(faqquestions.this, "Successfully completed", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(faqquestions.this, Results.class));
} else {
Toast.makeText(faqquestions.this, "Submission failed", Toast.LENGTH_LONG).show();
}
}
});
}
private void setupUIViews() {
question1 = (EditText)findViewById(R.id.question1);
question2 = (EditText)findViewById(R.id.question2);
question3 = (EditText)findViewById(R.id.question3);
question4 = (EditText)findViewById(R.id.question4);
question5 = (EditText)findViewById(R.id.question5);
question6 = (EditText)findViewById(R.id.question6);
question7 = (EditText)findViewById(R.id.question7);
question8 = (EditText)findViewById(R.id.question8);
question9 = (EditText)findViewById(R.id.question9);
question10 = (EditText)findViewById(R.id.question10);
submitfaq = (Button)findViewById(R.id.submitfaq);
}
private Boolean validate() {
boolean result = false;
questionOne = question1.getText().toString();
questionTwo = question2.getText().toString();
questionThree = question3.getText().toString();
questionFour = question4.getText().toString();
questionFive = question5.getText().toString();
questionSix = question6.getText().toString();
questionSeven = question7.getText().toString();
questionEight = question8.getText().toString();
questionNine = question9.getText().toString();
questionTen = question10.getText().toString();
if(questionOne.isEmpty() || questionTwo.isEmpty() || questionThree.isEmpty() || questionFour.isEmpty() || questionFive.isEmpty() || questionSix.isEmpty()|| questionSeven.isEmpty() || questionEight.isEmpty() || questionNine.isEmpty() || questionTen.isEmpty()) {
Toast.makeText(faqquestions.this, "Please enter in all feilds", Toast.LENGTH_LONG).show();
} else {
result = true;
}
return result;
}
private void sendScoreData() {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reff = firebaseDatabase.getReference(fAuth.getUid());
faqinputs FAQinputs = new faqinputs(questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix, questionSeven, questionEight, questionNine, questionTen);
reff.setValue(FAQinputs);
}

If you want to update existing data at a location in the database, then you should use updateChildren() which accepts a Map of specific child/value pairs to change at that location.

Related

Android If statement not breaking when condition is true

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.

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();

Why does my cloud function send multiples of the same notification to the target phones?

The problem occurs when my users sign in or out (all this does is change a child under each user in my database called "logged_in" to true or false). When they do this it sends a ton of new notifications to the other user's phones and I'm not sure why this happens. How can I get firebase to only send the notification once and then forget about it? Why does it even store/remember by notifications at all?
Here is the cloud function that I have deployed.
function Efar (distance_away, token, message) {
this.distance_away = distance_away;
this.token = token;
this.message = message;
this.getToken = function() {
return this.token;
}
this.getMessage = function() {
return this.message;
}
}
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotificationAdded = functions.database.ref('/emergencies/{id}').onCreate(event => {
return admin.database().ref('/tokens').on('value', function(snapshot) {
var efarArray = snapshotToArray(snapshot, event.data.child('latitude').val(), event.data.child('longitude').val());
efarArray.sort(function(a, b) {
return a.distance - b.distance;
});
var payload = {
notification: {
title: "New stuff :)",
body: "Info given: " + event.data.child('other_info').val(),
//badge: '1',
sound: 'default',
}
};
tokens_to_send_to = [];
if(efarArray.length >= 5){
//only send to the 5 closest efars
for (var i = 4; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}else{
for (var i = efarArray.length - 1; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}
return admin.messaging().sendToDevice(tokens_to_send_to, payload).then(response => {
});
});
});
//code for function below from https://ilikekillnerds.com/2017/05/convert-firebase-database-snapshotcollection-array-javascript/
function snapshotToArray(snapshot, incoming_latitude, incoming_longitude) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var distance_to_efar = distance(childSnapshot.child('latitude').val(), childSnapshot.child('longitude').val(), incoming_latitude, incoming_longitude);
var item = {
latitude: childSnapshot.child('latitude').val(),
longitude: childSnapshot.child('longitude').val(),
token: childSnapshot.key,
distance: distance_to_efar
};
returnArr.push(item);
});
return returnArr;
};
Here is my android login class:
public class loginScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
//button to get back to patient screen
Button backButton = (Button) findViewById(R.id.login_back_button);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchPatientScreen();
finish();
}
});
Button submitButton = (Button) findViewById(R.id.login_submit_button);
final EditText user_name = (EditText) findViewById(R.id.login_name_field);
final EditText user_id = (EditText) findViewById(R.id.login_id_field);
final TextView errorText = (TextView) findViewById(R.id.errorLoginText);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String old_id = sharedPreferences.getString("old_id", "");
String old_name = sharedPreferences.getString("old_name", "");
if(old_id != "" && old_name != ""){
user_name.setText(old_name);
user_id.setText(old_id);
}
// logic for the login submit button
submitButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final String name = user_name.getText().toString();
final String id = user_id.getText().toString();
// make sure there is some data so app doesn't crash
if (name.equals("") || id.equals("")) {
Log.wtf("Login", "No data input. Cannot attempt login");
errorText.setText("ERROR: missing username or id...");
} else {
// check and validate the user
checkUser(name, id);
}
}
}
);
}
// Starts up launchEfarScreen screen
private void launchEfarScreen() {
Intent toEfarScreen = new Intent(this, EFARMainActivity.class);
finish();
startActivity(toEfarScreen);
}
// Starts up launchEfarScreen screen
private void launchPatientScreen() {
Intent toPatientScreen = new Intent(this, PatientMainActivity.class);
startActivity(toPatientScreen);
finish();
}
// checks to see if a user exists in the database
private void checkUser(String user_name, String user_id) {
final TextView errorText = (TextView) findViewById(R.id.errorLoginText);
final String name = user_name;
final String id = user_id;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users");
userRef.addListenerForSingleValueEvent(new
ValueEventListener() {
#Override
public void onDataChange (DataSnapshot snapshot){
// Check if id number is in database
if (snapshot.hasChild(id)) {
// check if name matches id in database
String check_name = snapshot.child(id + "/name").getValue().toString();
if (check_name.equals(name)) {
// store password and username for auto login
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("id", id);
editor.putString("name", name);
editor.putString("old_id", id);
editor.putString("old_name", name);
editor.putBoolean("logged_in", true);
editor.commit();
// update users info
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("users");
GPSTracker gps = new GPSTracker(loginScreen.this);
double my_lat = gps.getLatitude(); // latitude
double my_long = gps.getLongitude(); // longitude
userRef.child(id + "/name").setValue(name);
userRef.child(id + "/token").setValue(refreshedToken);
userRef.child(id + "/latitude").setValue(my_lat);
userRef.child(id + "/longitude").setValue(my_long);
userRef.child(id + "/logged_in").setValue(true);
//if all matches then go onto the efar screen
errorText.setText("");
finish();
launchEfarScreen();
} else {
errorText.setText("ERROR: username or id is incorrect...");
}
} else {
Log.wtf("Login", "FAILURE!");
errorText.setText("ERROR: username or id is incorrect...");
}
}
#Override
public void onCancelled (DatabaseError firebaseError){
}
}
);
}
//disables the werid transition beteen activities
#Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
}

Open different activities according to the login credentials entered

Below is my login activity.
It has a simple layout,where user enters his username and password and click login button.
A list of username and passwords is being stored in ms sql server.
And connection is also being established.
But the problem is on different combinations of usernames and passwords i want to open different activities.
How can i do it?
Lets say I have two combinations of username and password in my database-1.username1 , password1 (should open activity 1 on login button click)
2.username2, password2 (shoud open activity 2 on login button click)
Here is the code-----
public class Login extends Activity
{
private static final String DUMMY_CREDENTIALS = "user#test.com:hello";
// private UserLoginTask userLoginTask = null;
private View loginFormView;
private View progressView;
ConnectionClass connectionClass;
private AutoCompleteTextView emailTextView;
private EditText passwordTextView;
private Button btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
connectionClass = new ConnectionClass();
emailTextView = (AutoCompleteTextView) findViewById(R.id.email);
//loadAutoComplete();
passwordTextView = (EditText) findViewById(R.id.password);
btnlogin=(Button) findViewById(R.id.email_sign_in_button);
class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
String userid = emailTextView.getText().toString();
String password = passwordTextView.getText().toString();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
Toast.makeText(Login.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
Intent i = new Intent(Login.this, Activity1.class);//For any combination ,it will open activity1 now.
startActivity(i);
finish();
}
}
#Override
protected String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select EmailID,Password from Login_DB where EmailID='" + userid + "' and Password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successfull";
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = "Exceptions";
}
}
return z;
}
}
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoLogin doLogin = new DoLogin();// this is the Asynctask
doLogin.execute("");
}
});
}
}
Create a table in your database that links usernames to activities, and then query it after authenticating the user.

Scoreloop Android can't submit user or score

This is the code :
public class ProfileActivity extends Activity {
private final static int DIALOG_PROGRESS = 0;
private final static int DIALOG_SUCCESS = 1;
private final static int DIALOG_ERROR = 2;
private EditText usernameText;
private EditText emailText;
// saves the last error occurred, so we can read it in onPrepareDialog()
String dialogErrorMsg = "";
String dialogSuccessMsg = "";
public void onResume() {
super.onResume();
// here we fetch the user's profile data from Scoreloop to fill in
// the text fields
// first, a request observer...
RequestControllerObserver observer = new RequestControllerObserver() {
public void requestControllerDidReceiveResponse(RequestController requestController) {
UserController userController = (UserController)requestController;
dismissDialog(DIALOG_PROGRESS);
// insert values into text fields
User user = userController.getUser();
usernameText.setText(user.getLogin());
emailText.setText(user.getEmailAddress());
}
public void requestControllerDidFail(RequestController aRequestController, Exception anException) {
// the profile could not be loaded :(
dismissDialog(DIALOG_PROGRESS);
// show some error message
dialogErrorMsg = "خطأ في تحميل الملف الشخصي";
showDialog(DIALOG_ERROR);
}
};
// here's the UserController doing our work to update the profile data
UserController userController = new UserController(observer);
// show progress dialog
showDialog(DIALOG_PROGRESS);
// and fire the request
userController.loadUser();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.profile);
// find our text fields
usernameText = (EditText) findViewById(R.id.text_username);
emailText = (EditText) findViewById(R.id.text_email);
// set up click handler for the save button
((Button) findViewById(R.id.button_save_profile)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get the current User
User user = Session.getCurrentSession().getUser();
// update his values
user.setLogin(usernameText.getText().toString());
user.setEmailAddress(emailText.getText().toString());
// set up a request observer
RequestControllerObserver observer = new RequestControllerObserver() {
public void requestControllerDidReceiveResponse(RequestController aRequestController) {
dismissDialog(DIALOG_PROGRESS);
dialogSuccessMsg = "تم تحميل الملف الشخصي بنجاح";
showDialog(DIALOG_SUCCESS);
}
public void requestControllerDidFail(RequestController controller, Exception exception) {
dismissDialog(DIALOG_PROGRESS);
// Error handling has to account for many different types of
// failures...
if(exception instanceof RequestControllerException) {
RequestControllerException ctrlException = (RequestControllerException) exception;
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_EMAIL_TAKEN)) {
// this case is not quite a fatal error. if the email address is already
// taken, an email will be sent to it to allow the user to link this device
// with his account.
// that's why we'll show a success dialog in this case.
dialogSuccessMsg = "تم إستخدام الأميل من قبل شخص آخر";
showDialog(DIALOG_SUCCESS);
}
else {
// in any of these cases it's an error:
dialogErrorMsg= "";
// email may be invalid
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_EMAIL)) {
dialogErrorMsg += "خطأ في الأميل";
}
// username may be invalid, taken or too short
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TAKEN)) {
dialogErrorMsg += "تم إستخدام الأسم من قبل شخص آخر";
}
else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TOO_SHORT)) {
dialogErrorMsg += "الأسم قصير جدا";
}
else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_USERNAME)) {
dialogErrorMsg += "الأسم غير صالح للإستخدام";
}
showDialog(DIALOG_ERROR);
}
}
else {
// generic Exception
dialogErrorMsg = exception.getLocalizedMessage();
showDialog(DIALOG_ERROR);
}
// update displayed values
User user = ((UserController)controller).getUser();
usernameText.setText(user.getLogin());
emailText.setText(user.getEmailAddress());
}
};
// with our observer, set up the request controller
UserController userController = new UserController(observer);
// pass the user into the controller
userController.setUser(user);
showDialog(DIALOG_PROGRESS);
// submit our changes
userController.submitUser();
}
});
}
// handler to create our dialogs
#Override
protected Dialog onCreateDialog(final int id) {
switch (id) {
case DIALOG_PROGRESS:
return ProgressDialog.show(ProfileActivity.this, "", "جاري التحميل");
case DIALOG_ERROR:
return (new AlertDialog.Builder(this))
.setPositiveButton("إغلاق", null)
.setMessage("")
.create();
case DIALOG_SUCCESS:
return (new AlertDialog.Builder(this))
.setPositiveButton("إغلاق", null)
.setMessage("")
.create();
}
return null;
}
// handler to update the success and error dialog with the corresponding message
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ERROR:
AlertDialog errorDialog = (AlertDialog)dialog;
errorDialog.setMessage(dialogErrorMsg);
break;
case DIALOG_SUCCESS:
AlertDialog successDialog = (AlertDialog)dialog;
successDialog.setMessage(dialogSuccessMsg);
break;
}
}
}
It always fail to submit new user. without any reason and i already initialize it in my main screen.
Client.init(this, secret, null);
also i copied socreloop.properties to my assist folder.
Same problem also when submitting new score. it won't submit.
and thanks.
Are you testing it on emulator because in my case it took a long time when testing from emulator to add the new user and some time it even failed to add new user from emulator , try to test it from an android device.

Categories

Resources