How to change firebase URL for FirebaseReference in Android Studio? - android

i'm working on Login and register activity using Firebase that requires me to strore data in realtime database. I setup the firebase realtime database location in South East Asia, and this is the supposed URL: https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/
and this is my code on writing Users data on the DB, after succesfully creating user using .createUserWithEmailAndPassword(email, password) ==>>
myRef = FirebaseDatabase.getInstance().getReference("Users");
String currUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
User user = new User(username, "default");
myRef.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
} else{
}
}
});
After debugging, i found that the process fails at myRef.setValue(user) because the URL set up for database reference is https://chatapp-5e8ce-default-rtdb.firebaseio.com/Users instead of https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/Users.
How do i set the URL so it match my firebase database location?

You can pass the URL to FirebaseDatabase.getInstance(), so:
myRef = FirebaseDatabase.getInstance("https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
You can also download an updated google-services.json, which will contain the correct string and replace the existing (incompletely) file in your Android Studio project with that.

Related

FirebaseRemoteConfig.fetchAndActivate() fails with 'TOO_MANY_REGISTRATIONS' for some users

My code uses Remote Config to check for app updates as follows:
ForceUpdateChecker.with(this).onUpdateNeeded(this).check();
final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// set in-app defaults
Map<String, Object> remoteConfigDefaults = new HashMap();
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_REQUIRED, false);
remoteConfigDefaults.put(ForceUpdateChecker.KEY_CURRENT_VERSION, "2.00.229");
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_URL,
"https://play.google.com/store/apps/details?id=com.chiaramail.pento");
firebaseRemoteConfig.setDefaultsAsync(remoteConfigDefaults);
firebaseRemoteConfig.fetchAndActivate() // fetch config from server and activate
.addOnCompleteListener(new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
Log.d(TAG, "FirebaseRemoteConfig fetched");
} else {
Log.d(TAG, "FirebaseRemoteConfig error:" + task.getResult());
}
}
});
Since I've updated the release containing this code, several users have crashed with the result 'TOO_MANY_REGISTRATIONS'. I believe I've looked at all the SO posts that relate to this problem, but none of them are using fetchAndActivate(). Also, I only have about 1200 users at this point, so hopefully the number of fetches isn't the problem; besides, as I understand it, Remote Config was built to push changes out to one's entire user base, so 1200 users (perhaps up to 6000 devices, max) should not be a problem.

Unable to add data to document in firestore (Android)

I'm trying to add data to a document to Firebase Firestore. I've added a collection named users to it. Also the read/write permissions are open for now. I'm following this doc. And I'm not able to add data to document.
Here is what I'm trying to do:
private void getNewUserSnapShot() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d(TAG, "getNewUserSnapShot: user_uid: " + user.getUid());
DocumentReference user_doc_ref = db.collection("users").document();
Log.d(TAG, "getNewUserSnapShot: document ref: " + user_doc_ref.getId());
Map<String, Object> user_data = new HashMap<>();
user_data.put("name", user.getDisplayName());
user_data.put("email", user.getEmail());
user_data.put("profile_url", user.getPhotoUrl());
Log.d(TAG, "getNewUserSnapShot: user_data: " + user_data.toString());
user_doc_ref
.set(user_data)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(LoginActivity.this, task.toString(), Toast.LENGTH_LONG).show();
if (task.isSuccessful()) {
Log.d(TAG, "getNewUserSnapShot: success");
} else {
Log.d(TAG, "getNewUserSnapShot: failed");
}
}
});
}
In Logs I see only these (neither the log for failure nor for success):
2020-03-04 19:48:47.489 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: user_uid: iXOzfju6kORnhuUND8zFCPTzxY93
2020-03-04 19:48:47.499 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: document ref: 7AluPzcYMLzDKLh8YtBt
2020-03-04 19:48:47.499 30744-30744/com.example.expenditure D/LoginActivity: getNewUserSnapShot: user_data: {profile_url=https://someurl/security/reasons, name=Nikhil Wagh, email=null}
And when I see firebase console, I can't find the document with ID 7AluPzcYMLzDKLh8YtBt, according to logs which should have been created.
There is a similar question: Unable to add information to Cloud Firestore But it doesn't have right answers.
Can someone help. What am I doing wrong?
The issue was user.getPhotoUrl() returns url, but Firestore doesn't support urls. The url needs to be casted as a string, and then it works.
Cast your urls to string before adding data to Firestore.

Get old data from firebase when local user is deleted

Im working on a android app with email-password login.
The user is created in a local sqlite db and in firebase + auth.
Situation: The user uninstalls the app, the local db is deleted. Then the user re-installs the app and wants to login using old credentials, But the user does not exist locally thus the app tries to create a new. - but the user already exist remote in my firebase users table + auth.
Question: How do I query either firebase auth or firebase for the user info only using email, pass and perhaps a few extras.
Most answers I found refer to using the update event from firebase, but at this point it´s not possible as the user is not yet authenticated
I solved it myself.
It was simple and not at all. A part of my fix is below. But in short. I get the user from firebase, then make an update to firebase and then I restore the user in a addValueEventListener(new ValueEventListener()
_fbAuth.signInWithEmailAndPassword(_email, _password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Firebase login success");
FirebaseUser fbUser = _fbAuth.getCurrentUser();
String uid = fbUser.getUid();
FireBaseWriteHelper wh = new FireBaseWriteHelper();
FireBaseReadHelper fireBaseReadHelper = new FireBaseReadHelper(getApplicationContext(), uid, Util.VERSION_KEY_FREE);
DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
Date date = new Date();
wh.UpdateUserLastLogIn(uid, format.format(date));
_user = _userHelper.CheckUserExist(_email, _password);
mPasswordView.setError(null);
mEmailView.setError(null);
} else {
try {
throw task.getException();
} catch (FirebaseAuthInvalidUserException e) {
} catch (FirebaseAuthInvalidCredentialsException e) {
} catch (FirebaseNetworkException e) {
} catch (Exception e) {
}
}
}
});
You can use the Firebase in Offline mode. You don't need to use two databases. Guide here.

Using Firebase return an image that is linked to a user account

I am currently working on an app using android studio and currently have a working login using Firebase user authentication. However, I am trying to have an image appear on the screen when the user logs after using this authentication. I want this image to be linked to that specific user. Is this possible?
You can set a photo url on a user's firebase profile with the following code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Jane Q. User")
.setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
You would then retrieve the user's profile information (including their photo URL) like so:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();
// 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.getToken() instead.
String uid = user.getUid();
}
More info: https://firebase.google.com/docs/auth/android/manage-users
If you're using oAuth authentication and want to retrieve their profile photo from facebook, you'll find more information about how to do that at the link below:
https://firebase.google.com/docs/auth/android/facebook-login

Android app not able to post data on firebase

i have an android app which need to post data on firebase. It work perfectly when i test it with my development device.
when i publish it on store and my friend want to post data on same firebase account --- it not work --- no error message -- no crash --- just no data on server.
I need to ask that free plan of firebase works in such scenario with published app on Google store ? or i need to upgrade it with paid plan.
My code is below:
Firebase ref = new Firebase(my_URL);
String uniqueID = UUID.randomUUID().toString();
String date = Utility.getDateTime();
Firebase jobchild = ref.child(projectId);
jobchild.setValue(uniqueID);
Firebase jimages = jobchild.child("ProjectId");
jimages.setValue(projectId);
Firebase jdate = jobchild.child("LogDate");
jdate.setValue(date);
When I put your code into an Android app, it works fine for me:
Firebase.setAndroidContext(this);
Firebase ref = new Firebase("https://stackoverflow.firebaseio.com/32319324");
// Ensure we start out with no data at this location
ref.removeValue();
// Monitor the location and output any data there to a text view
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
TextView output = (TextView) Activity32319324.this.findViewById(R.id.content_32319324);
for (DataSnapshot project: snapshot.getChildren()) {
output.setText(
"key="+project.getKey() + "\n" +
"LogDate="+project.child("LogDate").getValue() + "\n" +
"ProjectId="+project.child("ProjectId").getValue()+"\n\n"
);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) { }
});
// Write data to the location
String projectId = "42";
String uniqueID = UUID.randomUUID().toString();
String date = new Date().toString(); //Utility.getDateTime();
Firebase jobchild = ref.child(projectId);
jobchild.setValue(uniqueID);
Firebase jimages = jobchild.child("ProjectId");
jimages.setValue(projectId);
Firebase jdate = jobchild.child("LogDate");
jdate.setValue(date);
See the app here: https://github.com/puf/firebase-stackoverflow-android (your code is in Activity32319324)

Categories

Resources