Firebase Overwrite - android

Here is my code.
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String emails = user.getEmail().toString().trim();
String titless = mtitle.getText().toString().trim();
String pricess = mprice.getText().toString();
String timess = mtime.getText().toString();
String productss = mproduct.getText().toString();
String detailss = mdetail.getText().toString();
String categorys = mspinner.getSelectedItem().toString().trim();
final ContactsInfo contact = new ContactsInfo(emails,titless,pricess,timess,productss,detailss,categorys);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
i = (int) dataSnapshot.child("商品").getChildrenCount();
}
#Override
public void onCancelled(DatabaseError error) {
}
});
mRef.child("商品").child(String.valueOf(i)).setValue(contact);
}
});
}}
When I use this code to write into my firebase,it will overwrite number0's data,after that it will work normally, I want to know how should I do if I don't want it to overwrite my previous data.

The onDataChange function code is executed at a later point of time than setValue. The onDataChange function is called asynchronously. Try the following code -
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth = FirebaseAuth.getInstance();
final FirebaseUser user = auth.getCurrentUser();
String emails = user.getEmail().toString().trim();
String titless = mtitle.getText().toString().trim();
String pricess = mprice.getText().toString();
String timess = mtime.getText().toString();
String productss = mproduct.getText().toString();
String detailss = mdetail.getText().toString();
String categorys = mspinner.getSelectedItem().toString().trim();
final ContactsInfo contact = new ContactsInfo(emails, titless, pricess, timess, productss, detailss, categorys);
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
i = (int) dataSnapshot.child("商品").getChildrenCount();
mRef.child("商品").child(String.valueOf(i)).setValue(contact);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
});

Related

How to filter edit text from a firebase data?

This is the code from which I get the text:
etSearchFriends = (EditText) findViewById(R.id.etSearchFriends);
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchText = etSearchFriends.getText().toString();
filterLocation(searchText);
}
});
Here's the filter where code should work but sadly it isn't:
private void filterLocation(final String s) {
final ArrayList<User> users = new ArrayList<>();
Log.d("UserData1",s);
fRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
fname = dataSnapshot1.child("fname").getValue(String.class);
}
for (User user1 : ListOfBranches.getUsers()) {
if (fname.toLowerCase().contains(s)) {
users.add(user1);
Log.d("UserData3", dataSnapshot.getValue(String.class));
}
}
friendsAdapter.filterLocation(users);
}
While this is the list where another data is fetched from database:
userRef = FirebaseDatabase.getInstance().getReference().child("UserFiture");
userRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// User user1 = dataSnapshot.getValue(User.class);
User u = new User();
String fname = dataSnapshot.child("fName").getValue(String.class);
String lname = dataSnapshot.child("lName").getValue(String.class);
String age = dataSnapshot.child("age").getValue(String.class);
String gender = dataSnapshot.child("gender").getValue(String.class);
u.setfName(fname);
u.setlName(lname);
u.setAge(age);
u.setGender(gender);
users.add(u);
Log.e("dataSnapshot", String.valueOf(u));
}
I want to get all the data here and show it if search text is equals to fname:

Retrieve specific data from firebase

