2

I am developing an application with the navigation drawer.My base activity is Dashboard activity.Thereis a navigation list. And When I click on items in the navigation list it shows some interface using a fragment(replacing the Dashboard Activity).On an AddPatient fragment I am displaying form.I am adding a Date_of_birth field, on which when I click on that date_of_birth(edit-text) view a date picker dialog should popup(making the background a transparent but dark), take the inputs, display it back on the fragment.

Problem is that I m not finding out how to display the date picker on fragment, the base activity(Dashboard Activity) extends Fragment Activity and the AddPatient Fragment extends DailogFragment. The code is given below. I don't know where I am going wrong.

The code for My Dashboard Activity is

    public class DashboardActivity extends FragmentActivity {
    Fragment fragment;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerList;
private ArrayList<NavDrawerItem> navDrawerItems;
private int groupP, childP;
private SwipeListView swipeListView;
List<CalenderDrawable> list;
List<String> menu_items;
Map<String, List<String>> childCollection;
public static List<String> childList;
public static List<String> childListForConnectedService;

private ActionBarDrawerToggle mDrawerToggle;
Session session;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    setContentView(R.layout.activity_dashboard);
    session = new Session(this);

    fragment = new DashboardFragment();
    getFragmentManager().beginTransaction()
            .replace(R.id.frame_container, fragment).commit();

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ExpandableListView) findViewById(R.id.list_slidermenu);

    createMenuItemList();
    createCollection();
    final ExpandableListAdapterNew adapter = new ExpandableListAdapterNew(
            DashboardActivity.this, menu_items, childCollection);
    mDrawerList.setAdapter(adapter);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    // getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayShowTitleEnabled(false);
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#33ffffff")));

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.empty, R.string.empty) {

        public void onDrawerClosed(View view) {

            invalidateOptionsMenu(); // Setting, Refresh and Rate App
        }

        public void onDrawerOpened(View drawerView) {

            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerList.setOnGroupExpandListener(new OnGroupExpandListener() {

        int previousGroup = -1;

        @Override
        public void onGroupExpand(int groupPosition) {
            Toast.makeText(getApplicationContext(),
                    menu_items.get(groupPosition) + " Expanded",
                    Toast.LENGTH_SHORT).show();

            if (groupPosition != previousGroup)
                mDrawerList.collapseGroup(previousGroup);
            previousGroup = groupPosition;

        }
    });

    mDrawerList.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(
                    getApplicationContext(),
                    menu_items.get(groupPosition)
                            + " : "
                            + childCollection.get(
                                    menu_items.get(groupPosition)).get(
                                    childPosition), Toast.LENGTH_SHORT)
                    .show();
            groupP = groupPosition;
            childP = childPosition;
            switch (groupPosition) {
            case 0:
                switch (childPosition) {
                case 0:
                    Log.d("CASE Patient ", "Add Patient");
                    fragment = new AddPatient();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.frame_container, fragment)
                            .commit();
                    break;
                case 1:
                    Log.d("CASE Patient ", "View Patient");
                    fragment = new DashboardFragment();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.frame_container, fragment)
                            .commit();
                    break;
    default:
                break;
            }

            mDrawerLayout.closeDrawer(mDrawerList);
            return false;
        }
    });
}

And the Code for Add Patient Frament On which the Date Picker is to be displayed is this..

    public class AddPatient extends Fragment implements OnClickListener {
View rootView;
private EditText edtGender, edtUsername, edtMobNo, edtFname, edtLname;
private static TextView edtDOB;
private TextView Heading, textWelcm;
private Button btnSubmit;
Session session;

public AddPatient() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.addpatient, container, false);
    init();
    Heading = (TextView) rootView.findViewById(R.id.textView1);
    Heading.setText("Add Patient");
    session = new Session(getActivity());
    String userType = session.restoreName(Session.USERTPYE);
    String userN = session.restoreName(Session.FULLNAME);
    textWelcm = (TextView) rootView.findViewById(R.id.textWelcm);
    if (userType.equals("D")) {
        textWelcm
                .setText(Html.fromHtml("<b>Welcome, </b>" + "Dr." + userN));
    } else if (userType.equals("O")) {
        textWelcm.setText(Html
                .fromHtml("<b>Welcome, </b>" + "Opt." + userN));
    }

    return rootView;
}

