Unable to mark post's as favorites - android

Hello everyone I am making an android application with the help of Firebase. The application is working fine but ever since I tried to add the functionality of a favorite button, I am unable to get the bug out of that "add favorite" part of the code.
current_state="not av"
The above part states the current favorite state of the user.
The below code is for "add favorite" part.
Holder.mFavourites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (current_state.equals("not fav")){
mFav.child(puid).child(kk).child("fav_status").setValue("Added as " +
"fav").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Holder.mFavourites.setImageDrawable(getContext().getDrawable(R.drawable.ic_star_black));
current_state = "fav";
Toast.makeText(getContext(),"Added to favourites",Toast
.LENGTH_SHORT).show();
}
});
}else if (current_state.equals("fav")){
mFav.child(puid).child(kk).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Holder.mFavourites.setImageDrawable(getContext().getDrawable(R.drawable.ic_star_border_black_24dp));
current_state = "not fav";
Toast.makeText(getContext(),"Removed from favourites",Toast
.LENGTH_SHORT).show();
}
}
});
}
}
});
I am getting a problem with the above code-
1. Whenever the first time user click on the code. He gets added to favourite and if he click again on the same button then he is removed from the favourites, but if the user after clicking once (i.e. after getting added as favourites)goes on and click on the add to fav button again,then the toast of removed from favorites appears regardless of whether the user is in favorites database or not.

Is current_state a class variable that equals "not fav"? Cause it looks like your if statement is just reading a string and doesnt actually know whats going on in the database. What if you query all the favs into an arraylist and test your if statement against the arraylist

Related

how to update recyclerview when delete an item from adapter class

everyone, I am working with recycler view in android and I'm getting data from firebase. The problem is when I press the delete button data is deleted from firebase but in the application new list is added with the old list but I want to show only the new list which does not change the position of the recycler view only remove that item. I'm doing this all in the adapter class.
final DatabaseReference referencePost = database.getReference().child("Posts").child(holder.postId);
referencePost.setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Toast.makeText(holder.itemView.getContext(), "" + Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
});
After making sure that the deletion process from Firebase is complete, you can add this line:
.
.
//Successfully Deleted
notifyDataSetChanged ();
You can read about it more than this.

Firebase: How to make one app hides button for another app

I have 2 android apps connected to the same Firebase database, and I want to add a button in the first app to hide another button in the inside the second app.
This is my code on the first app which hides 'btnact' depending on the status of the settings in Remote Config of Firebase:
myconfiguration=FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configuratonsettings = new FirebaseRemoteConfigSettings.Builder().build();
myconfiguration.setConfigSettings(configuratonsettings);
Map<String,Object> defaultvalues = new HashMap<>();
defaultvalues.put("btn_enable",false);
myconfiguration.setDefaults(defaultvalues);
fetcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myconfiguration.fetch(0).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
myconfiguration.activateFetched();
btnact.setEnabled(myconfiguration.getBoolean("btn_enable"));
}
else
{
Toast.makeText(MainActivity.this, "Something went Wrong\nPlease try again", Toast.LENGTH_SHORT).show();
}
}
});
}
});
I want a way to change this 'btnact' to the id of the button of the other app.. Can anyone have a clue for it?
You can fetch the value of the button you want to hide (boolean value: false or true) inside your second app, then set that button visibility to invisible or gone based on the fetched boolean value.
You can change the value that controls your second app's enabled status/visibility inside your first app.
I don't test this right now, but I think it should work and it is easy to accomplish what you want.

Random document that doesnt exist in firestore gets selected on android and deleted

I am trying to delete a document from Firestore. I am trying to do this based on the task ID that was randomly generated by Firestone. when a particular task is selected on android, I want to be able to delete that task. However, when I tried debugging the code, it shows a random ID that doesn't exist on the database and tries to delete that, sending me a success message in the console. I am not sure where I am going wrong. Please advice.
public void deleteTasks(View v) {
userId = mFirebaseAuth.getCurrentUser().getUid();
String tskid= fStore.collection("usersData").document(userId).collection("tasks").document().getId();
DocumentReference taskref = fStore.collection("usersData").document(userId).collection("tasks").document(tskid);
taskref.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("tag", "Task Deleted Successfully");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "Task Deletion Unsuccessful");
}
});
}
the above delete method is called on the button using android:OnClick
The Task I'd like to delete is Circled
When you are using the following line of code:
String tskid= fStore.collection("usersData").document(userId)
.collection("tasks").document()
.getId();
You are generating a new random ID. Actully, you are reserving a key for a document that you'll be writing in the future. When using this line:
DocumentReference taskref = fStore.collection("usersData").document(userId)
.collection("tasks").document(tskid);
You are creating a reference to that location. However, when using this line:
taskref.delete().addOnCompleteListener(/* ... */);
You are trying to delete a document that does not exist and this is because you didn't create it in the first place. If you need to delete a specific document, you need to know the ID. So the following lines of code will do the trick:
public void deleteTasks(View v) {
userId = mFirebaseAuth.getCurrentUser().getUid();
String tskid = "CQ45RKh8Ohd6DXjSQ8RO";
DocumentReference taskref = fStore.collection("usersData").document(userId)
.collection("tasks").document(tskid);
taskref.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("tag", "Task Deleted Successfully");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "Task Deletion Unsuccessful");
}
});
}
In order to delete that document, I have used the exact same ID that exists in the database.

