Hello everyone! i am facing an issue, the given code is showing me same product multiple times rather than showing all the available products. Can some one help me its my FYP and i really need to solve the issue today.
Details.
package com.rent.shopping;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rent.shopping.Model.Products;
import com.rent.shopping.Prevalent.Prevalent;
import com.rent.shopping.ViewHolder.ProductViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
import io.paperdb.Paper;
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DatabaseReference ProductsRef;
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ArrayList<String> vendorIds = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Vendors");
drawerLayout=findViewById(R.id.drawer_layout);
navigationView=findViewById(R.id.nav_view);
toolbar=findViewById(R.id.toolbar);
androidx.appcompat.widget.Toolbar toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Home");
setSupportActionBar(toolbar);
navigationView.bringToFront();
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView userNameTextView = headerView.findViewById(R.id.user_profile_name);
CircleImageView profileImageView = headerView.findViewById(R.id.user_profile_image);
userNameTextView.setText(Prevalent.currentOnlineUser.getName());
Picasso.get().load(Prevalent.currentOnlineUser.getImage()).placeholder(R.drawable.profile).into(profileImageView);
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(view -\> {
Intent intent = new Intent(HomeActivity.this,CartActivity.class);
startActivity(intent);
});
}
@Override
protected void onStart() {
super.onStart();
// Get a reference to the vendors node
// Retrieve vendor IDs
ProductsRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot vendorSnapshot : dataSnapshot.getChildren()) {
String vendorId = vendorSnapshot.getKey();
ProductsRef.child(Objects.requireNonNull(vendorId)).child("Products").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
FirebaseRecyclerOptions\<Products\> options =
new FirebaseRecyclerOptions.Builder\<Products\>()
.setQuery(ProductsRef, Products.class)
.build();
FirebaseRecyclerAdapter\<Products, ProductViewHolder\> adapter =
new FirebaseRecyclerAdapter\<Products, ProductViewHolder\>(options) {
@Override
protected void onBindViewHolder(@NonNull ProductViewHolder holder, int position, @NonNull final Products model) {
for (DataSnapshot url : snapshot.getChildren()) {
holder.txtProductName.setText(url.child("pname").getValue(String.class));
holder.txtProductDescription.setText(url.child("description").getValue(String.class));
holder.txtProductPrice.setText("Price = " + url.child("price").getValue(String.class) + "Rs.");
String productImage = url.child("image").getValue(String.class);
Picasso.get().load(productImage).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", url.child("pid").getValue(String.class));
intent.putExtra("pname", url.child("pname").getValue(String.class));
intent.putExtra("description", url.child("description").getValue(String.class));
intent.putExtra("price", url.child("price").getValue(String.class));
intent.putExtra("image", url.child("image").getValue(String.class));
startActivity(intent);
}
});
}
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
return new ProductViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
vendorIds.add(vendorId);
System.out.println(vendorIds);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
@Override
public void onBackPressed(){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else
{super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_cart) {
Intent intent = new Intent(HomeActivity.this,CartActivity.class);
startActivity(intent);
} else if (id == R.id.nav_search) {
Intent intent = new Intent(HomeActivity.this,SearchProductsActivity.class);
startActivity(intent);
}
else if (id == R.id.nav_settings) {
Intent intent=new Intent(HomeActivity.this,SettinsActivity.class);
startActivity(intent);
} else if (id == R.id.nav_logout) {
Paper.book().destroy();
Intent intent=new Intent(HomeActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
Here is the database look
here is the code i used to upload the products
package com.rent.shopping;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;
public class AdminAddNewProductActivity extends AppCompatActivity {
private String CategoryName, Description, Price, saveCurrentDate, saveCurrentTime ,security ,borowingprice;
public static String Pname;
private Button AddNewProductButton ;
private ImageView InputProductImage;
private EditText InputProductName, InputProductDescription, InputProductPrice,Securityprice,Borrowingprice;
private static final int GalleryPick = 1;
private Uri ImageUri;
private String productRandomKey, downloadImageUrl;
private StorageReference ProductImagesRef;
private DatabaseReference ProductsRef;
private ProgressDialog loadingBar;
String phone;
EditText PHONE;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add_new_product);
PHONE=findViewById(R.id.number);
CategoryName = getIntent().getExtras().get("category").toString();
ProductImagesRef = FirebaseStorage.getInstance().getReference().child("Product Images");
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Vendors");
AddNewProductButton = findViewById(R.id.add_new_product);
InputProductImage = findViewById(R.id.select_product_image);
InputProductName = findViewById(R.id.product_name);
InputProductDescription = findViewById(R.id.product_description);
InputProductPrice = findViewById(R.id.product_price);
Securityprice= findViewById(R.id.security_price);
Borrowingprice= findViewById(R.id.borrowing_price);
loadingBar = new ProgressDialog(this);
InputProductImage.setOnClickListener(view -> OpenGallery());
AddNewProductButton.setOnClickListener(view -> 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, 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();
security=Securityprice.getText().toString();
borowingprice=Borrowingprice.getText().toString();
phone=PHONE.getText().toString().trim();
if (ImageUri == null)
{
Toast.makeText(this, "Product image is mandatory...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Description))
{
Toast.makeText(this, "Please write product description...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Price))
{
Toast.makeText(this, "Please write product Price...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Pname))
{
Toast.makeText(this, "Please write product name...", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(security))
{
Toast.makeText(this, "Please write Security fees...", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(borowingprice))
{
Toast.makeText(this, "Please write Borrowing price...", Toast.LENGTH_SHORT).show();
}
else
{
StoreProductInformation();
}
}
private void StoreProductInformation()
{
loadingBar.setTitle("Add New Product");
loadingBar.setMessage("Dear Admin, please wait while we are adding the new product.");
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());
productRandomKey = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = ProductImagesRef.child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(e -> {
String message = e.toString();
Toast.makeText(AdminAddNewProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}).addOnSuccessListener(taskSnapshot -> {
Toast.makeText(AdminAddNewProductActivity.this, "Product Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
{
throw Objects.requireNonNull(task.getException());
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
downloadImageUrl = task.getResult().toString();
Toast.makeText(AdminAddNewProductActivity.this, "got the Product image Url Successfully...", Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
});
});
}
private void SaveProductInfoToDatabase()
{
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("category", CategoryName);
productMap.put("price", Price);
productMap.put("Borrowing price", borowingprice);
productMap.put("Security Fees", security);
productMap.put("pname", Pname);
ProductsRef.child(phone).child("Products").child(Pname).updateChildren(productMap)
.addOnCompleteListener(task -> {
if (task.isSuccessful())
{
Intent intent = new Intent(AdminAddNewProductActivity.this, AdminCategoryActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(AdminAddNewProductActivity.this, "Product is added successfully..", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.dismiss();
String message = Objects.requireNonNull(task.getException()).toString();
Toast.makeText(AdminAddNewProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
});
}}
package com.rent.shopping;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;
public class AdminAddNewProductActivity extends AppCompatActivity {
private String CategoryName, Description, Price, saveCurrentDate, saveCurrentTime ,security ,borowingprice;
public static String Pname;
private Button AddNewProductButton ;
private ImageView InputProductImage;
private EditText InputProductName, InputProductDescription, InputProductPrice,Securityprice,Borrowingprice;
private static final int GalleryPick = 1;
private Uri ImageUri;
private String productRandomKey, downloadImageUrl;
private StorageReference ProductImagesRef;
private DatabaseReference ProductsRef;
private ProgressDialog loadingBar;
String phone;
EditText PHONE;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add_new_product);
PHONE=findViewById(R.id.number);
CategoryName = getIntent().getExtras().get("category").toString();
ProductImagesRef = FirebaseStorage.getInstance().getReference().child("Product Images");
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Vendors");
AddNewProductButton = findViewById(R.id.add_new_product);
InputProductImage = findViewById(R.id.select_product_image);
InputProductName = findViewById(R.id.product_name);
InputProductDescription = findViewById(R.id.product_description);
InputProductPrice = findViewById(R.id.product_price);
Securityprice= findViewById(R.id.security_price);
Borrowingprice= findViewById(R.id.borrowing_price);
loadingBar = new ProgressDialog(this);
InputProductImage.setOnClickListener(view -> OpenGallery());
AddNewProductButton.setOnClickListener(view -> 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, 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();
security=Securityprice.getText().toString();
borowingprice=Borrowingprice.getText().toString();
phone=PHONE.getText().toString().trim();
if (ImageUri == null)
{
Toast.makeText(this, "Product image is mandatory...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Description))
{
Toast.makeText(this, "Please write product description...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Price))
{
Toast.makeText(this, "Please write product Price...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(Pname))
{
Toast.makeText(this, "Please write product name...", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(security))
{
Toast.makeText(this, "Please write Security fees...", Toast.LENGTH_SHORT).show();
}else if (TextUtils.isEmpty(borowingprice))
{
Toast.makeText(this, "Please write Borrowing price...", Toast.LENGTH_SHORT).show();
}
else
{
StoreProductInformation();
}
}
private void StoreProductInformation()
{
loadingBar.setTitle("Add New Product");
loadingBar.setMessage("Dear Admin, please wait while we are adding the new product.");
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());
productRandomKey = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = ProductImagesRef.child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(e -> {
String message = e.toString();
Toast.makeText(AdminAddNewProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}).addOnSuccessListener(taskSnapshot -> {
Toast.makeText(AdminAddNewProductActivity.this, "Product Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
{
throw Objects.requireNonNull(task.getException());
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
downloadImageUrl = task.getResult().toString();
Toast.makeText(AdminAddNewProductActivity.this, "got the Product image Url Successfully...", Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
});
});
}
private void SaveProductInfoToDatabase()
{
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("category", CategoryName);
productMap.put("price", Price);
productMap.put("Borrowing price", borowingprice);
productMap.put("Security Fees", security);
productMap.put("pname", Pname);
ProductsRef.child(phone).child("Products").child(Pname).updateChildren(productMap)
.addOnCompleteListener(task -> {
if (task.isSuccessful())
{
Intent intent = new Intent(AdminAddNewProductActivity.this, AdminCategoryActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(AdminAddNewProductActivity.this, "Product is added successfully..", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.dismiss();
String message = Objects.requireNonNull(task.getException()).toString();
Toast.makeText(AdminAddNewProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
});
}}
i am using java and firebase for MULTIVENDER renting app but its not showing me the products rightly only one product is showing me repeatedly