单击后退按钮时使用PutExtra发送数据

时间:2017-09-03 02:12:18

标签: java android android-intent

我有以下问题。

  • 活动1:我在哪里通过PutExtra发送用户ID。
  • 活动2:使用GetExtra获取数据。
  • 在活动2的某个时刻,我发送到活动3,再次使用PutExtra发送。

我想回到活动2,将数据作为PutExtra发送。但是在活动2中,您已经有一个GetExtra,它期望来自活动1的数据,所以它给出了一个错误。如何将此数据从活动3发送到活动2而不与活动2冲突,因为我已经预期来自活动1的GetExtra数据。

注意:发送的数据始终相同。它总是以PutExtra的形式发送的用户ID,也作为GetExtra收到。

修改

代码发送或从活动2发送到活动3

    public class PerfilEmpTab2 extends Fragment {

    private RecyclerView mCardServicoList;

    private String mId_Empresa = null;

    private DatabaseReference mDatabaseServicos;

    private boolean mProcessAddServico = false;


    public PerfilEmpTab2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_perfil_emp_tab2, container, false);

        /*  Recebe id de outra tela*/
        mId_Empresa = getActivity().getIntent().getExtras().getString("id_empresa");

        mDatabaseServicos = FirebaseDatabase.getInstance().getReference().child("Produtos_Empresas").child(mId_Empresa);

        /*Recuperar REcyclerView*/
        mCardServicoList = (RecyclerView) view.findViewById(R.id.cardListaServicos);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);

        //mCardCategList.setHasFixedSize(true);
        mCardServicoList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        /*Fim Recycler View*/

        loadServicos();


        return view;
    }

    private void loadServicos() {

        FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<CardServico_row, CardServicosViewHolder>(

                CardServico_row.class,
                R.layout.card_servicos_row,
                CardServicosViewHolder.class,
                mDatabaseServicos

        ) {
            @Override
            protected void populateViewHolder(final CardServicosViewHolder viewHolder, final CardServico_row model, int position) {

                final String servico_key = getRef(position).getKey();
                final String nome_produto = model.getNome_produto();
                final String duracao = model.getDuracao();
                final String valor = model.getValor();
                final String valorOld = model.getValorOld();


                viewHolder.setNome_produto(model.getNome_produto());
                viewHolder.setDuracao(model.getDuracao());
                viewHolder.setValor(model.getValor());
                viewHolder.setValorOld(model.getValorOld());


                /*Clique na view*/
                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
                        intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
                        startActivity(intentServicoDetalhes);

                    }
                });


                viewHolder.mAddBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        //Toast.makeText(Categorias.this, nome + post_key, Toast.LENGTH_LONG).show();
                        CharSequence opcoes[] = new CharSequence[] {"Editar Serviço", "Ver Detalhes"};

                        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        //builder.setTitle("Opçoes");
                        //builder.setCancelable(false);
                        builder.setItems(opcoes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // the user clicked on colors[which]

                                switch (which) {
                                    case 0:
                                        Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-"  + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
                                        /*Intent criarSubC = new Intent(Categorias.this, CadastroSubCategorias.class);
                                        criarSubC.putExtra("id_categ", post_key);
                                        startActivity(criarSubC);*/
                                        mProcessAddServico = false;
                                        break;
                                    case 1:
                                        Toast.makeText(getActivity().getApplication(), "Dados" + "-" + servico_key + "-" + nome_produto + "-" + duracao + "-"  + valor + "-" + valorOld, Toast.LENGTH_LONG).show();
                                        mProcessAddServico = false;
                                        break;
                                }


                            }

                        });
                        builder.show();

                    }
                });

            }
        };
        mCardServicoList.setAdapter(firebaseRecyclerAdapter);


    }




    public static class CardServicosViewHolder extends RecyclerView.ViewHolder{

    View mView;

    ImageButton mAddBtn;

    public CardServicosViewHolder (View itemView){
        super(itemView);

        mView = itemView;

        mAddBtn = (ImageButton) mView.findViewById(R.id.addServico_tab2);

    }


    public void setNome_produto(String nome_produto){

        TextView card_nomeProduto = (TextView) mView.findViewById(R.id.tvNomeProduto);
        card_nomeProduto.setText(nome_produto);

    }

    public void setDuracao(String duracao){

        TextView card_duracao = (TextView) mView.findViewById(R.id.tvDuracao);
        card_duracao.setText(duracao);

    }

    public void setValor(String valor){

        TextView card_valor = (TextView) mView.findViewById(R.id.tvValor);
        card_valor.setText(valor);

    }

    public void setValorOld(final String valorOld){

        if ( valorOld != null ){


            TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
            card_valorOld.setText(valorOld);
            card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // Risca o texto
            //card_valorOld.setPaintFlags(card_valorOld.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); // Remove o Risca o texto

        } else {

            TextView card_valorOld = (TextView) mView.findViewById(R.id.tvValorOld);
            card_valorOld.setText(valorOld);
            card_valorOld.setVisibility(View.GONE);

        }



    }

}
}

在活动3中,我得到:

mId_Empresa = getIntent().getExtras().getString("id_empresa");

1 个答案:

答案 0 :(得分:3)

当您开始活动时,请拨打startActivityForResult(intent, code)而不是startActivity(intint)。然后在活动3中覆盖finish()并调用setResult(Activity.RESULT_OK, data),其中数据是您创建的对象new Intent(),并根据需要调用putExtra data.putExtra(key, value)。然后在活动2中覆盖onActivityResult(int requestCode, int resultCode, Intent data)来处理它。 requestCode是您启动活动的代码。请注意onActivityResult发生在onResume之前,因此尝试从onActivityResult更新UI可能无法正常工作,例如通知适配器。

有关详细信息,请参阅此文档 https://developer.android.com/training/basics/intents/result.html

编辑:添加了代码示例

从活动2开始活动3:

static final int SERVICO_DETALHES_REQUEST = 1;  // The request code

@Override
public void onClick(View view) {
{
    Intent intentServicoDetalhes = new Intent(getActivity(), ServicoDetalhes.class);
    intentServicoDetalhes.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intentServicoDetalhes.putExtra("id_empresa", mId_Empresa);
    startActivityForResult(intentServicoDetalhes, SERVICO_DETALHES_REQUEST );
}

从活动3设置结果:

@Override    
public void finish() 
{
    Intent data = new Intent();
    data.putExtra("id_empresa", "new_id");
    setResult(Activity.RESULT_OK, data);
    super.finish();
}

处理活动2的结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK)
        String newId = data.getStringExtra("id_empresa");
}