Firebase push() method create multiple key continuously - android

I am trying to create a random key in a child on button click and insert data in this key
but When I click on the button it creates multiple keys with the same data and it goes continuously till I close the app in the background
above problem is in postreview() method in my code i call this method on the button clcik
public class DisplayStory extends AppCompatActivity {
TextView Tittle;
WebView webView;
String story;
String storyname;
String catagory;
String TAG = "display";
DatabaseReference storyref;
DatabaseReference ratingref;
RatingObject ratingObject;
// review stuff
RatingBar user_ratingBar;
EditText comment_EditText;
EditText senderName_editText;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_story);
Tittle = findViewById(R.id.TITLE);
webView = findViewById(R.id.webview);
// review stuff
user_ratingBar = findViewById(R.id.ratings_to_submit);
comment_EditText = findViewById(R.id.comment_to_submit);
senderName_editText = findViewById(R.id.sender_name);
submit = findViewById(R.id.submit_btn);
storyname = getIntent().getStringExtra("tittle");
catagory = getIntent().getStringExtra("catagory");
Log.d(TAG,"storyname "+storyname);
Log.d(TAG,"storyname "+catagory);
Tittle.setText(storyname);
storyref = FirebaseDatabase.getInstance().getReference(catagory).child(storyname);
ratingref = FirebaseDatabase.getInstance().getReference(catagory).child(storyname).child("rating");
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PostReview();
}
});
storyref.child("story").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
story = dataSnapshot.getValue().toString();
webView.loadData(story,"text/html", "UTF-8");
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
Log.d(TAG,"story exist ");
Log.d(TAG,"story "+story);
}
else {
Log.d(TAG,"no story exist ");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void PostReview(){
final String name,comment;
final float rating;
name = senderName_editText.getText().toString();
comment = comment_EditText.getText().toString();
rating = user_ratingBar.getRating();
ratingref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ratingObject =
new RatingObject(name,comment,rating);
ratingref.push().setValue(ratingObject);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}

As far as I can see, there is no need to attach a listener in your PostReview method since you don't use any data from the dataSnapshot in there.
So in that case, the code can be much simpler:
public void PostReview(){
final String name,comment;
final float rating;
name = senderName_editText.getText().toString();
comment = comment_EditText.getText().toString();
rating = user_ratingBar.getRating();
ratingObject = new RatingObject(name,comment,rating);
ratingref.push().setValue(ratingObject);
}
This will also solve the endless loop, which was caused by calling setValue inside the onDataChange of a listener added with addValueEventListener. For a longer explanation of that, see:
Changing value in Firebase results in infinite loop
Insert data to firebase -Android - and check specific properties

Related

IF-ELSE condition creating loop for new activity

im new to Android Studio. So, im trying to use IF-Else statement to retrive data from firebase using radio button. When click on submit button, it should open a new activity and all of the data should display in one page using listview. But, instead of one page, the output display in many activites. Each activity contain one data. I think its because of my if else statement. Can someone help me? Thank you
So this is my code for SelectAge.class
public class SelectAge extends AppCompatActivity {
Button sbmit;
RadioGroup rg1,rg2;
RadioButton rb1,rb2;
DatabaseReference dr;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_age);
rg1 = findViewById(R.id.A1);
rg2 = findViewById(R.id.A2);
dr = FirebaseDatabase.getInstance().getReference("Data");
sbmit = findViewById(R.id.SubmitBtn);
ArrayList<String> al = new ArrayList<>();
ArrayAdapter<String> ad;
sbmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioID1 = rg1.getCheckedRadioButtonId();
int radioID2 = rg2.getCheckedRadioButtonId();
rb1 = findViewById(radioID1);
rb2 = findViewById(radioID2);
dr.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
if (rb1.getText().equals(snapshot.child("Age").getValue()) && (!rb2.getText().equals(snapshot.child("Allergy").getValue()
))) {
String ingredient = snapshot.child("Ingredient").getValue().toString();
Intent intent = new Intent(SelectAge.this, result.class);
intent.putExtra("Result", ingredient);
startActivity(intent);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
public void checkButton(View v){
int radioID1 = rg1.getCheckedRadioButtonId();
int radioID2 = rg2.getCheckedRadioButtonId();
rb1 = findViewById(radioID1);
rb2 = findViewById(radioID2);
Toast.makeText(SelectAge.this,"Select" +rb1.getText(),Toast.LENGTH_LONG).show();
}
}
My sample data
In your use case do not use dr.addChildEventListener(new ChildEventListener() {...});
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
dr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
if (rb1.getText().equals(snapshot.child("Age").getValue()) && (!rb2.getText().equals(snapshot.child("Allergy").getValue()
))) {
String ingredient = snapshot.child("Ingredient").getValue().toString();
Intent intent = new Intent(SelectAge.this, result.class);
intent.putExtra("Result", ingredient);
startActivity(intent);
return; // stop looping we have found our item
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadIngredient:onCancelled", databaseError.toException());
// ...
}});
Detailed information in documentation
I hope this helps 😊

