How to add email address as child in Firebase? [duplicate] - android

This question already has answers here:
Good way to replace invalid characters in firebase keys?
(4 answers)
Closed 4 years ago.
I am working on an Android App where I want a Firebase database like
Basically, I want to verify email before creating a user on the app. Whenever a user registers in my app, First it will be checked whether the email address is available in the users database reference. if available, then only he is allowed to register.
But I found that Firebase doesn't allow an email as a child. So How can I do it? Any other suggestion for achieving this in Firebase Database.

Because Firebase does not allow symbols as . in the key, I suggest you encode the email address like this:
name#email.com -> name#email,com
As you probably see, instead of . I have used ,. To achieve this, you can use the following methods:
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}

Related

Does Firebase always return the submitted data in order? [duplicate]

This question already has answers here:
How to sort Firebase data according to Time Created?
(1 answer)
Firebase - Get Random Child From Database Node
(1 answer)
Closed 1 year ago.
I'm trying to show the user profiles of various users like tinder but I was wondering will the firebase always shows the user who registered first to other new users or if the iteration is random which will guarantee that the result will be random and everyone chances of getting displayed are equal?
If not does someone knows how to make it random in android?
How I'm doing it is
FirebaseDatabase.getInstance().getReference().child("Users").child(OppositeUserSex);
Edit
This is the code where I think sorting wouldn't help because I want it to be random
if(mAuth.getCurrentUser().isEmailVerified())
{
FirebaseDatabase.getInstance().getReference().child("Users").child(UserSex).child(currentUserID).child("isVerified").setValue(true);
}
DatabaseReference oppositeSexDB= FirebaseDatabase.getInstance().getReference().child("Users").child(OppositeUserSex);
System.out.println(OppositeUserSex + "oppositeUser");
oppositeSexDB.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull #NotNull DataSnapshot snapshot, #Nullable #org.jetbrains.annotations.Nullable String previousChildName) {
if(snapshot.exists())
{
if(!snapshot.child("Selection").child("Nah").hasChild(currentUserID)) {
if(snapshot.child("Url").exists() && snapshot.child("isVerified").exists()) { //If user has image only then show them else dont display them && if they are verified
items.add(new ItemModel(snapshot.child("Url").getValue().toString(), snapshot.child("Name").getValue().toString(), "", "", snapshot.getKey()));
}
adapter.notifyDataSetChanged();
}
}
}
Firebase doesn't guarantee that unless you enforce it with the query you make with "orderBy" and also need to specify the direction of sorting / ordering there.
Please have a look here: Order and Limit data with Firebase
So, basically pull the data the way you want it (which would save processing in Android. And if you cannot fully achieve it in query, then you may have to do the additional filtering / ordering in Android code (Java / Kotlin).
Please don't hesitate to ask if you have any more doubts on this. Thanks.
To my experience it shows in the order of when the data was inserted, but I wouldn't rely on that, I always define the fields I will use for sorting and retrieve sorted data based using them.
I bookmarked this video sometime ago, it might have all the answers you need
Sort and Filter Firebase Data

How to take two different Firebase account users to different activities? [duplicate]

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Closed 3 years ago.
I'm creating an android application, my app contains two types of user accounts linked with firebase, when the users log in to their accounts, the first user(teacher) should be carried to a different activity than the second (student) user.
I tried the if statements but I don't know how to distinguish between the teacher and student account.
You need to store the type of user when creating the account. Try to store that data in Firestore or Realtime Database.
XXXXXXXXXXXXXXX:{
date:"2019-07-16",
id:"XXXXXXXXXXXXXXX",
name:"Teacher1",
type: "teacher"
}
Fetch and identify the type of user at the time of login. Then you can navigate them.
You can create a userType value in the database. Then you check this value at the input and direct it accordingly.
For example if the logged-in user is admin, I wrote a code so that the button appears:
if (user.getAdmin().trim().equals("true")) {
cardDesingHolder.isThatAdmin.setText("Admin");
cardDesingHolder.Admin.setVisibility(View.VISIBLE);
cardDesingHolder.Admin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mContext.startActivity(new Intent(mContext, AdminPanel.class));
}
});
} else {
cardDesingHolder.isThatAdmin.setVisibility(View.INVISIBLE);
cardDesingHolder.Admin.setVisibility(View.INVISIBLE);
}
There is a part called admin in my database. If this value is true, the button appears, otherwise it does not. You can do something like that.
My Database Example : http://prntscr.com/opxm9e

