0

Having massive issues implementing a time picker in my android app.Everything works except the timepicker.I have the following code;

TimePickerFragment.java

    package com.deano.dfw;

    import java.util.Calendar;

    import android.app.Dialog;
    import android.app.TimePickerDialog;
    import android.content.Context;
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.widget.TimePicker;

    import com.deano.dfwcomputer.BookNowFragment.TimePickerFragmentListener;

    public class TimePickerFragment extends DialogFragment {

        public static String TAG1 = "TimePickerFragment";
        static Context tContext; //I guess hold the context that called it. Needed when making a DatePickerDialog. I guess its needed when conncting the fragment with the context
        static int tHour;
        static int tMinute;

        static TimePickerFragmentListener tListener;

        public static TimePickerFragment newInstance(Context context, TimePickerFragmentListener listener, Calendar now) {
            TimePickerFragment dialog = new TimePickerFragment();
            tContext = context;
            tListener = listener;

            tHour = now.get(Calendar.HOUR_OF_DAY);
            tMinute = now.get(Calendar.MINUTE);

            /*I dont really see the purpose of the below*/
            Bundle args = new Bundle();
            args.putString("title", "Set Time");
            dialog.setArguments(args);//setArguments can only be called before fragment is attached to an activity, so right after the fragment is created


            return dialog;
        }


        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //return new DatePickerDialog(tContext, mDateSetListener, tHour, tMinute);
            return new TimePickerDialog(tContext,
                    tTimeSetListener, tHour, tMinute, false);
        }


        private TimePickerDialog.OnTimeSetListener tTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                tHour = hourOfDay;
                tMinute = minute;

                tListener.updateChangedTime(hourOfDay, minute);
            }
        };
}

BookNowFragment.java

package com.deano.dfwcomputer;

import java.util.Calendar;
import java.util.regex.Pattern;

