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.
Related
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.
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.
I created tabbed activity for my project. I have three tabs which are Paid , Unpaid and Item Posted
I want to classify every of them based on the status. I have created the coding but I'm not sure on how to implement the method inside my coding. I want only order that have "PAID" as their status will be shown up inside my PaidFrag.
PaidFrag:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ds : orderSnapshot.getChildren()) {
Order order = ds.getValue(Order.class);
if (order.getStatus().equals("UNPAID")) ;
orderList.add(ds.getValue(Order.class));
}
}
psOrderAdapter PsOrderAdapter = new psOrderAdapter(orderList);
recyclerView.setAdapter(PsOrderAdapter);
}
}
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.name.setText("Name : " + orderList.get(i).getName());
myViewHolder.status.setText("Status : " + orderList.get(i).getStatus());
myViewHolder.total.setText("Total Price : RM " + orderList.get(i).getTotal());
myViewHolder.address.setText("Address : " + orderList.get(i).getAddress());
myViewHolder.dateTime.setText("Order ID :" + orderList.get(i).getOrder_id());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cust_id = orderList.get(i).getCust_id();
String oid = orderList.get(i).getOrder_id();
String status = orderList.get(i).getStatus();
String courier = orderList.get(i).getCourier();
String track = orderList.get(i).getTrackingNum();
String num = orderList.get(i).getPhone();
Intent intent = new Intent(context, updateStatus.class);
intent.putExtra("cust_id",cust_id);
intent.putExtra("order_id",oid);
intent.putExtra("status",status);
intent.putExtra("courier", courier);
intent.putExtra("trackingNum",track);
intent.putExtra("phone",num);
context.startActivity(intent);
}
});
It sounds like you're looking for a Firebase Database query, which limits what nodes are returns from the database:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
Query query = databaseReference.orderByChild("status").equalTo("PAID");
query.addValueEventListener(new ValueEventListener() {
...
You'll need to make sure that the status and PAID strings match the exact key and value that you have in your database.
For more on this, see the Firebase documentation on ordering and filtering data.
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) {
}
});
}
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.