简体   繁体   中英

How to get data from fragment to parent activity & pass it to back activity?

How flow goes?

Activity 1 -----> Activity 2 (containing/inside) ------> Fragment

WhatI want to achieve?

Fragment (sends some data back to Activity 2) ----> Activity 2 (onBackPressed : collects that data & send it back to Activity 1) ---> Activity 1

How should I achieve above. I really don't want to use any variables/constants to cache the fragment data. Need to know any in-built method to handle this?

Moreover,

  • Activity 2 loads Fragment inside it.
  • In onBackPressed, I'm using setResult in Activity 2 to do standard data passing using startActivityForResult from Activity 1.
  • Also, if I write any method inside Fragment & call from Activity 2 using then due to that to/fro process a WHITE screen appears. So, really don't want to write own method & need to manage it while leaving the Fragment.

You should start Activity2 with startActivityForResult as below;

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, requestCode);

And in Activity2/fragment, you should finish acitivity as below;

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
getActivity().setResult(Activity.RESULT_OK,returnIntent);
getActivity().finish()

And get result in Activity1 as below;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (this.requestCode == requestCode) {
        if(resultCode == Activity.RESULT_OK){
        //Get result
       }
    }
}

Hope it helps.

To pass data from Activity 2 to Activity 1 you can use startActivityForResult() in Activity 1 to start Activity 2 , and onActivityResult() in Activity 1 to receive that data.

To pass data from Fragment to Activity 2 , I'd suggest to use some interface like

interface OnSomeDataListener {
    void onSomeData(SomeData data);
}

Then implement a setter method for this interface to a fragment like

public void setOnSomeDataListener(OnSomeDataListener listener) {
    this.listener = listener;
}

And then in Activity, when instantiating a Fragment :

YourFragment fragment = new YourFragment();
fragment.setOnSomeDataListener(new OnSomeDataListener() {
    void onSomeData(SomeData data) {
        //return the result
        Intent intent = new Intent();
        intent.putExtra("data", data);
        setResult(RESULT_OK, intent);
        finish();
    }
}

And finally, in the fragment, when you want to return some data to Activity:

if(listener != null) {
    listener.onSomeData(dataToReturn);
}

i acheived in Following way

In Activity write setters and getters

public String getFilePath() {
    return filePath;
}
public void setFilePath(String filePath) {
    this.filePath = filePath;
}
public String getFileName() {
    return fileName;
}
public void setFileName(String fileName) {
    this.fileName = fileName;
}

and in Fragment

 filePath = ((YourActivity) getActivity()).getFilePath();
 fileName=((YourActivity) getActivity()).getFileName(); 

if You are Using Same Fragment in More Than 1 Activity You can Create a constructor for that fragment and Pass context and check context is of which activity

 public class BookmarkFragment extends Fragment {


private String filePath;
private String fileName;

Context contextCheckClass;

 public BookmarkFragment(Context ctx ) {

     this.contextCheckClass=ctx;

}

@SuppressLint("InflateParams")
   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     group= (View)inflater.inflate(R.layout.fragment_bookmark, null);

     if(contextCheckClass instanceof FirstReaderScreen){
     filePath = ((FirstReaderScreen) getActivity()).getFilePath();
     fileName=((FirstReaderScreen) getActivity()).getFileName();    
    // ispurchased=((FirstReaderScreen) getActivity()).isIspurchased(); 
     }
     else if(contextCheckClass instanceof MainReaderScreen){
         filePath = ((MainReaderScreen) getActivity()).getFilePath();
         fileName=((MainReaderScreen) getActivity()).getFileName(); 
    //   ispurchased=((MainReaderScreen) getActivity()).isIspurchased();    
     }
    return group;
}

for calling fragment

BookmarkFragment bookmarkFragment=new BookmarkFragment(FirstReaderScreen.this);
    getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.LL_Fragment, bookmarkFragment)//LL_fragment is container
    .addToBackStack(null)
    .commit();

From your FirstActivity call the SecondActivity using startActivityForResult() method

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity onBackPressed of SecondActivity.

 @Override
    public void onBackPressed() {
        super.onBackPressed();
       Intent returnIntent = new Intent();
        returnIntent.putExtra("result",result);
        returnIntent.putExtra("bool",true);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
    }

Now in your FirstActivity class write following code for the onActivityResult() method.

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

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
            boolean bool = data.getBooleanExtra("bool"); 

        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//

To send data from Fragment to Second activity, you can use interface callback

 public interface sendDataListener
    {
        void sendData(boolean foo);
    }

Implement this listener to Second activity

Try to do this:

public class MyFragment extends Fragment{
   private MyFragmentCommunicator myFragmentCommunicator;
   ....
   myFragmentCommunicator.sendDataToActivity(name, image, isSend);

   @Override
   public void onAttach(Activity activity) {
      super.onAttach(activity);
      myFragmentCommunicator = (MyFragmentCommunicator)activity;
   }
}

then declare your interface:

public interface MyFragmentCommunicator{
    void sendDataToActivity(String name, String image, boolean isSend);
}

and then in your Activity do this:

public class MyActivity extends AppCompatActivity implements MyFragmentCommunicator{

    @Override
    public void sendDataToActivity(String name, String image, String price) {
        //Manipulate the data
    }

}

Hope it helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM