Firebase realtime database doesn't update database when i sign up - java

I am trying to send information to the firebase database, I am connected and already checked multiple times and i can't find the error here's my code
Here's the database reference command
everything is well put together and working, i don't exactly know why it doesn't really allow me to send information doesn't show any errors and everything
userInformation = FirebaseDatabase.getInstance().getReference("Users").child("Users");
firebaseAuth = FirebaseAuth.getInstance();
private void saveUserInformation(){
String UserName = NameET.getText().toString();
String Userbirthday = dateBirth.toString();
String Userdate_drivinglicense = dateLicense.toString();
String UserCountry = Countries.getSelectedItem().toString();
String UserGender = Genders.getSelectedItem().toString();
String HouseLocationLat = String.valueOf(location.getLatitude());
String HouseLocationLong = String.valueOf(location.getLongitude());
Userinformation userInfo = new Userinformation(UserName,Userbirthday,Userdate_drivinglicense,UserCountry,UserGender,HouseLocationLat,HouseLocationLong);
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
userInformation.child(user.getUid()).setValue(userInfo);
}
Toast.makeText(UserInformationActivity.this, "Saving Information", Toast.LENGTH_SHORT).show();
}

The Issue i had was that i didn't implent an Getter and Setter in my Java Class which is connected to the UserInformation, and i had to create a new child in the database with the name "Users" since it wasn't created automatically as it should be, also changed the names of variables in my
Userinformation userInfo = new Userinformation(UserName,Userbirthday,Userdate_drivinglicense,UserCountry,UserGender,HouseLocationLat,HouseLocationLong);
So it can connect to the database correctly Thanks for all the help :)

Related

documentRef.get() not executed, simply ignored and passed over

My app should retrieve for the user the single String field "itemList" of their FireStore db document (named after their userID) to a String variable "json"
structure of FireStore db
if (currentUser != null) {
Log.d(TAG, "userID = " + currentUser.getUid());
documentRef.get()
.addOnSuccessListener(documentSnapshot -> {
Log.d(TAG, "success");
json = documentSnapshot.getString("itemList");
})
.addOnFailureListener(e -> {
Log.d(TAG, "failure");
});
}
The first log prints the proper userID, so the connection and authentication with Firebase are made.
But documentRef.get() is never executed (none of its two logs is printed). "json" remains indeed null, though an inspection through Firebase Console shows "itemList" contains the String data it is supposed to.
documentRef is initiated as
FirebaseFirestore db;
DocumentReference documentRef;
db = FirebaseFirestore.getInstance();
documentRef = db.collection("Users").document(currentUser.getUid());
which is preceded by the authentication section:
FirebaseAuth auth;
FirebaseUser currentUser;
auth = FirebaseAuth.getInstance();
currentUser = auth.getCurrentUser();
And these are the FireStore security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /Users/{userID} {
allow create, read, write, delete : if request.auth.uid == userID;
}
}
}
So it looks like documentRef.get() is being entirely ignored. There are no error messages. Of course, futher down the road, when it starts to use "json", the app throws a nullPointerException, because "json" has remained null.
I tried on both a virtual device in Android Studio and a real phone.
What is wrong?
PS: writing String data to "itemList" with documentRef.set() was no problem, as confirmed through Firebase Console. It is actually this data the app is trying to retrieve.

mixed up data in firebase database data

