I'm making an app that uses coupons. I want to know programmatically what is the coupon code that the user has entered and based on the input do the stuff.
For example, I have added manually to Cloud Firestore a code for signing up. How do I check in the app that this is the code used for signing up and the user has entered? And based on that coupon code do what should be done.
Database image
Any help?
Get the coupon code from the user in a EditText
Get the coupon code from Firebase
Compare both with
String inputCode = editText.getText().toString();
String cloudCode = task.getString("code");
if (inputCode.equals(cloudCode)){
//do your thing
}
here task is from firebaseFirestore.collection().get();
Edit 1:
Things to do before implementing Coupons
All coupon code should follow a Pattern
Pattern eg - SALE0040 or SIGN0050 or DISC0020
Patter like - ABCD0123 or anything suits your needs
Your code will understand the type by looking at 1st half - SIGN and it will understand how much discount to give with 2nd half - 0050
code -
String couponCode = task.getString("coupon");
String userCode = editText.getText().toString();
String type = couponCode.subString(0,4);
int discount = Integer.valueOf(couponCode.subString(4,couponCode.length()));
Same you can do with the user entered code
Now you have both values of both Coupons Discount/Coupon type and Discount amount
Assuming you have an EditText, to get the code that is entered by the user you should use the following line of code:
String coupon = editText.getText().toString().trim();
Now having this coupon you can search the database to see if it actually exists, using the following query:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference couponsRef = rootRef.collection("Coupons");
Query query = couponsRef.whereEqualTo("coupon", coupon);
query.get().addOnCompleteListener(/* ... */);
Edit:
If the code is only for signup, then you should add a new property under your coupon object named type and use the following query:
Query query = couponsRef.whereEqualTo("coupon", coupon).whereEqualTo("type", "signup");
Another way to solve this might be to get the name of the coupon and check if it starts with SIGNUPCOUPON.
Related
I am trying to push the form data to the firebase-firestore. And I also did it successfully. But, the problem is that whenever I am trying to submit the form data again and again it just updates the last data with the current data.
Actually, my requirement is that whenever the user hit the submit button. It creates a document with a random id and stores the all data into that specific id that is generated.
You are specifying the document ID in .document() so it'll overwrite the same document. If you want a document with a random ID on every click, try using add() instead as shown below:
val collectionRef = FirebaseFirestore.getInstance().collection("Maintainance")
collectionRef.add(user).addOnCompleteListener(...)
Alternatively, you can leave .document() empty to get a DocumentReference with a random ID:
val userDocument = FirebaseFirestore.getInstance().collection("Maintanance").document() // <-- don't pass an ID
In addition to #Dharmaraj answer:
CASE_1: In a case where you need to track each user's all submitted forms, probably from your explanation you may need to organize each user's form.
Therefore if you need to organize each user's form then create another sub-collection [example: document(userId).collection("USER_FORMS")] within userID document like this:
val documentRef = FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document();
CASE_2 : In a case where you need to make your own custom document ID:
1- make a random number or string or any other data type.
2- The random number/string variable must be local to the code block/method that will execute the form submision function.
3- use the number/string generated as the form document Id like this:
//This must be local so as user clicks submision button so as it generates new random number;
val randomFormId = "generateThenumberOrStringAndInitializeTheVariable";
Then use the random number as the form document Id like this:
val documentRef = FirebaseFirestore.getInstance().collection("Maintainance").document(UserUtils.user?.id.toString()).collection("USER_FROMS").document(randomFormId);
I'm stuck in between of a flutter project, can someone please help me in solving this issue?For this project I'm using firestore as a database.
Quick Summary of the project :
one app - > Two different account types.(say it as student and tutor)
tutor - generates a QR code. ( whenever QR code is generated, a field named as "TotalClassesTook" is created and maintains a value which is the number of QR codes generated by that particular tutor)
student - scans the QR code.( whenever QR code is scanned, a field named as "TotalClassesAttended" is created and maintains a value which is the number of QR codes scanned)
My Requirement Now :
Now in the student account type(which is in "Students" collection), how can i get the"TotalClassesTook" field values(which is in different collection named as "Tutors") and calculate attendance percentage for that particular student and display it in the student account?
Please let me know the way if that's possible
FireStore Structure of project
Like I mentioned in my comment, I think your logic is flawed, there is no link between tutor and student in the structure you shared, other than tutorid in the student collection which is null, so there is no way to know which tutor document to look for per each student.
Although you should come up with a solution to this yourself as only you will know what are the requirements of your app, I can give you some insights in how I would do this:
First you need to create a link between a student and all the tutors, assuming that a tutor can only teach one class (and if this not true you can create a second identifier like classname of something like that) you could create a subcollection of student where each subdocument will act like a student information for that specific class, so you will have this structure:
students Collection
email
fullName
mobileNumber
role
rollNumber
studentClass Subcolletion
tutorId
totalClassesAttended
present
At this point you can get the StudentClass document's totalClassesAttended to calculate the attendence like this:
FirebaseFirestore.instance
.collection('students')
.doc('YOUR_STUDENT_ID')
.collection('studentClass')
.where('tutorId', isEqualTo: 'YOUR_TUTOR_ID')
.get()
.then((snapshot) {
//this will be the value you want
String classesAttended = snapshot.data['totalClassesAttended'].toString();
});
I'm working on using a collectionGroup query and trying to pass it to a Recyclerview but it seems to always be coming up empty.
Firstly, my understanding is that collectionGroups used not to be so great but now I hear it's fixed and it allows a query to grab all documents under a collectionGroup name.
The query I show below doesn't grab anything and I can't figure out why. From the explanation in the documentation, it should be able to grab all bookPendingRequests items across all books(the parent Items) that have an owner of whoever is logged in.
String mAuthUser = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
the line above allows me to grab the logged in username
Query query = firestoreDB.collectionGroup("bookPendingRequests").whereEqualTo("mOwner", mAuthUser)
This line above is what i imagine should work.
code
FirestoreRecyclerOptions<BookRequestModel> options = new FirestoreRecyclerOptions.Builder<BookRequestModel>()
.setQuery(query, BookRequestModel.class)
.build();
mBookRequestsAdapter = new BookRequestsAdapter(options);
RecyclerView bookRequestListRecyclerView = findViewById(R.id.bookRequestListRecyclerViewId);
bookRequestListRecyclerView.setHasFixedSize(true);
bookRequestListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
bookRequestListRecyclerView.setAdapter(mBookRequestsAdapter);
here's an image of what it looks link in firebase:
here's an image of my index for the collectionGroup
Right now I'm just trying to get the query to actually grab the "bookPendingRequests".
Any help or guidance is appreciated.
I am tryign to store the current username in the class and having such a tough time.
This is only part of the code
String usernameNewbet = currentUser.getUsername().toString();
bets.put("EndDate", endDate);
bets.put("EndTime", actualTimeString);
bets.put("Player_Pointer", usernameNewbet);
But when I am trying to save I am getting this error.
You probably created a Pointer column named "Player_Pointer" and tried inserting a String into it. When saving pointers in Parse, you're supposed to provide the actual object, in this case the User itself, to the field, and not the objectId.
In your case, change this:
String usernameNewbet = currentUser.getUsername().toString();
bets.put("Player_Pointer", usernameNewbet);
To this:
bets.put("Player_Pointer", currentUser);
I´m coding an app that will allow the user to take a picture, add some title and description to it and upload it to Google´s Servers. That package (picture+title+description) is named "Gift". I've used Google´s automated Backend Engine generator and added an #Entity class named Gift.
After taking the picture and clicking on submit, the "Gift" is successfully sent to Google and looking my Google App Engine Dashboard, now I have a Gift with a proper ID, a Blob (image), Description and Title.
Now what I want to do is show all those "Gifts"/Entities on a ListView, so that the user can interact with the "Gifts". What is the best way to do that?
I think I found the answer, here´s the code I´m using:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter keyFilter = new FilterPredicate(Entity.KEY_RESERVED_PROPERTY,
FilterOperator.GREATER_THAN,
0);
Query q = new Query("Gift").setFilter(keyFilter);
PreparedQuery pq = datastore.prepare(q);
for (Entity result : pq.asIterable()){
String title = (String) result.getProperty("title");
String description = (String) result.getProperty("description");
Blob bmp = (Blob) result.getProperty("bmp");
//new Object using variables above
}
This way I think I can iterate through the results and associate them with new objects of the type Gift.