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.
Related
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 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) {
}
});
}
I am trying to populate a TextView from a firebase database. Here is the sample json file.
{
"Player" : {
"Club" : "Valley Rovers",
"Name" : "John Murphy"
}
}
Here is my android code:
public class MainActivity extends AppCompatActivity {
private TextView mPlayer;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer = (TextView) findViewById(R.id.player);;
mDatabase = FirebaseDatabase.getInstance().getReference("Player").child("Name");
final String player = mDatabase.push().getKey();
mDatabase.child("Name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Check for null
if (player == null) {
Log.e(TAG, "User data is null!");
return;
}
mPlayer.setText(player);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I want to add the name John Murphy to the firebase database and doing so the TextView mPlayer will populate with John Murphy.
You are getting the child "Name" twice on your code (leading to Player/Name/Name). Remove it from the mDatabase initialization:
mDatabase = FirebaseDatabase.getInstance().getReference("Player");
And you're never really getting the value from the DataSnapshot received. To do so, use this:
mDatabase.child("Name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String playerName = dataSnapshot.getValue(String.class);
mPlayer.setText(playerName);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In case someone wants to use POJO approach to this problem in future, follow the example below:
Remove the child("Name") from mDatabase.child("Name").addValueEventListener(new ValueEventListener()
unless you want to fetch the "Name" child only. Also remember to effect the correction made on mDatabase initialization.
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// String playerName = dataSnapshot.getValue(String.class);
PlayerModel playerModel = dataSnapshot.getValue(PlayerModel.class);
((TextView)findViewById(R.id.textviewName)).setText(playerModel.getName());
((TextView)findViewById(R.id.textviewClub)).setText(playerModel.getClub());
// mPlayer.setText(playerName);
}
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