2

I am calling dialog fragment from FragmentA and returning some values to fragmentA. Now issue is whenever i go to another fragmentB from same fragmentA and return to it my dialog fragment values get cleared.

when i click on consultant doctor textview, a dialog opens (Pic 2). On Selecting an item (Pic 2),returns a value back to FragmentA. Pic 3 is a Fragment B which opens on same activity. But when i click on cross button on pic 3 and popBackStack , my value for consult doctor clears shown in Pic 4.

enter image description here

enter image description here

enter image description here

enter image description here

Pic 4 is an ISSUE

DialogFragment

 @Override
  public void onStart() {
    super.onStart();
    getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    getDialog().getWindow().setGravity(Gravity.CENTER);
    getDialog().setCancelable(false);
    getDialog().setCanceledOnTouchOutside(false);
    getDialog().closeOptionsMenu();

  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

    View rootView = inflater.inflate(R.layout.consultant_doc_dialog, container, false);

    recyclerView = (RecyclerView)rootView.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setHasFixedSize(true);
    adapter = new ConsultantDoctAdapter(getContext(),this);
    adapter.getDocList().addAll(new ArrayList<DoctorList>());
    recyclerView.setAdapter(adapter);
    adapter.getDocList().clear();
    adapter.getDocList().addAll(list);
    adapter.notifyDataSetChanged();


    close = (ImageButton)rootView.findViewById(R.id.bt_close);
    close.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        getDialog().dismiss();
      }
    });
    //cityEditText.setOnQueryTextListener(onQueryTextListener);

    return rootView;
  }

Fragment

@Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.layout_create_leads, container, false);
    ButterKnife.bind(this, view);
    setRetainInstance(true);

      init();
      setPicker();
      setSpinnerListener();
      btCheckCalendar.setOnClickListener(this);
      etCityId.setOnClickListener(this);
      etConsultingDocId.setOnClickListener(this);
      btSubmit.setOnClickListener(this);
      tvClientReferral.setOnClickListener(this);
      etSalesPerson.setText(sharedPref.getString(AppConstants.PREFERENCE_USER_NAME, ""));
      etZone.setText(sharedPref.getString(AppConstants.USER_ZONE, ""));
      etAreaCode.setText(sharedPref.getString(AppConstants.USER_AREA_CODE, ""));
      setSpinner();
      getConsultantDoctorList();
    return view;
  }

Fragment B callBack:

getActivity().getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.content_main, new MyCalendarFragment())
    .addToBackStack("calendarFragment")
    .commit();

DialogCallack:

ConsultantDocDialogFragment consultantDocDialog = new ConsultantDocDialogFragment();
        consultantDocDialog.setParameter(getContext(), this, doclist);
        consultantDocDialog.show(getActivity().getSupportFragmentManager(),
            ConsultantDocDialogFragment.class.getSimpleName());
        break;

Please help me so that i can able to save state of values got from dialog fragment.

young_08
  • 1,196
  • 2
  • 13
  • 35

4 Answers4

1

A simple way to return values from DialogFragment is using setTargetFragment for calling a fragmentB creation, then return data to getTargetFragment (if not null). In fragmentA you can receive data through onActivityResult.

Another way is using SharedPreferences. You can get a new value with onResume or onHiddenChanged.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
  • SharedPrefences....i am getting somewhat 8 fields values from dialog , some from datepicker/timepicker and all of them are clearing on returning back. Hence, You still suggest to use Shared Pref and save so many values in there.? – young_08 Apr 24 '17 at 06:35
  • 1
    @young_08 well its not a big issue to use shared prefs for 8 values if you think it realy is then you can use sqlite or follow the other suggested solution by CoolMind – Adeel Turk Apr 24 '17 at 06:47
  • @AdeelTurk So i have tried other solution by CoolMind which is setTargetFragment. Facing same issue as soon as i came back from Fragment B to Fragment A , my getTargetFragment value which i have set in consultant doctor fields clears. This is only happening with dialog and datePickers. Other fields retaining there values. ): – young_08 Apr 24 '17 at 07:02
  • try singelton model then – Adeel Turk Apr 24 '17 at 07:17
  • @young_08, when and how do you pass values to `getTargetFragment`? I usually do this on back press (onDetach with conditions) or click. In code, for instance, it is: getTargetFragment().onActivityResult(100, Activity.RESULT_OK, data); – CoolMind Apr 24 '17 at 07:19
  • @AdeelTurk, you can also add an answer with SQLite and Singleton, thanks. :) – CoolMind Apr 24 '17 at 07:20
  • @CoolMind onDismiss i am calling : getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK,getActivity().getIntent()); – young_08 Apr 24 '17 at 07:23
  • @young_08, sorry, I changed to onDetach (forgot that event). – CoolMind Apr 24 '17 at 07:24
  • @CoolMind didnt get you – young_08 Apr 24 '17 at 07:24
  • @young_08, public void onDetach() { if (isRemoving()) { Intent data = new Intent(); data.putExtra(EXTRA_SOMETHING, 12345); getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data); } } – CoolMind Apr 24 '17 at 07:28
  • @CoolMind i will try this. And get back to you – young_08 Apr 24 '17 at 07:34
  • Thanks, @young_08. Don't forget to check `if (getTargetFragment() != null)` if you use this DialogFragment in several places. – CoolMind Apr 24 '17 at 07:51
