Giorgos Giorgalis Giorgos Giorgalis - 2 months ago 12
Android Question

How to call startActivityForResult from fragment's custom ArrayAdapter

I have a fragment and inside there is a ListView.

In the ListView Item there are ImageButtons like Delete and Update

In the Adapter of ListView I have

EditTeam.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v)
{
Intent intent=new Intent(getContext(),AddTeam.class);
((Activity)getContext()).startActivityForResult(intent, 2);

}
});


but its not returning to fragment's ActivityOnResult method

So I am guessing its the ((Activity)getContext()) part.. which needs to be something declaring the fragment?

the ActivityForResult method which is inside the fragment is the following:

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

if(requestCode==2)
{
Toast.makeText(getContext(),"NEW TEAM SAVED",Toast.LENGTH_LONG).show();
}

}


How I can fix this

Thank you

Answer

In you must forward results to fragment method, it's not automatic

You must receive your result in your activity's onActivityResult, the you must get your current fragment and invoke manually his onActivityResult method. Something like this:

Activity code

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

    // find your fragment as you need, here is by id

    // Pass the activity result to the fragment
    Fragment fragment = getSupportFragmentManager().findFragmentById(NavigationHelper.CONTAINER_RES_ID);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}