How can i add userID into firebase database, Android - android

I am developing an events app in which users can add themselves into prexisting events.
When +Add me is clicked the userID will be added to the database.
I have an adapter and POJO class linking the UI. But I am confused as to where the .setValue() command should do.
I have put it inside the adapter and it just sends the member id to the first child.
public static class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = current_user.getUid();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Members").child(uid);
DatabaseReference eventRef = FirebaseDatabase.getInstance().getReference().child("Events").child("lists");
public EventViewHolder(View itemView) {
super(itemView);
addMe = (TextView) itemView.findViewById(R.id.add_me);
addMe.setOnClickListener(this);
#Override
public void onClick(final View v) {
if (v.getId() == addMe.getId()) {
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String uName = dataSnapshot.child("member").getValue().toString();
addMe.setText(uName);
int position = 0;
eventRef.child(mListl.get(position).getId()).child("members").setValue(uid);
Snackbar snackbar = Snackbar
.make(v, "You have been added to the event!", Snackbar.LENGTH_LONG)
.setAction("- Remove me", new View.OnClickListener() {
#Override
public void onClick(final View view) {
Snackbar snackbar1 = Snackbar.make(v, "You have been removed from the event!", Snackbar.LENGTH_SHORT);
snackbar1.show();
}
});
snackbar.show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
The above piece of code just adds the UID into the first node.
I'm not sure if I'm using the right approach or right code. I just want multiple users to be able to click on +add me, which in turn would add them inside a child node 'members' But most importantly, only to the event which they have clicked +add me in the card view.
Hope I am making myself clear.
Would really appreciate some help to my particular problem.
I would assume i would have to eventually use a hashmap of sorts, but i just want to see if im on the right track.

I did a workaround which enabled me to gather the userID:
On a really high level:
I attached a textbox and kept its value as hidden,
upon clicking I gathered the userid from the ui and fired it into firebase dtabase !

Related

Changing values in Realtime Database Android Studio Java

so basically my problem is kind of weird. It updates the values however, I need to close the app again in order for me to update the fields again.
Here is my update code.
saveEditProfile_studentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
String studentUser = firebaseAuth.getCurrentUser().getUid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(studentUser);
Toast.makeText(StudentProfileEditAct.this, studentUser, Toast.LENGTH_SHORT).show();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String replaceName = studentChangeFullName.getText().toString().trim();
String replacePhoneNumber = studentChangePhoneNum.getText().toString().trim();
Map<String, Object> updates = new HashMap<>();
updates.put("fullName", replaceName);
updates.put("phoneNumber", replacePhoneNumber);
databaseReference.updateChildren(updates);
Toast.makeText(StudentProfileEditAct.this, "Changes has been made", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
and here's my realtime database. I just want to change the name and the phone number.
But for some strange reason, it logout the current user and relog it back and when i'll try to update the values, the values from the realtime (fullname,phonenumber) the data goes back from the old value and new value and it's highlighted as yellow.
The images below when I tried to update the second time around without closing the app first.
If you want to update a value in the database based on its current value, you should use a transaction to prevent conflicting writes.
But in your code, I see no reason to first read the user node before updating it. You can use this much simpler code, which may solve your problem:
public void onClick(View v) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
String studentUser = firebaseAuth.getCurrentUser().getUid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(studentUser);
String replaceName = studentChangeFullName.getText().toString().trim();
String replacePhoneNumber = studentChangePhoneNum.getText().toString().trim();
Map<String, Object> updates = new HashMap<>();
updates.put("fullName", replaceName);
updates.put("phoneNumber", replacePhoneNumber);
databaseReference.updateChildren(updates);
Toast.makeText(StudentProfileEditAct.this, "Changes has been made", Toast.LENGTH_SHORT).show();
}
One quick fix is to use the .setValue property in the Database Reference.
You may use a model class if you intended to change different fields at once.
Based on firebase documentation, valueeventlisteners are generally made for reading and listening to data changes and not writing which might be the problem of your code

How can i get firebase child key value when i click on recyclerview item which is pushed to firebase

When using datasnapshot it deletes all messages but I want to delete the selected message only, so when I click on recyclerview item which is a message, delete that message from recyclerview as well as from firebase
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference freezerItemsRef = rootRef.child("messages");
freezerItemsRef.child(freezerItemsRef.getKey()).removeValue();
}
});
final DatabaseReference deleteChatRef = FirebaseDatabase.getInstance().getReference(Common.CHATS);
deleteChatRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (Objects.requireNonNull(snapshot.getRef().getKey()).equals(chatRef.get(position))) {
deleteChatRef.child(chatRef.get(position)).removeValue();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
write this query in on clicklistener of your recycler view just write the path of your database chat node correctly instead of Common.Chat
To delete a specific message, you'll need to know the key of that message. In Firebase Realtime Database, such keys typically start with -L.... So say the user clicked the message with key -Lasdasd19191, you can delete the message with:
freezerItemsRef.child("-Lasdasd19191").removeValue();
To know the key of the message that the user clicked on, you'll typically need to map back from the index/position (which is what Android uses) in the list view that the user clicked on, to the key in the database (which is what Firebase needs). See my longer explanation of that here: Deleting row from recycler view and firebase

Remove value from Firebase Database issue (Android)

everyone! I want to delete the value from Firebase Database using RecyclerView.
However, I cannot find the key of a child, which I want to delete.
Firstly, I add data to the database like this:
String key = MainActivity.databaseReference.push().getKey();
MainActivity.databaseReference.child(key).setValue(myAppModel);
In terms of deleting, in my RecyclerView adapter i have written onClickListener to ImageView and delete item from list successfully!
In addition, i tried many ways of how to delete this item from database as well, but the data still untouched.
Here is the code:
holder.appDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAppModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mAppModelList.size());
final ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getValue(AppModel.class);
MainActivity.databaseReference.child(mAuth.getUid()).child(dataSnapshot.getRef().getKey()).removeValue();
System.out.println(dataSnapshot.getRef().getKey()); // it gives me user id...but in my MainActivity it gives the real key
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
MainActivity.databaseReference.addListenerForSingleValueEvent(eventListener);
}
});
As i mentioned in code comment, getRef().getKey() gives me the Firebase user id, like mAuth.getUid()
And in MainActivity i receive the real name(key) of child
Query query = databaseReference;
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
AppModel appModel = dataSnapshot.getValue(AppModel.class);
appModelResult.add(0, appModel);
AddAppDialog.setAppModelResult(appModelResult);
System.out.println(dataSnapshot.getRef().getKey());
reloadFragment(fragment);
}
What i should do to delete the data from database?
Thanks everyone in advance!
Solved it!
Initially, when I want to delete item I wrote
MainActivity.databaseReference.child(mAuth.getUid()).child(appModel.getAppId()).removeValue();
However, as i noticed, you should not write user id
MainActivity.databaseReference.child(appModel.getAppId()).removeValue();
And here we are!
Hope, it could help everyone

