Issue with Switch Case Statement - java

I have three methods:
The first checks the gender of the user
The second checks the housing assortment type
The third puts the sorted users into my card adapter
My issue is with the second method checkHousing(). If the user chooses Same Sex housing it checks all the other Males who have selected Same Sex housing.Vice-versa for the Female users. So far Iv only been able to get all the the users who have chosen Same Sex, both male and female.
Any suggestions? I feel like there is a more efficient way to do this but cant seem to figure it out.
By the way, I'm using Firebase Real Time database to store the user's info.
private String userSex;
private String thisUserSex;
public void checkUserSex() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference userDb = usersDb.child(user.getUid());
userDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.child("sex").getValue() != null) {
userSex = dataSnapshot.child("sex").getValue().toString();
switch (userSex) {
case "Male":
thisUserSex = "Male";
break;
case "Female":
thisUserSex = "Female";
break;
}
checkHousing();
} } }
#Override
public void onCancelled(DatabaseError databaseError) {
} }); }
private String housingType;
private String assortment;
public void checkHousing() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference userDb = usersDb.child(user.getUid());
userDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.child("Housing").getValue() != null) {
housingType = dataSnapshot.child("Housing").getValue().toString();
switch (housingType) {
case "Same Sex":
assortment = "Same Sex";
break;
case "Uni-Sex":
assortment = "Uni-Sex";
break;
} if (assortment == "Same Sex") dataSnapshot.getValue().toString().equals(thisUserSex);
else { assortment = "UniSex";
}
}
}getRoomMates();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void getRoomMates(){
usersDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.child("Housing").getValue() != null) {
if (dataSnapshot.exists() &&
!dataSnapshot.child("connections").child("nope").hasChild(currentUId) &&
!dataSnapshot.child("connections").child("yeps").hasChild(currentUId) &&
dataSnapshot.child("Housing").getValue().toString().equals(assortment)) {
String profileImageUrl = "default";
if (!dataSnapshot.child("profileImageUrl").getValue().equals("default")) {
profileImageUrl =
dataSnapshot.child("profileImageUrl").getValue().toString();
}
cards item = new cards(dataSnapshot.getKey(),
dataSnapshot.child("name").getValue().toString(), profileImageUrl);
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
} } }

