将日期选择器中选择的日期传递给另一个活动?

时间:2015-05-13 11:11:02

标签: android date picker

我在将日期发送到其他活动时遇到了问题。出于某种原因,新的Intent不接受Datepicker.this并且给我一个这不是一个封闭的类错误。任何帮助,将不胜感激。

编辑:原始问题已修复,但现在当我尝试通过应用程序崩溃的日期时。

public class Setup  extends Activity {       

private Button btnReport;
private AlertDialog.Builder dialogBuilder;
private String strWeekNumber = "strWeekNumber";
private Button openAppButton;
private TextView report_date;

int year_x, month_x, day_x;
static final int DIALOG_ID = 0;


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



    final Calendar cal = Calendar.getInstance();
    year_x = cal.get(Calendar.YEAR);
    month_x = cal.get(Calendar.MONTH);
    day_x = cal.get(Calendar.DAY_OF_MONTH);
    setupOpenAppButton();
    showDialogOnButtonClick();

}

public void showDialogOnButtonClick() {


    btnReport = (Button) findViewById(R.id.btnReport);

    btnReport.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showDialog(DIALOG_ID);
                }
            }
    );


}

@Override
protected Dialog onCreateDialog(int id) {
    if (id == DIALOG_ID)
        return new DatePickerDialog(this, dpickerListner, year_x, month_x, day_x);
    return null;
}

private DatePickerDialog.OnDateSetListener dpickerListner
        = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        year_x = year;
        month_x = monthOfYear + 1;
        day_x = dayOfMonth;


        Intent o = new Intent(Setup.this, UnitsForm.class);


        o.putExtra("Date", year_x +"/"+month_x + "/"+ day_x + "/");

        startActivity(o);



    }

};

UnitsForm活动:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    Bundle dateData = getIntent().getExtras();
    if (dateData == null) {
        return;
    }
    String dateSet = dateData.getString("Date");
    final TextView reportDate = (TextView)findViewById(R.id.report_date);
    reportDate.setText(dateSet);

2 个答案:

答案 0 :(得分:3)

你应该传入Intent你的实际上下文,在你的情况下它将是

Intent intent = new Intent(Setup.this, UnitsForm.class);

而不是

Intent o = new Intent(DatePicker.this, UnitsForm.class);

您的UnitsForm活动存在的问题是,您需要在setContentView(R.layout.layout_for_UnitsForm);之前致电final TextView reportDate = (TextView)findViewById(R.id.report_date);,否则TextViewnull

答案 1 :(得分:0)

试试吧

Intent o = new Intent(Setup.this, UnitsForm.class);
o.putExtra("Date", year_x +"/"+month_x + "/"+ day_x + "/");
startActivity(o);