How can I get child value with if & else condition (Firebase,SDK) - firebase

I am having trouble with my codes. What I want to do in my Login page is log as admin using email/password and when "role" is equal to admin (the other role is Guest). The admin page is MainActivity.class and the Guest page is Home.class. Can someone help me :)
And here is my code:
private void onAuthSuccess(FirebaseUser user) {
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String role = ds.getKey();
DatabaseReference userKeyDatabase = FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot == null) {
Toast.makeText(getApplicationContext(), "****NULLL****", Toast.LENGTH_LONG).show();
} else if(dataSnapshot.child("role").getValue().equals("Admin")) {
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}else{
startActivity(new Intent(SignInActivity.this, Home.class));
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userKeyDatabase.addListenerForSingleValueEvent(eventListener);
}}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
}
I am not sure about my code as well :(

To check role of users login you can do something like this
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference db=firebaseDatabase.getReference().child("users");
db.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists()){
Log.d("user exits","usere hai");
String value =dataSnapshot.child("role").getValue().toString();
if(value.equals("Admin") && value != null){
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}else{
startActivity(new Intent(SignInActivity.this, Home.class));
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});

Related

OnDataChange not fire up

Hey I try to use addValueEventListener
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Phone");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()){
if(snapshot1.getValue()==phone){
Toast.makeText(LoginActivity.this, "seeee"
, Toast.LENGTH_LONG); }
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
when I try to debug this the onDataChange method is not firing up
instead is goes out from addValueEventListener
Can anyone know how to fix this ?

How to rewrite the following code since the FirebaseInstanceId() is deprecated?

The code was found from a Youtube tutorial called realtime location firebase and it's important for my Final Year Project. I appreciate all the help that i could get. Thanks in advance.
private void updateToken(FirebaseUser firebaseUser) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.TOKENS);
//Get Token
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
tokens.child(firebaseUser.getUid()).setValue(instanceIdResult.getToken());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void updateToken(FirebaseUser firebaseUser) {
DatabaseReference tokens = FirebaseDatabase.getInstance()
.getReference(Common.TOKENS);
FirebaseInstallations.getInstance().getId()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
tokens.child(firebaseUser.getUid())
.setValue(task.getResult());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
also try some dependencies in build.gradle(:app)
implementation platform('com.google.firebase:firebase-bom:26.8.0')
implementation 'com.google.firebase:firebase-database'

how to delete a node from firebase

I am developing an android project with firebase. and now I want to delete a node on clicking on a button. but this error occurred and I can not solve it. I want to delete the node of 1589445758397. as I press the delete button all posts in the node post start deleting one by one and then the upper node with name Posts delete. please help me to solve it.
here's my code-
private void deletePostsWithImages(final String pId, String pImage) {
////////////////////////////
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Deleting Post");
progressDialog.setMessage("Please wait...");
progressDialog.show();
/////////////////////
StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(pImage);
picRef.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Query fQuery = FirebaseDatabase.getInstance().getReference("Posts")
.orderByChild("pId").equalTo(pId);
fQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void deletePostsWithoutImages(final String pId) {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Deleting Post");
progressDialog.setMessage("Please wait...");
progressDialog.show();
Query fQuery = FirebaseDatabase.getInstance().getReference("Posts")
.orderByChild("pId").equalTo(pId);
fQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/r7nrI.png
Instead of:
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
try:
dataSnapshot.setValue(null);
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
If you want to remove some specific node and you have the ID of the node then why are you listening and looping?
Just point to the node and remove it:
private void deletePostsWithoutImages(final String pId) {
.......
.......
//point to the node
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts").child(pId);
//remove that node
ref.removeValue();
........
}

Retrieving images from firebase storage

I have uploaded some photos to firebase storage, and I need to connect each of those images with a document in my Cloud Firestore and then show them in my recyclerView. Do i get the url of each image, and add a field "image" to each of the documents in the firestore and use the url as a value? And then how do I put them in my RecyclerView?
I have successfully retrieved other data from the Firestore, using FirestoreUI, however I'm not sure how to do the same for images.
RecyclerViewAdapter Class
public class FirebaseRecyclerViewAdapter extends
FirestoreRecyclerAdapter<Buildings,
FirebaseRecyclerViewAdapter.FirebaseRecyclerViewHolder> {
public FirebaseRecyclerViewAdapter(FirestoreRecyclerOptions<Buildings>
options) {
super(options);
}
#Override
protected void onBindViewHolder(FirebaseRecyclerViewHolder holder, int
position, Buildings model) {
holder.textViewName.setText(model.getName());
}
#NonNull
#Override
public FirebaseRecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate
(R.layout.buildings_row_item, parent, false);
return new FirebaseRecyclerViewHolder(v);
}
class FirebaseRecyclerViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
public FirebaseRecyclerViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
}
}
}
MainActivity Class
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference buildingRef = db.collection("Building");
StorageReference storageReference =
FirebaseStorage.getInstance().getReference();
private FirebaseRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_2);
setUpRecyclerView();
getSupportActionBar().hide();
}
private void setUpRecyclerView() {
Query query = buildingRef.orderBy("name", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Buildings> options = new
FirestoreRecyclerOptions.Builder<Buildings>()
.setQuery(query, Buildings.class)
.build();
adapter = new FirebaseRecyclerViewAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
first of all, you need to upload the image you want to the Firestore Storage using
StorageReference
then you have to save the URL using
getDownloadUrl()
Next Step is to save the URL into field in the document and here an Example
upload the image
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context, "Upload successful", Toast.LENGTH_LONG).show();
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
image=new Images(mID+"",Objects.requireNonNull( uri.toString()));
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Upload Failed", Toast.LENGTH_LONG).show();
}
});
}
}
)
.addOnFailureListener(e ->
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show())
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(context, "Uploading...", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(context, "No file selected", Toast.LENGTH_SHORT).show();
}
}
save the URL to Firestore document
if(!TextUtils.isEmpty(image.getmImageUrl()))
mProperty = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking,Objects.requireNonNull(image.getmImageUrl()));
else
mProperty = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking);
db.collection("Property").document(mProperty.getmID() + "").set(mProperty)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(context, "done",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(context, "Failed",
Toast.LENGTH_SHORT).show();
}
});
boolean flag;
} else {
mError.setText("Empty Fields");
mError.setVisibility(View.VISIBLE);
}
i am using a model to insert data into firestore you should do that too
and in RecyclerAdapter you can bind the image to the Recyclerview using either Picasso or Bitmap
Picasso.get().load(model.getmImageDrawable()).
fit().placeholder(R.drawable.placeholder_image).
error(R.drawable.no_img).into(holder.mImage)

Google Play Games Login with Firebase notworking

Hello here is my code for my App, and I try to login via Google Play Games, but it doesn't work. I hope you can tell me some solutions. I have Google Login working, on another activity but Play Games Login won't work.
public class start extends AppCompatActivity implements
View.OnClickListener{
private static final String TAG = "StartActivity";
GoogleApiClient mGoogleApiClient;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private AdView mAdview;
private InterstitialAd interstitialAd;
private FirebaseAnalytics mFirebaseAnalytics;
private ProgressDialog loadingBar;
private Status statusTextView;
TextView LoginUserName, LoginUserEmail;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
private Button LogOutBtn;
private Button playgames;
private TextView mStatusTextView;
private TextView mDetailTextView;
private TextView mPlayername;
private boolean mResolvingConnectionFailure = false;
private boolean mAutoStartSignInflow = true;
private boolean mSignInClicked = false;
private final static int RC_SIGN_IN = 9001;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseUser currentUser = mAuth.getCurrentUser();
signInSilently();
mGoogleApiClient.connect();
updateUI(currentUser);
}
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
LogOutBtn = findViewById(R.id.logout);
mAuth = FirebaseAuth.getInstance();
mStatusTextView = findViewById(R.id.status);
mDetailTextView = findViewById(R.id.detail);
mPlayername = findViewById(R.id.mPlayername);
playgames = findViewById(R.id.playgames);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
LogOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(start.this, SignIn.class));
}
});
playgames.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSignInIntent();
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
.requestServerAuthCode(XXXXXX)
.requestEmail()
.requestProfile()
.requestIdToken(XXXXXX)
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(start.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//End of Authentification
}
// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());
AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(start.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
// The signed in account is stored in the task's result.
GoogleSignInAccount signedInAccount = task.getResult();
firebaseAuthWithPlayGames(signedInAccount);
} else {
// Player will need to sign-in explicitly using via UI
Toast.makeText(start.this, "Cannot Connect", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
firebaseAuthWithPlayGames(signedInAccount);
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
Toast.makeText(start.this, "Cannot Connect 1", Toast.LENGTH_SHORT).show();
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
private void updateUI(FirebaseUser user) {
if (user != null) {
String playerName = user.getDisplayName();
mPlayername.setText(playerName);
// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.logout:
startActivity(new Intent(start.this, SignIn.class));
break;
case R.id.playgames:
startSignInIntent();
break;
// ...
}
}
}
I really hope someone has a working example, or can help me here, cause I'm stuck at this code for a month now.

Resources