Realtime database add value from dropdown all item at the same time - java

I already done one by one add value to realtime database from the dropdown with add button.
here my code for adding a single value
private void SaveStudent() {
Query query = databaseReference.orderByChild("lrn").equalTo(StudentLRN);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
databaseReference = firebaseDatabase.getReference("Class");
Query query = databaseReference.child(className).child("StudentLRN")
.child(StudentLRN);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
autoCompleteSelectStudent.setText("");
autoCompleteSelectSection.setText("");
textInputLayoutStudent.setVisibility(View.GONE);
Toast.makeText(TeacherClassroomActivity.this, StudentName + " Already Added!", Toast.LENGTH_SHORT).show();
} else {
databaseReference = firebaseDatabase.getReference("Class");
databaseReference.child(className)
.child("StudentLRN").child(StudentLRN)
.child("LRN").setValue(StudentLRN);
databaseReference.child(className)
.child("StudentLRN").child(StudentLRN)
.child("StudentName").setValue(StudentName);
autoCompleteSelectStudent.setText("");
autoCompleteSelectSection.setText("");
Toast.makeText(TeacherClassroomActivity.this, StudentName + " Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
query.addListenerForSingleValueEvent(eventListener);
} else {
Toast.makeText(TeacherClassroomActivity.this, "No Student Exist in this LRN!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
query.addListenerForSingleValueEvent(eventListener);
}
Student list
and from the image above i want to add all student from dropdown list in one submit button.

Related

retrive data from firebase of list of saved ids

I have list of node's ids and i want to retrive all child of that node.
This is my data
where each id is a recipe id :
This my code to retrive the ids then i save it in an arrylist :
data_ref_user = FirebaseDatabase.getInstance().getReference("Users").child(current_uid).child("My Recipes");
data_ref_user.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot:snapshot.getChildren()){
String recipe_id = dataSnapshot.getValue().toString();
list_recipes_id.add(recipe_id);
}//end for
}else {
Toast.makeText(getContext(), "No data found!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
And then i try to loop throught list_recipe_id adding a valueEventListener and saving the recipe into recipe_list .
data_ref_recipe = FirebaseDatabase.getInstance().getReference("Recipes");
data_ref_recipe.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data:snapshot.getChildren()) {
for (String ids :list_recipes_id){
Recipe recipe = data.child(ids).getValue(Recipe.class);
recipe_list.add(0,recipe);
}//end inner loop
Recipe recipe = data.getValue(Recipe.class);
recipe_list.add(0,recipe); //0 to put data in first not buttom
}
newAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
i hope i can find a way to retrive the data of all saved id?

How to retrieve Firebase images to ImageView?

Here is my Firebase Realtime Database structure:
I want to retrieve each and every image in a child(images1,images2,images3,images4 are the child names)
private void loadmybanners1() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("BannerImages");
ref.orderByChild("images2").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
final String myImg1 = "" + ds.child("image").getValue();
try{
Picasso.get().load(myImg1).networkPolicy(NetworkPolicy.OFFLINE).into(ban2Iv, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(myImg1).into(ban2Iv);
}
});
} catch (Exception e) {
ban2Iv.setImageResource(R.drawable.ic_image);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I have used this code to retrieve the image2. But from that, I can only retrieve the images1 child data. What are the modifications to do?
I want to retrieve each and every image in a child
To get each and every child within your BannerImages node, there is no need to use a query, you can simply use a DatabaseReference, as in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference bannerImagesRef = rootRef.child("BannerImages");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String myImg1 = dataSnapshot.child("images1").child("image").getValue(String.class);
Picasso.get().load(myImg1)
String myImg2 = dataSnapshot.child("images2").child("image").getValue(String.class);
Picasso.get().load(myImg2)
//And so on for the other images3, images4, and images5 children
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
bannerImagesRef.addListenerForSingleValueEvent(valueEventListener);
Add this dependency
implementation 'com.github.bumptech.glide:glide:4.10.0'
After getting Url from Firebase.Just Use below line
Glide.with(context).load(Firbase Url).into(imageView);

Compare two different child nodes from two different parent nodes

I am trying to compare two different child nodes from two different parent nodes. The JSON structure is the following: Attending Event > postId > userId and the second one is structured as follows: Following > firebaseUserId > userId. The goal here is to compare the userId's and if I am following that userId and also that person / userId IS attending the event, then I want to populate a list with those users.
I already wrote two methods, one to get the users that I am following getFollowing(); and another to get the users that are attending the event getAttendingEvent();. Is there a way to compare the lists / usersIds from the two methods I have already written, or do I have to write a new method entirely?
I´m really not sure how to go about this… Am I on the right track with the getFriendsAttendingEvent(); method I just wrote?
FollowersActivity
public class FollowersActivity extends AppCompatActivity {
String mId;
String mTitle;
String mPostId;
List<String> mIdList;
RecyclerView mRecyclerView;
UserAdapter mUserAdapter;
List<User> mUserList;
FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Intent intent = getIntent();
mId = intent.getStringExtra("id");
mTitle = intent.getStringExtra("title");
mPostId = intent.getStringExtra("postid");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(mTitle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(v -> finish());
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUserList = new ArrayList<>();
mUserAdapter = new UserAdapter(this, mUserList, false);
mRecyclerView.setAdapter(mUserAdapter);
mIdList = new ArrayList<>();
switch (mTitle) {
case "Likes":
getLikes();
break;
case "Following":
getFollowing();
break;
case "Followers":
getFollowers();
break;
case "Attending Event":
getAttendingEvent();
case "Friends Attending":
// Create this method
}
}
private void getFriendsAttendingEvent(List<User> userList, List<User> userList1) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Events").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user1 = snapshot.getValue(User.class);
userList1.add(user1);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Compare the two lists user's somehow..
if (userList.equals(userList1)) {
showUsers();
}
}
private void getLikes() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Likes").child(mPostId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getAttendingEvent() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Event").child(mPostId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowing() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Followers").child(mId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUsers() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for (String id : mIdList) {
if (user != null)
if (user.getId().equals(id)) {
mUserList.add(user);
}
}
}
mUserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

