Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - Why while shifting from ProductDetailsActivity to HomeActivity, a toast appears from the LoginActivity?

Please, help me solve this issue. I have working on this for days.

ProductsDetailActivity

            package com.example.spree;
        
        import androidx.annotation.NonNull;
        import androidx.appcompat.app.AppCompatActivity;
        
        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.ImageView;
        import android.widget.TextView;
        import android.widget.Toast;
        
        import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
        import com.example.spree.Models.Products;
        import com.example.spree.Models.Users;
        import com.example.spree.Prevalent.Prevalent;
        import com.google.android.gms.tasks.OnCompleteListener;
        import com.google.android.gms.tasks.Task;
        import com.google.android.material.floatingactionbutton.FloatingActionButton;
        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.squareup.picasso.Picasso;
        
        import java.text.SimpleDateFormat;
        import java.util.Calendar;
        import java.util.HashMap;
        
        import io.paperdb.Paper;
        
        public class ProductsDetailActivity extends AppCompatActivity {
        
            private Button addToCart;
            private ImageView productDetailImage;
            private ElegantNumberButton numberButton;
            private TextView productNameDetail, productDescriptionDetail, productPriceDetail;
            private String productID = "";
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_products_detail);
        
        
        
                productID = getIntent().getStringExtra("pid");
        
        
                productDetailImage = findViewById(R.id.product_image_details);
                productNameDetail = findViewById(R.id.product_name_details);
                productDescriptionDetail = findViewById(R.id.product_description_details);
                productPriceDetail = findViewById(R.id.product_price_details);
                numberButton = findViewById(R.id.elegant_button);
                addToCart = findViewById(R.id.product_cart);
        
        
        
        
        
                
                getProductDetails(productID);
        
                addToCart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
        
                        addToCartList();
                    }
                });
            }
        
            private void addToCartList() {
        
        
                String saveCurrentTime, saveCurrentDate;
        
                Calendar callForDate = Calendar.getInstance();
        
                SimpleDateFormat currentDate = new SimpleDateFormat("MMM-dd-yyyy");
                saveCurrentDate = currentDate.format(callForDate.getTime());
        
                SimpleDateFormat currentTime = new SimpleDateFormat(" HH:mm:s a");
                saveCurrentTime = currentTime.format(callForDate.getTime());
        
        
               final DatabaseReference cartListRef = FirebaseDatabase.getInstance()
                       .getReference().child("Cart List");
        
                final HashMap<String, Object> cartMap = new HashMap<>();
                cartMap.put("pid", productID);
                cartMap.put("pname", productNameDetail.getText().toString());
                cartMap.put("price", productPriceDetail.getText().toString());
                cartMap.put("date", saveCurrentDate);
                cartMap.put("time", saveCurrentTime);
                cartMap.put("quantity", numberButton.getNumber());
                cartMap.put("discount", "");
        
        
                cartListRef.child("User View").child(Prevalent.currentOnlineUser.getPhone())
                        .child("Products")
                        .child(productID)
                        .updateChildren(cartMap)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
        
                                if(task.isSuccessful()){
        
                                    cartListRef.child("Admin View").child(Prevalent.currentOnlineUser.getPhone())
                                            .child("Products")
                                            .child(productID)
                                            .updateChildren(cartMap)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    
                                                    if (task.isSuccessful()){
                                                        Toast.makeText(ProductsDetailActivity.this, "Added to cart successfully.", Toast.LENGTH_SHORT).show();
        
        
                                                        Intent pIntent = new Intent(ProductsDetailActivity.this, HomeActivity.class);
        
                                                        startActivity(pIntent);
        
                                                    }
                                                    
                                                }
                                            });
        
                                }
                            }
                        });
        
            }
        
            private void getProductDetails(String productID) {
                DatabaseReference productReference = FirebaseDatabase.getInstance().getReference().child("Products");
        
        
                productReference.child(productID).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
        
                        if (snapshot.exists()){
                            Products products = snapshot.getValue(Products.class);
        
                            productNameDetail.setText(products.getPname());
                            productPriceDetail.setText(products.getPrice());
                            productDescriptionDetail.setText(products.getDescription());
        
                            Picasso.get().load(products.getImage()).into(productDetailImage);
        
                        }
                    }
        
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
        
                    }
                });
            }
        
        
        }

HomeActivity

    package com.example.spree;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.spree.Models.Products;
import com.example.spree.Prevalent.Prevalent;
import com.example.spree.ViewHolder.ProductViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import de.hdodenhof.circleimageview.CircleImageView;
import io.paperdb.Paper;

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener
{

    //private AppBarConfiguration mAppBarConfiguration;

    private DatabaseReference productsRef;
    private RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;

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

        Paper.init(this);

        productsRef = FirebaseDatabase.getInstance().getReference().child("Products");

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("Home");
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        View headerView = navigationView.getHeaderView(0);
        TextView userNameTextView = headerView.findViewById(R.id.user_profile_name);
        CircleImageView profileImageView = headerView.findViewById(R.id.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);

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
//        mAppBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
//                .setDrawerLayout(drawer)
//                .build();
//        NavController navController = Navigation.findN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If anyone's viewed my question on kept on wondering why? I have found a solution (Yay!). In my LoginActivity I have written:

    myRef.addValueEventListener(new ValueEventListener() {...

But I should have written instead:

    myRef.addListenerForSingleValueEvent(new ValueEventListener() {...

Because addValueEventListener() keep listening to query or database reference it is attached to. But addListenerForSingleValueEvent() executes onDataChange method immediately and after executing that method once,it stops listening to the reference location it is attached to. Thus, problem has been resolved.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...