I have tried too many times but not works this code .How to update specific fields in Firebase database which is mentioned in structure
Here is my structure:
Blog
-LOkCTZQtuMIPT_c9ESK
desc: "wow"
id: "-LOkCTZQtuMIPT_c9ESK"
image:"firebase image"
title:"gh"
uid:"6757576gfgHh6"
So how i can update the desc,image,title these particular fields only with the help of id
Here is my code:
mCurrentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("users").child(mCurrentUser.getUid());
private void startPosting() {
mProgress.setMessage("Posting...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mNameFieldUpdate.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
mProgress.show();
final StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
final Uri downloadUri = taskSnapshot.getDownloadUrl();
final String id = mDatabase.getKey();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mDatabase.child(id).child("title").setValue(title_val);
mDatabase.child(id).child("desc").setValue(desc_val);
mDatabase.child(id).child("image").setValue(downloadUri.toString());
mProgress.dismiss();
Intent mainIntent = new Intent(Update_Post.this, Main2Activity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Blog");
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot data: dataSnapshot.getChildren()){
String uid=data.child("uid").getValue().toString();
if(uid.equals((mCurrentUser.getUid()){
String keyid=data.getKey();
ref.child(keyid).child("title").setValue(newtitle);
ref.child(keyid).child("image").setValue(newurl);
ref.child(keyid).child("desc").setValue(newdesc);
}
}
}
Have the location of the listener at child("Blog") and then iterate inside of it and get the key which is keyid. Then to update the values simple point it to the right location and update each one.
You're using getKey() on your base blog DB reference (/Blog). You need to create a new node within that reference with push(), and then getKey() on your newly created child.
final String id = mDatabase.push().getKey();
Related
I am making an android app using the firebase Realtime database. My rules structure is given below:
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"Users": {
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
}
}
It means that a user should be signed in as an authenticated user to write some data. But when it comes to read no sign in is required.
Now I need to ignore the uid of the user to give free access to other users( i.e. without signing in).
This is the java code I am using currently to read data.
final Intent k = getIntent();
final String school = Objects.requireNonNull(k.getExtras()).getString("School");
final Intent i = getIntent();
final String roll = Objects.requireNonNull(i.getExtras()).getString("Roll");
myRef = myfire.getReference("Users")
.child("GcZoeK7JIbNWVOog6ZjUPiBfxwn2")// **I have problem here.**
.child(school).child(roll);
myRef.child("basic").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("fb01name").getValue().toString();
String number = (String) dataSnapshot.child("fb04roll").getValue().toString();
if(name == null){
Toast.makeText(getApplicationContext(),"Invalid",Toast.LENGTH_SHORT).show();
}
basic model = new basic(name,number);
tvName.setText(name);
tvRoll.setText(number);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I could not decide what to write instead of the first child to read any data without signing in.
.child("GcZoeK7JIbNWVOog6ZjUPiBfxwn2")
Please guide me How to ignore this child? Any help will be appreciated.
EDIT
The advice "try to refrain from using deeply nested children" by #Abdullah Z Khan further provided me insight into the problem. I changed my codes as given below :
myfire = FirebaseDatabase.getInstance();
final Intent k = getIntent();
final String school = Objects.requireNonNull(k.getExtras()).getString("School");
final Intent i = getIntent();
final String roll = Objects.requireNonNull(i.getExtras()).getString("Roll");
//--------------------the trick----------------
if (school.equals("224613")){
tvSchool.setText("GcZoeK7JIbNWVOog6ZjUPiBfxwn2");
}else if (school.equals("224614")){
tvSchool.setText("uQx5jDVRp9PV3QpM2FBU6HPq5SJ3");
}
final String uid = tvSchool.getText().toString();
//---------------------------------------------------
myRef = myfire.getReference("Users").child(uid).child(roll);
myRef.child("basic").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("fb01name").getValue().toString();
String number = (String) dataSnapshot.child("fb04roll").getValue().toString();
if(name == null){
Toast.makeText(getApplicationContext(),"Invalid",Toast.LENGTH_SHORT).show();
}
basic model = new basic(name,number);
tvName.setText(name);
tvRoll.setText(number);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Although this PLAN B has temporarily relieved me a bit yet the question is still unanswered.Beacuse I have to write the uid code of users each time they join the app( and have to update and publish the app again and again.A better solution is awaited.
EDIT: Added values in >>> marked lines for understanding
From what is given, this is your database structure:
{
"uid": {
"schoolId": {
"roll": {
}
}
}
}
Because it is so much nested (I'd suggest a different hierarchy altogether), there is no
easy way to access a child with an unknown parent as is. However, if you can change the database structure to this:
{
>>> "224614":"GcZoeK7JIbNWVOog6ZjUPiBfxwn2",
"schoolId2":"uid2",
>>> "GcZoeK7JIbNWVOog6ZjUPiBfxwn2": {
"224614": {
"roll": {
}
}
}
}
You'll get a uid lookup table. You can then use that to reach the node. Keep in mind this isn't a direct answer to what you asked, which is how to get a nested node(not value) without knowing the parent, but here you can dynamically access uids of whatever school is needed, assuming each school has exactly one parent.
After that, nest your listener:
myRef = myfire.getReference("Users");
myRef.child(school).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String uid=dataSnapshot.getValue(String.class);
myRef.child(uid)// **I have problem here.**
.child(school).child(roll);
myRef.child("basic").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("fb01name").getValue().toString();
String number = (String) dataSnapshot.child("fb04roll").getValue().toString();
if(name == null){
Toast.makeText(getApplicationContext(),"Invalid",Toast.LENGTH_SHORT).show();
}
basic model = new basic(name,number);
tvName.setText(name);
tvRoll.setText(number);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
In practice, try to refrain from using deeply nested children, rather use references to other nodes.
I hope this helps!!
how about this:
final Intent k = getIntent();
final String school = Objects.requireNonNull(k.getExtras()).getString("School");
final Intent i = getIntent();
final String roll = Objects.requireNonNull(i.getExtras()).getString("Roll");
myRef = myfire.getReference("Users")
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child(school).child(roll).child("basic").child("fb01name").getValue().toString();
String number = (String) dataSnapshot.child(school).child(roll).child("basic").child("fb04roll").getValue().toString();
if(name == null){
Toast.makeText(getApplicationContext(),"Invalid",Toast.LENGTH_SHORT).show();
}
basic model = new basic(name,number);
tvName.setText(name);
tvRoll.setText(number);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Well, I don't know if I understood your question, but if you are trying to read the children of all the nodes without specifying them, you can try to do something like the code below: (I didn't test it, I just changed your sample)
myRef = myfire.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot keySnap : dataSnapshot.getChildren()) {
for (DataSnapshot schoolSnap : keySnap.getChildren()) {
for (DataSnapshot rollSnap : schoolSnap.getChildren()) {
String mRollSnap = rollSnap.getKey();
String name = mRollSnap.child("basic").child("fb01name").getValue().toString();
String number = (String) mRollSnap.child("basic").child("fb04roll").getValue().toString();
if(name == null){
Toast.makeText(getApplicationContext(),"Invalid",Toast.LENGTH_SHORT).show();
}
basic model = new basic(name,number);
tvName.setText(name);
tvRoll.setText(number);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
Thanks for the previous help, I managed to write to the firebase database, the problem now is that I can't take the specific node to edit.
When opening an element from a recyclerview and obtaining the data and modifying the interno value and pressing update button , the database checks it but saves it outside the uid of the selected cow. You can see it better in the image.
This is the code where im trying to do the update. I've been testing and may have missing or leftover code, sorry. I do it only with interno as a test to later add the rest of the keys
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
String key = ref.child("Vacas").push().getKey();
Cow cow = new Cow();
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("interno", tvinterno.getText().toString());
ref.updateChildren(updates);
}
I am not taking the reference correctly, I hope you can help me solve this problem, thank you
EDIT
I am using the database in a recyclerview, you can see in the image, when I click on a cow, a new activity opens with all the information in the database, this is where I am interested in editing the values ( Attached image).
I want to edit the values based on the selected cow from the app, this is where I don't know if the solution you proposed to Mr. HaroldSer and Mr. Arup will work
EDIT 2
This is how I set the values in the Edit activity
in my adapter in the onBindViewHolder, I send them to the Edit activity through an intent
#Override
public void onBindViewHolder(#NonNull final cowviewHolder holder, int position) {
final Cow vacaslist = vacas.get(position);
holder.textViewinterno.setText(vacaslist.interno);
holder.textViewsiniiga.setText(vacaslist.siniiga);
String url= vacaslist.getUrl();
if (url == null|| url.isEmpty()){
holder.imageviewrec.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(vacaslist.getUrl()).error(R.drawable.ic_imageinf).into(holder.imageviewrec);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Cowdetail.class);
intent.putExtra("keyint", vacaslist.getInterno());
intent.putExtra("keysin", vacaslist.getSiniiga());
intent.putExtra("madre", vacaslist.getMadre());
intent.putExtra("padre", vacaslist.getPadre());
intent.putExtra("nacimiento", vacaslist.getNacimiento());
intent.putExtra("toro", vacaslist.getToro());
intent.putExtra("estatus", vacaslist.getEstatus());
intent.putExtra("inseminacion", vacaslist.getInseminacion());
intent.putExtra("notas", vacaslist.getNotas());
intent.putExtra("img", url);
v.getContext().startActivity(intent);
}
});
}
in this way I set them in Edit activity (Cowdetail)
public class Cowdetail extends AppCompatActivity {
EditText tvinterno, tvsiniiga, tvpadre, tvmadre, tvnacimiento, tvinseminacion, tvtoro, tvestatus, tvnotas;
AppCompatImageView tvimage;
Button tvbutton;
String cow_key;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailcow);
tvinterno = (EditText) findViewById(R.id.tvinterno);
tvsiniiga = (EditText) findViewById(R.id.tvsiniiga);
tvpadre = (EditText) findViewById(R.id.tvpadre);
tvmadre = (EditText) findViewById(R.id.tvmadre);
tvnacimiento = (EditText) findViewById(R.id.tvnacimiento);
tvinseminacion = (EditText) findViewById(R.id.tvinsemincion);
tvtoro = (EditText) findViewById(R.id.tvtoro);
tvestatus = (EditText) findViewById(R.id.tvestatus);
tvnotas = (EditText) findViewById(R.id.tvnotas);
tvimage = (AppCompatImageView) findViewById(R.id.tvimage);
tvbutton = findViewById(R.id.actualizar);
String vpadre = "";
String vmadre = "";
String vinterno = "";
String vsiniiga = "";
String vnacimiento = "";
String vinseminacion = "";
String vtoro = "";
String vestatus = "";
String vnotas = "";
String vurl;
Bundle extras = getIntent().getExtras();
if (extras !=null);
vinterno = extras.getString("keyint");
vsiniiga = extras.getString("keysin");
vmadre = extras.getString("madre");
vpadre = extras.getString("padre");
vnacimiento = extras.getString("nacimiento");
vinseminacion = extras.getString("inseminacion");
vtoro = extras.getString("toro");
vestatus = extras.getString("estatus");
vnotas = extras.getString("notas");
String image = extras.getString("img");
if (image == null|| image.isEmpty()){
tvimage.setImageResource(R.drawable.ic_imageinf);
} else {
Picasso.get().load(image).fit().centerCrop().into(tvimage);
}
tvpadre.setText(vpadre);
tvinterno.setText(vinterno);
tvsiniiga.setText(vsiniiga);
tvmadre.setText(vmadre);
tvnacimiento.setText(vnacimiento);
tvinseminacion.setText(vinseminacion);
tvtoro.setText(vtoro);
tvestatus.setText(vestatus);
tvnotas.setText(vnotas);
tvbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Update();
}
});
}
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
String key = ref.child("interno").getKey();
Cow cow = new Cow();
Map<String, Object> updates = new HashMap<String, Object>();
updates.put("interno", tvinterno.getText().toString());
ref.child(key).updateChildren(updates)
}
}
EDIT 3
this is how i add the node_id to onDataChange
mReferenceCow.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
vacas.clear();
for (DataSnapshot snapshot1 :
snapshot.getChildren()) {
Cow vaca = snapshot1.getValue(Cow.class);
vaca.setNode_id(snapshot.getKey());
vacas.add(vaca);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
The rest of the code you told me, I did it as is, except in the ref, because if I don't add -- " " -- to the node_id it marks an error
ref.child("node_id").updateChildren(updates)
this keeps happening
EDIT 4
With this code i can get the interno value and edit it from the app. But now the problem is when I enter from the app to edit the interno value of a single node, it is changed in all nodes
private void Update() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("Vacas").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot datas: snapshot.getChildren()){
String key = datas.getKey();
Map<String, Object> update = new HashMap<String, Object>();
update.put("interno", tvinterno.getText().toString());
FirebaseDatabase.getInstance().getReference().child("Vacas")
.child(key).updateChildren(update);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
You just need to update below code:
from:
ref.updateChildren(updates);
to:
ref.child(cow_key).updateChildren(updates);
where cow_key is one of the cow's key such as: "1717" or "1836".
If I'm not wrong you want to update your existing data in firebase right? If this is the case then
I am not taking the reference correctly Yes
Try this
EDIT
Add node_id field to vacaslist pojo class and generate Getter and Setter.
Now add vacaslist.setNode_id(snapshot.getKey()); in onDataChange where you are setting data for recycler view.
Add this intent.putExtra("node_id", vacaslist.getNode_id()); to your onBindViewHolder
Get the value in EditActivity String node_id = extras.getString("node_id");
First take the reference
DatabaseReference dRef = FirebaseDatabase.getInstance().getReference().child("Vacas");
For example Now I want to update interno in 1717 child node then I'll do in this way
private void Update() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Vacas");
HashMap<String, Object> updates = new HashMap();
updates.put("interno", tvinterno.getText().toString());
dRef.child(node_id).updateChildren(updates);
}
Finally, I changed the EditActivity for a Dialogplus in onBindViewHolder of my AdapterActivity. Here i setted my information and using Hashmap for update the specific nodes.
#Override
public void onClick(View v) {
final DialogPlus dialogPlus = DialogPlus.newDialog(holder.imageviewrec.getContext())
.setContentHolder(new com.orhanobut.dialogplus.ViewHolder(R.layout.dialog_detail))
.setExpanded(true, 2000)
.create();
View myview = dialogPlus.getHolderView();
final EditText interno = myview.findViewById(R.id.dinterno);
final EditText siniiga = myview.findViewById(R.id.dsiniiga);
interno.setText(model.getInterno());
siniiga.setText(model.getSiniiga());
dialogPlus.show();
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String, Object> map = new HashMap<>();
map.put("interno", interno.getText().toString());
map.put("siniiga", siniiga.getText().toString());
FirebaseDatabase.getInstance().getReference().child("Vacas")
.child(getRef(position).getKey()).updateChildren(map)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialogPlus.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dialogPlus.dismiss();
}
});
}
});
}
});
I'm new to Android development. I need to put and get information through Firebase. I managed to make the assignment of information, but I can not make getting information from the database.
test_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
String testData = edit_data_FB.getText().toString();
Map newPost = new HashMap();
newPost.put("testData",testData);
current_user_db.setValue(newPost);
}
});
test_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id).child("testData").val;
//Map newPost = new HashMap();
//String data = newPost.get();
//text_get.setText();
}
});
Mission database has the following form
Firebase Database I need to get the testData value
To retrieve testData try the following:
String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
current_user_db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String testData = dataSnapshot.child("testData").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Attach a listener to your reference and then you will be able to retrieve testData
I am trying to get data from firebase, to show it in the TextView. Actually, I am new to android can anybody tell me what is the problem here is my code.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("https://videoanimation-a931e.firebaseio.com/");
auth = FirebaseAuth.getInstance();
String userId = auth.getCurrentUser().getUid();
DatabaseReference uidRef = rootRef.child("Person").child(userId);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(user !=null) {
String name = user.getName();
String email = user.getEmail();
String designation = user.getDesignation();
textViewName.setText(name);
textViewEmail.setText(email);
textViewDesignation.setText(designation);
}else {
Toast.makeText(ProfileActivity.this, "user is null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
}
i dot know if my answer can help you, but please take a look at my snipshet code, this method how i get value firebase Realtime database child user value
//Getting Uid user
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = ""+dataSnapshot.child("nama").getValue().toString();
String jabatan = ""+dataSnapshot.child("jabatan").getValue().toString();
String image = ""+dataSnapshot.child("image").getValue().toString();
display_name.setText(""+name);
display_address.setText(""+jabatan);
if (!image.equals("default") && image!= null){
Glide.with(getApplicationContext()).load(image).listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
}).into(circleImageView);
}else {
}
mUserRef.child("role").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String srole = dataSnapshot.getValue().toString();
preferenceManager.simpanRole(srole);
setdashbourUI(preferenceManager.ambilRole());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
full implement code you can check HERE !!
This fragment
User user = dataSnapshot.getValue(User.class);
try to change to this
User user = dataSnapshot.toObject(User.class);
And up use
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
I have this firebase database:
That has been created with this code:
private DatabaseReference mDatabase;
private EditText tbfirstname;
private EditText tblastname;
private EditText tbemail;
private Button btnSubmit;
private String str_firstname;
private String str_lastname;
private String str_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
//GUI DECLARATIONS
tbfirstname = (EditText) findViewById(R.id.tb_firstname);
tblastname = (EditText) findViewById(R.id.tb_lastname);
tbemail = (EditText) findViewById(R.id.tb_email);
btnSubmit = (Button) findViewById(R.id.btn_register);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//HANDLES VALUES FROM TB TO STR
str_firstname = tbfirstname.getText().toString().trim();
str_lastname = tblastname.getText().toString().trim();
str_email = tbemail.getText().toString().trim();
HashMap<String, String> dataMap = new HashMap<String, String>();
dataMap.put("Firstname", str_firstname);
dataMap.put("Lastname", str_lastname);
dataMap.put("Email", str_email);
mDatabase.push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Registered Successfully!",Toast.LENGTH_LONG).show();
tbfirstname.setText("");
tblastname.setText("");
tbemail.setText("");
} else {
Toast.makeText(MainActivity.this, "There was an Error. Try Again!", Toast.LENGTH_LONG).show();
}
}
});
}
});
}
It's actually a simple app that let users register some data. What I wanna do is I want to create a search textboxthat will locate specific data in the database based on what the user has entered in that textbox and returns a value.
For example I'll search steve#sample.com, if there is an email in the database that has the same value, I want it to return its root value namely L4JyRA77YKldmMWM-C7. If somehow there is no said record, I want it to return with false or something.
Requirements:I'm really a beginner in Android and Firebase so if you could make the code newbie-friendly, that'll really be a great help. Thanks!
first of all you need to fetch all records from firebase database List<User>
create copy of list List<User> temp = new ArrayList();
you can add particular searchable user detail in temp - temp.add(users.get(i));
Now you can get useremail like this email = temp.get(i).getEmailId();
FirebaseDatabase.getInstance().getReference().child("Your table name").orderByChild("email").equalTo(your searchable emailid ).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
List<User> users = new ArrayList<>();
while (dataSnapshots.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshots.next();
User user = dataSnapshotChild.getValue(User.class);
users.add(user);
}
String userids = "";
List<User> temp = new ArrayList();
try {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getEmailid().equals("your searchable email")) {
temp.add(users.get(i));
//Here you can find your searchable user
Log.e("temp", "+" + temp.get(i).getFirebaseId());
email = temp.get(i).getEmailId();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Logs", e.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("Email").equalTo("editext.getText()");
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) {
}
});
Some general things to remember is never name nodes with Capital letters