odin_allfather
odin_allfather

Reputation: 29

Save current date and time in Android

First of all I read many posts about Date and found out how to get Date and customize it. But my problem is that I need current date for every time I press button. To be more clear:

DateFormat date = new SimpleDateFormat("MMM dd yyyy, h:mm");
String dateFormat = date.format(Calendar.getInstance().getTime());

And after that I'm calling my Model class to setDate gramHelp.setDate(dateFormat); That works fine but when I check list of dates in my SQL database I only get current date and time for this moment and not for moment when I saved the date. The same problem is in my another activity where I'm calling getDate() to list all dates in database.

DateFormat datum = new SimpleDateFormat("MMM dd yyyy, h:mm");
String date = datum.format(Calendar.getInstance().getTime());
holder.date.setText(date)

The code is basically the same, just this time I'm calling getTime() and not setTime().

For example, this is the list of dates:

enter image description here

for the moment when I'm writing this post. You can see that I have 5 inputs, but I did that every few minutes. Nevertheless in SQL database and my list this is result.

So how to get (save) date and time exactly when I pressed the button ? I guess the answer is really simple but still didn't manage to find it.

UPDATE

In first activity I have FAB that saves date/time in SQL database after click.

 public void onClick(View v) {        
            DateFormat date = new SimpleDateFormat("MMM dd yyyy, h:mm");
            String dateFormat = date.format(Calendar.getInstance().getTime());
            GramHelp gramHelp = new GramHelp();              
            gramHelp.setDate(dateFormat);
            mDatabase.addGramTotal(gramHelp);
        }

GramHelpis my model class where I have all constructors and getter() and setter() methods. I am also calling addGramTotal() function from my database. This is simple function with ContentValues for inserting value in my SQL database.

public void addGramTotal(GramHelp gramHelp){
    ContentValues values = new ContentValues();      
    values.put(FoodEntry.COLUMN_DATE, String.valueOf(gramHelp.getDate()));       
    SQLiteDatabase db = this.getWritableDatabase();
    db.update(FoodEntry.TABLE_NAME_HELPER, values, null, null);
}

To display all dates/times in SQL database I'm using RecyclerView. In activity with RecyclerView I am calling one more function called listHistory(). This function is simple SELECT * FROM table ORDER BY COLUMN_DATE. That part should be fine.

And also in my Adapter class for RecyclerView inside onBindViewHolder() method I have:

public void onBindViewHolder(HistoryAdapter.HistoryViewHolder holder, final int position) {               
    DateFormat datum = new SimpleDateFormat("MMM dd yyyy, h:mm");
    String date = datum.format(Calendar.getInstance().getTime());
    holder.date.setText(date);     
}

SECOND UPDATE:

So this is of my table where date/time is saved. screenshoot As you can see, time is showing only newest insert. This is my whole SELECT code from my database. You can see that I am saving more values in this table. Also I set date as String because I couldn't get Date for some reason (in RecyclerView Adapter method onBindViewHolder). It works with String.

But problem shouldn't be with retrieving date/time. Because date/time is changed (updated) every time when I insert new value into table.

Also this is library I use to inspect my database.

public List<GramHelp> listHistory(){
    String sql = "SELECT * FROM " +FoodEntry.TABLE_NAME_HELPER + " ORDER BY " +FoodEntry.COLUMN_DATE + " ASC ";
    SQLiteDatabase db = this.getReadableDatabase();
    List<GramHelp> listDate = new ArrayList<>();
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor.moveToFirst()){
        do {
            int id = (cursor.getInt(0));
            int id_food = (cursor.getInt(1));
            int id_menu = (cursor.getInt(2));
            double gram = cursor.getDouble(3);
            double gram_total = cursor.getDouble(4);
            String date = new String(cursor.getString(5));
            listDate.add(new GramHelp(id, id_food, id_menu, gram, gram_total, date));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return listDate;
}

Upvotes: 1

Views: 6547

Answers (2)

Nick Cardoso
Nick Cardoso

Reputation: 21733

If I understood your question correctly, I would expect your code to look more like this:

DateFormat date = new SimpleDateFormat("MMM dd yyyy, h:mm");
String dateFormatted = date.format(Calendar.getInstance().getTime());
gramHelp.setDate(dateFormatted);

And reading to look like:

//DateFormat datum = new SimpleDateFormat("MMM dd yyyy, h:mm");
//String date = datum.format(gramHelp.getDate());
holder.date.setText(gramHelp.getDate())

Where gramHelp is a Model. Otherwise Calendar.getInstance().getTime() is reading the current time again.

Edit:

Now you've added additional info I can see you are calling db.update with no id. This will result in no rows being updated (if you read the return value you should see 0)

You have two approaches:

  1. If you are only ever supposed to have 1 item in the table (I can't imagine this is the case) or if the insert happens earlier, then when you do the insert read the return value which is the row id, use the id on future updates.

    • int id = db.insert
    • db.update(..., ..., "WHERE " + FoodEntry.ID + "=?", new String[] { String.valueOf(id) } )
  2. If it should create a new row for each item, then replace db.update with db.insert

    • If you are using this 2nd approach you need to make sure that when you read the data back, you read the correct row by ID or by using ordering FoodEntry.COLUMN_DATE + " asc"

For debugging database stuff I really recommend Stetho by Facebook. Add it to your project with a single line and you can view all the contents of your database from Google Chrome on your computer. (So you know what's in your database and can work out if the data is wrong (from writing) or your query is wrong (for reading)

Upvotes: 4

Arjun Solanki
Arjun Solanki

Reputation: 236

Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int date = calendar.get(Calendar.DATE);
    int month2 = calendar.get(Calendar.MONTH);
    int month = month2 + 1;
    int year = calendar.get(Calendar.YEAR);

Above code is simple for get a current date and time.

Upvotes: -1

Related Questions