Problem with DatePicker on Android

0

The intention is that when you click on an EditText there will be the datepicker.

Attachment screenshot where you see the error + code

import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

EditText fechas;
int dia, mes, year, uno, dos, tres;

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fechas = (EditText)findViewById(R.id.fechas);




    fechas.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar c = Calendar.getInstance();

            dia = c.get(Calendar.DAY_OF_MONTH);
            mes = c.get(Calendar.MONTH);
            year = c.get(Calendar.YEAR);

    DatePickerDialog d = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            fechas.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
        }
    }
    ,dia,mes,year);
            d.show();


        }
    });



}

}

    
asked by Sergio 04.09.2017 в 03:09
source

1 answer

1

When you initialize the DatePickerDialog , the first parameter must be a Context and you are passing the instance of the interface View.OnClickListener :

fechas.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar c = Calendar.getInstance();

            dia = c.get(Calendar.DAY_OF_MONTH);
            mes = c.get(Calendar.MONTH);
            year = c.get(Calendar.YEAR);

// this no se refiere al contexto, sino a la instancia actual de la interfaz
    DatePickerDialog d = new DatePickerDialog(this, //...

You have to send the instance of the context or activity as follows:

 DatePickerDialog d = new DatePickerDialog(NombreActividadActual.this, new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            fechas.setText(dayOfMonth+"/"+(monthOfYear+1)+"/"+year);
        }
    }
    ,dia,mes,year);

Where NombreActividadActual is the name of the activity where you are creating the DatePickerDialog .

    
answered by 04.09.2017 / 03:21
source