Problem showing date on Android

Asked

Viewed 1,073 times

1

When displaying a date that has been entered in the database, of type DateTime, the app shows the current date:

Data atual errada

I’d also like to convert that date to dd/mm/yyyy to adjust to a portrait layout.

Part of the code that handles that list:

public List<Despesa> getLista() {
    Cursor c = getWritableDatabase().query(TABELA, COLUNAS, null, null, null, null, null);
    List<Despesa> lista = new ArrayList<>();

    while (c.moveToNext()) {
        java.util.Date parsedDate = new java.util.Date();
        String a = c.getString(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
        SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");

        try {
            parsedDate = dateFormat.parse(a);
            a = parsedDate.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }
     //   String returnDate=outputFormatTime.format(inputFormat);

        Despesa despesa = new Despesa();
        despesa.setValor(c.getFloat(0));
        despesa.setData(parsedDate);
        despesa.setDescricao(c.getString(2));
        despesa.setPago(c.getString(3).equalsIgnoreCase("TRUE"));
        despesa.setIdSubgrupo(c.getInt(4));
        despesa.setId(c.getInt(5));

        lista.add(despesa);
    }
    c.close();

    return lista;
}

What’s wrong with the code? The variable String a receives the correct date value, but is not of the type Date, how to convert it to Date and display it in format dd-mm-yyyy?

Getview of the Adapter

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    final int auxPosition = position;

    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final RelativeLayout layout = (RelativeLayout)
            inflater.inflate(R.layout.row, null);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(context, EditaDespesaActivity.class);
            intent.putExtra("valor", lista.get(auxPosition).getValor());
            intent.putExtra("data", lista.get(auxPosition).getData());
            intent.putExtra("descricao", lista.get(auxPosition).getDescricao());
            context.startActivity(intent);
        }
    });

    TextView data = (TextView)
            layout.findViewById(R.id.ddata);
    data.setText(lista.get(position).getData().toString());

    TextView desc = (TextView)
            layout.findViewById(R.id.ddesc);
    desc.setText(lista.get(position).getDescricao());

    TextView valor = (TextView)
            layout.findViewById(R.id.vvalor);
    valor.setText(lista.get(position).getValor().toString());

    return layout;
}

Method to save expense

public void salvarDespesa(View view){

    String[] data = etData.getText().toString().split("/");

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    despesa.setValor(Float.valueOf(etValor.getText().toString().substring(2,etValor.getText().toString().length()).replace(",", ".")));
    try {
        despesa.setData(dateFormat.parse(data[2]+ "-" + data[1]+ "-" + data[0]));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    despesa.setDescricao(etDesc.getText().toString());

    DespesaDAO despesaDAO = new DespesaDAO(this);
    despesaDAO.inserir(despesa);

    Toast.makeText(this,"Despesa adicionada!", Toast.LENGTH_SHORT).show();

    finish();
}
  • How are you creating the layout item? Using ListAdapter? Or with a Adapter own? If it is a Adapter own, could include the method getView of your Adapter?

  • What format is Data being saved to the database?

  • DATETIME, I’m in the bank through a Datepickerdialog. @Fernando

  • @Allanchrystian, There is no Datatype DATETIME in Sqlite, there are alternative methods recommended in the documentation (I particularly recommend and use with INTEGER, using UNIX Time, can I post an example of how to do it, if you think it might be the cause or help? ), maybe this is confusing you and causing the problem.

  • Inserted method to explain better, I think the answer you were looking for was this @Fernando

  • I think the problem is not in the @Fernando database, because when debugging I see that the cursor returns the correct insertion date, I’m just not able to show on the screen.

  • @Allanchrystian, Hello, this is incorrect according to documentation: TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). Then you must save in this format: "YYYY-MM-DD HH:MM:SS.SSS"

  • I don’t understand @Fernando, could you explain in detail what’s wrong with my code?

  • @Allanchrystian, check your first block of code on this snippet: try { parsedDate = dateFormat.parse(a); a = parsedDate.toString(); } catch (ParseException e) { e.printStackTrace(); }, is not falling into the catch? Debug and inform us.

  • @Fernando does not fall in the catch, he executes but shows the current date, not the date that was set in the expense insertion.

  • Allan, the lista.get(position).getData() is a Date or Calendar? If it is recommended to use a DateFormat to properly format as dd/MM/YYYY or something like.

  • It is @Wakim, like Date, how I would do this conversion and how would that line look?

Show 7 more comments

1 answer

3


To format an object Date more humanely just use the SimpleDateFormat.

In the builder of your Adapter just create an instance:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

And use in your getView to properly format:

data.setText(sdf.format(lista.get(position).getData()));

Obs: If you want to display the correct date formatting for the device language just use one of the static methods:

DateFormat.getDateInstance()
DateFormat.getDateTimeInstance()
DateFormat.getTimeInstance()

The only difference is having to deal with the superclass (DateFormat) instead of the subclass.

Anything just look at the documentation with several examples: http://developer.android.com/reference/java/text/SimpleDateFormat.html

  • Solved! Thanks for the reply, very good.

Browser other questions tagged

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