You could split the Same Sex into Same SexM andSame SexF and store those seperatley, and then chose the roommates based on the M or F in the database.
Inside of the switch:
if(thisUserSex.equalsIgnoreCase("Male"){
assortment = "Same SexM";
}else{
assortment = "Same SexF";
}

Check what information is in the database, I have had instances where the data is not being changed during run time and that might be the cause of it always returning the same result. I know that you can use a debug mode in most editors or you can print out the current value for the string housing type.
Edit: Looking closer at the code you are using a real time database so check if the information you are submitting is getting processed correctly.

Related

Unable to use boolean values in IF statements

I have a database that is being checked using a Cursor. This database compares the data in the database to the user entered username and password. If they match data in the database a boolean is returned true. I can use a toast to output the boolean which correctly outputs as true or false if the input data does or does not match.
However, i am trying to use the boolean to move to the next activity. If the boolean is true the next intent is started. This does not work for some reason and I cant seem to work out why. Any help would be great. Thanks!
public Button btnLogin, btnSignup;
public EditText UsernameInput, PasswordInput;
public DatabaseHelper db;
public static String passUser, passPass, passFirst, passSecond;
public int count;
public Boolean matchingUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Align page and remove notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Define everything
btnLogin = findViewById(R.id.btnLogin);
btnSignup = findViewById(R.id.btnSignup);
UsernameInput = findViewById(R.id.UsernameInput);
PasswordInput = findViewById(R.id.PasswordInput);
db = new DatabaseHelper(this);
// validation button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateLogin(UsernameInput.getText().toString(), PasswordInput.getText().toString());
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateUser();
}
});
}
// Validation code
public void validateLogin(String userName, String userPassword)
{
if (userName.equals("")|| userPassword.equals(""))
{
Toast.makeText(getApplicationContext(),"Fields are empty",Toast.LENGTH_SHORT).show();
}
else
{
// CHECKING USER LOGIN DETAILS
Cursor cursor = db.CompareUserData();
for (count = 0; count<=cursor.getCount();count++)
{
if (cursor.moveToPosition(count))
{
if (UsernameInput.getText().toString().equals(cursor.getString(0))&&PasswordInput.getText().toString().equals(cursor.getString(1)))
{
matchingUser = true;
}
}
Toast.makeText(this, "boolean : "+ matchingUser, Toast.LENGTH_SHORT).show();
if (matchingUser = true)
{
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in", Toast.LENGTH_SHORT).show();
LoginValidation();
}
if (matchingUser = false)
{
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}}
}
}
private void LoginValidation()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,Login_Biometrics.class));
}
private void CreateUser()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,createUser.class));
}
public static String getUser ()
{
return passUser;
}
public static String getPass ()
{
return passPass;
}
public static String getFirst ()
{
return passFirst;
}
public static String getSecond ()
{
return passSecond;
}
It wont work with one = equal sign just do:
if(matchingUser) {
// if true do something
} else {
// if false do something
}
In your case:
if (matchingUser) {
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in",Toast.LENGTH_SHORT).show();
LoginValidation();
} else {
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}
You have to understand some basics:
Assignment operator =
Is used to assign value to some variable.
Logical operator ==
Is used to make some logical comparison.
So instead of doing this:
if (matchingUser = true)
{
...
Do this
if (matchingUser == true)
{
...
Apply this for every condition checking in your code.

Firebase Android Java - Can't get value of a child

So I have been trying to implement a way to check if the user had already sent a friend a request to the profile visited, or if the user has received a friend request from the profile visited. Based on the results, the buttons will be set to sent request, accept request ,add friend or friends
However, in my Firebase function, the first 3 if statements aren't met, even if one of them was supposed to be met. The first else if statement should have worked because I already sent a friend request to the profile visited.
When I ran a debug, it shows something like value = {sentFriendRequests={jmarston=2}}. So Firebase knows that I added John Marston as a friend, but for some reason the else if statement wasn't working. Its the else statement that works instead
My code is down below:
checkFriendRequestStatus function
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
onViewCreated function
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
sRFullName = (TextView) view.findViewById(R.id.sRUFullNameET);
addFriendBtn = (Button) view.findViewById(R.id.sRUAddFriendBtn);
sentRequestBtn = (Button) view.findViewById(R.id.sRUFriendReqSentBtn);
acceptRequestBtn = (Button) view.findViewById(R.id.sRUAcceptRequestBtn);
wereFriendsBtn = (Button) view.findViewById(R.id.sRUWeFriendsBtn);
final String strVisitedUserID = getArguments().getString("sRUserID");
final String visitedUsername = getArguments().getString("sRUsername");
ShPreference = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// converts Stringed userID back to Int
final String strSignedInUID = ShPreference.getInt(currentUserID, 0) + "";
final String signedInUsername = ShPreference.getString(currentUsername, "");
// converts the userSignedIn id to string
//final String strSignedInUID = userSignedInID + "";
// checks if the current User visited has been sent a friend Request
checkFriendRequestStatus(new ButtonStatus() {
#Override
public void setButtonStatus(int choice, int button) {
/**
* The choice params is for the choose if to show or hide buttons.
* The buttons params selects which buttons are to show or hide
*/
addFriendBtn.setVisibility(View.GONE);
sentRequestBtn.setVisibility(View.GONE);
acceptRequestBtn.setVisibility(View.GONE);
wereFriendsBtn.setVisibility(View.GONE);
// if choosed to show buttons
if (choice == 1) {
// show buttons depending on the friendRequest status
if (button == 1) {
wereFriendsBtn.setVisibility(View.VISIBLE);
}
else if (button == 2) {
sentRequestBtn.setVisibility(View.VISIBLE);
}
else if (button == 3) {
acceptRequestBtn.setVisibility(View.VISIBLE);
}
else {
addFriendBtn.setVisibility(View.VISIBLE);
}
}
}
}, strSignedInUID, visitedUsername, strVisitedUserID);
// sets the name with the Full Name; called from SearchResultsAdapter
sRFullName.setText(getArguments().getString("sRFullName"));
}
To compare String object use equals instead of == (double equals). Double equals will compare reference not their values.
Update your code of comparison like below:
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Values of override method not reflecting on main variables

I am trying to change values of my class from an override method as shown below:
public class QuestionAnalyser extends AppCompatActivity {
String question;
String entityIdentified;
static boolean identified = false;
DatabaseReference entityRef;
TranslatorServant t = new TranslatorServant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interface);
}
public void analyse(String userQues) {
if (!(Interface.deviceLang.equals("en"))) {
TranslatorServant t = new TranslatorServant();
question = t.translateText(userQues);
} else {
question = userQues;
}
question = question.replaceAll("\\p{Punct}|\\d", "");
final String[] words = question.split(" ");
getEntity(words);
if (identified == true) {
initialiseEntityServant(entityIdentified, question, words);
} else {
mimicOtherMessage("Sorry, I have failed to understand your question");
}
return;
}
private void getEntity(final String[] words) {
entityRef = FirebaseDatabase.getInstance().getReference().child("IRAdata").child("Entities");
entityRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot entity : dataSnapshot.getChildren()) {
String[] synonyms = entity.child("syn").getValue().toString().split(",");
for (String syn : synonyms) {
for (String word : words) {
if (word.equalsIgnoreCase(syn) || question.equalsIgnoreCase(syn)) {
mimicOtherMessage("found");
entityIdentified = entity.getKey();
identified = true;
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
if (identified == false) {
for (String yes : YesNo.yes) {
for (String w : words) {
if (w.equalsIgnoreCase(yes) || question.equalsIgnoreCase(yes)) {
identified = true;
entityIdentified="basic";
}
}
for (String no : YesNo.no) {
for (String w : words) {
if (w.equalsIgnoreCase(no) || question.equalsIgnoreCase(no)) {
identified = true;
entityIdentified="basic";
}
}
}
}
}
return;
}
}
From the analyse() method i am calling the getEntity() method, the override method is working fine and is changing the value of identified and entityIdentified accordingly but, when the method is completed the updates are not reflected on the variables.
I have tried to debug, i could see the values changing in the override method, but when i check the values of the variables after the override method, i could only get the initial values. Somebody can help me on this please?
I have tried implementing threads as well, to make sure the method getEntity() gets completed before returning to the main, but the problem persists.
The code you have written is not very detailed to me, but your logic could be restructured in a way, similar to what I have done below:
public class QuestionAnalyser extends AppCompatActivity {
String question;
String entityIdentified;
static boolean identified = false;
DatabaseReference entityRef;
TranslatorServant t = new TranslatorServant();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interface);
}
public void analyse(String userQues) {
if (!(Interface.deviceLang.equals("en"))) {
TranslatorServant t = new TranslatorServant();
question = t.translateText(userQues);
} else {
question = userQues;
}
question = question.replaceAll("\\p{Punct}|\\d", "");
final String[] words = question.split(" ");
getEntity(words);
// remove any logic that depends on the return of getEntity(words) from here
// it is best if the logic is called from within the Firebase call
}
private void getEntity(final String[] words) {
entityRef = FirebaseDatabase.getInstance().getReference().child("IRAdata").child("Entities");
entityRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot entity : dataSnapshot.getChildren()) {
String[] synonyms = entity.child("syn").getValue().toString().split(",");
for (String syn : synonyms) {
for (String word : words) {
if (word.equalsIgnoreCase(syn) || question.equalsIgnoreCase(syn)) {
mimicOtherMessage("found");
entityIdentified = entity.getKey();
identified = true;// under what condition will this be false
// this is the best place to put the logic
initialiseEntityServant(entityIdentified, question, words);
} else {
identified = false;// I hope this condition for setting it to false is satisfactory
mimicOtherMessage("Sorry, I have failed to understand your question");
for (String yes : YesNo.yes) {
for (String w : words) {
if (w.equalsIgnoreCase(yes) || question.equalsIgnoreCase(yes)) {
identified = true;
entityIdentified = "basic";
}
}
for (String no : YesNo.no) {
for (String w : words) {
if (w.equalsIgnoreCase(no) || question.equalsIgnoreCase(no)) {
identified = true;
entityIdentified = "basic";
}
}
}
}
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// the logic here will have to also be moved into the Firebase call
}
}
Note that, the parts that required the check on identified have all been moved to the onDataChanged method.
Please move your code written after getEntity()
Inside onDataChange() method. When onDataChange() completes it will execute added code. You will get latest values in variables.

Problem with Firebase adding a fab button cant delete entry

Currently a have a floating action bottom in my detailView in this activity I bring the information of the Object with an intent. I want that when the user enters the detailView activity I have a filled heart if that Automoviles objectId already exist in the Favorites Node.if not add the information into the Database. If the favorite already exist and it has the filled heart if the user clicks again it will remove it from the database.
This is my favorites class:
public class Favorites {
private String id;
private String automovilesId;
private String userId;
private String fecha;
public Favorites() {
}
public Favorites(String automovilesId, String userId, String fecha) {
this.automovilesId = automovilesId;
this.userId = userId;
this.fecha = fecha;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAutomovilesId() {
return automovilesId;
}
public void setAutomovilesId(String automovilesId) {
this.automovilesId = automovilesId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
}
At the moment i have this code:
databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference usersRef = rootRef.child("Favorites");
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
}
});
Which Leads this entry in the database:
Firebase Data
This is all good but i need to verify also if favorites exist or not in the database or else everytime i run the android emulator it will create another favorites node.
Now i added more code . But when i run it and i add this AddFavorite method it will create infinite loops of Favorite Nodes in the database
databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference usersRef = rootRef.child("Favorites");
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String car = ds.child("automovilesId").getValue(String.class);
Favorites fav =ds.getValue(Favorites.class);
String carId =fav.getAutomovilesId();
Log.i("No","Este es el nombre------>:"+carId);
String id=ds.getKey();
AddFavoritesuser();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
This is the AddFavorite method and the delete method:
private void AddFavoritesuser() {
favoritesButton.setImageResource(R.drawable.ic_favorite);
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
}
And the delete:
private void deleteFavoritesUser(String key) {
favoritesButton.setImageResource(R.drawable.ic_favorite_border);
databaseReference.child(key).getRef().removeValue();
}
In short i want it to verify if that object of Automoviles object exist . If it exist the user enters and sees the filled heart, if he wants to delete this favorite then he clicks again and it will run the deleteFavoritesUser method. But my question is what if Favorites is still no created in the database how can i also validate this?.
I runned the app again and I have the same vale created again:
As you can see I have the same automovilesId entry
basically you need to make your favorite button as a toggle button
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// in place of YES/NO you can take any values to present true/false state
boolean status = v.getTag() != null ? v.getTag().equals("YES") : false;
v.setTag(status ? "NO" : "YES");
if (status) {
// Do favorite me
//AddFavoritesuser();
} else {
// Do un favorite me
//deleteFavoritesUser(key);
}
}
}
everytime i run the android emulator it will create another favorites node.
This is happening because everytime you are trying to add a new object of Favorites class to the database, you are using the push() method, which generates a new random key everytime is called. This is what this method does. So in order to check a property from the database, you need to use in your reference the same key, not to generate another one. Please see in my answer from this post, where I have explained how you can achieve this.

