1

What I want?: Write a method to:

  • 1st: Get date.

  • 2nd: Make it a String.

  • 3rd: setText(String) into an EditText.

What I've done:

private void setToday() {
    String dateToday = "";
    DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
    dateToday = df.format(Calendar.getInstance().getTime());
    EditText title = (EditText) findViewById(R.id.Title);
    dateToday = df.toString();
    title.setText(dateToday);
}

Also:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

EditText & Button:

 <EditText
            android:id="@+id/Title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Title" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Today"
            android:onClick="setToday"/>

What should it do?: In Utopia, this should get date, focus on EditText and put date into EditText.

What it does?: Button clicked = App crashes.

This is a brand new app. I've tryed even only:

private void setToday() {
        EditText title = (EditText) findViewById(R.id.Title);
        title.setText("HOY");
    }

It still crashes. I'm doing something wrong, but cannot figure what it is.

EDIT: I managed to find logcat:

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not find method setToday(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton

at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)

at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)

at android.view.View.performClick(View.java:4232)

at android.view.View$PerformClick.run(View.java:17298)

at android.os.Handler.handleCallback(Handler.java:615)

at android.os.Handler.dispatchMessage(Handler.java:92)

at android.os.Looper.loop(Looper.java:137)

at android.app.ActivityThread.main(ActivityThread.java:4921)

at java.lang.reflect.Method.invokeNative(Native Method)

at java.lang.reflect.Method.invoke(Method.java:511)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

at dalvik.system.NativeStart.main(Native Method)

Thanks for help.

PS: Here is all my code:

Java

package com.example.android.notastxt;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity {

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

    private void setToday() {
        String dateToday = "HOY";
        DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
        dateToday = df.format(Calendar.getInstance().getTime());
        EditText title = (EditText) findViewById(R.id.Title);
        dateToday = df.toString();
        title.setText(dateToday);
    }

}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.android.notastxt.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/Title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Title" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Today"
            android:onClick="setToday"/>
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="start"
        android:hint="Write" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save" />


</LinearLayout>
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Josue Fas
  • 39
  • 7
  • 1
    What error do you get if connect your phone to the pc and watch logcat? – meow Sep 25 '17 at 22:53
  • Let's start with catching an execption inside your method... – Sheinbergon Sep 26 '17 at 00:03
  • Ok. After breaking my head, I could finaly find logcat. I'm editing main post. – Josue Fas Sep 26 '17 at 12:44
  • 1
    To let everyone know your problem is solved, please accept an answer by clicking the tick mark to the left of the answer. You may accept your own answer if you think it best describes the solution. – Ole V.V. Sep 27 '17 at 02:35
  • Thanks, Ole V.V. I'll do as soon as system allow me. Right now it promts: "You can accept your own answer in 11 hours". – Josue Fas Sep 27 '17 at 11:03

2 Answers2

3

Speaking just to your date-time work…

Description of formatter?!

Your code:

String dateToday = "";
DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
dateToday = df.format(Calendar.getInstance().getTime());  // <-- Good, you have your string representing date-time value. But then you replace it two lines below.
EditText title = (EditText) findViewById(R.id.Title);
dateToday = df.toString();  // <-- Why ask for a description of the formatter?
title.setText(dateToday);

…is replacing your intended date-time string with a description of the formatter. Should be:

DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
String dateToday = df.format(Calendar.getInstance().getTime());
EditText title = (EditText) findViewById(R.id.Title);
title.setText(dateToday);

Using java.time

Even better, stop using these troublesome old date-time classes. They are now legacy, supplanted by the java.time classes. For Android, see the last bullets below.

Instant is a moment on the timeline in UTC. It replaces java.util.Date, but with a finer resolution of nanoseconds rather than milliseconds.

Instant instant = Instant.now() ; 

Apply the time zone through which you want to view the wall-clock time. For any given moment both the date and the time-of-day varies by zone. Noon in Europe/Paris is a much later time-of-day in Asia/Kolkata and a much earlier time-of-day in America/Montreal.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Let java.time automatically localize.

Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;

Or specify a custom pattern.

Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd MM uuuu, HH:mm" , locale ) ;
String output = zdt.format( f ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • The part about using ThreeTenABP and `java.time` is certainly good advice no matter what. It seems to me you are not explaining the reason for the crash that the asker experienced (I haven’t guessed the reason either). – Ole V.V. Sep 26 '17 at 07:14
  • @OleV.V. No, I don’t know why the crash, thus the first line line of my Answer. – Basil Bourque Sep 26 '17 at 07:17
  • I added logcat text to question. – Josue Fas Sep 26 '17 at 12:55
1

I deserve all your laughts. This was simply newbie mistake.

Changed

private void setToday() {

For

public void setToday(View View) {

Voilà! It worked flawlessly.

I used code from @Basil Bourque from here: https://stackoverflow.com/a/46415908/8662218

DateFormat df = new SimpleDateFormat("dd MM yyyy, HH:mm");
String dateToday = df.format(Calendar.getInstance().getTime());
EditText title = (EditText) findViewById(R.id.Title);
title.setText(dateToday);

Thank you, Basil.

Problem solved.

Josue Fas
  • 39
  • 7