I am new to firebase and Android programming in general. In my app I'm simply saving fullName, password, phoneNumber, Email, gender and a confirmed password. All these fields get stored in the database but their mixed up
Users
+23407066082195
email: '0000'
fullName: '+23407066082195'
gender: 'male'
password: 'k..gmail.com'
phoneNo: 'Tim...'
retypedPassword: '0000'
this is my code : for the first activity
btnSignUp = findViewById(R.id.btnSignUp);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!validateEdtName() | !validateEdtEmail() | !validatePhoneNumber() | !validateEdtPassword() | !validateEdtRePassword() | !validateGender()) {
return;
}
progressBar.setVisibility(View.VISIBLE);
selectedGender = findViewById(gender.getCheckedRadioButtonId());
String gender = selectedGender.getText().toString();
String myName = fullName.getEditableText().toString().trim();
String myEmail = email.getEditableText().toString().trim();
String myPassword = password.getEditableText().toString().trim();
String myRetypedPassword = retypedPassword.getEditableText().toString().trim();
String getUserEnteredPhoneNumber = phoneNumber.getEditableText().toString().trim();
String phoneNo = "+" + countryCodePicker.getFullNumber() + getUserEnteredPhoneNumber;
Intent intent = new Intent(SignUp.this, VerifyOTP.class);
intent.putExtra("PhoneNumber", phoneNo);
//intent.putExtra("fullName", fullName);
intent.putExtra("myName", myName);
intent.putExtra("myEmail", myEmail);
intent.putExtra("myPassword", myPassword);
intent.putExtra("myRetypedPassword", myRetypedPassword);
intent.putExtra("gender", gender);
startActivity(intent);
for the next activity: created a class to hold the strings which is the UserHelperClass
FirebaseDatabase rootNode = FirebaseDatabase.getInstance();
DatabaseReference reference = rootNode.getReference("Users");
UserHelperClass addNewUser = new UserHelperClass(fullName,phoneNo,password,email,retypedPassword,gender);
reference.child(phoneNo).setValue(addNewUser);
any suggestions will be helpful.
I analyzed your code. Either you haven't correctly initialized your EditTexts (maybe their ids aren't correct) or you haven't correctly implemented the constructor of UserHelperClass. Check both of them, you will probably see the bug.
P.S. I would encourage you to check Parcelable documentation. It is for sharing objects via intents.

How to retrieve the real name (Name and surname) of a Facebook profile that signed in with Firebase?

How can I retrieve the real first name and surname of a Facebook profile that logged in using the Firebase authentication?
mAuth = FirebaseAuth.getInstance();
fullNameTextView.setText(mAuth.getCurrentUser().getDisplayName());
userNameTextView.setText(mAuth.getCurrentUser().getDisplayName());
Picasso.get().load(mAuth.getCurrentUser().getPhotoUrl()).placeholder(R.drawable.ic_action_profile).into(profilePictureImageView);
That information doesn't exist in the FirebaseUser object. To solve this, you should first get the list of providers and find the one you are interested in. So please check the following lines of code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
List<? extends UserInfo> userInfoList = firebaseUser.getProviderData();
for (UserInfo userInfo : userInfoList) {
String providerId = userInfo.getProviderId();
if (providerId.equals(FacebookAuthProvider.PROVIDER_ID)) {
String name = userInfo.getDisplayName();
Log.d("TAG", name);
}
}
The result in the logcat will be the name of the user that has was authenticated using Facebook.

Accessing SQLite database values in an activity android

I am working on a book app and I save the book contents in SQLite database which I placed in my assets folder in Android Studio. But now I want to retrieve the values in the database in an activity in my app, but with the method I have seen online I can only retrieve one value from the database.
Please bear with me because I don't know if I'm properly explaining what I want but let me show the code so I can explain better.
listItem = new ArrayList<>();
database = new Database(this);
// song = String.valueOf(database.getChapter());
SQLiteDbHelper dbHelper = new SQLiteDbHelper(this);
dbHelper.openDatabase();
modelArrayList = dbHelper.getDetails();
adapter = new SongAdapter(modelArrayList);
chapFind = findViewById(R.id.chap_find);
chapGo = findViewById(R.id.chap_go);
String tokenID = FirebaseInstanceId.getInstance().getToken();
Model count = modelArrayList.get(0);
final String chap = String.valueOf(count.getIds());
Toast.makeText(MainActivity.this,chap,Toast.LENGTH_LONG).show();
mDatabasse = FirebaseDatabase.getInstance().getReference().child("Token");
chapGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String num = chapFind.getText().toString();
if (num.equals(chap)){
Toast.makeText(MainActivity.this,"very good!",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"very bad",Toast.LENGTH_LONG).show();
}
}
});
}
So what I am trying to do with this code - is to get user input of the chapter they would like to read. Then - check if that chapter exists in the database and if it does app will send user to another activity where it will fully display the content of that chapter

GreenDao getter for related entities returns empty list

