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

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 .

Related

I'm trying to enter multiple values from an android activity to firebase Realtime database,but the button in the code dont work

I have already written code for inserting values into database.
button name is advbtn
Button does not respond to click.How to make it work?
public void Advbtn(View view) //code for button
{
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
getvalues();
ref.child("user").setValue(advposts);
Toast.makeText(Advpost.this,"Posted successfully",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
}
I have also declared classes for making a table in the database and called it in this program.
you have to use
yourbutton.setonClickListner(New OnClickLisnter) method
your method mainly use for starting a new activity..

How can i add userID into firebase database, 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 !

Firebase DatabaseReference

I have 2 DatabaseReference:
1 is "Active" child
2 is "Finish" child
I want to MOVE child from "active" to "finish", but I wasn't able to do it. Any ideas how? Thanks.
I have this code:
public class SingleGameActivity extends AppCompatActivity {
private DatabaseReference mDatabaseActivGame;
private DatabaseReference mDatabaseFinishGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_game);
game_key = getGameKey();
mDatabaseActivGame = FirebaseDatabase.getInstance().getReference().child("Games").child("Active").child(game_key);
mDatabaseGame.keepSynced(true);
mDatabaseFinishGame = FirebaseDatabase.getInstance().getReference().child("Games").child("Finish").child(game_key);
mDatabaseGame.keepSynced(true);
...
Inside Active child, I have game_key and inside, multiple child values.
I want to move it to finish because the recyclerview shows me the active child. Thanks!
Following code will read value from "your-project-root/Games/Active/game_key"
// mDatabaseActivGame is still the same like in your sample
mDatabaseActivGame.addListenerForSingleValueEvent(new ValueEventListener() {
... onDataChange(DataSnapshot dataSnapshot) {
// data is in dataSnapshot object
// do something here
}
...
});
Then following code will write data in "your-project-root/Games/Finish/game_key"
// mDatabaseFinishGame is still the same like in your sample
mDatabaseFinishGame.setValue(yourValueHere);
So combine them we get code like this:
mDatabaseActivGame.addListenerForSingleValueEvent(new ValueEventListener() {
... onDataChange(DataSnapshot dataSnapshot) {
mDatabaseFinishGame.setValue(dataSnapshot);
}
...
});
I haven't test this myself but in theory it should work. Hope this helps

Get the data from the Firebase in limit to perform pull to refresh and load more functionality

Yet now i am getting the all data from the FireBase at one time.What i want to do that getting data in LIMITS like 15 records at a time. Like in first time user get the 15 records from the Firebase and when user load more data at the bottom/TOP of the screen than 15 more records should come from Firebase and added to the bottom/TOP of the list.
I have implemented the logic to get the 15 records at a top OR bottom of the database from Firebase like below:-
public class ChatActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener {
private FirebaseAuth mAuth;
private DatabaseReference mChatRef;
private Query postQuery;
private String newestPostId;
private String oldestPostId;
private int startAt = 0;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(this);
mChatRef = FirebaseDatabase.getInstance().getReference();
mChatRef = mChatRef.child("chats");
/////GETTING THE VIEW ID OF SWIPE LAYOUT
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
/////GETTING FIRST 10 RECORDS FROM THE FIREBASE HERE
mChatRef.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
oldestPostId = child.getKey();
System.out.println("here si the data==>>" + child.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//////FOR THE PULL TO REFRESH CODE IS HERE
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Refresh items
System.out.println("Here==>>> "+oldestPostId);
///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE
mChatRef.startAt(oldestPostId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
System.out.println("here AFTER data added==>>" + child.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
I have searched here on SO for it , but did not get the expected result, below link which i have searched for it
1. First Link
2. Second Link
3. Third Link
4. Forth Link
Please look at my firebase data structure in image.
I have implemented the logic for the getting 15 OR 10 records at first time and it works..and also implemented the logic for loading more records in limits but not getting proper solution (NOT WORKING) , please help and let me know where am i doing wrong..Thanks :)
EDIT SOLUTION
:- I have implemented the load more or pull to refresh functionality on this link:- Firebase infinite scroll list view Load 10 items on Scrolling
You are missing orderByKey(). For any filtering queries you must use the ordering functions. Refer to the documentation
In your onRefresh method you need to set the limit:
public void onRefresh() {
// Refresh items
///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE
mChatRef.orderByKey().startAt(oldestPostId).limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
.....
So the data you retrieve is the only 10 new records after you got your first 10 records.
Make sure to save the oldest key of the newly retrieved data so that on next refresh new data from this key is only retrieved.
Suggestion: Instead of adding a child value listener to find the last key, you can just use the value listener and get the last data snapshot with the size to get the last record's key.
restructure your database, set a new child id which is incremental like 0,1,2,3... etc
"chats": {
"-KZLKDF": {
"id": 0,
"message": "Hi",
"name":"username"
},
then make a method for query
public void loadFromFirebase(int startValue,int endValue){
mChatRef.orderByChild(id).startAt(startValue).endAt(endValue).addListenerForSingleValueEvent(this);
}
make sure you have implemented addListenerForSingleValueEvent then do adapter related task.
Initially call from onCreate method:
loadFromFirebase(0,10);
NB: loading new content in the list you have to be aware with adapter.

Getting the relevant key from ValueEventListener

I'm building an app that is basically a table for soccer that updates every time I change it in my DB.
I'm using Firebase in this way:
I'm trying to use an addValueEventListener, but I don't know which one of the values is the one that changes (dif,score,points...) therefore I don't which field in my table I should update.
public class table extends AppCompatActivity {
Button insert;
TextView name, games, win, lost, tie, score, dif, points;
Team A;
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference FootballRef = mRootRef.child("Football");
DatabaseReference HouseARef = FootballRef.child("HouseA");
protected void onStart() {
super.onStart();
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
String key = dataSnapshot.getKey() ;
Toast.makeText(table.this,key, Toast.LENGTH_SHORT).show();
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
// ...
}
};
HouseARef.addValueEventListener(postListener);
}
}
See here, when let's say I'm updating the name of housaA, I want to get back the key that got updated (in my case, name), but when I'm using
dataSnapshot.getKey() the Toast I'm getting back is HouseA and not name.
You won't be able to do this using a valuelistener.
Instead put a childeventlistener on the houseA.
Now inside onChildChanged, you should get the child node under houseA which has changed as a datasnapshot and from this snapshot, you can get the key which has changed

Categories

Resources