Retrieve other values of child

So, I have this Firebase Structure.
I made an autocompletetext to get all child named "alimento".
That's OK!
But now, based on this "alimento" selection, I want to get all other childs in TextViews referent to this selection.
Is It possible? I don't know If I was clear enough.
This is my code: (I tried a lot of stuff, but all always return 0.00, so I won't put anything)
public class MainActivity extends AppCompatActivity {
private Button btnList, buttonAdicionar;
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnList = (Button) findViewById(R.id.btnList);
buttonAdicionar = (Button) findViewById(R.id.buttonAdicionar);
//Nothing special, create database reference.
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Create a new ArrayAdapter with your context and the simple layout for the dropdown menu provided by Android
final HRArrayAdapter<String> adapter = new HRArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line);
//Child the root before all the push() keys are found and add a ValueEventListener()
database.child("alimentos").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
adapter.clear();
//Basically, this says "For each DataSnapshot *Data* in dataSnapshot, do what's inside the method.
for (DataSnapshot suggestionSnapshot : dataSnapshot.getChildren()){
//Get the suggestion by childing the key of the string you want to get.
String autocomplete = suggestionSnapshot.child("alimento").getValue(String.class);
adapter.add(autocomplete);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.acTV);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String alimento = (String) parent.getItemAtPosition(position);
Log.d("TAG", alimento);
Toast.makeText(getApplicationContext(), alimento, Toast.LENGTH_SHORT).show();
}
});
btnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FoodActivity.class));
}
});
buttonAdicionar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), NewAlimentoActivity.class));
}
});
}
}
This is an example that what I want (using SQL):
If you're asking how to get all child nodes with a specific value in their alimento property, that'd be something like:
database.child("alimentos")
.orderByChild("alimento")
.equalTo("Arroz, integral, cozido")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String base = snapshot.child("base").getValue(String.class);
double baseValue = Double.parseDouble(base);
...
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});

In Android Studio, retrieving Data from Firebase does not work

When running the app the data is not retrieved but when debugging i can see where it is in terms of the database link.
When it runs and get to addValueEventListener, it doesn't go into the function which is pretty weird, don't know if this is because its async or not but either way data from Firebase does not get retrieved.
public GarbageItems(int itemNum) {
String itemId = String.valueOf(itemNum);
database = FirebaseDatabase.getInstance();
gameObjectRef = database.getReference().child("gameObjects");
itemInformationGrabber(gameObjectRef, itemId);
}//GarbageItems(Constructor)
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
String color = dataSnapshot.getValue(String.class);
setColor(color);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is in a different classs that calls GarbageItem
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
colorTextView = findViewById(R.id.ColorTextView);
itemTextView = findViewById(R.id.ItemNameTextView);
GarbageItems garbageItems = new GarbageItems(1);
Color = garbageItems.getColor();
}
try this...
private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
DatabaseReference dataReference = gameObjectRef.child(itemId);
DatabaseReference itemColor = dataReference.child("Color");
itemColor.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
for(Datasnapshot dataSnap : dataSnapshot.getChildren()){
String color = dataSnap.child("Color").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Hope it helps you :)

Trying to replace a data from specific child (Firebase Database)

