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)
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");
}
});
}
});
I'm using this hashmap to transfer the username from one child(Users) to another(Notes) in database.
In my app you can create as well as update notes.
I want that every time a note is created or updated in the database a username is added along with the note. the username is saved in the users child.
But when the note is created the username doesn't show up. But when the note is updated, it is added in the child.
here is the code:
fAuth = FirebaseAuth.getInstance();
fNotesDatabase = FirebaseDatabase.getInstance().getReference()
.child("Notes").child(fAuth.getCurrentUser().getUid());
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
current_user_id = fAuth.getCurrentUser().getUid();
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
createNote(title, content);
putUsername();
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void putUsername() {
UsersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.child("username").getValue().toString();
HashMap usernameMap = new HashMap();
usernameMap.put("username", username);
fNotesDatabase.child(noteID).updateChildren(usernameMap);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I'm not able to understand as how come the username is added when the note is updated but not when the note us created.
I have updated the second note thats why there is a username but when is simply created the upper one there username is not showing.
EDIT
putData method :
private void putData() {
if (isExist) {
fNotesDatabase.child(noteID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) {
String title = dataSnapshot.child("title").getValue().toString();
String content = dataSnapshot.child("content").getValue().toString();
etTitle.setText(title);
etContent.setText(content);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
createNote method:
private void createNote(String title, String content) {
if (fAuth.getCurrentUser() != null) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
if (isExist) {
Map updateMap = new HashMap();
updateMap.put("title", etTitle.getText().toString().trim());
updateMap.put("content", etContent.getText().toString().trim());
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
fNotesDatabase.child(noteID).updateChildren(updateMap);
SendUsersToPostActivity();
Toast.makeText(this, "Article updated", Toast.LENGTH_SHORT).show();
} else {
final DatabaseReference newNoteRef = fNotesDatabase.push();
final Map noteMap = new HashMap();
noteMap.put("title", title);
noteMap.put("content", content);
noteMap.put("timestamp", ServerValue.TIMESTAMP);
noteMap.put("date",saveCurrentDate);
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
newNoteRef.setValue(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article Created", Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mainThread.start();
}
}
}
It's hard to be certain, but I don't see where you set the noteID value that putUsername depends on.
In general though, I'd recommend changing createNote to take all the data that it needs for the new note, including the user name:
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = etTitle.getText().toString().trim();
String content = etContent.getText().toString().trim();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content) && fAuth.getCurrentUser() != null) {
UsersRef.child(current_user_id).child("username").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String username = snapshot.getValue(String.class);
createNote(title, content, current_user_id, username);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException()
}
});
} else {
Snackbar.make(view, "Fill empty fields", Snackbar.LENGTH_SHORT).show();
}
}
});
private void createNote(String title, String content, String uid, String username) {
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
Map updateMap = new HashMap();
updateMap.put("title", title);
updateMap.put("content", content);
updateMap.put("timestamp", ServerValue.TIMESTAMP);
updateMap.put("date",saveCurrentDate);
updateMap.put("uid",uid);
updateMap.put("username",username);
final DatabaseReference noteRef = isExist ? fNotesDatabase.push() : fNotesDatabase.child(noteID);
noteRef.updateChildren(noteMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(NewNoteActivity.this, "Article "+(isExists ? "updated" : "created"), Toast.LENGTH_SHORT).show();
SendUsersToPostActivity();
} else {
Toast.makeText(NewNoteActivity.this, "ERROR: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
Some of the changes in this code versus yours:
Looks up the user name before creating the new note. Uses a addListenerForSingleValueEvent for this, to ensure we only do this once for every button click.
Only loads the username child of the user profile, since that's all you use.
Use the values you pass into createNote instead of recalculating them from the UI views.
Only has a single write to the database, as updateChildren works fine for creating the initial data too.
There is no need to run the Firebase setValue call on a new thread, as Firebase runs it off the main thread already.
Please don't leave onCancelled empty, as it may hide important error messages.
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);
I have compared the others questions but they have different problems.
My question is, how can I display (on the user activity) all the products that the sellers have added on the firebase database?
The sellers have their own register and login activity before they add the products, meaning each seller will be having is own name or id.
You can check my database sample on the picture below.
**Sorry guys I have updated the code but now it is crashing the app every time I click the button to go to the add products activity**
public class SellerAddProductActivity extends AppCompatActivity {
private String saveCurrentDate;
private String saveCurrentTime;
private String CategoryName;
private String downloadImageUrl;
private String productRandomKey;
private String Description;
private String Price, Quantity, State;
private String Pname, Store;
private Button AddProductButton;
private EditText InputProductName;
private EditText InputProductPrice, InputStoreName;
private EditText InputProductDescription, InputProductQauntity, InputProductState;
private StorageReference ProductImageRef;
private Uri ImageUri;
private DatabaseReference ProductsRef, ProductsInfo;
private ProgressDialog loadingBar;
private static final int GalleryPick = 1;
private ImageView InputProductImage;
FirebaseUser currentUser;
FirebaseUser mAuth;
String userID = mAuth.getUid(); //--> Store each seller name with this ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_add_product);
ProductImageRef = FirebaseStorage.getInstance().getReference().child("Product Images");
CategoryName = getIntent().getExtras().get("category").toString();
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
ProductsInfo = FirebaseDatabase.getInstance().getReference().child("ProductsInfo");
mAuth = FirebaseAuth.getInstance().getCurrentUser();
AddProductButton = (Button) findViewById(R.id.add_product);
InputProductName = (EditText) findViewById(R.id.product_name);
InputProductImage = (ImageView) findViewById(R.id.product_image_select);
InputProductPrice = (EditText) findViewById(R.id.product_price);
InputProductQauntity = (EditText) findViewById(R.id.product_quantity);
InputProductState = (EditText) findViewById(R.id.product_state);
InputStoreName = (EditText) findViewById(R.id.store_name);
loadingBar = new ProgressDialog(this);
InputProductDescription = (EditText) findViewById(R.id.product_description);
InputProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateProductData();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#Override
protected void onActivityResult
(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
InputProductImage.setImageURI(ImageUri);
}
}
private void validateProductData() {
Description = InputProductDescription.getText().toString();
Price = InputProductPrice.getText().toString();
Pname = InputProductName.getText().toString();
Quantity = InputProductQauntity.getText().toString();
State = InputProductState.getText().toString();
Store = InputStoreName.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please Add Product Image!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please Enter the Product Description!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Price)) {
Toast.makeText(this, "Please Enter the Product Price!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Pname)) {
Toast.makeText(this, "Please Enter the Product Name!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Quantity)) {
Toast.makeText(this, "Enter Quantity in Number!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(State)) {
Toast.makeText(this, "Specify the State of your Product!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Store)) {
Toast.makeText(this, "Store Name is Mandatory!", Toast.LENGTH_SHORT).show();
} else {
StoreProductInfo();
}
}
private void StoreProductInfo() {
loadingBar.setTitle("Adding Product");
loadingBar.setMessage("Please wait!");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calendar.getTime());
// Unique Random Key for the Products added by the admin
productRandomKey = saveCurrentDate + saveCurrentTime;
// Unique Random Key to store the image added by the admin
final StorageReference filePath = ProductImageRef.
child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
//Displaying the Upload Error to the seller
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String message = e.toString();
Toast.makeText(SellerAddProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SellerAddProductActivity.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadImageUrl = task.getResult().toString();
Toast.makeText(SellerAddProductActivity.this, "Product Image Added",
Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase() {
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("storename", Store);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("Category", CategoryName);
productMap.put("state", State);
productMap.put("quantity", Quantity);
productMap.put("price", Price);
productMap.put("pname", Pname);
ProductsRef.child("Products").child(userID).child(productRandomKey);
ProductsInfo.child(productRandomKey).updateChildren(productMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(SellerAddProductActivity.this, SellerAddProductActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(SellerAddProductActivity.this, "Product
Added",Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
String message = task.getException().toString();
Toast.makeText(SellerAddProductActivity.this,
"Error:"+message,Toast.LENGTH_SHORT).show();
}
}
});
} }
This how I'm displaying the products on the buyer/user activity
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private DatabaseReference productsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
productsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(productsRef, Products.class).build();
FirebaseRecyclerAdapter<Products, ProductsViewHolder> adapter
= new FirebaseRecyclerAdapter<Products, ProductsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductsViewHolder holder,int position,#NonNull final Products model){
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
//sending the product ID to the ProductDetailsActivity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
});
}
#NonNull
#Override
public ProductsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_products,parent,false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
};
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
As I understand, you want to bring up all the sellers information to the one logged in in your app.
To do that you can do a for loop inside products to get each seller id, and then querie each user to get the products.
But you will need to change your database structure to make it easier.
I recommend to you to store inside the nested child Products the id of that product to querie in another table. For example
Products
|
--- userID
|
--- Products
|
--- product_key1: true
|
--- product_key2: true
And then in another node have the information of that product
ProductsInfo
|
--- product_key1
| |
| --- productName: "Orange"
| |
| --- productPrice: 1
|
--- product_key2
|
--- productName: "Pineapple"
|
--- productPrice: 3
So now, we will just get each userID and get each user products
First, instead of hardcoded seller names you should use getUid() to get each seller unique UID.
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this ID
Now we just loop inside Products to get each user ID
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
Log.d("SellersID", userKey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now that you have all the sellers key you can loop inside products and get each product key for each seller, and with that you can now get the data from ProductsInfo node
Your problem is at your database reference productsRef
You should add more to your reference, based on what you want to get from your database:
productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"
Hope it helps. For more informations ask me
I have two functions working fine in an android app with Firebase. I can upload an image to my storage and I can add attributes to my database, but how do I build a relationship between the two entries.
Here's my database code:
private void addCar(){
String make = editTextMake.getText().toString().trim();
String model = editTextModel.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
Car car = new Car(make, model, description);
FirebaseUser user = auth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(car);
Toast.makeText(this, "Information Saved....", Toast.LENGTH_LONG).show();
}
And here is my storage code:
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(uploadActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(uploadActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
I'd like a User to be able to pick an image of a car, enter the attributes relating to that image like Make/Model and press an upload button to enter both into Firebase, while knowing that the specific image is related to the specific attributes.
StorageReference filess= storageReference.child("images/" + UUID.randomUUID());
filess.putFile(url)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.e("url", taskSnapshot.getDownloadUrl() + ":");
// Get Url from here and add to your Database
addFirebase(taskSnapshot.getDownloadUrl());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
Firebase insert data
private void addFirebase(String url){
String make = editTextMake.getText().toString().trim();
String model = editTextModel.getText().toString().trim();
String description = getText().toString().trim();
Car car = new Car(make, model, description,url);
FirebaseUser user = auth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(car);
Toast.makeText(this, "Information Saved....", Toast.LENGTH_LONG).show();
}