在 TextView 中显示日期

Show Date in a TextView

您好,我想在文本视图中显示实际日期,但我遇到了一些问题。 我正确地收到了日期,并将其打印在日志上并看到了。我将日期保存在一个字符串中,但是当我尝试将字符串传递给文本 returns 时出现空指针异常,我不知道为什么,因为我在日志上打印了该字符串并且我看到了它。 我的代码:

public void ComprobarDia() {
    Calendar c = Calendar.getInstance();

    SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
    String formattedDate = df.format(c.getTime());
    Datos.fecha=formattedDate;
    Log.d("Calendario", Datos.fecha);
    TV.setText(Datos.fecha);
}

我是在OnCreate方法中执行的。 "Datos.fecha" 是一个 public 静态字符串。 为什么我在最后一行收到 nullpointerexception 但在日志中它显示正确?

您还没有初始化您的 TextView,因此它是 null

您的 onCreate() 方法需要包含此代码。

//Layout with your TextView
setContentView(R.layout.yourLayout);
TextView TV = (TextView) findViewById(R.id.yourTextViewId);

然后,您可以拨打

TV.setText(Datos.fecha);