I want to replace kids/[id]/kidLimit/[new data]
So what I do is I make a spinner with kidName data, then with the selected item from that spinner I want to replace the data of kidLimit (with the same parent as the selected item from the spinner).
The first thing I do is to find the unique key of the selected item, then go to the kidLimit with that unique key to then use the setValue() method.
public class setLimit extends AppCompatActivity {
private DatabaseReference db;
private EditText etLimit;
private Button btnSetLimit;
private Spinner kidSpinner;
private String kidKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_limit);
etLimit = findViewById(R.id.et_limit);
btnSetLimit = findViewById(R.id.btn_confirm);
kidSpinner = findViewById(R.id.spinner_kid);
//PUTTING STRING LIST FROM FIREBASE TO SPINNER DROPDOWN STARTS HERE
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<String> kid = new ArrayList<>();
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
String kidName = dataSnapshot1.child("kidName").getValue(String.class);
kid.add(kidName);
}
ArrayAdapter<String> kidNameAdapter = new ArrayAdapter<>(setLimit.this, android.R.layout.simple_spinner_item, kid);
kidNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kidSpinner.setAdapter(kidNameAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//ENDS HERE
//ONCLICKLISTENER
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
}
//FINDING KEY FROM THE SELECTED SPINNER ITEM
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
So basically what I did was using the snapshot inside the onclick method to find the key. But when I check them on the log, it showed that the kidkey variable is null the first time I press the button, but after that it's not null anymore.
What can I to do so when I press the button, I can go to a specific child to replace it's data without getting any null pointer exception?
Here's the database that I use
When you do this
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
String newLimit = etLimit.getText().toString().trim();
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
});
findId(); is executed but you don't know when it will finish, so after that method is executed and waiting for data, this line
db.child(kidKey).child("kidLimit").setValue(newLimit);
will have kidKey with a null value because it has not been pulled yet from the database, so instead, you should move your code to the onDataChange() or make a new callback when all the asynchronous process finishes
btnSetLimit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findId();
}
});
public void findId(){
String kidName = kidSpinner.getSelectedItem().toString();
String newLimit = etLimit.getText().toString().trim();
db = FirebaseDatabase.getInstance().getReference().child("kids");
db.orderByChild("kidName").equalTo(kidName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
kidKey = dataSnapshot1.getKey();
}
db.child(kidKey).child("kidLimit").setValue(newLimit);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Whenever I input data while logged in to the current user, the data saves for all users. How to save data for the current logged in User only?

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mood);
databaseAtrtists = FirebaseDatabase.getInstance().getReference("Artists");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
spinnerEmo = (Spinner) findViewById(R.id.spinnerEmo);
buttonTips = (Button) findViewById(R.id.buttonTips);
listViewArtists = (ListView) findViewById(R.id.listViewArtist);
listMood = new ArrayList<>();
mRemoveButton = (Button) findViewById(R.id.removeButton);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addAtrist();
}
});
mRemoveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseAtrtists.removeValue();
}
});
}
private void configureTipsButton() {
final Button buttonTips = (Button) findViewById(R.id.buttonTips);
buttonTips.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Mood.this, MoodsTips.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseAtrtists.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
listMood.clear();
for (DataSnapshot artistSnapshot : dataSnapshot.getChildren()) {
MindYourMood level = artistSnapshot.getValue(MindYourMood.class);
listMood.add(level);
}
MoodLists adaptor = new MoodLists(Mood.this, listMood);
listViewArtists.setAdapter(adaptor);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void addAtrist() {
String name = editTextName.getText().toString().trim();
String emotion = spinnerEmo.getSelectedItem().toString();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)) {
String id = databaseAtrtists.push().getKey();
MindYourMood level = new MindYourMood(id, name, emotion, genre);
databaseAtrtists.child(id).setValue(level);
Toast.makeText(this, "Emotion Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter a date", Toast.LENGTH_SHORT).show();
}
}
Above is my code which allows a user to enter data into the firebase database. It saves the data so the current logged in user can view it. However, the issue I have is that, it does not save the data only for the logged in user. Whenever I log in with other users, it displays the same inputted data.
I'm confused on how to fix this.
Any help will be helpful.
*Note - do I need to set something up on the main activity file or is there some code I use for each separate class file to ensure its specific for the current logged in user.
You need to use this database:
Artists
userId
artistName: "userX"
artistEmail: "userx#gmail.com"
userId
artistName: "userY"
artistEmail: "usery#gmail.com"
After a user logs in, then you can retrieve his unique userId, and save data under only that id:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference("Artists").child(userId);
ref.child("artistName").setValue("userZ");
ref.child("artistEmail").setValue("userZ#gmail.com");
Here a new user is logged in and his data is saved in the database, under only his id.

Categories

Resources