Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我怎样才能得到卖家的产品_Java_Android_Firebase_Firebase Realtime Database - Fatal编程技术网

Java 我怎样才能得到卖家的产品

Java 我怎样才能得到卖家的产品,java,android,firebase,firebase-realtime-database,Java,Android,Firebase,Firebase Realtime Database,我比较了其他问题,但它们有不同的问题。 我的问题是,如何(在用户活动中)显示卖家在firebase数据库中添加的所有产品? 卖家在添加产品之前有自己的注册和登录活动,这意味着每个卖家都有自己的姓名或id。 您可以在下图中查看我的数据库示例。 **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 activ

我比较了其他问题,但它们有不同的问题。 我的问题是,如何(在用户活动中)显示卖家在firebase数据库中添加的所有产品? 卖家在添加产品之前有自己的注册和登录活动,这意味着每个卖家都有自己的姓名或id。 您可以在下图中查看我的数据库示例。

**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**
公共类SellerAddProductActivity扩展了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",
私有字符串saveCurrentDate;
私有字符串saveCurrentTime;
私有字符串CategoryName;
私有字符串下载ImageURL;
私钥;
私有字符串描述;
私有字符串价格、数量、状态;
私有字符串Pname,存储;
私有按钮AddProductButton;
私有EditText InputProductName;
private EditText InputProductPrice、InputStoreName;
私有EditText InputProductDescription、InputProductQanity、InputProductState;
私有存储参考ProductImageRef;
私有Uri-ImageUri;
私有数据库参考产品ref,ProductsInfo;
私有进程对话框加载栏;
专用静态最终int GalleryPick=1;
私有ImageView InputProductImage;
FirebaseUser当前用户;
FirebaseUser mAuth;
字符串userID=mAuth.getUid();//-->使用此ID存储每个卖家名称
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u seller\u add\u product);
ProductImageRef=FirebaseStorage.getInstance().getReference().child(“产品图像”);
CategoryName=getIntent().getExtras().get(“类别”).toString();
ProductsRef=FirebaseDatabase.getInstance().getReference().child(“产品”);
ProductsInfo=FirebaseDatabase.getInstance().getReference().child(“ProductsInfo”);
mAuth=FirebaseAuth.getInstance().getCurrentUser();
AddProductButton=(按钮)findViewById(R.id.add\u产品);
InputProductName=(EditText)findViewById(R.id.product\u name);
InputProductImage=(ImageView)findViewById(R.id.product\u image\u select);
InputProductPrice=(EditText)findViewById(R.id.product\U price);
InputProductQanity=(EditText)findViewById(R.id.product\U数量);
InputProductState=(EditText)findViewById(R.id.product\u状态);
InputStoreName=(EditText)findViewById(R.id.store\u name);
loadingBar=新建进度对话框(此对话框);
InputProductDescription=(EditText)findViewById(R.id.product\u description);
InputProductImage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
OpenGallery();
}
});
AddProductButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
validateProductData();
}
});
}
私有void OpenGallery(){
Intent gallerycontent=新Intent();
GalleryContent.setAction(Intent.ACTION\u GET\u CONTENT);
GalleryContent.setType(“image/*”);
startActivityForResult(GalleryContent,GalleryPick);
}
@凌驾
活动结果上的受保护无效
(int requestCode、int resultCode、@Nullable Intent data){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==GalleryPick&&resultCode==RESULT\u OK&&data!=null){
ImageUri=data.getData();
InputProductImage.setImageURI(ImageUri);
}
}
私有void validateProductData(){
Description=InputProductDescription.getText().toString();
Price=InputProductPrice.getText().toString();
Pname=InputProductName.getText().toString();
数量=InputProductQUnity.getText().toString();
State=InputProductState.getText().toString();
Store=InputStoreName.getText().toString();
如果(ImageUri==null){
Toast.makeText(这是“请添加产品图像!”,Toast.LENGTH_SHORT.show();
}else if(TextUtils.isEmpty(Description)){
Toast.makeText(这是“请输入产品描述!”,Toast.LENGTH_SHORT.show();
}否则如果(TextUtils.isEmpty(价格)){
Toast.makeText(这是“请输入产品价格!”,Toast.LENGTH_SHORT.show();
}else if(TextUtils.isEmpty(Pname)){
Toast.makeText(这是“请输入产品名称!”,Toast.LENGTH_SHORT.show();
}else if(TextUtils.isEmpty(数量)){
Toast.makeText(这是“在数字中输入数量!”,Toast.LENGTH_SHORT.show();
}else if(TextUtils.isEmpty(State)){
Toast.makeText(这是“指定产品的状态!”,Toast.LENGTH_SHORT.show();
}else if(TextUtils.isEmpty(存储)){
Toast.makeText(这是“商店名称是必需的!”,Toast.LENGTH_SHORT.show();
}否则{
StoreProductInfo();
}
}
私有void StoreProductInfo(){
加载条。设置标题(“添加产品”);
loadingBar.setMessage(“请稍候!”);
加载条。设置为取消到外部(false);
loadingBar.show();
日历=Calendar.getInstance();
SimpleDataFormat currentDate=新的SimpleDataFormat(“MMM dd,yyyy”);
saveCurrentDate=currentDate.format(calendar.getTime());
SimpleDataFormat currentTime=新的SimpleDataFormat(“HH:mm:ss a”);
saveCurrentTime=currentTime.format(calendar.getTime());
//管理员添加的产品的唯一随机密钥
productRandomKey=saveCurrentDate+saveCurrentTime;
//用于存储管理员添加的图像的唯一随机键
最终StorageReference文件路径=ProductImageRef。
子对象(ImageUri.getLastPathSegment()+productRandomKey+“.jpg”);
final UploadTask UploadTask=filePath.putFile(ImageUri);
//向卖家显示上传错误
uploadTask.addOnFailureListener(新的OnFailureListener(){
@凌驾
public void onFailure(@NonNull异常e){
字符串消息=e.toString();
Toast.makeText(SellerAddProductActivity.this,“错误:+消息,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
    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);
    }
productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"
Products
    |
    --- userID
           |
           --- Products
                 |
                 --- product_key1: true
                 |
                 --- product_key2: true
ProductsInfo
    |
    --- product_key1
    |            |
    |            --- productName: "Orange"
    |            |
    |            --- productPrice: 1
    |
    --- product_key2
                 |
                 --- productName: "Pineapple"
                 |
                 --- productPrice: 3
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this 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) {

    }
});