I'm new to firebase, I tried to look into the documentation and youtube but just couldn't figure it out.
I have a simple id and display_name structure database in firebase:
AppName{
users{
HzIYTbIbSzSlinF1Aa52WYUcD4E2{
display_name: "Greg Nks"
}
}
And I want the data to get into a User object, with Id(string) and display_name(string)
I tried to test my retrieving data, but I cant get it.
this is my code:
public void initializeVariables(View view){
mToolBar = view.findViewById(R.id.users_appBar);
usersRv = view.findViewById(R.id.friends_list_rv);
mLayoutManager= new LinearLayoutManager(view.getContext());
myDataset = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null){
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//remember it will called in the start of the fragment
showData(dataSnapshot); //TODO fix the reading from firebase
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void showData(DataSnapshot dataSnapshot){
User u= dataSnapshot.getValue(User.class);
u=null;
}
Thanks!
Class User {
private String display_name;
private String userKey;
public User(){
}
public User(String name,String key){
display_name = name;
userKey = key;
}
public void setDisplay_name(Sring name)
{
display_name = name;
}
public String getDisplay_name()
{
return display_name;
}
public void setUserKey(Sring key)
{
userKey = key;
}
public String getUserKey()
{
return userKey;
}
}
now change this statment
User u= dataSnapshot.getValue(User.class);
by this :
String key = datasnapshot.getKey();
String name = datasnapshot.child('display_name').getValue().toString();
User user = new User(name, key);

Android: Compare data between input and data retrieved from firebase

User data in firebase:
User class:
public User(String mName, String mEmail, String password, int mAge, String mGender) {
this.mName = mName;
this.mEmail = mEmail;
this.mAge = mAge;
this.mPassword=password;
this.mGender = mGender;
}
public String getPassword() {
return mPassword;
}
public String getEmail() {
return mEmail;
}
Retrieve user table:
#Override
protected void onStart() {
super.onStart();
mDataBase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
mUser = userSnapshot.getValue(User.class);
mUsers.add(mUser);
}
}
Then I was trying to validate email and password with input:
mEmail = (String) mEmailEt.getText().toString().trim().toLowerCase();
mPassword = (String) mPwdEt.getText().toString().trim().toLowerCase();
mLoginButton = findViewById(R.id.loginBtn);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(mEmail, mPassword) == 1){
Intent intent = new Intent(getApplicationContext(),MainPage.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Login Failed", Toast.LENGTH_LONG).show();
}
}
});
public int validate(String email, String pwd) {
for (User user : mUsers) {
if (email.equals(user.getEmail().trim().toLowerCase()) && pwd.equals(user.getPassword().trim().toLowerCase())){
return 1;
}
}
return 0;
}
The problem is I did successfully retrieve the data, but I have no idea why the comparison always return 0. I cannot see any wrong here. Any answer would be a great help. Thanks!

Edit item under pushed ID from firebase through Android Studio

My goal is to edit the "price" under a pushed ID in my database. My current code does not let me edit it, but instead it creates another pushed ID. How do I edit it and not create not pushed ID? Thanks in advance.
This is my code for editing the data:
String uid = currentUser.getUid();
prodidref = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products");
String prodid = prodidref.push().getKey();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Products");
profdb = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products").child(prodid);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String keyprice = "price";
String valueprice = ETPrice.getText().toString();
DatabaseReference child = profdb.child(keyprice);
child.setValue(valueprice);
}
});
Here's a screenshot from my database:
This is the result of my current code:
If you don't know the key of the product you want to modify, you will need to perform a query find that key. This means that you must know something about the product on which you can query. E.g. if you're trying to set a price of 20 on Broccoli, you can run a query to find the Broccoli and update based on that:
DatabaseReference products = FirebaseDatabase.getInstance().getReference().child("Products");
Query broccolis = products.orderByChild("name").equalTo("Broccoli");
broccolis.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot broccoli: snapshot.getChildren()){
broccoli.getRef().child("price").setValue(20);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException()l
}
});
I hope this help you !
String uid = currentUser.getUid();
String pushKey;
prodidref = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products");
String prodid = prodidref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren())
{
Log.d("kkkk activelink",""+snapshot.getKey());
pushKey = snapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
profdb = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products").child(pushKey);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String keyprice = "price";
String valueprice = ETPrice.getText().toString();
DatabaseReference child = profdb.child(keyprice);
child.setValue(valueprice);
}
});

Android Studio Firebase Database return null object reference

Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data
private void user_info(String user_id, String user_display_name) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Name",user_display_name);
userMap.put("Balls","30");
userMap.put("Level","1");
mProgressDialog.setMessage("Please Wait...");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}
else
Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
And how I try to retrieve the data
private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_acticity);
//Image
mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);
//Firebase
mUser = FirebaseAuth.getInstance().getCurrentUser();
String user_id = mUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
The toast don't show anything because it null
Change this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
to this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.

Categories

Resources