Android studio firebase submission form - android

I'm new to Android studio. I was able to create login and auth for my app using firebase.
I'm now trying to create a submission form for the user to create and log all the fields in firebase. I would also need the ability as admin to approve the submission request and notify user by push notification or email. The email is one of the fields in the submission form.
Looking for some guidance.
Thanks

Use Firebase Realtime Database + Firebase Functions.
You can see examples here.

You'll need to use FirebaseDatabase for that, go through this to set things up-
https://firebase.google.com/docs/database/android/start/
So first of all, add a EditText fields (simplest way) for each entry you want in your xml such as emails, password, etc.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"/>
</EditText>
Next, in your java file, convert these entries to strings.
Create a DatabaseReference (Make sure you have included firebase database library in you app level build.gradle file) and point to the location where you want to store the form entries.
Create a HashMap in which you store id and entry of each field. Directly upload this map instead of uploading each and every field separately.
Don't forget to check that the entries aren't empty.
Somewhat like this-
//global variables in class
private EditText email;
private DatabaseReference mdatabase;
//inside onCreate() method
mdatabase=FirebaseDatabase.getInstance().getReference().child("Wherever you want to store this data");
email = (EditText) findViewById(R.id.emailf);
String mymail = email.getText().toString();
if(!TextUtils.isEmpty(myname)&&!TextUtils.isEmpty(mymail)&&!TextUtils.isEmpty(mypass))
{
//create a map
HashMap< String,String> hm =
new HashMap< String,String>();
hm.put("email", mymail);
hm.put("password", mypass);
hm.put("name", myname);
mdatabase.setValue(hm).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//do whatever you want, your details have been uploaded to your database- mdatabase
}
}
});
}
Push Notifications can be implemented using Firebase Cloud Messaging service and node.js
You'll also need to learn about Firebase Functions, very necessary.
Begin here-
https://firebase.google.com/docs/cloud-messaging/
and here-
https://www.youtube.com/watch?v=BsCBCudx58g
and then here-
https://www.youtube.com/watch?v=2MYgZQjX7N0&list=PLk7v1Z2rk4hjxP_CHAhjXQN3zrcEhluF_
I hope this answered your question!

Related

How to make rules for chat app using flutter and firebase

I am writting chat app with flutter, I don't know how to set the rule on firebase such only the 2 users in a group chat can write and read. This is how I store message on firebase.
String date = DateTime.now().millisecondsSinceEpoch.toString();
groupId = userId-anotherId
var ref = FirebaseFirestore.instance
.collection('messages')
.doc(groupId)
.collection(groupId)
.doc(date);
FirebaseFirestore.instance.runTransaction((transaction) async {
transaction.set(ref, {
"senderId": userId,
"receiverId": anotherId,
"timestamp": date,
'content': msg,
"type": 'text',
});
});
Thank you for any help.
Contacting database from frontend is not the most secure way.
If you are making this app for learning then it is fine.
But for production app, you should add custom logic like this in your backend and connect your frontend with that API.
Something like this.
Flutter app --> API --> YOUR_LOGIC --> DATABASE
You would need a collection of members for a group chat. That way you can very easy check with the rules just if a member uid is under the path of groupChats/{groupID}/members/{id}. You can even make a function for the firestoe rules like this:
//Checks if user is member of group
function isMember(groupID) {
return get(/databases/$(database)/documents/groupChats/${groupID}/members/$(request.auth.uid)).data==true
}
The databse structure would be:
-
groupChats
--group1
members
--userUid1
--userUid2
--group2
members
--userUid2
--userUid4
You can use a boolean or any data you want.
The solution was very simple. I saw in youtube. enter link description here
This is the security rule:
match /messages/{groupChatId}/{document=**} {
allow write, read:if request.auth.uid in groupChatId.split(" - ") }

Check which coupon is used - Android

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.

How to retrieve data from a child node in Android Firebase

