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
Related
I had already done on the data update part and now i would like to extract the data and display it based on user input. I have a edit text column for user to key-in and text view to display the data that i stored in Firebase. May i know what is the best coding to work on this ? I found alot of them are using DataSnapshot but they directly read specific value from android studio while i would like to read the value from user input.[https://i.stack.imgur.com/aYrOF.png]
Edittext key in -> 978
TextView shows = 12
tv_displayIsland=(TextView)findViewById(R.id.tv_displayIsland);
et_scanIsbn=(EditText)findViewById(R.id.et_scanIsbn);
database= FirebaseDatabase.getInstance().getReference();
database.addValueEventListener(new ValueEventListener() {
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
-- need the coding to read the et_scanIsbn and display in tv_displayIsland--
}
}
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You can retrieve the value of et_scanIsbn by doing the following:
String sbn = et_scanIsbn.getText().toString();
Then you can do:
database.child("Island").orderByChild("isbn").equalTo(sbn).addValueEvent....
Inside the onDataChange you can display the retrieved value inside the TextView:
for(DataSnapshot ds : dataSnapshot.getChildren()){
String island = ds.child("island").getValue(String.class);
tv_displayIsland.setText(island);
This is my code now.
package com.example.scanning;
public class Scan extends AppCompatActivity {
DatabaseReference database;
TextView tv_displayIsland;
EditText et_scanIsbn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
tv_displayIsland = (TextView) findViewById(R.id.tv_displayIsland);
et_scanIsbn = (EditText) findViewById(R.id.et_scanIsbn);
String sbn = et_scanIsbn.getText().toString();
database = FirebaseDatabase.getInstance().getReference();
database.child("Island").orderByChild("isbn").equalTo(sbn).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String island = ds.child("island").getValue(String.class);
tv_displayIsland.setText(island);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user
here is users and edu1 full show of user
I need display just subchildren of signed user
and here is my code
private FirebaseAuth fAuth;
private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_education);
fAuth = FirebaseAuth.getInstance();
listView = findViewById(R.id.listview);
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");
fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String values = datas.getKey();
arraylist.add(values);
adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
listView.setAdapter(adapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can you try this code and see if it is working with you :
FirebaseAuth mAuth = FirebaseAuth.getInstance();
// get the current user-id to read data easly
String currentUserId = mAuth.getCurrentUser().getUid();
DatabaseReference userRef = FirebaseDatabase.getInstance()
.getReference().child("notes").child("education");
// get data to them
userRef.child(currentUserId).addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot datas: dataSnapshot.getChildren()){
String values = datas.getKey();
arraylist.add(values);
adapter = new ArrayAdapter(Education.this,
android.R.layout.simple_list_item_single_choice,
arraylist);
listView.setAdapter(adapter);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You seem to have a data structure like /Education/Notes/$uid. So to just read the notes of the currently signed in user, do:
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
fNotesDatabase.child(uid).addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
...
Try the following:
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String userId = currentFirebaseUser.getUid();
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");
fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String values = datas.getKey();
db = FirebaseDatabase.getInstance().getReference().child(values).orderByKey().equalTo(userId);
db.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get data
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here you add reference to education then retrieve the direct children under education then using orderByKey() you can check if there is a key equal to the current logged in user and retrieve the data.
Above is my firebase database I am trying to pull from.
As you can see I have a "table" called "Make". I have succesfully been able to pull this data into a Listview within my app. The code for this is below.
I now need to pull all the data from "VW_Data" table. This table has over 1000 childen named as "0" up to "1000" with the same headings in each such as "Bearing", "Altitude" etc but with different values. I would like to be able to pull "Bearing" value only from ALL 1000 children of "VW_Data" and display in a list.
However i have attempted only to try pull "VW_Data/0/Bearing" multiple ways which have not worked.
Here is my updated code for this class:
public class Graphview extends Activity
{
//Holds the values gathered from firebase
final ArrayList<String> graphlist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets the layout according to the XML file
setContentView(R.layout.activity_graphview);
//XML variable
final ListView listViewG = findViewById(R.id.listviewG);
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
database.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot datas : dataSnapshot.getChildren())
{
String bearing = (String) datas.child("Bearing").getValue();
//Add the info retrieved from datasnapshot into the ArrayList
graphlist.add(bearing);
arrayAdapter = new ArrayAdapter<>(Graphview.this, R.layout.itemview, graphlist);
listViewG.setAdapter(arrayAdapter);
//Will refresh app when the data changes in the database
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}//End onCreate()
Try this :
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> verticalSnapshotItr = dataSnapshot.getChildren();
if (verticalSnapshotItr != null) {
for (DataSnapshot verticalItemSnapshot : verticalSnapshotItr) {
String altitude = (String) verticalItemSnapshot.child("Altitude").getValue();
// Parse rest keys here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this:
DatabaseReference db = FirebaseDatabase.getInstance()
.getReference()
.child("VW_Data");
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String bearing = datas.child("Bearing").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
snapshot is at VW_Data then use the for loop, you will be able to iterate inside "0" and retrieve the value bearing
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.
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.