Firebase Event Listener never triggered

I am trying to retrieve some data from Firebase, but it is not working for one of my nodes
Note that the UnverifiedEmployees node works fine but the Companies node is not
I am able to see the Log RIGHT BEFORE the Event Listener, but nothing inside of it prints
I am referring to this area:
public void addDataToFirebase() {
Log.i("BEFORE", "BEFORE COMPANIES REF");
companiesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("COMPANIESREF", "INSIDE COMPANIES REF ONDATACHANGE");
I have tried this on a different phone. I have tried it on wifi and 4g. I also tried logging in with a different user
I have also tried uninstalling the app from my phone and reinstalling. I have tried writing different implementations of the addListener.
I have also tried looking this up but did not find a lot (e.g. Android Firebase addListenerForSingleValueEvent not called) ( Firebase Android addListenerForSingleValueEvent sometimes not returning data)
Database: (If UserID exists, grab the CompanyID its related to)
Entirety of Code: AddEmployeeActivity.java:
public class AddEmployeeActivity extends Activity {
private EditText firstNameET, lastNameET, phoneNumberET, emailET, ssnET;
private ImageView checkmarkImage;
private static FirebaseUser currentUser;
private static final String TAG = "RealtimeDB";
private FirebaseDatabase database;
private DatabaseReference unverifiedRef, companiesRef;
String emailKey, ssnKey, phoneKey, companyId;
int num;
private FirebaseMethods firebaseMethods;
private Context mContext;
ArrayList<EmployeeUser> myListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_addemployees);
mContext = AddEmployeeActivity.this;
firstNameET = (EditText) findViewById(R.id.firstNameET);
lastNameET = (EditText) findViewById(R.id.lastNameET);
phoneNumberET = (EditText) findViewById(R.id.phoneNumberET);
emailET = (EditText) findViewById(R.id.emailET);
ssnET = (EditText) findViewById(R.id.ssnET);
checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);
database = FirebaseDatabase.getInstance();
unverifiedRef = database.getReference("/Unverified Employees");
companiesRef = database.getReference("/Companies");
currentUser =
FirebaseAuth.getInstance().getCurrentUser();
checkmarkImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = emailET.getText().toString().trim();
final String ssn = ssnET.getText().toString().trim();
final String phone = phoneNumberET.getText().toString().trim();
//Add EditText info to Firebase UnverifiedEmployees Node
addDataToFirebase();
}
});
} //End of ONCREATE
public void addDataToFirebase() {
Log.i("BEFORE", "BEFORE COMPANIES REF");
//companiesRef.addValueEventListener(new ValueEventListener(){
companiesRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("COMPANIESREF", "INSIDE COMPANIES REF ONDATACHANGE");
EmployeeUser user = new EmployeeUser();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
for (DataSnapshot ds2 : ds.getChildren()) {
for (DataSnapshot ds3 : ds2.getChildren()) {
for (DataSnapshot ds4 : ds3.getChildren()) {
for (DataSnapshot ds5 : ds4.getChildren()) {
Log.i(TAG, "checkIfUsernameExists: datasnapshot: " + ds5);
//user.setCompanyId(ds5.getValue(EmployeeUser.class).getCompanyId());
user.setCompanyId(ds5.getValue(String.class));
Log.i(TAG, "checkIfUsernameExists: ID: " + user.getCompanyId());
//callback.gotDataSnapshot(dataSnapshot);
if (user.getCompanyId() != null) {
companyId = user.getCompanyId();
}
}
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i("Cancelled", "In onCancelled: " + databaseError);
}
//};
}); //END OF ADDLISTENER
// companiesRef.addListenerForSingleValueEvent(eventListener);
emailKey = unverifiedRef.child(currentUser.getUid()).push().getKey();
unverifiedRef.child(currentUser.getUid()).child(emailKey).child("emailAddress").setValue(emailET.getText().toString(), completionListener);
Log.i("getKey EMAIL", emailKey);
ssnKey = unverifiedRef.child(currentUser.getUid()).push().getKey();
unverifiedRef.child(currentUser.getUid()).child(ssnKey).child("socialSecurityNumber").setValue(ssnET.getText().toString(), completionListener);
unverifiedRef.child(currentUser.getUid()).child(ssnKey).child("CompanyID").setValue(companyId, completionListener);
Log.i("getKey SSN", ssnKey);
Log.i("get COMPANY ID", companyId);
phoneKey = unverifiedRef.child(currentUser.getUid()).push().getKey();
unverifiedRef.child(currentUser.getUid()).child(phoneKey).child("phoneNumber").setValue(phoneNumberET.getText().toString(), completionListener);
Log.i("getKey Phone", phoneKey);
}
You cannot achieve this in the way you do. There is no way in which you can get a parent based on the value of one of its childs. With other words, you cannot get the value of L4bs8bH5... if that id RC9zI1... exists beneath it. To solve this, you need to consider using denormalization, which is a common practice when it comes to Firebase. This means that you need to duplicate data in order have those results. For that, I recomend you see this tutorial, Denormalization is normal with the Firebase Database, for a better understanding.
So, in this case you typically should consider augmenting your data structure to allow a reverse lookup. For example, in your scenario, I'd add a list of companies under a userId. Doing this, you'll be able to query all the companies that belong to a single user, if obviously it exists.
I think the problem lies in the references, you're creating.
If you want to get reference to "Unverified Employees" and "Companies" nodes you should create
unverifiedRef = database.getReference("Unverified Employees");
companiesRef = database.getReference("Companies");
instead of
unverifiedRef = database.getReference("/Unverified Employees");
companiesRef = database.getReference("/Companies");
(notice missing slash / sign in the reference string name)
Hope this will help