How to check if the data in my child exists?

This is the code, and it doesn't check if the value in my editText exists.
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String title_val = mPostTitle.getText().toString().trim();
mDatabase2 = FirebaseDatabase.getInstance().getReference().child("Forums");
mDatabase2.child("title").child("KS1: "+title_val).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
String success = "Your title already exists...";
Toast.makeText(PostActivityKinderSection1.this, success, Toast.LENGTH_LONG).show();
mSubmitBtn.setEnabled(true);
}
else {
mSubmitBtn.setEnabled(false);
startPosting();
}
}
});
}
});
I want to avoid saving multiple times with the same title in my firebase.
You can not only check if title child exist, you have to iterate over all forums to find out if there is already one with title you want to save. You can do it like this:
final String title_val = "KS1: " + mPostTitle.getText().toString().trim();
mDatabase2 = FirebaseDatabase.getInstance().getReference().child("Forums");
mDatabase2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
void onDataChange(DataSnapshot forumsSnapshot) {
boolean isTitleAlreadyUsed = false;
for (DataSnapshot specificForum : forumsSnapshot.getChildren()) {
// Check if key 'title' exists and if title value is equal to value to save (title_val)
if (specificForum.hasChild("title") && (title_val.equals(specificForum.child("title").getValue()))){
isTitleAlreadyUsed = true;
}
}
if (isTitleAlreadyUsed) {
String success = "Your title already exists...";
Toast.makeText(PostActivityKinderSection1.this, success, Toast.LENGTH_LONG).show();
mSubmitBtn.setEnabled(true);
}
else {
mSubmitBtn.setEnabled(false);
startPosting();
}
}
}
If you have performance issue try to replace for-loop with while-loop, or use the title as child key in your db construction.

Categories