30

I want to know is it possible on onActivityResult()to use inside Fragment and if yes then how it works please explain with example.

GGWP
  • 1,111
  • 2
  • 12
  • 24
Shweta Nandha
  • 728
  • 1
  • 8
  • 19

8 Answers8

39

Within your fragment, you need to call:

startActivityForResult(myIntent, MY_INTENT_REQUEST_CODE);

where myIntent is the intent you already defined, and MY_INTENT_REQUEST_CODE is the int constant you defined in this fragment as a global variable as the request code for this intent.

And then, still inside your fragment, you need to override this method:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   //super.onActivityResult(requestCode, resultCode, data); comment this unless you want to pass your result to the activity.
}
schv09
  • 995
  • 1
  • 9
  • 15
HaroldSer
  • 2,025
  • 2
  • 12
  • 23
5

Yes you can use OnActivityResult inside Fragment.like this

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//super.onActivityResult(requestCode, resultCode, intent);
// perform your action here
}

EDIT

The for more information check this old question

https://stackoverflow.com/a/17085889/7666442

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
5

Use this code in the activity.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(childTag);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, intent);
    }
}
Android Geek
  • 8,956
  • 2
  • 21
  • 35
3

Definitely it will work, It will work same like in activities. You have call startActivityForResult(intent, requestCode); and normally get result in

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
}
Ajeet Choudhary
  • 1,969
  • 1
  • 17
  • 41
2

if you call startActivityForResult() in fragment , result is delivered to parent activity.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);//will deliver result to desired fragment.
}

How is works

if you see requestCode in activity it will be like 655545, now

super.onActivityResult () will calculate desired fragment and request code.

if your fragment in ViewPager desired fragment index is found using

requestCode>>16

and requestCode is found by requestCode&0xffff.

Rahul Devanavar
  • 3,917
  • 4
  • 32
  • 61
1
In kotlin: - I can explain using two classes. if user go from one Activity to Another Activty and in back want data then this code help you

In class Abc
startActivityForResult(Intent(context, Bcd::class.java), 141)

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 141) {
            if (data!!.extras.get("add").equals("safal")) {
                Log.e("Print Name",data!!.extras.get("add"))
            }
        }
    }

In Class Bcd
 val intent = Intent()
 intent.putExtra("add", "safal")
 setResult(Activity.RESULT_OK, intent)
safal bhatia
  • 195
  • 1
  • 5
0

you can call onActivityResult inside a Fragment in android studio 3.5 with ease

, first, there should be an activity where you are coming to get result . OnActivity result means it has to give a resultant view when prompted. Now in the previous activity lets say

first is an activity and the other is a fragment in the second activity

Xml code for first activity may be like the following:

     <RelativeLayout
     xmlns:androclass="http://schemas.android.com/apk/res/android"  
     xmlns:tools="http://schemas.android.com/tools"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     tools:context=".MainActivity" >  
    <TextView  
    android:id="@+id/t1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignLeft="@+id/button1"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="48dp"  
    android:text="Default Message" />  
 <Button  
    android:id="@+id/b1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/textView1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="42dp"  
    android:text="GetMessage" />  
    </RelativeLayout>  

Xml code for second will be

     <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".SecondActivity" >  
<EditText  
    android:id="@+id/et1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="61dp"  
    android:layout_toRightOf="@+id/textView1"  
    android:ems="10" />  
<TextView  
    android:id="@+id/t1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignBaseline="@+id/editText1"  
    android:layout_alignBottom="@+id/editText1"  
    android:layout_alignParentLeft="true"  
    android:text="Enter Message:" />  
<Button  
    android:id="@+id/b1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/editText1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="34dp"  
    android:text="Submit" />  
  </RelativeLayout>  

Now we will add startActivityForResult() method and onActivityResult() method

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

    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==2)
    {
        String message=data.getStringExtra("MESSAGE");
        if (message!=null){
            profileNameText.setText(message);
        }
      }
     }


     @Override
    public void onClick(View v) {
    Intent i ;
    switch (v.getId()){
        case R.id.profile_option_menu:
            Log.i("profileclicked","profile_menu_image_clicked()");
            PopupMenu popupMenu = new PopupMenu(getActivity(),v);
            MenuInflater inflater = popupMenu.getMenuInflater();
            inflater.inflate(R.menu.profile_menu,popupMenu.getMenu());
            popupMenu.show();
            popupMenu.setOnMenuItemClickListener(new 
            PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    Intent i;
                    switch (item.getItemId()) {

                            case R.id.edit_det:
                            i = new Intent(getActivity().getApplicationContext(), 
                            FirstActivity.class);
                            startActivityForResult(i, 2);
                            return true;
                        default:
                            return onOptionsItemSelected(item);
                    }
                }
            });
            break;
    }
}

the code for the first activity class will be like this

        public class FirstActivity extends Activity {  
         EditText editText1;  
         Button button1;  
         @Override  
          protected void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
          setContentView(R.layout.activity_first);  
          editText1=(EditText)findViewById(R.id.et1);  
          button1=(Button)findViewById(R.id.b1);  
          button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                String message=editText1.getText().toString();  
                Intent intent=new Intent();  
                intent.putExtra("MESSAGE",message);  
                setResult(2,intent);  
                finish();//finishing activity  
             }  
         });  
       }  

Here I am writing a method setResult(2, intent) where 2 is result code which will be checked inside fragment in first activity class it will check the result code and and if the condition satifies then it will change the text inside the TextView .

0

In Kotlin we can do this in a very simplistic way as followings:

In ExampleFragment.kt, let start activity to pic an image.

private val REQUEST_CODE_GALLERY = 101

private fun openGallery() {
    val intent = Intent(Intent.ACTION_PICK)
    intent.type = "image/*"

    requireActivity().startActivityFromFragment(this, intent, REQUEST_CODE_GALLERY)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_GALLERY) {
        Log.d("TAG", "${data.toString()}")
    }
}

Hope, this will be helpful!

protanvir993
  • 2,759
  • 1
  • 20
  • 17