用户正在使用其他活动时调用MainActivity的OnCreate

我有一个活动(ServicosUserActivity),其中产品在recyclerview中列出,其中包含从firebase加载的数据。当用户从购物篮中添加(或删除)这些项目之一时,应用程序的主屏幕将启动(调用MainActivity onCreate)。 我注意到在用户操作完成后,将调用ServicosUserActivity onPause方法,然后调用MainActivity onCreate方法。我要在屏幕上保留ServicosUserActivity,直到用户决定进行其他活动

ServicosUserFragment

public class ServicosUserFragment extends Fragment {

private String idUsuario;
private RecyclerView recyclerView;
private AdapterServicoUser adapterServicoUser;
private List<ServicoCliente> servicos = new ArrayList<>();
private List<String> carrinho = new ArrayList<>();
private DatabaseReference carrinhoRef,servicoRef;
private DatabaseReference postagemRef= ConfiguracaoFirebase.getReferenciaFirebase();
private SecurityPreferences mySecurityPreferences;
private ValueEventListener v1, v2;


public ServicosUserFragment() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_servicos_user, container, false);

    idUsuario = ConfiguracaoFirebase.getIdUsuario();

    carrinhoRef = postagemRef.child("usuarios").child(idUsuario).child("carrinho");
    servicoRef = ConfiguracaoFirebase.getReferenciaFirebase().child("servicos");

    recyclerView = view.findViewById(R.id.recyclerServicosUser);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapterServicoUser = new AdapterServicoUser(servicos,idUsuario,carrinho,getActivity());
    recyclerView.setAdapter(adapterServicoUser);
    gerenciaServicos();

    return view;
}

private void gerenciaServicos() {

    v1 = carrinhoRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            carrinho.clear();

            if(dataSnapshot.getValue()!=null) {
                for (DataSnapshot dados : dataSnapshot.getChildren()) {
                    String item;
                    item = (String) dados.getValue();
                    carrinho.add(item);
                }
            }


        }

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

        }
    });

    servicoRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            servicos.clear();
            for (DataSnapshot dados: dataSnapshot.getChildren()){
                ServicoCliente servico = dados.getValue(ServicoCliente.class);
                servico.setKey(dados.getKey());
                for(String item : carrinho) {
                    if (servico.getKey().equals(item)) {
                        servico.setCarrinho(true);
                    }
                }
                servicos.add(servico);
            }
            Collections.reverse(servicos);
           adapterServicoUser.notifyDataSetChanged();

        }

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

        }
    });

}

public void onStop() {
    super.onStop();
    carrinhoRef.removeEventListener(v1);
}

}

AdapterServicoUser

public class AdapterServicoUser extends RecyclerView.Adapter<AdapterServicoUser.MyViewHolder> {
private DatabaseReference ref = ConfiguracaoFirebase.getReferenciaFirebase().child("usuarios");
private DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols();
private List<ServicoCliente> servicos;
private List<String> carrinho;
private String idUsuario;
private AlertDialog dialog;
private Context context;

public AdapterServicoUser(List<ServicoCliente> servicos,String idUsuario, List<String> carrinho, Context context) {
    this.servicos = servicos;
    this.carrinho = carrinho;
    this.idUsuario = idUsuario;
    this.context = context;
}


@NonNull
@Override
public AdapterServicoUser.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_servico_user, parent, false);
    return new MyViewHolder(itemLista);
}

@Override
public void onBindViewHolder(@NonNull final AdapterServicoUser.MyViewHolder holder, int position) {

    unusualSymbols.setDecimalSeparator(',');
    unusualSymbols.setGroupingSeparator('.');
    DecimalFormat decimalFormat = new DecimalFormat("R$ ###,###,##0.00",unusualSymbols);
    String precoFormatado;

    Log.i("pqp","Adapter servicos");

    final ServicoCliente servico = servicos.get(position);
    holder.textNome.setText(servico.getNome());
    String tempo;
    tempo = "Duração média do atendimento: " + servico.getTempo() +
            "min";

    holder.textTempo.setText(tempo);

    precoFormatado = decimalFormat.format(servico.getPreco());
    holder.textPreco.setText(precoFormatado);


    if(servico.getCarrinho()){
        holder.imageCarrinho.setImageResource(R.drawable.ic_add_shopping_cart_accent_24dp);
    }else {
        holder.imageCarrinho.setImageResource(R.drawable.ic_add_shopping_cart_black_24dp);
    }

    //Log.i("CHECK","Passou aqui 4" + postagem.getKey() + "     " + postagem.getCarrinho());

    holder.imageCarrinho.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(servico.getCarrinho()){

                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Carrinho").setMessage("Gostaria de remover este serviço do carrinho?");
                builder.setCancelable(false);

                builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Log.i("CHECK","Passou aqui 5" + servico.getKey() + " ==  " + s.getCarrinho());
                        int i = 0;
                        int j = 0;
                        for (String item : carrinho){

                            if (servico.getKey().equals(item)){
                                j=i;
                            }
                            i++;
                        }

                        carrinho.remove(j);

                        holder.imageCarrinho.setImageResource(R.drawable.ic_add_shopping_cart_black_24dp);
                        ref.child(idUsuario).child("carrinho").setValue(carrinho);


                    }
                });
                builder.setNegativeButton("Cancelar", null);

                AlertDialog dialog = builder.create();
                dialog.show();

            }else{




                 AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Carrinho").setMessage("Gostaria de adicionar este serviço ao carrinho?");
                builder.setCancelable(false);

                builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Log.i("CHECK","Passou aqui 6" + postagem.getKey() + "     " + postagem.getCarrinho());
                        holder.imageCarrinho.setImageResource(R.drawable.ic_add_shopping_cart_accent_24dp);
                        String item = servico.getKey();
                        carrinho.add(item);
                        ref.child(idUsuario).child("carrinho").setValue(carrinho);



                    }
                });
                builder.setNegativeButton("Cancelar", null);

                AlertDialog dialog = builder.create();
                dialog.show();

            }
        }
    });


}

@Override
public int getItemCount() {
    return servicos.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView textNome, textPreco, textTempo;
    ImageView imageCarrinho;

    public MyViewHolder(@NonNull View v) {
        super(v);
        textNome = v.findViewById(R.id.textAdapterNomeServicosUser);
        textTempo = v.findViewById(R.id.textAdapterTempoServicosUser);
        textPreco = v.findViewById(R.id.textPrecoAdapterServicoUser);
        imageCarrinho = v.findViewById(R.id.imageCarrinhoServico);
    }
}

}

评论