1

Please find the following code it may help you-

This is Fragment Code where you can get CallBack from Dialog Fragment-

HomeFragment.java

public class HomeFragment extends Fragment implements AlertDFragment.Callback {
    private static final int DIALOG_FRAGMENT = 100;
    Button alertdfragbutton;
    private View rootView;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        initUI(rootView);
        return rootView;
    }

    private void initUI(View rootView) {
        alertdfragbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                AlertDFragment alertdFragment = new AlertDFragment();
                alertdFragment.setTargetFragment(HomeFragment.this, DIALOG_FRAGMENT);
                // Show Alert DialogFragment
                alertdFragment.show(getChildFragmentManager(), "Alert Dialog Fragment");
            }
        });
    }

    @Override
    public void accept() {
        Log.e("Home  ", "OK");
    }

    @Override
    public void decline() {

    }

    @Override
    public void cancel() {
        Log.e("Home  ", "CANCEL");
    }
}

Here is Dialog Fragment where we declare CallBack with methods-

public class AlertDFragment extends DialogFragment {
    Callback callback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        callback = (Callback) getTargetFragment();
        return new AlertDialog.Builder(getActivity())
                // Set Dialog Icon
                .setIcon(R.drawable.androidhappy)
                // Set Dialog Title
                .setTitle("Alert DialogFragment")
                // Set Dialog Message
                .setMessage("Alert DialogFragment Tutorial")

                // Positive button
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        callback.accept();
                        // Do something else
                        //getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                    }
                })

                // Negative Button
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        callback.cancel();
                        // Do something else
                        // getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                    }
                }).create();
    }

    public static interface Callback {
        public void accept();

        public void decline();

        public void cancel();
    }
}
PankajSharma
  • 1,529
  • 14
  • 27
0

Instead of using the "Fragment Transition" why don't you just POP-UP your custom view Just Create a global reference of

Dialogue dialogue
View popupView

and on click of whatever textview button etc. you can just call a method like

void popup(){
    popupView = LayoutInflater.from(getActivity()).inflate(R.layout.your_calenderlayout, null);
    //suppose you have TextView cal_textview in popUp view i.e, your_calenderlayout
    cal_textview    = (TextView ) popupView.findViewById(R.id.cal_textview);
    dialog          = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCanceledOnTouchOutside(true);
    dialog.setContentView(popupView); //and just add your popUpview
    // For setting backgroung
    /*dialog.getWindow().setBackgroundDrawableResource(android.R.color.Transparent);
      */ 
    //For setting the width or height of popup     
    /*WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    lp.copyFrom(dialog.getWindow().getAttributes());

    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;

    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

    lp.gravity = Gravity.CENTER;
    dialog.getWindow().setAttributes(lp);*/
    dialog.show();
    }

and on dismiss of popUp or on click of the view inside popupView you set the value of variables or member inside the fragment directly

Hope this will help

R7G
  • 1,000
  • 1
  • 10
  • 15
0

You can use Shared prefs or sqlite to get your values and if you think its use less to save your temporary data in share prefs or sqlite Then Singleton model is a good option .. i believe we should follow KISS design principle :P

Adeel Turk
  • 897
  • 8
  • 23