Android Date Picker not working properly

时间:2015-06-25 10:04:12

标签: android

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?

4 个答案:

答案 0 :(得分:0)

删除此行

 Log.d("date",selectedDate);

并在返回日期

中添加此行
public void returnDate(String s) { 
     selectedDate=s; 
     Log.d("date",selectedDate); 
} 

答案 1 :(得分:0)

试试此代码

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;
   }
 }

答案 2 :(得分:0)

更改后续行

getActivity().showDialog(999);

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

答案 3 :(得分:0)

在您的主要活动中尝试此代码。然后只需在布局中使用正确的id名称创建一个按钮和textview并运行它。您可以在下面找到完整的博文,其中的源代码位于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");
    }
}