import android.support.v4.app.DialogFragment;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class BookNowFragment extends Fragment implements OnClickListener {
    DateDialogFragment frag;
    TimePickerFragment fragTime;
    Button button;
    Button buttonTime;
    Button buttonSubmit;
    Calendar now;
    EditText edittextName;
    EditText edittextPhone;
    EditText editTextProblem;
    private Drawable error_indicator;
    static final int DATE_DIALOG_ID = 0;
    static final int TIME_DIALOG_ID = 2;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // final View rootView = inflater.inflate(R.layout.fragment_booknow,
        // container, false);
        LayoutInflater lf = getActivity().getLayoutInflater();
        final View rootView = lf.inflate(R.layout.fragment_booknow, container,
                false);

        // Setting custom drawable instead of red error indicator,
        error_indicator = getResources().getDrawable(R.drawable.icon);

        int left = 0;
        int top = 0;

        int right = error_indicator.getIntrinsicHeight();
        int bottom = error_indicator.getIntrinsicWidth();

        error_indicator.setBounds(new Rect(left, top, right, bottom));

        edittextName = (EditText) rootView.findViewById(R.id.edittextName);
        edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
        editTextProblem = (EditText) rootView
                .findViewById(R.id.editTextProblem);

        // Called when user type in EditText
        edittextName.addTextChangedListener(new InputValidator(edittextName));
        edittextPhone.addTextChangedListener(new InputValidator(edittextPhone));
        editTextProblem.addTextChangedListener(new InputValidator(
                editTextProblem));

        // Called when an action is performed on the EditText
        edittextName.setOnEditorActionListener(new EmptyTextListener(
                edittextName));
        edittextPhone.setOnEditorActionListener(new EmptyTextListener(
                edittextPhone));
        editTextProblem.setOnEditorActionListener(new EmptyTextListener(
                editTextProblem));

        now = Calendar.getInstance();
        button = (Button) rootView.findViewById(R.id.date_button);
        button.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + "-"
                + String.valueOf(now.get(Calendar.MONTH) + 1) + "-"
                + String.valueOf(now.get(Calendar.YEAR)));
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        buttonTime = (Button) rootView.findViewById(R.id.time_button);
        buttonTime.setText(String.valueOf(now.get(Calendar.HOUR_OF_DAY)) + ":"
                + String.valueOf(now.get(Calendar.MINUTE)));
        buttonTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String strPhoneNo = "0417538062";
                TextView txtName = (TextView) rootView
                        .findViewById(R.id.edittextName);
                TextView txtPhone = (TextView) rootView
                        .findViewById(R.id.edittextPhone);
                TextView txtDate = (TextView) rootView
                        .findViewById(R.id.date_button);
                TextView txtTime = (TextView) rootView
                        .findViewById(R.id.time_button);

                TextView txtProblem = (TextView) rootView
                        .findViewById(R.id.editTextProblem);
                String strName = "Name: " + txtName.getText().toString();
                String strPhone = "Phone: " + txtPhone.getText().toString();
                String strDate = "Date: " + txtDate.getText().toString();
                String strTime = "Time: " + txtTime.getText().toString();

                String strProblem = "Problem: "
                        + txtProblem.getText().toString();
                String strMessage = strName + "\n" + strPhone + "\n" + strDate
                        + "\n" + strTime + "\n" + strProblem;

                BookNowSMS(strPhoneNo, strMessage);

            }
        });

        return rootView;
    }

    // ---sends a SMS message to another device---
    private void BookNowSMS(String phoneNumber, String message) {

        /*
         * PendingIntent pi = PendingIntent.getActivity(this, 0, new
         * Intent(this, test.class), 0); SmsManager sms =
         * SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
         * message, pi, null);
         */

        String SENT = "SMS_SENT";
        // String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
                new Intent(SENT), 0);

        /*
         * PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
         * Intent(DELIVERED), 0);
         */

        // ---when the SMS has been sent---
        getActivity().registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getActivity(), "Message Sent",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getActivity(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getActivity(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getActivity(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;

                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getActivity(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));

        SmsManager sms = SmsManager.getDefault();
        Toast.makeText(getActivity(), "Sending Please Wait", Toast.LENGTH_SHORT)
                .show();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
        // rootView.findViewById(R.id.edittextName);
        TextView text = (TextView) getActivity()
                .findViewById(R.id.edittextName);
        text.setText(null);
        TextView text1 = (TextView) getActivity().findViewById(
                R.id.edittextPhone);
        text1.setText(null);
        TextView text2 = (TextView) getActivity().findViewById(
                R.id.editTextProblem);
        text2.setText(null);
        resetDate();

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    public void showDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            FragmentActivity activity = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ft = activity.getFragmentManager()
                    .beginTransaction();
            frag = DateDialogFragment.newInstance(getActivity(),
                    new DateDialogFragmentListener() {
                        public void updateChangedDate(int year, int month,
                                int day) {
                            button.setText(String.valueOf(day) + "-"
                                    + String.valueOf(month + 1) + "-"
                                    + String.valueOf(year));
                            now.set(year, month, day);
                        }
                    }, now);

            frag.show(ft, "DateDialogFragment");

        case TIME_DIALOG_ID:
            // return new TimePickerFragment(getActivity(), tListener, hours,
            // min, false);
            FragmentActivity activityTime = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ftime = activityTime.getFragmentManager()
                    .beginTransaction();
            fragTime = TimePickerFragment.newInstance(getActivity(),
                    new TimePickerFragmentListener() {
                        public void updateChangedTime(int hour, int minute) {
                            buttonTime.setText(String.valueOf(hour) + ":"
                                    + String.valueOf(minute));
                            now.set(hour, minute);
                        }
                    }, now);

            fragTime.show(ftime, "TimePickerFragment");
        }
        return;

    }

    public interface DateDialogFragmentListener {
        // this interface is a listener between the Date Dialog fragment and the
        // activity to update the buttons date
        public void updateChangedDate(int year, int month, int day);
    }

    public interface TimePickerFragmentListener {
        // this interface is a listener between the Time Dialog fragment and the
        // activity to update the buttons time
        public void updateChangedTime(int hour, int minute);
    }

    public void resetDate() {
        now = Calendar.getInstance();
        button = (Button) getActivity().findViewById(R.id.date_button);
        button.setText(String.valueOf(now.get(Calendar.DAY_OF_MONTH)) + "-"
                + String.valueOf(now.get(Calendar.MONTH) + 1) + "-"
                + String.valueOf(now.get(Calendar.YEAR)));
    }

    private class InputValidator implements TextWatcher {
        private EditText et;

        private InputValidator(EditText editText) {
            this.et = editText;
        }

        public void afterTextChanged(Editable s) {

        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (s.length() != 0) {
                switch (et.getId()) {
                case R.id.edittextName: {
                    if (!Pattern.matches("^[\\sa-zA-Z]{1,25}$", s)) {
                        et.setError("Name must have only a-z or A-Z E.g. John Doe");
                    }
                }
                    break;

                case R.id.edittextPhone: {
                    if (!Pattern.matches("^[0-9]{1,10}$", s)) {
                        et.setError("Phone Number must be 10 numbers only with no spaces E.g. 0417538062");
                    }
                }
                    break;
                case R.id.editTextProblem: {

                    if (!Pattern.matches("^[\\w\\sa-zA-Z0-9.']{1,65}$", s)) {
                        et.setError("Text must only contain a-z and A-Z and numbers.");
                    }
                }
                    break;

                }
            }
        }
    }

    private class EmptyTextListener implements OnEditorActionListener {
        private EditText et;

        public EmptyTextListener(EditText editText) {
            this.et = editText;
        }

        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                // Called when user press Next button on the soft keyboard

                if (et.getText().toString().equals(""))
                    et.setError("Oops! empty.", error_indicator);
            }
            return false;
        }
    }

}

