How to get the child name in Firebase Android - android

I'm trying to get the unique child name but its always returning the same id or it's returning what I enter in quotes for child.
uid hold "users" instead of traveling into users
Im trying to get the child name under users which is the long key/string:
public class displayUserBooks extends AppCompatActivity {
ListView listViewBooks;
List<existingBooks> existingBookses;
private FirebaseAuth mAuth;
FirebaseDatabase databaseViewbooks = FirebaseDatabase.getInstance();
DatabaseReference myRef = databaseViewbooks.getReference("Books");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user_books);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
listViewBooks= (ListView) findViewById(R.id.listViewBooks);
existingBookses = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkBooks(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkBooks(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid=ds.child("users").getKey();
existingBooks eBooks = new existingBooks();
eBooks = ds.getValue(existingBooks.class);
// if(user.getUid().equals(uid))
existingBookses.add(eBooks);
}
Booklist adapter = new Booklist(displayUserBooks.this,existingBookses);
listViewBooks.setAdapter(adapter);
}}

enter image description herethe root cause most likely is in the construction of the reference to the child node. It may be defined "too deep". Please refer to the snapshot of hierarchical picture of the DB tree, and portion of working code below. Inside the listener, it's traveling into the data of every user (defined by user ID):
FirebaseDatabase frDb = FirebaseDatabase.getInstance();
DatabaseReference frDbRef = frDb.getReference("apps/gastracking").child("users").child(mAuth.getCurrentUser().getUid());
ChildEventListener chEvLst = frDbRef.addChildEventListener(new ChildEventListener() {
ArrayList<RawReport> listOfRawreports = new ArrayList<RawReport>();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot ds1 : dataSnapshot.getChildren())
//<...... Put your code here.....>
}
}
}
Hierarchical structure of the DB nodes: unfortunately I can't add flat snapshot - so please refer to the link at the beginning of my answer.

Related

Unable to retrievw data of firebase current online user

I want to retrieve data of specific node (clicksRemain) of current online user from firebase into a textView but the data is not showing. Below is my code.
PracticeActivity
public class PracticeActivity extends AppCompatActivity {
TextView link1;
DatabaseReference dRef;
FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice);
link1 = findViewById(R.id.link1);
firebaseDatabase = FirebaseDatabase.getInstance();
dRef = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
dRef.child("clicksRemain").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String remainingClicks = snapshot.getValue(String.class);
link1.setText(remainingClicks);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}else{
link1.setText("10");
}
}
}
I think the code is correct to check if a user is logged in or not as if a user is logout then the app shows the value 10 as written in this code.
Snapshot of database
Thanks in advance
I have done these changes and now successfully retrieved the data.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uID = user.getUid();
dRef = FirebaseDatabase.getInstance().getReference("Users");
dRef.child(uID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String remainingClicks = String.valueOf(snapshot.child("clicksRemain").getValue(Integer.class));
link1.setText(remainingClicks);
}

retrieve data from firebase with authentication user do not show on ListView

I want to retrieve data from firebase with authentication user. I use ListView to display the data. But it do not show up after running.
public class InfoDisplayActivity extends AppCompatActivity {
private ListView listViewINFO;
DatabaseReference databaseReference;
FirebaseAuth firebaseAuth;
List<UserInformation> infoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_display);
listViewINFO = findViewById(R.id.listViewINFO);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,RegisterActivity.class));
}
//FirebaseUser user = firebaseAuth.getCurrentUser();
infoList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
FirebaseUser user = firebaseAuth.getCurrentUser();
String UserID = user.getUid();
databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot INFOSnapshot : dataSnapshot.getChildren()){
UserInformation userInfo = INFOSnapshot.getValue(UserInformation.class);
infoList.add(userInfo);
}
UserInfoAdapter userInfoAdapter = new UserInfoAdapter(InfoDisplayActivity.this, infoList);
listViewINFO.setAdapter(userInfoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I follow this tutorial on YouTube.
The problem in your code is that you are using the User Information reference twice. Once when declaring the databaseReference object:
databaseReference = FirebaseDatabase.getInstance().getReference("User Information");
// ^
And second when you attach the listener:
databaseReference.child("User Information").child(UserID).addListenerForSingleValueEvent(/* ... */);
// ^
To solve this, simply remove .child("User Information") from the above line of code:
databaseReference.child(UserID).addListenerForSingleValueEvent(/* ... */);

How to compare data in firebase?

I want to read back the data in Firebase which is medical = "Diabetes" which key in by the user.If this user has the medical history of diabetes will display something not allow the user to buy. Anyone can teach me how to write this condition in the android studio?
Firebase data structure
public class Pain_and_Fever extends AppCompatActivity implements View.OnClickListener{
private Button btnSubmit, btnCancel;
private String userID;
Query query;
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pain_and__fever);
btnSubmit = (Button) findViewById(R.id.bttnsubmit);
btnCancel = (Button) findViewById(R.id.bttncancel);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
myRef = mFirebaseDatabase.getReference();
btnSubmit.setOnClickListener(this);
btnCancel.setOnClickListener(this);
query = myRef.orderByChild("medical").equalTo("Diabetes");
}
private void submit(){
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot issue : dataSnapshot.getChildren()){
UserInformation uInfo = issue.getValue(UserInformation.class);
if (uInfo.getMedical().equals("Diabetes")){
startActivity(new Intent(getApplicationContext(),Medicine.class));
}else{
myRef.child("Medicines").child("Pain and Fever").child(userID).setValue("Acetaminophen");
startActivity(new Intent(getApplicationContext(),Medicine.class));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onClick(View view) {
if (view == btnSubmit){
submit();
}
if (view == btnCancel){
startActivity(new Intent(this,Medicine.class));
}
}
}
Try this way, this works for me
Query chatRoomsQuery = mFirebaseDatabase.orderByChild("medical").equalTo("your value");
chatRoomsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
search_list=new ArrayList<SearchModel>();
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
UserRegisterModel mModel = issue.getValue(UserRegisterModel.class);
if(mModel.getArea().equals(sel_area))
hidepDialog();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Make an ArrayList from Firebase Data

I have an ArrayList defined in my Android app for my MainActivity.
I've been running into difficulties trying to understand how to retrieve the interests of the user and add it to my array list.
Here's how my Firebase data is set up:
I understand that I must load the data asynchronously, but I'm confused as to how I should go about that.
here's my code for trying to add to the ArrayList:
public class MainActivity extends AppCompatActivity {
private DatabaseReference eventDatabase;
private DatabaseReference usersDatabase;
private FirebaseAuth mAuth;
private String currentUserID;
private ArrayList<String> userInterests = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventDatabase = FirebaseDatabase.getInstance().getReference().child("Event");
usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested){
userInterests.add(postSnapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println(userInterests);
I want the ArrayList to consist of the user's interests, if it is false in the database, it won't be added to the list. Example: [COMPETITION, CULTURE, EDUCATION...etc]
When it returns the list in the console, I just see an empty list -- "[]"
This is what you want.
usersDatabase.child(currentUserID).child("interests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
boolean isInterested = (Boolean)postSnapshot.getValue();
if (isInterested) {
userInterests.add(postSnapshot.getKey());
}
}
If you are using firebase with Android, then i would suggest you to use firebase-ui components, Firebase UI, it will be very helpful
Or Instead of trying to cast in Boolean, try with String and the convert it to Boolean

How to synchronized data using firebase

I'am try to get data from someone database references, but when i'll do onDataChange it's synchronized method so all my logics app chrashed. I want to do first fast_get_innfouser method,then get_all_user and after all root.addValueEventListener(. How i must to do that?
There is code:
public class chatRooms extends Activity {
private DatabaseReference root = FirebaseDatabase.getInstance().getReference();
private FirebaseDatabase database;
public FirebaseAuth auth;
private ChatInfo ChatInfo = new ChatInfo();
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private FirebaseUser user;
private ArrayList<String> all_uid = new ArrayList<>();
private User us ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_rooms);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
if (user != null) {
database = FirebaseDatabase.getInstance();
root.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
get_all_user(database.getReference());
fast_get_innfouser(database.getReference(user.getUid()));
return null;
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
root = database.getReference(user.getUid()).child("chat");
}
});
}
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
/*........some code here...........*/
}
});
}
private void get_all_user(DatabaseReference reference) {
all_uid = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
//some code here
}
}
});
}
private void fast_get_innfouser(DatabaseReference myRef) {
final Integer[] temp = {1};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
//some code here
}
json:
This sounds like a great use case for RXjava.
Here are some bindings for rxjava and firebase: (Note I haven't tested them - I wrote my own)
https://gist.github.com/gsoltis/86210e3259dcc6998801
https://github.com/nmoskalenko/rxFirebase
Then you can use zip/concat to take your multiple requests and then combine them and act on them at the end.
Try move get_all_user(database.getReference()); to inside onDataChange inside method fast_get_innfouser method
I suggest you to check as reference(or just use it) one of the next libraries which use Reactive model with RxJava:
RxJava : https://github.com/nmoskalenko/RxFirebase
RxJava 2.0: https://github.com/FrangSierra/Rx2Firebase
One of them works with RxJava and the other one with the new RC of RxJava 2.0. If you are interested of it, you can see the differences between both here.

Categories

Resources