I already have a onDataChange written to get values from a different child node,but what I need is to change the key to let's say "new" and then retrieve the data from that child
Any inputs would be appreciated ..
As far as i understand, you want to change a field and bring back the changed data.
for e.g, for this data structure, if you want the change Username, create a User modal with different name, User newUser = new User("https://...","newUserName). And change the field in User modal
public String Profile;
public String newKey;
Then give the new modal to that uid,
FirebaseDatabase.getInstance().getReference().child("Users").child("ECWHIksxJ0Q5SUIIrev4BjnjmrJ3").setValue(newUser, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
DatabaseReference yourRef = databaseReference.getRef();
}
});
Now you have the changed data's reference. Did you try something like this?
Update:
If you want to update multiple value/field with single action, you should create a map and put every path into it with values.
In firebase, every table, every specific field is an path. Consider the data structure shown above. If you want change Username field:
HashMap<String, Object> updateMap = new HashMap<>();
updateMap.put("/Users/ECWHIksxJ0Q5SUIIrev4BjnjmrJ3/Username", "newUserName");
For different user:
updateMap.put("/Users/DIFFERENT_USER_KEY/Username", "newUserName2");
For diffrent table:
updateMap.put("/YourOtherTable/DifferentPath/DifferentField", true);
Then get your database root reference and update all at once.
FirebaseDatabase.getInstance().getReference().updateChildren(updateMap).addOnCompleteListener(new OnCompleteListener...)
This is very simple way to update a lot of things in one action, but it's causing problems when writing firebase rules. Because you get your root reference and try to set a value to it. The choice is yours.

How to correctly nest data and write to Firebase

I have some Edittext that allows the user to enter data:
AppName
Date
Title
Quantity
User
I started a new Firebase project and it is currently a blank slate.
I am setting up my Firebase instance like this:
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://myapp.firebase.io");
How I want it is everytime a new adding occurs, I would like to add it like this (AppName is the common ground for all entry):
AppName
Date
Title
Quantity
User
Date
Title
Quantity
User
...
...
AppName
Date
Title
Quantity
User
Date
Title
Quantity
User
...
...
How can I do the following:
The first time it is added, the AppName will be the parent node, and
anytime after Firebase should check to see if the parent node exist
and is the same and add it to that, otherwise create a new parent node
and add the children node to the new parent node.
I currently have my auth set up like this:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
I had to change to true for my app to write to Firebase.
How can I:
Not register the user but only allow the app to able to write to
Firebase.
EDIT:
I am doing the following:
mDatabase.child("AppName").setValue(etName.getText().toString());
mDatabase.child("AppName").child("Date").setValue(etDate.getText().toString());
mDatabase.child("AppName").child("Title").setValue(etQuantity.getText().toString());
mDatabase.child("AppName").child("Quantity").setValue(User.getText().toString());
mDatabase.child("AppName").child("User").setValue(etUser.getText().toString());
Instead of adding, it is overwriting the previous entry. How can I append.
If I understood you, you need that not registered users could edit your database on Firebase and how to know If you added an ID.
First of all, as Ishan Fernando said, If you add data with the same id, this data will be overwrited, and using the push method, Firebase will create an unic ID to add you data
Read this: https://firebase.google.com/docs/database/android/read-and-write?hl=en
This Gist, thanks to the user realgt, could help you to know if the Appname exists or not: https://gist.github.com/anantn/4323949#gistcomment-998628
This will get all your data and you could check if you need add it or not
And, if you don't want to register users, but you need them to write the database, I think that you need to register them as anonymous users:
https://firebase.google.com/docs/auth/android/anonymous-auth
Firebase needs registered users (using social networks, email o anonymously) to modify it, so try the anonymous method. The problem is when the user get out of your app, this user will keep registered on your database. So, I recommend you, (Please, correct me if I'm wrong) to erase the user when onStop starts and create it again when onReady starts.
I hope it helps.

Firebase on Android Studio (LoginScreen)

So I'm trying to create a login screen for my app in java on Android Studio using Firebase. Currently, in creating accounts, I am doing it this way:
if (password.getText().toString().equals(confirm.getText().toString())) {
Map map = new HashMap<String, String>();
map.put(username.getText().toString(), password.getText().toString());
myFirebaseRef.push().setValue(map);
error.setText("Account created!");
}
else {
error.setText("Passwords do not match");
}
But it saves the data on my Firebase like
this
So now on my login screen, once a user types in their username, I wanna search my Firebase for the username, and make sure it exists, then see if the password matches what they entered. How Would I do that? Thanks!
As Amy already said: no matter what else you do, immediately change your code to stop storing passwords in plain text. That is an incredibly bad practice. In general authentication is better left to dedicated tools, such as Firebase Authentication.
Aside from that, you'll want to change the way you store the users a bit. It seems you identify users by their name, store them under their name:
Map map = new HashMap<String, String>();
map.put(username.getText().toString(), password.getText().toString());
myFirebaseRef.updateChildren(map);
Now you can look up a user by their name with:
Firebase userRef = myFirebaseRef.child(username.getText().toString());
userRef.addListenerForSingleValueEvent(...
See the Firebase guide on reading data for more on that.

Categories

Resources