I'm making an edit page for the user profile in Firebase. I've tried a few different ways. But I could not update. Just a added as a new user to the database.
I am getting new values in the Alert Dialog. Please help me.
My Update Method Code's :
public void editAlert() {
LayoutInflater layoutInflater = LayoutInflater.from(ProfilePage.this);
View design = layoutInflater.inflate(R.layout.edit_profile, null);
final EditText editTextUserName = design.findViewById(R.id.username_editTextProfileEdit);
final EditText editTextRealName = design.findViewById(R.id.realName_editTextProfileEdit);
final EditText editTextSurname = design.findViewById(R.id.username_editTextProfileEdit);
final EditText editTextEmail = design.findViewById(R.id.email_editTextProfileEdit);
final EditText editTextPassword = design.findViewById(R.id.password_editTextProfileEdit);
AlertDialog.Builder alertDialoga = new AlertDialog.Builder(ProfilePage.this);
alertDialoga.setTitle("Edit Profile");
alertDialoga.setView(design);
alertDialoga.setPositiveButton("Finish", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String username = editTextUserName.getText().toString().trim();
String realName = editTextRealName.getText().toString().trim();
String surname = editTextSurname.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
String admin = "false";
String url = "test_url";
String key = myRef.push().getKey();
Users user = new Users(key,username,realName,surname,email,password,url,admin);
HashMap<String,Object> data = new HashMap<>();
data.put("user_email", email);
data.put("user_name", realName);
data.put("user_password", password);
data.put("user_surname", surname);
data.put("username", username);
myRef.child(user.getUser_id()).updateChildren(data);
Toast.makeText(ProfilePage.this, "Uptaded!", Toast.LENGTH_SHORT).show();
}
});
alertDialoga.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialoga.show();
}
My Create User Code's :
// Sign Up Method
// Kullanıcı Kayıt etme metodu
public void signUp(View view) {
UUID uuid = UUID.randomUUID();
final String imageName = "ProfileImages/"+uuid+".jpg";
final ProgressDialog dialog = new ProgressDialog(signupPage.this);
dialog.setTitle("Creating user record.. ");
dialog.setMessage("User registration is in progress..");
dialog.show();
StorageReference storageReference = mStorageRef.child(imageName);
storageReference.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Url
StorageReference newReference = FirebaseStorage.getInstance().getReference(imageName);
newReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dowloadURL = uri.toString();
if (dowloadURL != null) {
mAuth.createUserWithEmailAndPassword(emailText.getText().toString(), passwordText.getText().toString())
.addOnCompleteListener(signupPage.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) /* Kullanıcı girişi başarılı ise bu çalışacak */ {
Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
String userName = user_name.getText().toString();
String userSurname = user_surname.getText().toString();
String username = user_username.getText().toString();
String user_email = emailText.getText().toString();
String key = myRef.push().getKey();
String password = user_password.getText().toString();
String imageURL = dowloadURL;
Users user = new Users(key, userName, username, userSurname, user_email, password,imageURL, admin);
myRef.push().setValue(user);
Intent homePage = new Intent(signupPage.this, ProfilePage.class);
startActivity(homePage);
finish();
dialog.dismiss();
} else /* Kullanıcı girişi başarısız ise bu çalışacak */ {
/*Intent signBack = new Intent(signupPage.this, signupPage.class);
startActivity(signBack);
finish(); */
dialog.dismiss();
}
}
}).addOnFailureListener(signupPage.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
The download url comes from a separate image selection method, by the way.
My user creation codes are like this.
Your problem is that instead of storing a constant and valid key in your firebase database, every time you change your profile you create a new node. How so? Well, you do this:
String key = myRef.push().getKey();
Which every time creates a new node(that is why the push is there) and you get the key of that node. That is also why you create a new user, instead of updating your account profile. The correct way to do it is the following.
When creating your user get the key with this:
String key = FirebaseAuth.getInstance().getCurrentUser().getUid();
After you create your User Object with this key, do the following:
myRef.child(key).setValue(user);
When you want to update your user, you can access the key the same way you created it. After getting all the update information and the key, then do:
myRef.child(key).setValue(data); //For updating
or
myRef.child(key).updateChildren(data); //For updating
//Get reference to update location
DatabaseRefrence dR = FirebaseDatabase.getInstance().getRefrence().child(your child name in string);
//set value
Map<String, Object> hasMap = new HashMap<>();
hasmap.put("name","Ethrak");
//update reference
dR.updateChildren(hashmap);
Related
I have tried all of the StackOverflow methods but all the methods are checking if it's null or not.
I wanted to check the particular strings under the "Users" node. example: (aaaaa) (bbbbb) or the child value in it (username : "aaaaa")
if users enter username as "asaaa" or "bbbbb" in registration will be a prompt error. (i want to check all of the values in all of the nodes of firebase)
I have searched all over the stack overflow but most of the solutions need to know the node names in order to run. I want to retrieve all of the names of the nodes under "Users" back to check.
if a user uses "aaaaa" as a username during registration will be setError in the TextInputLayout.
public class RegisterActivity extends AppCompatActivity {
EditText username, fullname, email, password;
Button register;
TextView txt_login;
public String strUsername;
FirebaseAuth auth;
DatabaseReference reference;
ProgressDialog pd;
private static final String TAG = "RegisterActivity";
private static String users_from_database;
private ArrayList<String> username_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = findViewById(R.id.username);
fullname = findViewById(R.id.fullname);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
register = findViewById(R.id.btn_Register);
txt_login = findViewById(R.id.txt_login);
auth = FirebaseAuth.getInstance();
checkForUsername();
txt_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,HomeActivity.class));
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = new ProgressDialog(RegisterActivity.this);
pd.setMessage("Please wait...");
pd.show();
String str_username = username.getText().toString();
String str_fullname = fullname.getText().toString();
String str_email = email.getText().toString();
String str_password = password.getText().toString();
strUsername = username.getText().toString().trim();
if (!username_list.contains(strUsername)) {
// do your job here , suppose send verification code to phone number
if(TextUtils.isEmpty(str_username) || TextUtils.isEmpty(str_fullname) || TextUtils.isEmpty(str_email) ||
TextUtils.isEmpty(str_password)){
Toast.makeText(RegisterActivity.this,"All fields are required!",Toast.LENGTH_SHORT).show();
pd.dismiss();
} else if (str_password.length() < 6) {
Toast.makeText(RegisterActivity.this,"Password must be over 6 characters.",Toast.LENGTH_SHORT).show();
pd.dismiss();
} else {
register(str_username,str_fullname,str_email,str_password);
}
} else {
username.setError("Username Exist");
}
}
});
}
private void checkForUsername(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
users_from_database = (String) ds.child("username").getValue();
username_list.add(users_from_database);
StringBuilder stringBuilder = new StringBuilder();
for (String s : username_list) {
stringBuilder.append(s + "\n");
}
Log.d("ZI", stringBuilder.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("ZI", "Failed");
}
});
}
private void register(final String username, final String fullname, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser firebaseUser = auth.getCurrentUser();
String userID = firebaseUser.getUid();
firebaseUser.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegisterActivity.this,"Verification Email Has Been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Email not sent" + e.getMessage());
}
});
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(username);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("username",username.toLowerCase());
hashMap.put("fullname",fullname);
hashMap.put("email",email);
hashMap.put("password",password);
hashMap.put("imageurl","");
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
pd.dismiss();
Intent intent = new Intent(RegisterActivity.this,EmailActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
});
} else {
pd.dismiss();
Toast.makeText(RegisterActivity.this,"Register Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
}
pic 2
You can create a public path usernames where you just store the usernames that are already used and are publicly visible. When registering a new user you can check there is a username already exists. Also don't try to get all of then to check if a single one exists. Just call the path usernames/{username} and if that is null there username doens't exist. Reading all of them would blow up your Firebase bill.
I have searched all over the stack overflow but most of the solutions need to know the node names in order to run.
Even in your example, you can check if a user exists by checking the existence of the following node in the database:
root/users/$userName
In code should look like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
DatabaseReference userNameRef = usersRef.child("aaaaa");
userNameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
if(snapshot.exists()) {
String fullName = snapshot.child("fullName").getValue(String.class);
Log.d("TAG", fullName);
} else {
Log.d("TAG", "The user doesn't exist!");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
While #TarikHuber answer it will work, please note that in this case, it's not necessary to create an additional node to hold all usernames, since your database structure already does that. So in terms of checking if a user exists:
root/users/$userName
It's the exact same thing as:
root/usernames/$userName
Since the nodes in the Realtime Database are represented by pairs of keys and values, please note that the keys are unique. So there is no way you can have duplicate nodes. As each node can be considered a Map.
However, if by chance you can have multiple users in the database sharing the same user name, then you should use a query as in the following lines of code:
Query queryByUserName = usersRef.orderByChild("username").equalTo("aaaaa");
queryByUserName.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
if(ds.exists()) {
String fullName = ds.child("fullName").getValue(String.class);
Log.d("TAG", fullName);
} else {
Log.d("TAG", "The user doesn't exist!");
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
According to your screenshot, in both cases, the result in the logcat will be:
james
P.S. While #ZahidIslam answer might also work, downloading the entire "Users" node and performing the check on the client is not the best option, as it's considered very costly. It's a waste of bandwidth and resources.
Edit:
According to you last comment:
I think u misunderstood me. I want to search thru all the nodes under the rootNodes
There is no way you can create a Query that can search under all nodes inside your database. You can, however, download the entire database and do the filtering on the client, but this is very costly and not recommended.
The best option that you have is to create a separate query for each and every node, but only if all the children have the same fields. Or you can keep the users only in the "Users" node (as you do right now), and the code in my answer will always work perfectly fine.
Yes you can do it by following steps .
get all username child from your DatabaseReference and add it to a ArrayList.
Check user provided username is available in ArrayList (from step 1) or not . If contains then set error , otherwise do your job to complete registration .
Update- I think you are performing button click for registration before executing / finished checkForUsername(); method. So the if...else statement not working properly and its overriding data . It was my mistake . We should perform check all users from database first then perform the next part of registration . So without using checkForUsername() method separately in onCreate() , we will do everything in button on click . check the code -
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = new ProgressDialog(LoginActivity.this);
pd.setMessage("Please wait...");
pd.show();
String str_username = username.getText().toString();
String str_fullname = fullname.getText().toString();
String str_email = email.getText().toString();
String str_password = password.getText().toString();
strUsername = username.getText().toString().trim();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
users_from_database = (String) ds.child("username").getValue();
username_list.add(users_from_database);
StringBuilder stringBuilder = new StringBuilder();
for (String s : username_list) {
stringBuilder.append(s + "\n");
}
// Log.d("ZI", stringBuilder.toString());
if (!username_list.contains(strUsername)) {
// do your job here , suppose send verification code to phone number
if (TextUtils.isEmpty(str_username) || TextUtils.isEmpty(str_fullname) || TextUtils.isEmpty(str_email) ||
TextUtils.isEmpty(str_password)) {
Toast.makeText(LoginActivity.this, "All fields are required!", Toast.LENGTH_SHORT).show();
pd.dismiss();
} else if (str_password.length() < 6) {
Toast.makeText(LoginActivity.this, "Password must be over 6 characters.", Toast.LENGTH_SHORT).show();
pd.dismiss();
} else {
register(str_username, str_fullname, str_email, str_password);
}
} else {
username.setError("Username Exist");
pd.dismiss();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("ZI", "Failed");
}
});
}
});
Update- you can check DataSnapshot exist or not . If not exist , then you can set test value to start your database . This will execute only one time . You may check -
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = new ProgressDialog(LoginActivity.this);
pd.setMessage("Please wait...");
pd.show();
String str_username = username.getText().toString();
String str_fullname = fullname.getText().toString();
String str_email = email.getText().toString();
String str_password = password.getText().toString();
strUsername = username.getText().toString().trim();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()) {
HashMap<String, Object> testHash = new HashMap<>();
testHash.put("username", "testusername");
ref.child("test")
.setValue(testHash).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
ref.keepSynced(true);
Toast.makeText(LoginActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
pd.dismiss();
} else {
Log.d("ZI", "Failed ", task.getException());
}
}
});
} else {
for (DataSnapshot ds : snapshot.getChildren()) {
users_from_database = (String) ds.child("username").getValue();
username_list.add(users_from_database);
StringBuilder stringBuilder = new StringBuilder();
for (String s : username_list) {
stringBuilder.append(s + "\n");
}
Log.d("ZI", stringBuilder.toString());
if (!username_list.contains(strUsername)) {
// do your job here , suppose send verification code to phone number
if (TextUtils.isEmpty(str_username) || TextUtils.isEmpty(str_fullname) || TextUtils.isEmpty(str_email) ||
TextUtils.isEmpty(str_password)) {
Toast.makeText(LoginActivity.this, "All fields are required!", Toast.LENGTH_SHORT).show();
pd.dismiss();
} else if (str_password.length() < 6) {
Toast.makeText(LoginActivity.this, "Password must be over 6 characters.", Toast.LENGTH_SHORT).show();
pd.dismiss();
} else {
register(str_username, str_fullname, str_email, str_password);
}
} else {
username.setError("Username Exist");
pd.dismiss();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("ZI", "Failed");
}
});
}
});
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 had users stored in firestore collection under the path users.
i want that query get the data for a users depend on what I put for users.
i.e : I had a students and notification for different stages . if stage second. i retrieve second from getuser() fun then pars it to init() fun. i had tried that but it shows that string value is null
private void init() {
Query query = firebaseFirestore.collection("docs").orderBy("date", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<download> docsFirestoreRecyclerOptions = new FirestoreRecyclerOptions.Builder<download>()
.setQuery(query, download.class)
.build();
adapter = new FirestoreRecyclerAdapter<download, docViewHolder>(docsFirestoreRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull final docViewHolder holder, int position, #NonNull final download model) {
//teacher, name, date, url;
holder.teacher.setText(model.getTeacher());
holder.name.setText(model.getName());
holder.date.setText(model.getDate());
holder.url.setText(model.getLink());
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),R.string.under_dev, Toast.LENGTH_SHORT).show();
}
});
final String url = holder.url.getText().toString();
holder.doc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);*/
if (url.isEmpty()) {
Toast.makeText(getContext(), "this doesn't contains a link for download", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(v.getContext(), otherUrl.class);
i.putExtra("URL", url);
v.getContext().startActivity(i);
}
}
});
}
#NonNull
#Override
public docViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.downloads, parent, false);
return new docViewHolder(view);
}
};
}
public void checkuser() {
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
boolean emailVerified = user.isEmailVerified();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid().toString();
DocumentReference ref=firebaseFirestore.collection("users").document(userId);
ref.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
assert value != null;
// docView=value.getString("stage");
textStage.setText(value.getString("stage"));
getStage=value.getString("stage");
}
});
}
}
As per your question, you are saying that you want to fire a query to select a particular user from the database. Is that true?
then
String user - "uid12321";
Query query = firebaseFirestore.collection("docs").collection(user);
Fire above query to get particular user.
I'm not sure what the problem is. I'm a beginner developer and I coded a registration/login page for an Android app I'm working on. New users are saved in Firebase Authorization but not in Firebase Database. My current rules are set to false but when I try to set them to true, the app keeps returning to the SetupActivity rather than the MainActivity. The app works fine when the rules are set to false but as I said, nothing appears in the Database. Here is my code:
public class SetupActivity extends AppCompatActivity {
private EditText FullName, EmailAddress, Password, CountryName;
private Button SaveInfoButton;
private ProgressDialog LoadingBar;
private CircleImageView ProfileImage;
private FirebaseAuth register_auth;
private DatabaseReference userreference;
private String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
register_auth = FirebaseAuth.getInstance();
currentUserID = register_auth.getCurrentUser().getUid();
userreference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
FullName = findViewById(R.id.name_setup);
EmailAddress = findViewById(R.id.email_setup);
Password = findViewById(R.id.password_setup);
CountryName = findViewById(R.id.country_setup);
SaveInfoButton = findViewById(R.id.save_button);
ProfileImage = findViewById(R.id.profile_setup);
LoadingBar = new ProgressDialog(this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String full_name = FullName.getText().toString();
String email = EmailAddress.getText().toString();
String password = Password.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(full_name)) {
Toast.makeText(this, "Please enter your name.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country)) {
Toast.makeText(this, "Please enter country.", Toast.LENGTH_SHORT).show();
}
else {
LoadingBar.setTitle("Creating new account!");
LoadingBar.setMessage("Please wait while your account is being created.");
LoadingBar.show();
LoadingBar.setCanceledOnTouchOutside(true);
register_auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
LoadingBar.dismiss();
Toast.makeText(SetupActivity.this, "Registration was successful!", Toast.LENGTH_SHORT).show();
SaveAccountInformation();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Registration unsuccessful." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
private void SaveAccountInformation() {
String full_name = FullName.getText().toString();
String country = CountryName.getText().toString();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("fullname", full_name);
childUpdates.put("country", country);
childUpdates.put("status", "Hey there, I am using Study Guide!");
childUpdates.put("birthday", "none");
userreference.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendToLogin();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "An error occurred. " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SendToLogin() {
Intent LoginIntent = new Intent(SetupActivity.this,LoginActivity.class);
LoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(LoginIntent);
finish();
}
}
If someone could point me in the right direction or let me know what I'm doing wrong, it will be very much appreciated!
Hazal you are not saving the data , you are updating the data so change your code
from
userreference.updateChildren(childUpdates)
To
userreference.setValue(childUpdates)
You need to manually save the users in your Firebase Database once a new user is registered.
You can look at the docs on how to write data.
In my database, I have table called Product, and inside the product child from another table which is the FK of the Product table. And the PK of the table Product is pro_id.
So I wanted to create update for product page. I've write the coding but i realized it I wrote the code wrongly and now I'm not sure on how to call this table so that I can update my product table. enter image description here
how should I write for the first child ?
I have declare my database but it seems like key refer to the pro_id instead of the child before the product id. How to do that please help me.
key=getIntent().getExtras().get("key").toString();
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference("Product").child(key);
mStorageRef= FirebaseStorage.getInstance().getReference();
Product product = new Product(id,pname,pcategory,pprice,downloadUrl.toString());
databaseReference.child("Product").child("").child(id).setValue(product) //table and primary key
this is code for add product
private void createProduct(){
if(CropImageUri !=null){
final String id = databaseReference.push().getKey();
final StorageReference ref = mStorageRef.child("images").child(id + "." +getFileExtension(CropImageUri));
mUploadTask = ref.putFile(CropImageUri)//save image into storage reference
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot task) {
Toast.makeText(getApplicationContext(),"Upload Successful",Toast.LENGTH_LONG).show();
//get url from the storage reference and assign to uri
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
String name = pro_name.getText().toString().trim();
// String description = pro_desc.getText().toString().trim();
String price = pro_price.getText().toString().trim();
String category = pro_category.getSelectedItem().toString();
String imgurl = downloadUrl.toString();
Product product = new Product(id,name,price,imgurl,category);
databaseReference.child("Product").child(key).child(id).setValue(product) //table and primary key
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(AddProductActivity.this, "Add Successfully", Toast.LENGTH_SHORT).show();
finish();
Intent intent = new Intent(AddProductActivity.this, BrandActivity.class);
intent.putExtra("pro_id", id);
startActivity(intent);
} else {
Toast.makeText(AddProductActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
Toast.makeText(getApplicationContext(), "No file selected", Toast.LENGTH_SHORT).show();
}
}
this is my product adapter
Picasso.with(context).load(productList.get(i).getPro_image()).into(myViewHolder.image);
myViewHolder.name.setText(productList.get(i).getPro_name());
myViewHolder.category.setText(productList.get(i).getPro_category());
myViewHolder.price.setText(productList.get(i).getPro_price());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
// String key1 = brandList.get(i).getBrand_id();
String key = productList.get(i).getPro_id();
String name = productList.get(i).getPro_name();
String category= productList.get(i).getPro_category();
String price = productList.get(i).getPro_price();
String image = productList.get(i).getPro_image();
Intent intent = new Intent(context, updateProduct.class);
// intent.putExtra("key1",key1);
intent.putExtra("key",key);
intent.putExtra("pro_name",name);
intent.putExtra("pro_category",category);
intent.putExtra("pro_price",price);
intent.putExtra("pro_image",image);
context.startActivity(intent);
}
});
}
and I don't really know on how to refer that "key" inside my updateProduct page
The .child("") should contain a key reference to product collection.
Product product = new Product(id,pname,pcategory,pprice,downloadUrl.toString());
databaseReference.child("Product").child("p1").child(id).setValue(product)