startActivityForResult () and onActivityResult () in Fragments

3

I have a MainActivity that allows me to open two Fragments . The Fragment_1 class has a Button that in its Listener opens a second activity through the following call:

Intent intent = new Intent(getActivity(), SegundaActivity.class);
getActivity().startActivityForResult(intent, 1);

My problem is that in class Fragment_1 I can not catch the Intent response through the onActivityResult() method:

if (resultCode == Activity.RESULT_OK && requestCode == 1) {
String resposta = data.getStringExtra("resposta");}

In class SegundaActivity , the response is sent as follows:

Intent devolve = new Intent();
devolve.putExtra("resposta", "Resposta");
setResult(Activity.RESULT_OK, devolve);
finish();
    
asked by anonymous 24.07.2015 / 16:12

1 answer

3

Example of the solution to my problem:

Fragment_1 class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    botao.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), SegundaActivity.class);
            startActivityForResult(intent, 1);
        }

    });
    ...
    return viewlayout;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == getActivity().RESULT_OK && requestCode == 1) {
        String resposta = data.getStringExtra("resposta");
        Toast.makeText(getActivity(),"Mensagem Recebida da SegundaActivity:\n" + resposta, Toast.LENGTH_LONG).show();
    }
}

SegundaActivity

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

    Button botao = (Button) findViewById(R.id.button1);     
    botao.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent devolve = new Intent();
        devolve.putExtra("resposta", "Resposta");
        setResult(RESULT_OK, devolve);
        finish();               
    });     
}
    
24.07.2015 / 21:35