Logcat error when radio button is clicked - android

My app is crashing when this button is clicked. I think it is something with my variable declaration of balance and amount. Balance is stored in my user model as double balance. I am not sure what is causing the error exactly as the code has no errors.
else if (rdiAccountBalance.isChecked()) {
Double amount = 0.0;
amount.valueOf(textTotalPrice.toString());
if (Common.currentUser.getBalance() >= amount) {
Request request = new Request(
Common.currentUser.getPhone(),
Common.currentUser.getName(),
editAddress.getText().toString(),
textTotalPrice.getText().toString(),
"0",
"Paid",
"Account Balance",
cart
);
//Submit to Firebase
//We will using System.CurrentMills to key
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//Delete cart
new Database(getBaseContext()).cleanCart();
//update balance
Double balance = Common.currentUser.getBalance() - amount;
Map<String, Object> update_balance = new HashMap<>();
update_balance.put("balance", balance);
FirebaseDatabase.getInstance()
.getReference("User")
.child(Common.currentUser.getPhone())
.updateChildren(update_balance)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
FirebaseDatabase.getInstance()
.getReference("User")
.child(Common.currentUser.getPhone())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
;
});
Toast.makeText(Cart.this, "Thank you, Order Place.", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(Cart.this, "Your account balance is not sufficient", Toast.LENGTH_SHORT).show();
}
This is the logcat error I am getting. I think it could be the variable declaration.
2020-01-30 11:56:15.100 3255-3749/? E/DatabaseUtils: Writing exception to parcel
java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings.
at com.android.providers.settings.SettingsProvider.warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(SettingsProvider.java:2105)
at com.android.providers.settings.SettingsProvider.enforceRestrictedSystemSettingsMutationForCallingPackage(SettingsProvider.java:1858)
at com.android.providers.settings.SettingsProvider.mutateSystemSetting(SettingsProvider.java:1662)
at com.android.providers.settings.SettingsProvider.insertSystemSetting(SettingsProvider.java:1607)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:549)
at android.content.ContentProvider$Transport.call(ContentProvider.java:403)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:272)
at android.os.Binder.execTransact(Binder.java:739)

Related

how to stop slash from splitting the firebase database child

I am working on an App that allows the student to register using their registration number. the registration number is like 17/csc/001 till infinity. The student registration number will saved as a child of that firebase reference but the issue I am having is that firebase splits the registration number into three places due to the slash that's found there. I need help on how to resolve it because there's no how a student's registration number will be without the slash.
I need something like this "Registration Numbers","17/csc/001" but I am having this
"Registration Numbers": {
"17": {
"CSC": {
"001": {
"registrationNumber": "17/CSC/001"
}
}
}
}
void addRegistrationNumber(){
progressBar.setVisibility(View.VISIBLE);
String regNumber = editText.getText().toString();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child("Registration Numbers").child(regNumber).exists()){
progressBar.setVisibility(View.GONE);
showMessage("Error","You have Already Added this Registration Number");
}else {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("registrationNumber",regNumber);
databaseReference.child("Registration Numbers").child(regNumber).updateChildren(hashMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Registration Number Added Successfully", Toast.LENGTH_SHORT).show();
}else {
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Error Occurred, Please try Again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AdminAddOrRemoveARegistrationNumberActivity.this, "Database error "+error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
The / character is not allowed to be present in keys in the Firebase Realtime Database. So there's no way for you to include them in the keys.
What you'll want to do instead is to encode the / values in your student registration numbers, with a value that can't occur in those numbers but is allowed in the database keys. For example, if _ can't occur in your student registration numbers, then you could encode 17/csc/001 as 17_csc_001.

checking if a user is in a specific child for login firebase

I am making an android application using Firebase database and I want to check that the user is not in registered as an "Association" so I am checking if he belongs to the child "Association".
The method userLogin is supposed to not log in the user if he is under the child "Associations" and log in him otherwise.
However, it is not working and the user is logged in even if he is under "Associations"
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I did not tried this, but it should work, first, after you log in with a user and enters inside task.isSuccessful , you can retrieve the current logged in user with task.getResult().getUser().getUid(). Then just loop inside Associations and get each user key (I assume that Associations has userIDs inside as nodes with a certain value), then compare if the current logged in user is equal to one inside that node, if matchs it will pop up your Toast, if not you will be redirected.
Try this
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations");
jLoginDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals(task.getResult().getUser().getUid()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
I used addListenerForSingleValueEvent because we only need to loop once at the reference and not keep listening for data

How to check child in firebase database?

i need to avoid duplication of data in the table.
when ever a new user add some information to the database if the "category" field data is present then need to show this data is already present in the database.
if(!group_link.isEmpty()&&!group_name.isEmpty()&&e2.length()<=50 && e2.length()>=40&&(e2.getText().toString().contains("https://chat.whatsapp.com/"))) {
HashMap<String, String> datamap = new HashMap<String, String>();
datamap.put("category", selected_item);
datamap.put("group_name", group_name);
datamap.put("group_link", group_link);
datamap.put("group_type",group_type);
datamap.put("language",language);
datamap.put("report_status",count);
mref.push().setValue(datamap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Usr_add.this, "Data Submited successfully :) ", Toast.LENGTH_SHORT).show();
e1.setText("");
e2.setText("");
} else
Toast.makeText(Usr_add.this, "Something Wrong :( ", Toast.LENGTH_SHORT).show();
}
});
}
i need to check if category data field is present or not.
DatabaseReference rf = FirebaseDatabase.getInstance().getReference();
DatabaseReference retrieve =
rf.child("type").child("Whatsapp").child("Shopping deals");
retrieve.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot getdata : dataSnapshot.getChildren()){
if (getdata.child("category").exists()) {
Toast.makeText(this,"Stop it exists!!!",Toast.LENGTH_SHORT).show();
}}else{
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First you query on shopping deals, since there is a random key there you have to a for loop to be able to reach the name:value. Then using the exists() you can see if any attribute exists in your firebase database. In this case we are checking if category exists by using child("category")
If it exists then add a Toast to the user or watever you want.. if it does not exist then maybe add it to the database using setValue()

How to retrieve parent key in firebase android

I want to retrieve houfxWvbwyVmbHX60IGjpNkZR9w2 key , How to do?
Here is the code for the same
mQuery = mfollowing.orderByChild("following").equalTo(user_id);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String key = dataSnapshot.getKey();
mdatabaseUsers.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DatabaseReference newfollscreen = mdatabaseFollwer.child(key).child(newPost.getKey());
newfollscreen.child("screen").setValue(downloadUrl.toString());
newfollscreen.child("engagement").setValue("NA");
newfollscreen.child("url").setValue("NA");
newfollscreen.child("uid").setValue(user_id);
newfollscreen.child("name").setValue(dataSnapshot.child("name").getValue());
newfollscreen.child("image").setValue(dataSnapshot.child("image").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(AddimageActivity.this, "Posted among your followers", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(AddimageActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled (DatabaseError
databaseError){
}
});
Here is the Firebase database
second image
enter image description here
I tried using child data snapshot method but did not worked. Any help for this will be much appreciated.
Assuming you have a DataSnapshot that points to the children rhZ4...wt2, you can call snapsthot.getRef().toString() which will return you something like https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2. From there you can extract the parent key.
From your example, after you query the database using mQuery, inside onDataChange you have a DataSnapshot.
So calling dataSnapshot.getRef().toString() will give you https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2/following.
Code to extract the parent key (put it inside your 1st onDataChange):
String reference = dataSnapshot.getRef().toString();
String[] tokens = reference.split("/");
String parentKey = tokens[tokens.length - 3];
This parentKey should be your houfxWvbwyVmbHX60IGjpNkZR9w2.

How to search if a username exist in the given firebase database?

{
users:
{
apple:
{
username : apple
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
This is what I am doing
CREATING USER if checkUsername method returns 0
if(checkFirebaseForUsername(username)==0) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getBaseContext(),"inside",Toast.LENGTH_LONG).show();
User newUser = new User();
newUser.setUserId(mAuth.getCurrentUser().getUid());
newUser.setUsername(username);
newUser.setEmailId(email);
try{
mRef.child("users").child(username).setValue(newUser);
}
catch(Exception e){
Toast.makeText(SignUpActivity.this,"error while inserting",Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_success)
.setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
My checkUsername method -
public int checkFirebaseForUsername(String passedUsername){
final int[] flag = {0};
final String myPassedUsername = passedUsername;
Log.e("tag","working now");
//flag[0]=1;
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child("users").child(passedUsername).addChildEventListener(new ChildEventListener() {
#Override
public void onDataChanged(DataSnapshot dataSnapshot) {
Log.e("tag","checking");
if(dataSnapshot.exists()){
Log.e("tag","exists");
flag[0]=1;
}
}
#Override
public void onCancelled(DataSnapshot datasnapshot){
}
});
if(flag[0]==1)
return 1;
else
return 0;
}
This is how I am inserting users in my firebase-database and I want to check if a username is available for a new user or not.
Therefore I need to check is there any user already registered with that username....Please help I have already tried whatever I could understand after reffering to documentation provided on the official firebase blog but all in vain!!
EDIT: New answer, old one still below.
I would get rid of your method "checkFirebaseForUsername" because it will always return 0, no matter what.
What you need to do is this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
// Let the user know he needs to pick another username.
} else {
// User does not exist. NOW call createUserWithEmailAndPassword
mAuth.createUserWithPassword(...);
// Your previous code here.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Old Answer:
{
users:
{
apple[X]:
{
username : apple[Y]
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
If for example, the node apple[X] will always have the same name as the child property "username":apple[Y], then it is as simple as this.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
} else {
// "username" does not exist yet.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
however, if say, the node apple[X] can have a different value than the property apple[Y], and you want to see if any node exists where the "username" property is the same, then you will need to do a query.
Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo("usernameToCheckIfExists");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
// 1 or more users exist which have the username property "usernameToCheckIfExists"
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You may try this.
final String userName = unameEditText.getText().toString();
databaseReference.child("users").orderByChild("username").equalTo(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(Constants.TAG, "dataSnapshot value = " + dataSnapshot.getValue());
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exists
Toast.makeText(getApplicationContext(), "Username already exists. Please try other username.", Toast.LENGTH_SHORT).show();
} else {
// User Not Yet Exists
// Do your stuff here if user not yet exists
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
}
);
You just check if user is already exits or not by below code:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
final String userName = "your_user_name"; // replace with your user name
mDatabase.child("users").child(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exits
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
You can also see Firebase doc for the same on below link:
Read data once

Categories

Resources