Delete child from firebase [duplicate]

This question already has answers here:
How to remove child nodes in firebase android?
(4 answers)
Closed 5 years ago.
I use following code to add a child and set a value to it in FireBase.
String ref = Constants.Client+"/"+Constants.firebaseProjects+"/"+Constants.ProjectName+"/xyz";
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseRefer);
ref.child("mockChild").push().setValue("")
What can I do to delete the "mockChild" ?
ref.child("mockChild").removeValue();
Code to add child - ref.child("mockChild").push().setValue("Hello");
Code to remove child - ref.child("mockChild").removeValue();
Lets take an example in a user db:
ref.child("Users").child("User1").setvalue("User 1");
ref.child("Users").child("User2").setvalue("User 2");
ref.child("Users").child("User3").setvalue("User 3");
Now if you want to remove a specific user from the database you have to use this code:
ref.child("Users").child("User2").removeValue();
Since firebase is a key value database, it will remove the value from User2 and also the key since the key can't be on it's own. This will remove the entire reference to User2 from your database.
To solve this, please use the following code:
String key = ref.child("mockChild").push().getKey();
ref.child("mockChild").child(key).setValue("yourValue");
ref.child("mockChild").child(key).removeValue(); // This is how you remove it
or you can use:
ref.child("mockChild").child(key).setValue(null);
It's also accepted and means that when you give Firebase a null value for a property/path, you indicate that you want to property or path to be deleted.
If you want to remove the entire child, then just use:
ref.child("mockChild").removeValue();
Note, it will remove everything that mockChild contains.

Android studio firebase submission form

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!

How to do order by query using firebase [duplicate]

This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 7 years ago.
I'm using firebase on my android app. I need help to find an issue to my trouble. I want to do a request like this: I was using the oderbyChild("date") to oder my data from the nearest date to the farest by doing this.
MyApplication.backend.child(urls).orderByChild("value").addValueEventListener(new ValueEventListener() {
}
now i want to this select all where the activity value is done and order theme by my date value. i have write this :
MyApplication.backend.child(urls).orderByChild("task").equalTo("done").addValueEventListener(new ValueEventListener(){
}
My problem is that it's not possible to do 2 two orderByChild on the same fireBase query. How can i fix this ? please need help.
Assuming your data looks like this
activities
-JKjasjiji
date: 20151129
is_done: false
-Ykkjaso23
date: 20151128
is_done: true
-Jkaisjiij
date: 20151127
is_done: false
There are a few ways to go about this.
1) query for all activities where is_done: true then sort the results in code. This could be very inefficient depending on data set size. Sorting 1 Million in code would be bad.
2) Store the done activities in another node
activities
-JKjasjiji
date: 20151129
-Jkaisjiij
date: 20151127
done_activities
-Ykkjaso23
date: 20151128
3) Store the data in a format that will enable an 'and' type query
activities
-JKjasjiji
done_and_date: false_20151129
-Ykkjaso23
done_and_date: true_20151128
-Jkaisjiij
done_and_date: false_20151127
Then user .startAt and .endAt...
ref.orderByKey().startAt("true_20151128").endAt("true_20151129")
Would give return all activities that are done between the two specified dates.
Structuring your data can simplify your queries.
#Jay's answer is great. Here's another way to crack this nut, with the Bolt compiler.
Let's say you're building an expense reporting app, and your data structure goes as follows:
type User {
name: String;
uid: String;
}
type Expense {
id: String;
amount: Number;
uid: uid;
year: Number;
}
path /users/$uid is User;
path /expenses/$expense_id is Expense;
Now let's say you want to get all of the expenses by user 1 that happened in 2014. If this were SQL you could say:
SELECT *
FROM Expenses
WHERE uid == "1" AND year == 2014
With the Firebase SDK you would like to do something like this:
ref.child('expenses')
.orderByChild('uid')
.equalTo('1')
.orderByChild('year')
.equalTo('2014');
But, that's not possible. So what are we to do? Re-structure our data to fit this kind of query.
Rather than store all the expenses under the /expenses location, we can create an index for year with /expenses/year. This would look like:
path /expenses/$year/$expense_id is Expense
Now the query we wanted to do above can be acheived with:
ref.child('2014')
.orderByChild('uid')
.equalTo('1');
The structure you choose for your data will allow you to get the data as you need. You may find that you need to duplicate your data to do this. This is okay. And if you need to keep your data consistent across multiple locations, you can use client-side fanout.

Categories

Resources