0

I have two fragments with time and date picker. I need to send data chosen by the user from the fragment and pass them to to fragments activity, in order to combine data and send it to another activity. I used this solution Link but data is null.

This is FragmentOne - FramentTwo is the same

public FragmentOne(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
   View view = inflater.inflate(R.layout.fragment_one_layout,container,false);

   //FROM SIDE
   timeButtonFrom = (Button)view.findViewById(R.id.time_button);
   dateButtonFrom = (Button)view.findViewById(R.id.date_button);
   tvDateFrom = (TextView)view.findViewById(R.id.time_textview);
   tvTimeFrom = (TextView)view.findViewById(R.id.date_textview);


    timeButtonFrom.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Calendar now = Calendar.getInstance();
           // TimePickerDialog tpd = TimePickerDialog.newInstance(
           TimePickerDialog tpd = TimePickerDialog.newInstance(
                   FragmentOne.this,
                   now.get(Calendar.HOUR_OF_DAY),
                   now.get(Calendar.MINUTE),true);//24H Enable, If 12 set false
           tpd.setThemeDark(true);
           tpd.enableMinutes(true);
           tpd.setTitle("Choose Time");
           tpd.setTimeInterval(1,15);//setTimeInterval to 1H and 15Min


           tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
               @Override
               public void onCancel(DialogInterface dialogInterface) {
                   Log.d("TimePicker", "Dialog was cancelled");
               }
           });

           tpd.show(getFragmentManager(), "ChooseTimeFrom");
       }
   });// end Button Listener FROM

   dateButtonFrom.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Calendar now = Calendar.getInstance();
           DatePickerDialog dpd = DatePickerDialog.newInstance(
                   FragmentOne.this,
                   now.get(Calendar.YEAR),
                   now.get(Calendar.MONTH),
                   now.get(Calendar.DAY_OF_MONTH)
           );
           dpd.setThemeDark(true);
           dpd.showYearPickerFirst(true);
           dpd.setTitle("Choose Date");
           dpd.show(getFragmentManager(), "ChooseDateFrom");
       }
   });//END DATEBUTTONFROM
  return  view;

}//END ONCREATEVIEW

@Override
public void onResume() {
    super.onResume();
    DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag("ChooseDateFrom");
    if(dpd != null) dpd.setOnDateSetListener(this);
    TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag("ChooseTimeFrom");
    if(tpd != null) tpd.setOnTimeSetListener(this);

}



@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

    String date = "You picked the following date: "+year+"/"+(++monthOfYear)+"/"+dayOfMonth;
    tvDateFrom.setText(date);

}

@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {

    String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
    String minuteString = minute < 10 ? "0"+minute : ""+minute;
    String secondString = second < 10 ? "0"+second : ""+second;
    String time = "You picked the following time: "+hourString+"h"+minuteString+"m"+secondString+"s";
    tvTimeFrom.setText(time);
}

This is my Activity

public class DatePickerActivity extends AppCompatActivity {
private static final String TAG = "DatePickerActivity";
ViewPager viewPager;
PickerAdapter adapter;
String myString = "TEST";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.date_fragment);
    String strObj = getIntent().getStringExtra("Location");
    GetParamsClass getParamsClass = new Gson().fromJson(strObj,GetParamsClass.class);

    adapter = new PickerAdapter(getFragmentManager());
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(adapter);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    for(int i=0;i<adapter.getCount();i++) tabLayout.getTabAt(i).setText(adapter.getTitle(i));



}

public String getMyData() {
    return myString;
}

class PickerAdapter extends android.support.v13.app.FragmentPagerAdapter {
    private static final int NUM_PAGES = 2;
    Fragment fragmentOne;
    Fragment fragmentTwo;

    public PickerAdapter(FragmentManager fm) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                return fragmentOne;
            case 1:
            default:
                return fragmentTwo;
        }
    }

    public int getTitle(int position) {
        switch(position) {
            case 0:
                return R.string.tab_title_time;
            case 1:
            default:
                return R.string.tab_title_date;
        }
    }
}
}

EDIT

public class DatePickerActivity extends AppCompatActivity implements  FragmentOne.OnDateTimeSelectedListener {
private static final String TAG = "DatePickerActivity";
ViewPager viewPager;
PickerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.date_fragment);

    adapter = new PickerAdapter(getFragmentManager(),this);
    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(adapter);

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    for(int i=0;i<adapter.getCount();i++) tabLayout.getTabAt(i).setText(adapter.getTitle(i));
}

@Override
public void onDateTimeSelected(String date) {
    Log.d(TAG, "onDateTimeSelected: "+ date);
}

class PickerAdapter extends android.support.v13.app.FragmentPagerAdapter {
    private static final int NUM_PAGES = 2;
    Fragment fragmentOne;
    Fragment fragmentTwo;

    public PickerAdapter(FragmentManager fm,DatePickerActivity activity) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
        fragmentOne.setOnDateTimeSelectedListener(activity);//THIS LINE GIVES ERROR

    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                return fragmentOne;
            case 1:
            default:
                return fragmentTwo;
        }
    }

    public int getTitle(int position) {
        switch(position) {
            case 0:
                return R.string.tab_title_time;
            case 1:
            default:
                return R.string.tab_title_date;
        }
    }
}

Fragment One

public class FragmentOne extends DialogFragment implements DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener {

Button timeButtonFrom ;
Button dateButtonFrom;
TextView tvDateFrom ;
TextView tvTimeFrom ;


public interface OnDateTimeSelectedListener{
    void onDateTimeSelected(String date);
}



private OnDateTimeSelectedListener onDateTimeSelectedListener;

public void setOnDateTimeSelectedListener(OnDateTimeSelectedListener onDateTimeSelectedListener){
    this.onDateTimeSelectedListener = onDateTimeSelectedListener;
}

public OnDateTimeSelectedListener getOnDateTimeSelectedListener(){
    return onDateTimeSelectedListener;
}




public FragmentOne(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.fragment_one_layout,container,false);

    //FROM SIDE
    timeButtonFrom = (Button)view.findViewById(R.id.time_button);
    dateButtonFrom = (Button)view.findViewById(R.id.date_button);
    tvDateFrom = (TextView)view.findViewById(R.id.time_textview);
    tvTimeFrom = (TextView)view.findViewById(R.id.date_textview);



    timeButtonFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar now = Calendar.getInstance();
            // TimePickerDialog tpd = TimePickerDialog.newInstance(
            TimePickerDialog tpd = TimePickerDialog.newInstance(
                    FragmentOne.this,
                    now.get(Calendar.HOUR_OF_DAY),
                    now.get(Calendar.MINUTE),true);//24H Enable, If 12 set false
            tpd.setThemeDark(true);
            tpd.enableMinutes(true);
            tpd.setTitle("Choose Time");
            tpd.setTimeInterval(1,15);//setTimeInterval to 1H and 15Min


            tpd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    Log.d("TimePicker", "Dialog was cancelled");
                }
            });

            tpd.show(getFragmentManager(), "ChooseTimeFrom");
        }
    });// end Button Listener FROM

    dateButtonFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar now = Calendar.getInstance();
            DatePickerDialog dpd = DatePickerDialog.newInstance(
                    FragmentOne.this,
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            );
            dpd.setThemeDark(true);
            dpd.showYearPickerFirst(true);
            dpd.setTitle("Choose Date");
            dpd.show(getFragmentManager(), "ChooseDateFrom");
        }
    });//END DATEBUTTONFROM




    return  view;

}//END ONCREATEVIEW

@Override
public void onResume() {
    super.onResume();
    DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag("ChooseDateFrom");
    if(dpd != null) dpd.setOnDateSetListener(this);
    TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag("ChooseTimeFrom");
    if(tpd != null) tpd.setOnTimeSetListener(this);

}



@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

    String date = "You picked the following date: "+year+"/"+(++monthOfYear)+"/"+dayOfMonth;
    tvDateFrom.setText(date);

    if(tvTimeFrom != null && tvTimeFrom.getText() != null && !tvTimeFrom.getText().toString().equals("")){

        String dateTimeString = date + tvTimeFrom.getText().toString();
        onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
    }


}

@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {

    String hourString = hourOfDay < 10 ? "0"+hourOfDay : ""+hourOfDay;
    String minuteString = minute < 10 ? "0"+minute : ""+minute;
    String secondString = second < 10 ? "0"+second : ""+second;
    String time = "You picked the following time: "+hourString+"h"+minuteString+"m"+secondString+"s";
    tvTimeFrom.setText(time);

    if(tvDateFrom != null && tvDateFrom.getText() != null && !tvDateFrom.getText().toString().equals("")){

        String dateTimeString = tvDateFrom.getText().toString() + time;
        onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
    }




}
}//END FRAGMENT CLASS
Community
  • 1
  • 1
Posa
  • 53
  • 9
  • I didn't see your code but with the title of your question I can say you can use interface to send back some data to activity. – Raghavendra Nov 24 '16 at 12:25
  • Do you have same example ? – Posa Nov 24 '16 at 12:26
  • Check the solution http://stackoverflow.com/questions/40520149/how-to-refresh-recyclerview-in-one-fragment-when-data-changed-in-another-fragmen/40521446#40521446 – Raghavendra Nov 24 '16 at 12:28
  • U can use interface or local broadcast to communicate – Nithinlal Nov 24 '16 at 12:28
  • @T.Nice I hope u need similar implementation in that solution. Let me know if u didn't get that? – Raghavendra Nov 24 '16 at 12:29
  • http://stackoverflow.com/questions/13700798/basic-communication-between-two-fragments – Nithinlal Nov 24 '16 at 12:31
  • @Raghavendra I see your hint but I don't know where to start xD I'm new to Android – Posa Nov 24 '16 at 12:31
  • 3
    There are multiple ways to pass data between activity and fragment. In your case, one simple solution is Create Globar variable in your activity class to which you want to set picked values. In your fragment class call getActivity() method that will give reference to your activity(Cast from Activity to your Activity class) and by using that access the global variable declared earlier and set values to it. Interface approach is much cleaner than this approach. – Pruthviraj Nov 24 '16 at 12:34
  • @T.Nice can u tell me after which "method" in fragment u want to send date to activity? – Raghavendra Nov 24 '16 at 12:35
  • @Raghavendra after OnTimeSet and OnDateSet. User have to pick date and time and I need to pass it to Activity. – Posa Nov 24 '16 at 12:39
  • @Android_developer do you have an example? Thanks – Posa Nov 24 '16 at 12:40
  • @T.Nice try Android_developer soln. – Raghavendra Nov 24 '16 at 12:43
  • @Raghavendra sorry the silly question... Where I have to find it? xD – Posa Nov 24 '16 at 12:45
  • @T.Nice you don't have a proper order right? First u can select date then you can select time or vice versa but tell me exactly when you want to send datestring to activity? – Raghavendra Nov 24 '16 at 12:57
  • @Raghavendra Yes i don't have an order. I have to send the values After user's choice – Posa Nov 24 '16 at 13:07

