How to insert data of two tables in Firebase? - android

I am new to Firebase and I am planning to switch from SQLite to Firebase.
I have 2 tables in SQLite.
First one is NAME OF REPOSITORIES. This will will be general for all users which is accessible to all the users of the application.
Second one is BOOKMARKS. This will be specific to a particular user . I know that there is no table structure in Firebase .
Question is, how can I structure this type of data in Firebase? I have tried understanding tree structure of Firebase, but didn't get help for this type of scenario.

To create two tables you have to create object of DatabaseReference for second table. Also you have to create second node.
public class MainActivity extends AppCompatActivity {
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
//Create an object of DatabaseReference to create second table
private DatabaseReference mFirebaseDatabase1;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'RepositoryName' node
mFirebaseDatabase = mFirebaseInstance.getReference("RepositoryName");
// get reference to 'Bookmarks' node
mFirebaseDatabase1 = mFirebaseInstance.getReference("Bookmarks");
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String confirmPassword = inputConfirmPassword.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email, password, confirmPassword);
}
}
});
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email, String password, String confirmPassword) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
/*userId store the unique key like KYNGnlMMIf3w11VukqD
in this key store usename and email as JSON format in firebase cloud database*/
// "mFirebaseDatabase" is for table1(i.e RepositoryName)
//userId = mFirebaseDatabase.push().getKey();
// "mFirebaseDatabase1" is for table2(i.e Bookmarks)
userId = mFirebaseDatabase1.push().getKey();
}
User user = new User(name, email, password, confirmPassword);
//insert data in firebase database RepositoryName
mFirebaseDatabase.child(userId).setValue(user);
//insert data in firebase database Bookmarks
mFirebaseDatabase1.child(userId).setValue(user);
}
}
Hope this helps you :)

Hello at the first you should try with understanding the basic concept of denormalizing data. You can check one of the blog post.
Again, for more information of stucturing data in detail is here.
You can start structuring data using these links again. You have to have denormalised structure to developer best experience in firebase.
Coming to you point, Two tables.
You need to create 2 nodes in firebase. First one is with NAME OF REPOSITORIES and BOOKMARKS. If you are having any relations for both the table create a new node with that relation lets say USERBOOKMARK and try adding reference to the node.

Related

Understanding Firebase DB

I'm new to Android development and Firebase. I am making an app in Java.
I've used Firebase Auth for sign-in and sign-up of a user. There are other variables I want to associate with each user (e.g. max squat, it's a fitness app) however, I saw a YT video that said you cannot do this with Firebase Auth. I will need to create a second array/ database to store this user information...if I were to use Firebase DB am I able to easily reference the variables/info stored for my methods?..e.g. If a user's max squat is stored can I easily reference it/assign it to a local variable so I could calculate how many reps they should do? Finally, if the user signs in using Firebase Auth, how do I link this with their info/variables stored in Firebase DB?
Apologies if my use of proper terminologies is lacking, as I said I'm relatively new.
Thanks
Firebase Auth is used only for users to SignIn and SignUp. You should continue using Firebase Auth for that part of your application. There is something called Uid and this is created during registration of a user with Firebase Auth. You can get this with (if user is logged in):
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
Then you can use this uid as an ID for your database item. When creating a new user in Firebase Realtime Database. Let's say you have a Model class named User.class.
public class User {
public String username;
public String email;
public int squats;
...
...
public User() { //Default constructor required for calls to DataSnapshot.getValue(User.class)
public User(String username, String email) {
this.username = username;
this.email = email;
}
And so on, you need getters and setters I guess you know that part. Then you can do this:
User user = new User(username, email);
user.setSquats(10);
...
...
//Add all data you need to add
Then you can set this value to Database under "users" reference which you need to create earlier like this:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
This will create a new child under "users" inside Realtime database with all the values you have inside User.class. If you want to get those values back, just use this:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseUsers = database.child("users");
User myUser = null;
Query usersQuery = databaseUsers.orderByChild("username").equalTo(uid); //you can use any value to order as you want, or you don't have to, there is many options for this query
usersQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChanged(#NonNull DataSnapshot snapshot) {
try {
for (DataSnapshot user : snapshot.getChildren()) {
myUser = user.getValue(User.class);
}
} catch (Exception e) {
e.printStackTrace();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

How to update a list view taken from a database with no user accounts

my current app takes customer details, sends them to a real time firebase database, a switch activity button takes the user to a customer information page where it displays all data in the database, i am wondering if its possible to update specific users without using authentication to log in as its the shop owner using this app not customers.
All videos i have found use the firebase authentication which allows for user details to be updated, but my app lists all database data as no specfic logged in user.
below is my class that recieves the database information and displays it on screen
public class CustomerDataRetrieved extends AppCompatActivity {
private ListView listView;
DatabaseReference databaseReference;
Firebase firebase;
List<CustomerName> customerNameList;
public static final String Database_Path = "Customer Details";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_data_retrieved);
listView = (ListView) findViewById(R.id.list_view);
firebase = new Firebase(Firebase_Server_URL);
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
customerNameList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot customerSnapshot : dataSnapshot.getChildren()) {
CustomerName customers = customerSnapshot.getValue(CustomerName.class);
customerNameList.add(customers);
}
CustomerInfoAdapter customerInfoAdapter = new CustomerInfoAdapter(CustomerDataRetrieved.this,customerNameList);
listView.setAdapter(customerInfoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
If this helps, this is an image of my Customer Information activity which uses a listview to display all the data from the database, and i am wondering if its possible to update specific information from each user if required through my app, for instance if the customers quoted price changes, or contact number has changed
In order to update a specific node in the database you need to know something that identifies that node. When storing user data that is typically the UID of the user. But if you're not using Firebase Authentication, it can be anything else that identifies the user(s) whose node you want to update.
In addition to to knowing the path, you must also have permission to update the node. This is why you often see Firebase Authentication's UID being used, as it allows securing access to the data based on who the user is. If you're not using Firebase Authentication, you'll have to come up with a different scheme to protect your data.

Is there an option to pass two parameter in where clause in android to access firestore database

Is there a way to write a raw query or pass multiple parameters in android for firestore?
I have tried with
`db.collection("users").whereEqualTo("uername", "JHON")`
but i can pass only one parameter not multiple. I want to convert the below sample SQL query to firestore query
Example:
select * from login where username = "Jhon" and password = "12345"
For raw query you may go with firebase Query, here is example
Query query = yourCollectionRef.whereEqualTo("username ", "your_value_here")
.whereEqualTo("password", "your_value_here")
.whereEqualTo("email", "your_value_here");
Another way : you can follow standard approach
Store user data on user Registration in your Firebase database
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("credentials");
//to store values in your credentials node just use this code
ref.child("usernames").child(username);
ref.child("usernames").child(username).child("password").setValue(password);
// here username and password are the strings you want to store
You can do this with all of your new users to register them in your app. Also this make it easier(read faster) for you to search for the particular username and corresponding password.
You can do so using the following piece of code:
ref.child("credentials").orderByChild("usernames").equalTo(username).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// here you can do what you want, like comparing the password of the username and other things you require to do
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Android - Two types of users in Firebase

I am developing a simple android application with Firebase. I want to save the users in the real time database without using authentication with email and password. I simply want their name and their role (eg. teacher and student) picked by radiobuttons. Later I want to display all users in a list, but I was wondering how the database should be set up and how to display the right activity based on their role
Should it be:
User
"something"
username: "name"
role: "Teacher"
or
User
"KA2aslkdajsdlsad"
username: "name"
role: "teacher"
Definitely you need to use the second option. You need to use a unique identifier for all those users. For achieving a new unique key (based on time), i recomand you using push() method. It's also generated entirely on the client without consultation with the server.
On the other hand i recomand you using Firebase Anonymous Authentication.
Hope it helps.
First, make a POJO java object as per your user infos.
public class User{
String username;
int roleId; // 1 for student, 2 for teacher
public User(String username, int roleId){
this.username = username;
this.roleId = roleId;
}
}
Now Store your User inside your realtime database like:
FirebaseDatabase.getInstance()
.getReference()
.child("users")
.push()
.setValue(new User("John", 1));
If you need to fetch all your users, you can do in this way:
final List<User> userList = new ArrayList<>();
FirebaseDatabase.getInstance()
.getReference()
.child("users")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class); // this is your user
userList.add(user); // add to list
}
// Now may be display all user in listview
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Updating the data on Firebase Android

I want to update the date on Firebase on a specific node.
DB Structure:
I am trying as
private void updateData() {
database = FirebaseDatabase.getInstance();
myref = database.getReference();
myref.child("myDb").child("awais#gmailcom").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("leftSpace").setValue(newValue);
dialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("User", databaseError.getMessage());
}
});
}
I want to update the leftSpace key with the value of newValue, newValue is the type of string here. But it is not updating the value in Firebase.
If I give here
dataSnapshot.getRef().child("leftSpace").setValue(765);
it updates well. But I want to update in the format of string on the Firebase.
I saved the data on Firebase of all string types. (My pattern class contains all of the type strings)
Why it is not updating the newvalue of type string here?
Edit 1 Suggested by #Rjz Satvara
You method is adding a new node under myDB as
It is not updating the already one.
In Firebase To update specific value you can use it...
ref.child("myDb").child("awais#gmailcom").child("leftSpace").setValue("YourDateHere");
or you can move into child using "/" as follow :
ref.child("myDb/awais#gmailcom/leftSpace").setValue("YourDateHere");
you can assign new value in same child,like
Firebase firebase = new Firebase("your database link/myDb");
firebase.child("awais#gmail.com").child("leftSpace").setValue("newValue");
According to Firebase Official Documentation you can update the specific node of parent node in this way
Using setValue() in this way overwrites data at the specified location, including any child nodes. However, you can still update a child without rewriting the entire object. If you want to allow users to update their profiles you could update the username as follows:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseRef = database.getReference();
mDatabaseRef.child("TABLE_NAME").child("orderStatus").setValue(2);
Note! TABLE_NAME mean your parent node whose child node you want to update.

Categories

Resources