Firebaseでの値の交換の問題

Asif Hossain

フードデリバリーアプリの開発中にFirebaseで致命的な問題が発生しました。アラートダイアログで住所の値を指定すると、Firebaseに合計金額フィールドに保存されていることが表示されます。それを解決する方法を理解することはできません。

これが私のRequest.javaファイルです

public class Request{
    private String phone;
    private String name;
    private String address;
    private String total;
    private List<Order>foods;

    public Request() {
    }

    public Request(String phone, String name, String address, String total, List<Order> foods) {
        this.phone = phone;
        this.name = name;
        this.address = address;
        this.total = total;
        this.foods = foods;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public List<Order> getFoods() {
        return foods;
    }

    public void setFoods(List<Order> foods) {
        this.foods = foods;
    }
}

これが私のCart.javaファイルです:

public class Cart extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

    FirebaseDatabase database;
    DatabaseReference requests;

    TextView txtTotalPrice;
    Button btnPlace;

    List<Order> cart=new ArrayList<>();
    CartAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        //Firebase
        database=FirebaseDatabase.getInstance();
        requests=database.getReference("Requests");

        //Init
        recyclerView=findViewById(R.id.listCart);
        recyclerView.setHasFixedSize(true);
        layoutManager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        txtTotalPrice=findViewById(R.id.total);
        btnPlace=findViewById(R.id.btnPlaceOrder);

        btnPlace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

              showAlertDialog();

            }
        });

        LoadListFood();

    }

    private void showAlertDialog() {

        AlertDialog.Builder alertDialog=new AlertDialog.Builder(Cart.this);
        alertDialog.setTitle("One more step!");
        alertDialog.setMessage("Enter your address :");



        final EditText edtAddress=new EditText(Cart.this);
        LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );


        edtAddress.setLayoutParams(lp);
        alertDialog.setView(edtAddress);  //Add edit text to alert dialog
        alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);


        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Create new request

                Request request=new Request(

                        Common.currentUser.getPhone(),
                        Common.currentUser.getName(),
                        txtTotalPrice.getText().toString(),
                        edtAddress.getText().toString(),
                        cart

                );


                //Submit to Firebase
                //We will using System.currentMili to key

                requests.child(String.valueOf(System.currentTimeMillis()))
                        .setValue(request);


                //Delete cart
                new Database(getBaseContext()).cleanCart();

                Toast.makeText(Cart.this, "Thank you. Order placed", Toast.LENGTH_SHORT).show();
                finish();
            }
        });


        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.show();
    }

    private void LoadListFood() {
        cart=new Database(this).getCarts();
        adapter=new CartAdapter(cart,this);
        recyclerView.setAdapter(adapter);


        //Calculate total price

        int total=0;
        for (Order order:cart)
            total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));

        Locale locale=new Locale("en","US");
        NumberFormat fmt=NumberFormat.getCurrencyInstance(locale);

        txtTotalPrice.setText(fmt.format(total));

    }
}

これが私のFoodDetail.java

public class FoodDetail extends AppCompatActivity {

    TextView food_name,food_price,food_description;
    ImageView food_image;
    CollapsingToolbarLayout collapsingToolbarLayout;
    FloatingActionButton btnCart;
    ElegantNumberButton numberButton;


    String foodId="";
    FirebaseDatabase database;
    DatabaseReference foods;
    Food currentfood;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_detail);

        //Firebase

        database=FirebaseDatabase.getInstance();
        foods=database.getReference("Foods");


        //Init View

        numberButton=findViewById(R.id.number_button);
        btnCart=findViewById(R.id.btnCart);

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Database(getBaseContext()).addToCart(new Order(
                        foodId,
                        currentfood.getName(),
                        numberButton.getNumber(),
                        currentfood.getPrice(),
                        currentfood.getDiscountmenuId()

                ));

                Toast.makeText(FoodDetail.this, "Added to cart", Toast.LENGTH_SHORT).show();
            }
        });

        food_description=findViewById(R.id.food_description);
        food_name=findViewById(R.id.food_name);
        food_price=findViewById(R.id.food_price);
        food_image=findViewById(R.id.img_food);

        collapsingToolbarLayout=findViewById(R.id.collapsing);
        collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppbar);
        collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapseAppbar);

        //get Food Id from intent

        if (getIntent()!=null)
        foodId=getIntent().getStringExtra("FoodId");

        if (foodId != null && !foodId.isEmpty()){
            getDetailFood(foodId);
        }





    }

    private void getDetailFood(String foodId) {

        foods.child(foodId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                currentfood=dataSnapshot.getValue(Food.class);


                //set Image

                Picasso.get().load(currentfood.getImage()).into(food_image);

                collapsingToolbarLayout.setTitle(currentfood.getName());
                food_price.setText(currentfood.getPrice());
                food_name.setText(currentfood.getName());
                food_description.setText(currentfood.getDescription());

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

アドレスを入力すると次のようになります。

Ashish

モデルクラスにデータを書き込んだ方法が間違っています。

モデルを正しく確認してください:

Request request=new Request(
    Common.currentUser.getPhone(),
    Common.currentUser.getName(),
    txtTotalPrice.getText().toString(),
    edtAddress.getText().toString(),
    cart
);

合計価格の場所はモデルクラスの4番目の位置にあり、住所は3番目の位置にあります。Firebaseに送信しているときに、間違った順序で渡しました。

モデルデータを次のように変更します。

Request request=new Request(
    Common.currentUser.getPhone(),
    Common.currentUser.getName(),
    edtAddress.getText().toString(),
    txtTotalPrice.getText().toString(),
    cart
);

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

BotframeworkV4でのWebチャットの価値交換の問題

分類Dev

複数の交換の問題

分類Dev

SpringBoot RestTemplate交換でResponseEntityのParameterizedTypeReference変換に問題がある

分類Dev

弦を交換する際の問題

分類Dev

DB2交換の問題?

分類Dev

2つの配列の値を交換するときの説明できない問題

分類Dev

値変換の問題?

分類Dev

値変換の問題?

分類Dev

Cで2つのアレイを交換する際の問題

分類Dev

コードウォーズでの配列交換と反転の問題

分類Dev

Centrino Wireless-N 1030でのWi-Fiの問題、交換しますか?

分類Dev

PostgreSQLでの列値の交換

分類Dev

コイン交換問題へのメモ化の適用

分類Dev

mysqlの問題のためにpdoを交換する

分類Dev

マザーボードの交換の問題

分類Dev

CloudKitレコードの交換に関する問題

分類Dev

アドレスの交換に関する問題

分類Dev

ブール値の交換

分類Dev

右辺値との交換

分類Dev

Pythonのint()での変換の問題

分類Dev

WebRTCの「完璧な交渉」の問題

分類Dev

ブロックなしで交換する場合のESLint矢印本体の問題

分類Dev

Firebase authWithOAuthRedirect()の問題

分類Dev

交換の代替

分類Dev

真のNA値で、この値を交換する方法

分類Dev

負の値でのPythonsort()の問題

分類Dev

コイン交換問題のこの解決策の何が問題になっていますか?

分類Dev

問題の原因となる配列内の要素を交換する

分類Dev

連立常微分方程式のシステム-熱交換器の問題

Related 関連記事

ホットタグ

アーカイブ