How can I call OnActivityResult inside Fragment and how it work?
Asked Answered
O

8

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.

Organogenesis answered 19/6, 2017 at 4:34 Comment(6)
if you are starting activity from fragment you can use OnActivityResult in activityBorder
Yes you can. In fragment override methdod onActivityResult and comment the super.onActivityResult and work what you want to do in this method. If you did not get how then let me know.Exciting
@RameshKumar can you plz explain me with example. It's batter for me to understand as well implement.Organogenesis
What are your requirements? are you gonna call startActivityForResult() from fragment or activity?Calaverite
@ScottS FragmentOrganogenesis
if you are going to call startActivityForResult() from fragment then you shouldn't call "super.onActivityResult()", that will invoke the fragment's activity's onActivityResult().Calaverite
C
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.
}
Calaverite answered 19/6, 2017 at 5:10 Comment(2)
I startActivityForResult in a fragment, and want to receive in either fragment/activity but onReceive data always null.Amphetamine
Could you explain more? So what is "i"? and which command i need to call in activity and fragment?Chantell
L
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://mcmap.net/q/135847/-startactivityforresult-from-a-fragment-and-finishing-child-activity-doesn-39-t-call-onactivityresult-in-fragment

Loreanloredana answered 19/6, 2017 at 4:42 Comment(0)
D
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);
    }
}
Dasha answered 19/6, 2017 at 4:50 Comment(0)
S
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);
}
Southwester answered 19/6, 2017 at 4:53 Comment(0)
D
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.

Dominations answered 19/6, 2017 at 6:22 Comment(0)
C
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)
Chilson answered 11/12, 2019 at 12:33 Comment(0)
P
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 .

Pyriform answered 4/1, 2020 at 9:34 Comment(0)
B
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!

Bearded answered 4/2, 2021 at 5:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.