Firebase User always initialized to null in oncreate

Firebase user.currentuser() is always null in oncreate. I want to implement this access controll so that only a user called a credit controller can add items to the recyclerview using the floating action button, while other users can only see the items added.
I want the floating action button's visibility to be determined as soon as the activity is open. Is there any other way to achieve this?
I used the reveal button to achieve this but it's a very bad user experience to click it every time you want to go into this activity.
This is my code below:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collections);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
userEmail = user.getEmail();
FloatingActionButton buttonAddNote = findViewById(R.id.button_add_note);
Button revealButton = findViewById(R.id.revealButton);
revealButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(userEmail.equals("creditcontroller#outlook.com")){
buttonAddNote.setVisibility(View.VISIBLE);
revealButton.setVisibility(View.GONE);
}
else revealButton.setVisibility(View.GONE);
}
});
buttonAddNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CollectionsActivity.this, AddEditNoteActivity.class);
intent.putExtra("USER_EMAIL", userEmail);
startActivityForResult(intent, ADD_NOTE_REQUEST);
}
});
Unfortunately I can't upload images yet but the reveal button is just a button that's centered in the activity. Upon clicking it its visibility is set to gone and everything else is set to visible
The code is working but the user experience is pretty bad.
Firebase calls are asynchronous which means that you can't get results instantly.
You should add a callback to your calls.
FirebaseUser user = firebaseAuth.getCurrentUser();
userEmail = user.getEmail();
database.child(userEmail).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
Log.d(TAG, "email: " + email);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
The code is just an example. It may not work in your case, because you must know the structure of your nodes.
You can read more in the Firebase documentation: https://firebase.google.com/docs/database/android/read-and-write

Firebase SignUp always gives an error

i am implementing Fire-Base Authentication in my app, With SignUp and SignIn, however i am having a problem, every time i fill the form and click on the SignUp button the Fire-Base gives back an error even though the account was successfully created. My code for the SignUp method:
public class Signup extends AppCompatActivity {
EditText input_email,input_pass;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//View
input_email = (EditText)findViewById(R.id.id_email);
input_pass = (EditText)findViewById(R.id.id_pass);
//Init Firebase
auth = FirebaseAuth.getInstance();
}
public void iLogin (View v){
startActivity(new Intent(Signup.this, Login.class));
finish();
}
public void iForgot(View v){
//startActivity(new Intent(Signup.this, ForgotPassword.class));
finish();
}
public void iSignUp(View v){
signUpUser(input_email.getText().toString(),input_pass.getText().toString());
}
private void signUpUser(String email, String password) {
auth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(Signup.this, "Successfully created your account", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Signup.this, "ERROR has occurred", Toast.LENGTH_LONG).show();
}
}
});
}
}
So what happens is:
1- The user Opens the app for the first time, the app opens mainly on the MainActivity.class which then redirects the user to the SignUp.class (The one i have added above).
2- The user then fills two fields: (Email) and (Password) and clicks on the SignUp button
3- The SignUp.class (The one i have added above) then creates a new account and shows the Toast: ERROR has occurred, even though the account has been created successfully. In order for the class to display the correct Toast (Successfully created your account) i need to press on the button a second time.
So just to be clear: The first time you click, the account is created and i can see it in Fire-Base Console but the app still gives the wrong Toast, for it to show the correct one i need to click it again, Any thoughts on what's wrong with the code? Thanks in advance!
Just change:
if(!task.isSuccessful())
to:
if(task.isSuccessful())
and it should work. There is a success when task.isSuccessful() is true, so the ! sign make it false. That's why it works for the second time.

Categories

Resources