4 Answers4

1
Class Activity1
{
private String pickedDateValue;

public setPickedDateValue(string val)
{
pickedDateValue = val;
}
}

Class Fragment1
{
  Activity1 act1 = (Activity1)getActivity();
   act1.setPickedDateValue(pickedval)
}

//Where pickedvalis the value picked from date/time picker

Pruthviraj
  • 560
  • 6
  • 23
1

Try this, In FragmentOne Create an interface say

public interface OnDateTimeSelectedListener{
    void onDateTimeSelected(String date, S)
}



private OnDateTimeSelectedListener onDateTimeSelectedListener;

public void setOnDateTimeSelectedListener(OnDateTimeSelectedListener onDateTimeSelectedListener){
        this.onDateTimeSelectedListener = onDateTimeSelectedListener;
}

public OnDateTimeSelectedListener getOnDateTimeSelectedListener(){
        return onDateTimeSelectedListener;
}

In onDateSet(...) method check is time already selected if yes then call the callback

if(tvTimeFrom != null && tvTimeFrom.getText() != null && !tvTimeFrom.getText().toString().trim.equals("")){

    String dateTimeString = date + tvTimeFrom.getText().toString();
    onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
}

In onTimeSet method check is time already selected if yes then call the callback

if(tvDateFrom != null && tvDateFrom.getText() != null && !tvDateFrom.getText().toString().trim.equals("")){

    String dateTimeString = tvDateFrom.getText().toString() + time;
    onDateTimeSelectedListener.onDateTimeSelected(dateTimeString);
}

In DatePickerActivity

Update this line:

public class DatePickerActivity extends AppCompatActivity implements FragmentOne.OnDateTimeSelectedListener{


 // update inside

UPDATE:

   adapter = new PickerAdapter(getFragmentManager(), this);
  ....     

and In

public PickerAdapter(FragmentManager fm) 

constructor update the constructor and try to set the listener

UPDATE

public PickerAdapter(FragmentManager fm, DatePickerActivity activity) {
        super(fm);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
fragmentOne.setOnDateTimeSelectedListener(activity);
    }

And override

void onDateTimeSelected(String datetimeString){
    //You will get DatetimeString here
    //use it

}

UPDATE

Remove that line which was giving error and add these 2 methods and try

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
          onDateTimeSelectedListener = (OnDateTimeSelectedListener) activity;

    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }

}

@Override
public void onDetach(){
super.onDetach();    
onDateTimeSelectedListener = null

}

Reference :Communicating with Other Fragments

Raghavendra
  • 2,305
  • 25
  • 30
0

If Its parent activity then in your Fragment just add this code.

((DatePickerActivity)getBaseActivity()).saveData();

You can call saveData() function or pass data as Bundle object. Add save data inside your Activity.

Swapnil
  • 2,409
  • 4
  • 26
  • 48
0

You should use Callback interface to interract between Fragment and it's host Activity. For example:

  1. Declare in interface and it's metod with data, that you need to send to Activity as a parameter

    public interface Callback {
        void onDataPicked(Data data);
    }
    
  2. Your activity should implement this interface. Write your own code inside overrided method. For example:

    @Override
        public void onDataPicked(Data data) {
        Intent intent = new Intent(this, AnotherActivity.class);
        intent.putExtra("some_data", data);
        startActivity(intent);
    }
    
  3. Declare Callback instance and get the link to host Activity in your Fragment's onAttach method.

    private Callback mCallback;
    
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if(context instanceof Callback){
            mCallback = (Callback) context;
        }
    }
    
  4. Finnaly, when your data is ready call Calback instance's method ant it will run in Activity

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
    
        Button button = (Button) view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCallback.onDataPicked(new Data());
            }
        });
    }
    
  5. Don't forget to set mCallback to null in onDetach() method of your Fragment to avoid memory leaks

    @Override
    public void onDetach() {
        super.onDetach();
        mCallback = null;
    }