I have an android app in which I use greenDAO to model my database. I have an easy scenario but I don't understand how I can make it work. I've followed the documentation but I must be missing something.
I have 3 entities: User, Picture and Address. A User has Pictures and Addresses. My getters for Picture and Address always return null.
userEntity.getPicture(); -> returns null
userEntity.getAddress(); -> returns null
Here is my GreenDAO setup
Entity userEntity = schema.addEntity("User");
userEntity.addIdProperty();
userEntity.addStringProperty("firstName");
userEntity.addStringProperty("lastName");
Entity picture = schema.addEntity("Picture");
picture.addIdProperty();
picture.addByteArrayProperty("image");
picture.addStringProperty("imageName");
Entity address = schema.addEntity("Address");
address.addIdProperty();
address.addStringProperty("street");
address.addIntProperty("houseNumber");
address.addIntProperty("zipcode");
address.addStringProperty("city");
// a user can have multiple pictures but a picture is connected to one user
Property pictureIdProperty = picture.addLongProperty("userId").getProperty();
picture.addToOne(userEntity, pictureIdProperty).setName("user");
userEntity.addToMany(picture, pictureIdProperty).setName("picture");
// a user can have multiple addresses but an address is only connected to one user
Property addressIdProperty = address.addLongProperty("userId").getProperty();
address.addToOne(userEntity, addressIdProperty).setName("user");
userEntity.addToMany(address, addressIdProperty).setName("address");
Here is my testclass to test the relations
DevOpenHelper helper = new DaoMaster.DevOpenHelper(getApplication(), "relation_test_db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
this.daoSession = daoMaster.newSession();
UserDao userDao = this.daoSession.getUserDao();
PictureDao pictureDao = this.daoSession.getPictureDao();
AddressDao addressDao = this.daoSession.getAddressDao();
// clear all data
userDao.deleteAll();
pictureDao.deleteAll();
addressDao.deleteAll();
/**
* create data
*/
User bill = new User(null);
bill.setFirstName("Bill");
bill.setLastName("Murray");
Picture billsPicture = new Picture(null);
billsPicture.setImage("BillsExamplePictureByteArray".getBytes());
billsPicture.setImageName("BillsPictureName");
Address billsAddress = new Address(null);
billsAddress.setStreet("BillsStreet");
billsAddress.setHouseNumber(42);
billsAddress.setZipcode(12345);
billsAddress.setCity("Wilmette");
billsPicture.setUser(bill);
billsAddress.setUser(bill);
userDao.insert(bill);
pictureDao.insert(billsPicture);
addressDao.insert(billsAddress);
User user = userDao.queryBuilder().list().get(0);
ArrayList<Picture> billsPictureList = (ArrayList<Picture>) user.getPicture();
ArrayList<Address> billsAddressList = (ArrayList<Address>) user.getAddress();
if (billsPictureList == null || billsPictureList.size() == 0) {
// contact Markus
Toast.makeText(this, "Contact Stackoverflow", Toast.LENGTH_SHORT).show();
return;
}
if (billsAddressList == null || billsAddressList.size() == 0) {
// contact Markus
Toast.makeText(this, "Contact Stackoverflow", Toast.LENGTH_SHORT).show();
return;
}
Emanuel,
I am facing some similar issues when trying to save objects with 1-to-1 relations.
After spending pretty enough time with greenDAO I have found, that all "relational" objects should have appropriate mapping IDs of their "parents" before being saved to DB.
So I may suggest, that if you take a look at setUser methods of your generated Picture and Address entities, you will see something like:
public void setUser(User user) {
synchronized (this) {
this.user = user;
userId = user == null ? null : user.getId();
user__resolvedKey = userId;
}
}
Crucial is userId = user == null ? null : user.getId();
There are race conditions, as your created User object will not get ID until it is actually saved to DB. And if it does not have ID, there is a chance, that setUser of its relational entities will not work normally.
In your case you may try to change save sequence to:
//1. Save user to DB, this will give it ID
userDao.insert(bill);
//2. Set user entity with ID to its relational entities
billsPicture.setUser(bill);
billsAddress.setUser(bill);
//3. Save relational entities
pictureDao.insert(billsPicture);
addressDao.insert(billsAddress);
Hope my answer will be helpful to you.

Categories