简体   繁体   中英

Android Date Picker not working properly

I am trying to implement a date picker in android. The datepicker should appear after tapping on a button. Yeah,i know it's pretty straightforward but being a beginner, i am a bit stuck in this. Here are the parts of code relevant to the task.

 public class NeedFragment extends Fragment {

        private DatePicker datePicker;
        private Calendar calendar;
        private TextView dateView;
        private int year, month, day;
        Fragment fragment;
        String selectedDate=null;

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

            View rootView = inflater.inflate(R.layout.fragment_need_blood, container, false);
            Button button1 = (Button)rootView.findViewById(R.id.dialog_btn1);

    button1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    getActivity().showDialog(999);
                     if(selectedDate != null) {
                      Log.d("date",selectedDate); 
                     }
                    //openAppointments(dialog);
                }
            });
return rootView;
    }
    protected Dialog onCreateDialog(int id) {
              // TODO Auto-generated method stub
              if (id == 999) {
                 return new DatePickerDialog(getActivity().getApplicationContext()
                         , myDateListener, year, month, day);
              }
              return null;
           }

           private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
              @Override
              public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
                 // TODO Auto-generated method stub
                 // arg1 = year
                 // arg2 = month
                 // arg3 = day

                 StringBuilder sb=null;

                 sb.append(arg3).append("/")
                      .append(arg2+1).append("/").append(arg1);
                 returnDate(sb.toString());

              }
           };

           public void returnDate(String s)
           {
               selectedDate=s;
           }
       }

This is the error:

06-25 15:19:53.150: E/AndroidRuntime(13160): FATAL EXCEPTION: main
06-25 15:19:53.150: E/AndroidRuntime(13160): Process: com.bloodbank.slidingmenu, PID: 13160
06-25 15:19:53.150: E/AndroidRuntime(13160): java.lang.NullPointerException: println needs a message
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.println_native_inner(Native Method)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.println_native(Log.java:290)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.d(Log.java:323)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.bloodbank.slidingmenu.NeedBloodFragment$3.onClick(NeedBloodFragment.java:220)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.view.View.performClick(View.java:4761)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.view.View$PerformClick.run(View.java:19767)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Handler.handleCallback(Handler.java:739)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Handler.dispatchMessage(Handler.java:95)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Looper.loop(Looper.java:135)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.app.ActivityThread.main(ActivityThread.java:5312)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at java.lang.reflect.Method.invoke(Native Method)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at java.lang.reflect.Method.invoke(Method.java:372)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

EDIT: previous error was resolved. i have one more question though. can i start a activity after i click on ok in the date dialog box?

Remove this line

 Log.d("date",selectedDate);

and add this line inside your return date

public void returnDate(String s) { 
     selectedDate=s; 
     Log.d("date",selectedDate); 
} 

Try this code

public class NeedFragment extends Fragment {

private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
Fragment fragment;
String selectedDate="";

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

    View rootView = inflater.inflate(R.layout.fragment_need_blood, container, false);
    Button button1 = (Button)  rootView.findViewById(R.id.dialog_btn1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onCreateDialog(999);
            Log.d("date",selectedDate);
            //openAppointments(dialog);
        }
    });
  return rootView;
  }
  public Dialog onCreateDialog(int id) {
      // TODO Auto-generated method stub
      if (id == 999) {
         return new DatePickerDialog(getActivity()
                 , myDateListener, year, month, day);
      }
      return null;
   }

   public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
         // TODO Auto-generated method stub
         // arg1 = year
         // arg2 = month
         // arg3 = day

         StringBuilder sb=null;

         sb.append(arg3).append("/")
              .append(arg2+1).append("/").append(arg1);
         returnDate(sb.toString());

      }
   };

   public void returnDate(String s)
   {
       selectedDate=s;
   }
 }

Once change following line

getActivity().showDialog(999);

to

Dialog dialog=onCreateDialog(999);
 if(dialog!=null){
    dialog.show();
 }

Try this code in your main activity. Then simply create a button and textview in your layout with the correct id name and run it. You can find the full blog post from below with the source code on http://www.ahotbrew.com/android-datepicker-example/

package com.ahotbrew.datepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends ActionBarActivity {

    public static TextView SelectedDateView;

    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            SelectedDateView.setText("Selected Date: " + (month + 1) + "-" + day + "-" + year);
        }
    }

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

        SelectedDateView = (TextView) findViewById(R.id.selected_date);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM