Hello so I've been strugging for awhile now. I want to consult someone about my code. I want to apply
a coloring function to my app.
When the person presses the button when it's at its:
GREEN state it updates the value on the database to BEING HOUSEKEPT
YELLOW state when pressed sends READY FOR INSPECTION RoomStatus
RED state when pressed sends READY FOR HOUSEKEEPING RoomStatus
It was working earlier but when I tried to restrict the users that users who are Housekeepers can't access the RED STATE which are for House Keepers, I inserted somewhere in my code where I want to implement it.
I'm going over loops here can somebody tell me where I did wrong?
Here's my code:
Button room1;
private DatabaseReference mFirebaseDatabase, mFirebaseDatabase1, mFirebaseDatabase1room;
private FirebaseDatabase mFirebaseInstance;
private DatabaseReference referenceroom1;
private String roomStat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi_to_scan2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
mFirebaseDatabase = mFirebaseInstance.getReference("Users");
mFirebaseDatabase1room = mFirebaseInstance.getReference("Rooms").child("Room1");
referenceroom1 = mFirebaseDatabase1.child("Room1").child("RoomStatus");
room1 = (Button) findViewById(R.id.rm1Btn);
mFirebaseDatabase1.child("Room1").addValueEventListener(new ValueEventListener() { //attach listener
#Override
public void onDataChange(DataSnapshot dataSnapshot) { //something changed!
for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
String location = locationSnapshot.getValue().toString();
if (location.equals("READY FOR HOUSEKEEPING")) {
room1.setBackgroundColor(Color.GREEN);
roomStat = "Green";
} else if (location.equals("BEING HOUSEKEPT")) {
room1.setBackgroundColor(Color.YELLOW);
roomStat = "Yellow";
} else {
room1.setBackgroundColor(Color.RED);
roomStat = "Red";
}
if (roomStat.equals("Green")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "BEING HOUSEKEPT";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity3.class);
startActivity(next1);
}
});
} else if (roomStat.equals("Yellow")) {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR INSPECTION";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity2.class);
startActivity(next1);
}
});
} else {
room1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "READY FOR HOUSEKEEPING";
DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
reference.setValue(message);
Intent next1 = new Intent(getApplicationContext(), ReaderActivity.class);
startActivity(next1);
//I ALSO WANT TO PUT A CONDITION HERE FETCHING userType from Structure
// mFirebaseDatabase = mFirebaseInstance.getReference("Users").child("userKey");
//but doing this would mean that I would have to put a listener inside, would that be okay? I tried when this
//was working at first but it didin't and now the whole thing is not working
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.
}
});
}
Here's my structure:
Can you help me identify what's the problem with how i implemented this?
I see nothing wrong, try debugging. Android is buggy nowadays, especially when you're connecting to a cloud database. In the left side of the run button the bug shaped one. Debug.
Or maybe you could try to show your location which is your string, to check if you pulled the right info from your database. You can use logs. A guide can be found here
https://developer.android.com/studio/debug/am-logcat.html
Related
I'm working on Activity to show all the others app users except my user and i'm using Java android with Firebase .
But i cant find anyway to exclude item from DatabaseReference or from FirebaseRecyclerAdapter .
My Activity look like this
My Database look like this :
My code inside this Activity looks like below :
#Override
public void onStart() {
super.onStart();
database = FirebaseDatabase.getInstance();
myRef = database.getReference().child("users");
FirebaseRecyclerAdapter<Users,RecyclerViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, RecyclerViewHolder>(Users.class , R.layout.users_single_layout ,RecyclerViewHolder.class,myRef ) {
#Override
protected void populateViewHolder(RecyclerViewHolder viewHolder, Users model, int position) {
viewHolder.setDisolayName(model.getDisplay_name());
viewHolder.setStatus(model.getStatus());
viewHolder.setImage(model.getImager_thumb(), getContext());
frinds_relative.setVisibility(View.INVISIBLE);
final String users_id = getRef(position).getKey();
viewHolder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent target = new Intent(getActivity() , user_profile.class);
target.putExtra("profile_id" , users_id) ;
startActivity(target);
}
});
}
};
users_recycler.setAdapter(firebaseRecyclerAdapter);
}
I will be thankful if you have the solution .
I faced something similar once and how i did it was..
First thing is to give the parent layout and id in the users_single_layout xml file;
Reference the parent layout in the viewholder;
Then hide all the content of file by :
android:visibility="gone"
When That is done, You set and if statement in your FirebaseRecyclerAdapter:
Check the Code Below:
users_recycler = new FirebaseRecyclerAdapter<Users,RecyclerViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, RecyclerViewHolder>(Users.class , R.layout.users_single_layout ,RecyclerViewHolder.class,myRef ) {
#Override
protected void populateViewHolder(RecyclerViewHolder viewHolder, Users model, int position) {
if (adapter.getRef(position).getKey.equals(currentUid){
viewholder.thelayout.setVisibility(View.GONE);
} else {
viewHolder.setDisolayName(model.getDisplay_name());
viewHolder.setStatus(model.getStatus());
viewHolder.setImage(model.getImager_thumb(), getContext());
frinds_relative.setVisibility(View.INVISIBLE);
final String users_id = getRef(position).getKey();
viewHolder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent target = new Intent(getActivity() , user_profile.class);
target.putExtra("profile_id" , users_id) ;
startActivity(target);
}
});
}
}
};
users_recycler.setAdapter(firebaseRecyclerAdapter);
The FirebaseUI FirebaseRecyclerAdapter is a direct representation of the data in the underlying Query or exists at a location in a Firebase database. To exclude an item from an adapter, you have to exclude it first from the Firebase location or ensure it doesn't match that particular query anymore.
To achieve this, you can use the following line of code:
yourAdapter.getRef(position).removeValue();
I have put a button in my App. When I press the button +1 value saves to my database. So I want to check a method that when the button count =5 show an alert.It checks when i click the button. When my button count =5 alert shows 3-4 times. But I want to show it for 1 time :(
Here is the code :
private void ButtonChecker(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ezzeearnRef = rootRef.child(User1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long BRef1 = dataSnapshot.child("BRef").getValue(Long.class);
assert BRef1 != null;
int x = BRef1.intValue( );
ref = x;
if (x ==5){
showAlert("Don't CLick Button ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
ezzeearnRef.addValueEventListener(eventListener);
}
You're registering a new listener every time that the user presses the button. If the initial value is 3, the user has to press the button twice to get it to 5. That means your code registers two listeners and thus shows two alerts.
Two solutions:
Only register a listener once.
Register listeners that only get the current value.
Register listeners that only get the current value
This is the simplest change: we'll register a listener that:
Reads the current value
Automatically unregisters itself
The only change is how you register the listener:
ezzeearnRef.addListenerForSingleValueEvent(eventListener);
But this still registers/unregisters a listener for every click, which can be a bit wasteful. In addition: if you ever make your app multi-user, this misses the fact that other users may be incrementing the counter too.
Only register a listener once
Whenever possible, register and unregister your listeners in activity-lifecycle methods. For example, it is quite common to register the listeners in onStart and unregister them in onStop:
#Override
protected void onStart() {
super.onStart();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ezzeearnRef = rootRef.child(User1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long BRef1 = dataSnapshot.child("BRef").getValue(Long.class);
assert BRef1 != null;
int x = BRef1.intValue( );
ref = x;
if (x ==5){
showAlert("Don't CLick Button ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
ezzeearnRef.addValueEventListener(eventListener);
}
#Override
protected void onStop() {
super.onStop();
ezzeearnRef.removeEventListener(eventListener);
}
With this code your listener will be active during the lifecycle of the activity. During that time, if the counter (is or) becomes 5, the alert will show once.
Sometime firebase call for data multiple time so you will get same x value more then one time. to fix this use a boolean variable which store value about alert.
boolean isAlertShown = false;
private void ButtonChecker(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ezzeearnRef = rootRef.child(User1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long BRef1 = dataSnapshot.child("BRef").getValue(Long.class);
assert BRef1 != null;
int x = BRef1.intValue( );
ref = x;
if (x ==5 && !isAlertShown){
isAlertShown = true;
showAlert("Don't CLick Button ");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
ezzeearnRef.addValueEventListener(eventListener);
}
sorry I don't speak very well English.
My problem is that in the next fragment of code,
in valueEventListener, not enter, I don't know why, so, I can't getValue of "cantidad" of my realtime database.
The databaseReference get correctly, but when get the line eventValueEventListener = new Value..., not enter in onDataChange() method.
What is the problem?
Thanks.
btnGoToEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(auth != null && btnGoToEvent.getText().equals("¡ME APUNTO!")) {
btnGoToEvent.setText("Al final no voy a ir");
databaseReference = FirebaseDatabase.getInstance().getReference().child("Eventos").child(String.valueOf(position));
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cantidad = Integer.parseInt(dataSnapshot.child("cantidad").getValue().toString());
cantidad++;
databaseReference.setValue(cantidad);
databaseReference.push().setValue(new User(auth.getEmail()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
}else if(auth != null && btnGoToEvent.getText().equals("Al final no voy a ir")){
btnGoToEvent.setText("¡ME APUNTO!");
}else{
Toast.makeText(getApplicationContext(), "Necesita estar registrado para apuntarse", Toast.LENGTH_LONG).show();
}
}
});
All you're doing there is creating a new ValueEventListener. That won't get any callback until you add it to a Reference to listen to.
Maybe you meant to also write this line to set that up?
databaseReference.addValueEventListener(valueEventListener);
My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().
You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.
My Firebase database structure is:
I want to retrieve the full name of some user, when I have its key.
My code:
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private FirebaseAuth firebaseAuth;
private TextView textView;
private Button logbutton,wantToDeliverButton,lookForButton;
private String userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Firebase.setAndroidContext(this);textView = (TextView)findViewById(R.id.textView2);
Firebase usersRef = new Firebase("https://myfirstfirebaseauth.firebaseio.com");
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,LoginActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
Firebase ref = usersRef.child("User").child(user.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.getValue(User.class).getFullName();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
textView.setText("welcome "+userName);
}
}
But it set the textView to null. I try to put Toast inside the onDataChange() method, but it doesn't work. It seems it doesn't even get inside the method.
The line FirebaseUser user = firebaseAuth.getCurrentUser(); is correct because if i'm writing textView.setText("welcome "+ user.getEmail()); - I really get the correct email.
How to solve this? Am I using the correct listener? I don't want to change anything in the database, just retrieve.
Edit: it goes to onCancelled().
You're mixing capabilities from the legacy 2.5.X Firebase SDK (Example: Firebase.setAndroidContext()) and the new 9.X.X SDK (Example: FirebaseAuth.getInstance()). That is almost certainly a recipe for failure. Rework your code to use only the new SDK. The Setup Guide is here.