How to copy data from one table to another table in Firebase?

I have two tables - cartOrders and placedOrders. cartOrders is used to add products to cart, and placedOrders is activated when the user presses "Place Order" button.
I need to copy data from cartOrders to placedOrders when the user clicks the "Place Order" button, but I'm not able to do so.
cartDatabase = FirebaseDatabase.getInstance().getReference("cartOrders");
cartQuery = cartDatabase.child(orderID).orderByChild("productQuantity").startAt(1);
placedOrdersDatabase = FirebaseDatabase.getInstance().getReference("placedOrders");
placedOrderQuery = placedOrdersDatabase.child("orderID");
placeOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartDatabase.child(orderID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Logic to add data to data to placedOrders.
String name = dataSnapshot.child("productName").getValue(String.class);
System.out.println("ProductName: " + name);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Intent intent = new Intent(getApplicationContext(), OrderPlacedActivity.class);
intent.putExtra("ORDER_ID", orderID);
startActivity(intent);
}
});
In the code, I was checking if the code is picking up the data from the database, but it wasn't. The output is null. Both the tables have the same structure.
Any help will be appreciated.
Thanks!
My cartOrders table structure:
cartOrders:
----------OrderID:
-----------------ProductID:
---------------------------ProductID:
---------------------------ProductName:
---------------------------ProductPrice:
---------------------------ProductQty:
#Alex Mamo answered this question on a different question.
private void copyRecord(Query fromPath, final DatabaseReference toPath) {
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isComplete()) {
System.out.println("Complete");
} else {
System.out.println("Failed");
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
fromPath.addListenerForSingleValueEvent(valueEventListener);
}
The code works fine.
Link:Moving or copying data from one node to another in firebase database

How to create a condition if there is the same value in firebase

How can I see if there is an equal value in a child and not save if it exists.
I tried doing this here but it did not work:
How can I check if a value exists already in a Firebase data class Android
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario);
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("id")) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Create yourself another function that pushes the data to firebase and call it from inside your listener. (in this example, create the function pushValueToFirebase)
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean exists = false;
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals(idUsario) {
exists = true;
}
}
if (!exists) {
//Your code here to push idUsario
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this:
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario).child("id");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Add the child id to the reference above child("historico").child(idUsuario).child("id") then use exists() to check if this dataSnapshot is in your database.

Categories

Resources