Return Updated Android Date Time

Asked

Viewed 41 times

1

I made a class called Current Date containing this data:

package com.projeto.projetov1.model;

import java.text.SimpleDateFormat;

public class DataHoraAtual {
    long date = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    String dateString = sdf.format(date);
}

and in my main class, when the event is created has this code:

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

//aplica data hora atual do sistema no app
txtDataHoraOcorrencia = (EditText) 
findViewById(R.id.txtDataHoraOcorrencia);
DataHoraAtual dataHoraAtual = new DataHoraAtual();
txtDataHoraOcorrencia.setText(dataHoraAtual.toString());
}

Doing so the date and time is not displayed, but the following appears:

com.projecto.projetov1.model.Currenttime@4f3b05b

but if I do so, without calling the class the date and time appears:

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

//aplica data hora atual do sistema no app
txtDataHoraOcorrencia = (EditText) findViewById(R.id.txtDataHoraOcorrencia);
long date = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String dateString = sdf.format(date);
txtDataHoraOcorrencia.setText(dataHoraAtual.toString());
}

what I’m doing wrong?

Doing the procedure that Valdeir suggested presented the following:

inserir a descrição da imagem aqui

2 answers

1


If you want the method toString() return the value of dateString you have to overwrite it:

public class DataHoraAtual {
    long date = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    String dateString = sdf.format(date);

    @Override
    public String toString(){
        return dateString;
    }
}
  • Thanks @Ramaral worked

1

It’s not working because you’re getting the class hash.

For your code to work the way you want it, it is necessary to call the attribute value dateString

Thus:

txtDataHoraOcorrencia.setText(dataHoraAtual.dateString);
  • Valdeir, I did what you suggested, but it didn’t work, I edited the question for you to take a look... vlw

  • did not work because you used dateHoraAtual.dateString(),the 2 parentheses means you are calling a method and not an attribute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.