Firebase - How do I make a new table/structure?

So I am currently developing an API which gets data from Firebase and depending on that data the button changes its color. However, when I tried to make a new structure for my buttons. It won't let me make one.
I tried the answers here: How to insert data of two tables in Firebase? and here: How can I create an empty table from android app in Firebase? but neither did work for me.
Here's my sample code:
public class Normal extends AppCompatActivity {
Button suite, normal, room1;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private DatabaseReference mFirebaseDatabase1;
private FirebaseDatabase mFirebaseInstance;
//FIREBASE AUTH FIELDS
DatabaseReference mSearchedLocationReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal);
mFirebaseInstance = FirebaseDatabase.getInstance();
//FIREBASE
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
mSearchedLocationReference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
//ASSIGN ID's
room1 = (Button) findViewById(R.id.room2);
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
startActivity(new Intent(Normal.this, room2.class));
}
});
mSearchedLocationReference.addValueEventListener(new ValueEventListener() { //attach listener
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
String location = locationSnapshot.getValue().toString();
Log.d("Locations updated", "location: " + location); //log
if ( location.equals("Green")){
room1.setBackgroundColor(Color.GREEN);
}else if ( location.equals("Red")){
room1.setBackgroundColor(Color.RED);
}
else{
room1.setBackgroundColor(Color.YELLOW);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
}
PS: I created the User structure (which is for my login) on another class.
I think you should make a new structure at firebase you can do it by clicking the "+" beside your DB Name, here's an example:
Implement your methods and it should work. Then Connect again your firebase database.
I think the problem is when you are changing the value when (room 1) is clicked. You already declared this reference like this:
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
when you clicked the button (room 1) you triggered this reference to change value :
mFirebaseDatabase1.child("Rooms").child("Room1").child("RoomStatus").setValue("Green");
In other words
you are saying that you want to access
Rooms/Rooms/Room1/RoomStatus/Green
but you should be looking for this
Rooms/Room1/RoomStatus/Green
you have an extra child called Rooms that is repeated and causing the problem
Possible Solution
do this in the click listener of room 1
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mFirebaseDatabase1.child("Room1").child("RoomStatus").setValue("Green");
startActivity(new Intent(Normal.this, room2.class));
}
});
I just removed the extra(.child("Rooms")).
What i think is going wrong is that an array is returning and its last item is green
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren())
that is not letting you change the color of the button .
we will be able to help you if you show the model of your database .

Categories

Resources