как я могу получить продукцию продавцов - PullRequest
1 голос
/ 13 марта 2019

Я сравнил другие вопросы, но у них разные проблемы. У меня вопрос, как я могу отобразить (по активности пользователя) все продукты, которые продавцы добавили в базу данных Firebase? У продавцов есть собственный реестр и вход в систему, прежде чем они добавят продукты, то есть каждый продавец будет иметь свое имя или идентификатор. Вы можете проверить образец моей базы данных на картинке ниже.

**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",

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

Добавлено», Toast.LENGTH_SHORT) .show (); } еще { loadingBar.dismiss (); String message = task.getException (). ToString (); Toast.makeText (SellerAddProductActivity.this, "Ошибка:" + сообщение, Toast.LENGTH_SHORT) .show (); } } }); }}

Вот так я показываю продукты по активности покупателя / пользователя

открытый класс HomeActivity расширяет возможности AppCompatActivity 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);
    }

firebase database

Ответы [ 2 ]

1 голос
/ 14 марта 2019

Насколько я понимаю, вы хотите перенести всю информацию о продавцах на ту, которая вошла в ваше приложение.

Для этого вы можете выполнить цикл for внутри продуктов, чтобы получить идентификатор каждого продавца, а затемзапросите каждого пользователя для получения продуктов.

Но вам нужно будет изменить структуру базы данных, чтобы упростить ее.

Я рекомендую вам хранить внутри вложенных дочерних продуктов идентификатор этого продукта.запросить в другой таблице.Например,

Products
    |
    --- userID
           |
           --- Products
                 |
                 --- product_key1: true
                 |
                 --- product_key2: true

И затем в другом узле есть информация об этом продукте

ProductsInfo
    |
    --- product_key1
    |            |
    |            --- productName: "Orange"
    |            |
    |            --- productPrice: 1
    |
    --- product_key2
                 |
                 --- productName: "Pineapple"
                 |
                 --- productPrice: 3

Итак, теперь мы просто получим каждый идентификатор пользователя и получим каждый пользовательский продукт

Во-первых, вместо жестко закодированных имен продавцов вы должны использовать getUid() для получения уникального UID каждого продавца.

FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this ID

Теперь мы просто зациклились внутри Products, чтобы получить идентификатор каждого пользователя

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) {

    }
});

Теперь, когда у вас есть все ключи продавцов, вы можете зациклить их внутри products и получить каждый ключ продукта для каждого продавца, и теперь вы можете получать данные из ProductsInfo узла

0 голосов
/ 13 марта 2019

Ваша проблема в вашей базе данных productsRef

Вы должны добавить больше к вашей ссылке, основываясь на том, что вы хотите получить из вашей базы данных:

productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"

Надеюсь, это поможет. Для получения дополнительной информации спросите меня

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...