0

Do not understand fully fragment life-cycle.

Case:

Click FrameLayout from Activity to move to Fragment is working.

Problem:

In Fragment there are two spinners and one SubmitButton, when selected both spinner values, the clicking ofSubmitButton, should display those values from spinner back to the Activity's two Textviews . But, I am unable to do that.

My Solution:

I tried to use Intent, putExtras and then getExtras , but as we are in Fragment, Intent is not going to work for Fragment. Bundle also not helping.

P.S. Need someone who understand good Fragment's life-cycle. Read many posts from stackoverflow and other tutorials. Not found what I meant.

Do not want external libraries as such eventBus

Zafar Kurbonov
  • 2,077
  • 4
  • 19
  • 42
  • write interface to pass values – J Ramesh Sep 15 '17 at 07:03
  • When you are in a fragment you can use a callback, or getting the reference to the Activity using `getActivity()` or `getContext()` and pass the value back calling a specific method in the Activity – MatPag Sep 15 '17 at 07:04
  • Create `Fragment` from `android studio` and you will see example with interface that you can use to send data to activity. Right click on package New -> Fragment – Stanislav Bondar Sep 15 '17 at 07:09
  • I have read that post @Akshay, It differs from my case. otherwise, I would not have asked this question – Zafar Kurbonov Sep 15 '17 at 07:13

1 Answers1

1

Two ways you can do that

1) Casting getActivity() as your Activity and call the specific method and pass parameter.

public class MyActivity extends AppCompatActivity {

  public void setData(String value){
        // do whatever with the data
  }
}

public class MyFragment extends Fragment{

   public void someMethod(){
     ((MyActivity)getActivity).setData(your_data);
   }
}

2) Create an interface and pass the value to activity.

public class MyActivity extends AppCompatActivity implements SpinnerListener{

  @Override
  public void onSpinnerItemSelected(String value){
        // do whatever with the data
  }

  public interface SpinnerListener {
    void onSpinnerItemSelected(String value);
  }
}

public class MyFragment extends Fragment {

    private SpinnerListener spinnerListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceOf MyActivity)
           spinnerListener = ((MyActivity)context);
    }

   public void someMethod() {
      if(spinnerListener != null)
        spinnerListener.onSpinnerItemSelected(your_data); 
   }
}

Note: The safe method is using interface.

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66