How to check child in firebase database? - android

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()

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.

Logcat error when radio button is clicked

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)

Toast not working when data is not existing

My Toast not working when the data is not existing from Firebase database. What happen ?
public void searching(final String id){
DatabaseReference databaseReference = FirebaseDatabase.getInstance()
.getReference("Employee");
Query query = databaseReference.orderByChild("id").equalTo(id);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
It may be possible your query databaseReference.orderByChild("id").equalTo(id) this condition not able to getting any record so it will be not execute for loop so you may to check first the number of children are greater than 0 or not.
You can try this way Like :
if (dataSnapshot.dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
} else {
Toast.makeText(getContext(),"No data found.",
Toast.LENGTH_SHORT).show();
}
When dataSnapshot.getChildren() is empty you wont enter in your for block so Toast wont appear.

How to perform join query in firebase database using android

Here member’s key in Group is User’s key.
Task: Want to fetch comida_id froenter code herem User based on Group’s member key.
Here we are trying to first fetch member keys from Group. While fetching member key we also want to fetch User and User’s comida_id while that member’s loop is going. So the scenario will be First we are going to fetch all keys from Group based on Group’s key ( for example createTime, groupName, members ). Now from that we will execute loop on members so will get member’s key. Now while fetching this member’s key in that loop, we want to fetch comida_id from User’s, which will be fetch in that loop only.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key and comida_id ( in Loop (get member key then fetch comida_id ))
*My Code
FirebaseDatabase mDatabase_gp = FirebaseDatabase.getInstance();
mDatabase_gp.getReference("Group/"+group_key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
Map userkey = (Map) valuesMap.get("members");
Log.d("Members", String.valueOf(userkey));
for (Object ke: userkey.keySet())
{
Log.d("runfirst","First Run");
String key = String.valueOf(ke.toString());
Log.d("Member key",key);
// HERE WHAT CORRESPONDS TO JOIN
FirebaseDatabase User = FirebaseDatabase.getInstance();
User.getReference("User/"+key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
String userid = String.valueOf(valuesMap.get("comida_id"));
Log.d("comida_id",userid);
Toast.makeText(ChatSectionActivity.this,userid,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
}
Log.d("runlast","Last Run");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
*
In Above code we tried to achieve same thing but here this code will fetch all member keys from group first. After fetching all members it will fetch comida_ids in another loop.. So there will be like two different loops working to fetch comida_id from members. It’s not working like join query.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key (in Loop (get member key) after then fetch comida_id .
*1) I was try this solution - How to perform join query in Firebase?
**But get this error –
Incompatible types.
Required: com.google.firebase.database.DatabaseReference
Found: com.google.firebase.database.ValueEventListener
https://i.stack.imgur.com/ljlWo.png
Firebase doesn't have join queries. And what you are doing wrong is your are referencing your data base on Fireabaseuser, which is wrong.
mdatabaseReference.child("Answer").child("Answer"+QID).orderByChild("questionId").equalTo(QID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (muftiAnswer_List.size() > 0)
muftiAnswer_List.clear();
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
final AnswerClass muftiAnswer = postsnapshot.getValue(AnswerClass.class);
String ide=muftiAnswer.getMuftiId(); //getting AlimId From Class object
Log.e(TAG, "Alim:"+ muftiAnswer.getMuftiId());
//Using Query to get Alim Name From Data Table.!
mdatabaseReference.child("users").child("Alim").child(ide).addListenerForSingleValueEvent(new ValueEventListener() {
#Override //.orderByChild("alimId").equalTo(user_Id)
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "AlimNode:");
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Log.e(TAG, "EqualNode:");
if(postSnapshot.getKey().equals("alimName"))
{
Log.e(TAG, "AlimNameNodeSnapShot:");
//Setting Alim Name in Current Object replcing id for name
muftiAnswer.setMuftiId(postSnapshot.getValue().toString());
}
// resultMuftiAnswer_List.add(muftiAnswer);
}//End of snapshot
}//ondata Change
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});//End OF Alim Query
}//end of comments
circular_progress2.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Details_Activity.this, "LOLOLOL", Toast.LENGTH_SHORT).show();
}
});
You have to use nested loops for doing joins like MYSQL
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Visit link for better understanding
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html

How to retrieve data and specific user data from the Firebase

I am having problem in retrieving data from firebase. I have one root user's node and then inside that root I have one userID child node. Inside that child node I am storing user information according to its blood group.
Now, what I want is to fetch the name and email according to blood group, say fetch all user data whose blood group is B+.
Also, please tell me on how to fetch all entries in the firebase and show on textView.
//show data on text view
datashow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("inside click", "onClick: ");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference();
db.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Iterable<DataSnapshot > children = dataSnapshot.getChildren();
Log.i("children", "onDataChange: " + children);
for(DataSnapshot child : children)
{
Map<String , String> map = (Map)child.getValue();
Log.i("inside", "onDataChange: " + map);
name = map.get("name");
email = map.get("email");
dateof = map.get("userDob");
showData(name , email , dateof );
Log.i("datasnap", "onDataChange: data snapshot " + name + email + dateof);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
this is my snapshot for Firebase database
enter image description here
db.child("users").orderByChild("userBloodGroup").equalTo("B+").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
List<User> data = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot :
dataSnapshot.getChildren()) {
User element = snapshot.getValue(User.class);
element.setKey(snapshot.getKey());
data.add(element);
}
for (User user: data){
Log.i(TAG,"user name: " +user.getName());
Log.i(TAG,"user email: " +user.getEmail());
Log.i(TAG,"user dob: " +user.getUserDob());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
To query for all users with the bloodGroup B+, use a Firebase Query:
firebaseReference("users").orderByChild("userBloodGroup").equalTo("B+")
To get all the data of the users, you could use a Listener to get all of them and put them in whatever TextView you need. You could check the documentation on Firebase on how they read data. https://firebase.google.com/docs/database/android/read-and-write

Categories

Resources