private void init() {
    // TODO Auto-generated method stub
    edtUsername = (EditText) rootView.findViewById(R.id.edtUsername);
    edtMobNo = (EditText) rootView.findViewById(R.id.edtMobNo);
    edtFname = (EditText) rootView.findViewById(R.id.edtFname);
    edtLname = (EditText) rootView.findViewById(R.id.edtLname);
    edtDOB = (TextView) rootView.findViewById(R.id.edtDOB);
    edtDOB.setOnClickListener(this);
    edtGender = (EditText) rootView.findViewById(R.id.edtGender);
    btnSubmit = (Button) rootView.findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.edtDOB:
        Log.d("showDatePickerDialogBox", "showDatePickerDialogBox");
        LayoutInflater inflater = (LayoutInflater) getActivity()
                .getLayoutInflater();
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                getActivity());
        View customView = inflater.inflate(R.layout.datepicker, null);
        alertDialog.setView(customView);
        final Calendar now = Calendar.getInstance();
        final DatePicker datePicker = (DatePicker) customView
                .findViewById(R.id.dialog_datepicker);
        final TextView dateTextView = (TextView) customView
                .findViewById(R.id.dialog_dateview);
        final SimpleDateFormat dateViewFormatter = new SimpleDateFormat(
                "EEEE, dd.MM.yyyy", Locale.ENGLISH);
        final SimpleDateFormat formatter = new SimpleDateFormat(
                "dd.MM.yyyy", Locale.ENGLISH);
        // Minimum date
        Calendar minDate = Calendar.getInstance();
        try {
            minDate.setTime(formatter.parse("12.12.2010"));
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        datePicker.setMinDate(minDate.getTimeInMillis());
        // View settings
        alertDialog.setTitle("Choose a date");
        Calendar choosenDate = Calendar.getInstance();
        int year = choosenDate.get(Calendar.YEAR);
        int month = choosenDate.get(Calendar.MONTH);
        int day = choosenDate.get(Calendar.DAY_OF_MONTH);
        try {
            Date choosenDateFromUI = formatter
                    .parse(edtDOB.getText().toString());
            choosenDate.setTime(choosenDateFromUI);
            year = choosenDate.get(Calendar.YEAR);
            month = choosenDate.get(Calendar.MONTH);
            day = choosenDate.get(Calendar.DAY_OF_MONTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar dateToDisplay = Calendar.getInstance();
        dateToDisplay.set(year, month, day);
        dateTextView.setText(dateViewFormatter.format(dateToDisplay
                .getTime()));
        // Buttons
        alertDialog.setNegativeButton("Go to today",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        edtDOB.setText(formatter
                                .format(now.getTime()));
                        dialog.dismiss();
                    }
                });
        alertDialog.setPositiveButton("Choose",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Calendar choosen = Calendar.getInstance();
                        choosen.set(datePicker.getYear(),
                                datePicker.getMonth(),
                                datePicker.getDayOfMonth());
                        edtDOB.setText(dateViewFormatter.format(choosen
                                        .getTime()));
                        dialog.dismiss();
                    }
                });
        final AlertDialog dialog = alertDialog.create();
        // Initialize datepicker in dialog datepicker
        datePicker.init(year, month, day,
                new DatePicker.OnDateChangedListener() {
                    public void onDateChanged(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {
                        Calendar choosenDate = Calendar.getInstance();
                        choosenDate.set(year, monthOfYear, dayOfMonth);
                        dateTextView.setText(dateViewFormatter
                                .format(choosenDate.getTime()));
                        if (choosenDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                                || now.compareTo(choosenDate) < 0) {
                            dateTextView.setTextColor(Color
                                    .parseColor("#ff0000"));
                            ((Button) dialog
                                    .getButton(AlertDialog.BUTTON_POSITIVE))
                                    .setEnabled(false);
                        } else {
                            dateTextView.setTextColor(Color
                                    .parseColor("#000000"));
                            ((Button) dialog
                                    .getButton(AlertDialog.BUTTON_POSITIVE))
                                    .setEnabled(true);
                        }
                    }
                });
        // Finish
        dialog.show();
    default:
        break;
    }
}

}

Edit: Found the solution from www.open-sourced.de/show_article.php

Delimitry
  • 2,987
  • 4
  • 30
  • 39
user2833621
  • 165
  • 1
  • 13

1 Answers1

1

Use

DialogFragment picker = new AddPatient();
picker.show(getFragmentManager(), "datePicker");

You can find more information @

http://developer.android.com/reference/android/app/DialogFragment.html

Example:

How to transfer the formatted date string from my DatePickerFragment?

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Its giving error... The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentManager, String). – user2833621 Mar 07 '14 at 07:10
  • @user2833621 Show your imports for DialogFragment – Raghunandan Mar 07 '14 at 07:11
  • I have added the imports in my edits.. When i use FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); DialogFragment picker = new AddPatient();picker.show(ft, "datePicker");......... it displays the dailog on my Dashboard activity.. I want to create an Add Patient Fragment from my dashboard activity... And then display a dailog from it.. – user2833621 Mar 07 '14 at 07:41
  • @user2833621 i don't what you want. But this will help `picker.show(getSupportFragmentManager(), "datePicker");` since youa re using support based fragments – Raghunandan Mar 07 '14 at 07:43
  • @user2833621 also AddPatient is a DIalogFragment. You are really confused. Read the docs. – Raghunandan Mar 07 '14 at 07:44
  • @user2833621 if in fragment you can use `getActivity().getSupportFragmentManager()`. So untill you make it clear i can't help further. – Raghunandan Mar 07 '14 at 07:53
  • Sry if i have confused u through my code.. I want to make Add Patient a Fragment that will take the whole screen space...(It is displayed when i click on one of the menu item in the navigation Drawer).Add patient fragment contains Form.. in which there is a field DateofBirth.. on the click of that field i want to display date picker dailog – user2833621 Mar 07 '14 at 07:58
  • 1
    @user2833621 first add `AddPatient` Fragment to the container. Second Show a DIalogFragment From it. Third On Date Selection use interface as a callback to the Activity. four pass the date from Activity to AddPatient. Note: 2 fragments should not communicate directly. – Raghunandan Mar 07 '14 at 08:01
  • Ok..got it...I'l try doing it n wil reply back with the result and really thanks for your help.. – user2833621 Mar 07 '14 at 08:11
  • hey, thanks for your help.. I displayed the date picker in my fragment using alert dailog. I found it simpler..I updated my code for reference. – user2833621 Mar 08 '14 at 10:10