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
Related
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 want to create an "edit user profile" page on Android Studio. The user(which is logged in obviously) can go in and edit user info such as weight and age. Here is how my firebase database is set up:
The database
In this case, a user who is logged in as "Raxor2k", wants to change he`s info such as Age and Weight.
I have made a function that queries the database, and it manages to reach the "AdditionalUserInfo" table which is good. But the next task is to reach those specific values that belong to the logged-in user.
here is the code:
public class UserSettingsActivity extends AppCompatActivity {
private Button mEditInfoButton;
private TextView usernameField;
private EditText ageField, weightField;
private DatabaseReference dbUsernames;
DatabaseReference the_additional_userInfo_table = FirebaseDatabase.getInstance().getReference("AdditionalUserInfo");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_settings);
ageField = (EditText) findViewById(R.id.ageID);
weightField = (EditText) findViewById(R.id.weightID);
mEditInfoButton = (Button) findViewById(R.id.editButton);
usernameField = (TextView) findViewById(R.id.usernameTextViewID);
mEditInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QueryUserInfo();
}
});
}
public void QueryUserInfo(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference the_additional_userInfo_table = database.getReference("AdditionalUserInfo");
//Query query =the_additional_userInfo_table.child("username");
the_additional_userInfo_table.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(UserSettingsActivity.this, "User exists!", Toast.LENGTH_SHORT).show();
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
if(!dataSnapshot.exists()){
Toast.makeText(UserSettingsActivity.this, "nooooo user!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
To get the data under AdditionalUserInfo that corresponds to a specific user, you need to use a query that looks like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference additionalUserInfoRef = rootRef.child("AdditionalUserInfo");
Query userQuery = additionalUserInfoRef.orderByChild("username").equalTo("Raxor2k");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Object> map = new HashMap<>();
map.put("user-age", "30");
map.put("user-weight", "30");
ds.getRef().updateChildren(map);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userQuery.addListenerForSingleValueEvent(valueEventListener);
The result in your database will be the change of both properties from 25 to 30. Since you didn't add the database as a text, file I have used in the query he user name but a more elegant way of querying the database would be to use the uid.
Query userQuery = additionalUserInfoRef.orderByChild("user-id").equalTo("IXL ... Eoj");
I'm using firebase to store the messages under a randomly generated node , messages are successfully added to this node but, it only displays the first message sent.
Here's my class containing the listeners.
I tried changing the Single event listener in get chat id to a value event listener but it didn't solve the problem.
when I close the chat and open it again it shows the first message only.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mMatchId = getIntent().getExtras().getString("MatchId");
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId).child("connections").child("matches").child(mMatchId).child("ChatId");
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
getChatId();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(false);
mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mSendEditText = (EditText) findViewById(R.id.message);
mSendButton = (Button) findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String sendMessageText = mSendEditText.getText().toString();
if(!sendMessageText.isEmpty()){
DatabaseReference newMessageDb = mDatabaseChat.push();
Map newMessage = new HashMap();
newMessage.put("createdByUser", currentUserId);
newMessage.put("text", sendMessageText);
newMessageDb.setValue(newMessage);
}
mSendEditText.setText(null);
}
private void getChatId(){
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
mDatabaseChat = mDatabaseChat.child(chatId);
getChatMessages();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getChatMessages() {
mDatabaseChat.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot t : dataSnapshot.getChildren()) {
String message = null;
String createdByUser = null;
if (t.child("text").getValue() != null) {
message = t.child("text").getValue().toString();
}
if (t.child("createdByUser").getValue() != null) {
createdByUser = t.child("createdByUser").getValue().toString();
}
if (message != null && createdByUser != null) {
Boolean currentUserBoolean = false;
if (createdByUser.equals(currentUserId)) {
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message, currentUserBoolean);
resultChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database image
it is because you first time open the activity and your getChatId() function is called a single time and give you one single id of your single message. and then you pass it on addChildEventListener. so thats y it gives you the single messagr to your recyclerview. if you show ur database schema i will provide youy more specific query
List<Chat> chatMessageList = new ArrayList<>();;
DatabaseReference database = FirebaseDatabase.getInstance()
.getReference()
.child(Common.CHATS);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessageList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
assert chat != null;
chatMessageList.add(chat);
mChatAdapter = new ChatAdapter(context, chatMessageList);
mRecyclerView.setAdapter(mChatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
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 want to take some values from the database (firebase realtime database) and use it with some calculations or display it in a TextView but when the user clicks the button my application doesn't get the value until the next click with all my methods, with a loop or not. outside of the onClick() method I can get the values just fine.
This is a code for getting data from database and display it in a TextView inside onClick()
DatabaseReference myRef;
private double avgrate;
private String category;
private Button button;
private Spinner categories;
private TextView ratetxt;
protected void onCreate(Bundle savedInstanceState) {
myRef = FirebaseDatabase.getInstance().getReference("user_account");
//initialize
avgrate = 0.0;
button = (Button) findViewById(R.id.button);
ratetxt = (TextView) findViewById(R.id.ratetxt);
ratetxt.setVisibility(View.GONE);
// for category adapter -- it works
myRef.child("(username)").child("category").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> propertyAddressList = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String propertyAddress = ds.getKey();
if (propertyAddress != null) {
propertyAddressList.add(propertyAddress);
for (DataSnapshot ds2 : dataSnapshot.child(propertyAddress).getChildren()) {
String sub = (String) ds2.getValue();
if (sub != null && !sub.contains("null")) {
propertyAddressList.add(sub);
}
}
}
}
categories = (Spinner) findViewById(R.id.categ);
ArrayAdapter<String> addressAdapter = new ArrayAdapter<String>(myactivity.this, android.R.layout.simple_spinner_item, propertyAddressList);
addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(addressAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});
// ON CLICK
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
category = categories.getSelectedItem().toString();
if (category.isEmpty()) {
Toast.makeText(getApplicationContext(), "ERROR - CHOOSE CATEGORY", Toast.LENGTH_SHORT).show();
} else {
// take average rating -- HERE IS THE PROBLEM
myRef.child("(username)").child("rating").child(category).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String str = (String) dataSnapshot.child("avg").getValue(String.class);
if (str != null) {
avgrate = Double.parseDouble(str);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
}/*close else*/ }});// End of OnClick()
} // END OF OnCreate()
here is a code where I have to take the average rating for a chosen category, and set it in a text view, the first time I press the button the avg. will be 0.0 next time it will set the real value, if I don't initialize it, it will set null at first then the real value, I don't know how to fix it
Add these lines inside onDataChange() in button.setOnClickListener ()
Instead of writing outside the onDataChange ()
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
Below are codes after making changes. Hope this help.
myRef.child("(username)").child("rating").child(category).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String str = (String) dataSnapshot.child("avg").getValue(String.class);
if (str != null) {
avgrate = Double.parseDouble(str);
ratetxt.setVisibility(View.VISIBLE);
ratetxt.setText("AVG. RATE: "+avgrate+"");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
}
});