fragment_booknow.xml

<?xml version="1.0" encoding="utf-8"?>


    <TableLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchColumns="1"
        android:orientation="vertical" >

        <TableRow>

            <TextView
                android:layout_gravity="center_horizontal"
                android:layout_span="3"
                android:padding="10sp"
                android:text="@string/textBookService"
                android:textSize="22sp" />
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/edittextName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5px"
                android:layout_span="2"
                android:hint="@string/hintYourName" >
            </EditText>
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/edittextPhone"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5px"
                android:layout_span="2"
                android:hint="@string/hintPhone"
                android:saveEnabled="false" >
            </EditText>
        </TableRow>

        <TableRow>

            <TextView android:text="@string/SelectDate" />
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/date_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickMe"
                android:text="03-18-2012" />
        </TableRow>

        <TableRow>

            <TextView android:text="@string/SelectTime" />
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/time_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="clickMe"
                android:text="03-18-2012" />
        </TableRow>

        <TableRow>

            <EditText
                android:id="@+id/editTextProblem"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_span="2"
                android:hint="@string/hintProblem"
                android:minLines="3" >
            </EditText>
        </TableRow>

        <TableRow>

            <Button
                android:id="@+id/buttonSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_margin="5px"
                android:layout_span="2"
                android:text="@string/buttonSubmit" >
            </Button>
        </TableRow>
    </TableLayout>

The error I'm getting is in BookNowFragment.java

The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentTransaction, String)

and is from this part of the code;

fragTime.show(ftime, "TimePickerFragment");

strange part is the date dialog above is similar and works perfectly.Any ideas how to resolve this.

UPDATE 2

Fixed timepicker as follows;

Changed; return new TimePickerDialog(tContext, tTimeSetListener, tHour, tMinute, false);

To; return new TimePickerDialog(getActivity(), tTimeSetListener, tHour, tMinute, false);

But still have error The method show(FragmentManager, String) in the type DialogFragment is not applicable for the arguments (FragmentTransaction, String)

in the following frag.show;

case DATE_DIALOG_ID:
            FragmentActivity activity = (FragmentActivity) getActivity();
            // FragmentTransaction ft = getFragmentManager().beginTransaction();
            // //get the fragment
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            frag = DateDialogFragment.newInstance(getActivity(),
                    new DateDialogFragmentListener() {
                        public void updateChangedDate(int year, int month,
                                int day) {
                            button.setText(String.valueOf(day) + "-"
                                    + String.valueOf(month + 1) + "-"
                                    + String.valueOf(year));
                            now.set(year, month, day);
                        }
                    }, now);

            frag.show(ft, "DateDialogFragment");

1 Answer 1

1

You should use android.support.v4.app.FragmentManager instead of android.app.FragmentManager.

call like this it will help

call getSupportFragmentManager() but not getFragmentManager()

FragmentTransaction ft = activity.getFragmentManager().beginTransaction();

refer this doc : Document

10
  • Im still getting the error on show could you show me the code for showDialog
    – Deano
    Jul 7, 2014 at 9:19
  • updated please check this android-developers.blogspot.in/2012/05/… Jul 7, 2014 at 9:28
  • ok that switched the error from that one to frag.show(ft, "DateDialogFragment"); and it already seems to be correct.....Im way out of my depth here
    – Deano
    Jul 7, 2014 at 10:24
  • forgot to mention that timepicker still doesnt work it throws the following 07-07 20:29:31.030: E/AndroidRuntime(664): at com.deano.dfw.BookNowFragment$6.updateChangedTime(BookNowFragment.java:253) 07-07 20:29:31.030: E/AndroidRuntime(664): at com.deano.dfw.TimePickerFragment$1.onTimeSet(TimePickerFragment.java:55)
    – Deano
    Jul 7, 2014 at 10:31
  • this is another issue, first issue solved right ?, then accept it as anser...and post error related logs here will help how to solve Jul 7, 2014 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.