I'm a beginner and don't know how to insert and get the current date by using database.
For an insert into the database, I use a button for adding the information. Here is the full code:
public void Badd_Click(View view) {
db.execSQL("INSERT INTO Demo (event, venue, amount, textView) VALUES ('" + tEvent.getText().toString() + "'," + "'" + tLocation.getText().toString() + "'," + "'" + tAmount.getText().toString() +"' )");
Toast.makeText(this, "Create record successfully...", Toast.LENGTH_SHORT).show();
}
Then, for showing the information inserted into the database, I also use a button:
public void Btnshow_Click(View view){
String str = "";
Cursor c = db.rawQuery("SELECT * FROM "+DATABASE_TABLE,null);
c.moveToFirst();
for(int i = 0; i<c.getCount();i++){
str+="ID: "+c.getString(0)+"\n";
str+="Name : "+c.getString(1)+"\n";
str+="Location : "+c.getString(2)+"\n";
str+="Amount : "+c.getString(3)+"\n\n";
c.moveToNext();
}
I have searched for many solutions, but I am unable to do it successfully.
Please help :(
You can use below two methods to save and retrieve date from database in the format you want.
public static String getDbDateString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
return sdf.format(date);
}
public static Date getDateFromDb(String dateText) {
SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyyMMdd");
try {
return dbDateFormat.parse(dateText);
} catch ( ParseException e ) {
e.printStackTrace();
return null;
}
}
You can get current date with below code:
Date date = new Date(System.currentTimeMillis());
To add to database:
public void addDate() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("key", "value");
// Inserting Row
db.insert(table_name, null, values);
db.close(); // Closing database connection
}
To read from database:
public Date getDate(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_name,
new String[]{column_id,
column_date_value},
column_id + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
return new Date(cursor.getString(index_column_date));
}
Related
I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.
This method is supposed to update the friend in the database. But it is not. No error is shown, tried restarting to refresh the list etc still nothing. Log is showing me new values but they are not saved in the database.
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends,
values,
KEY_NAME + " = ?",
new String[] { String.valueOf(friend.getName()) });
db.close();
}
Here is the way how do I get items from db:
public List<Friend> getAllFriends() {
List<Friend> Friends = new LinkedList<Friend>();
String query = "SELECT * FROM " + TABLE_Friends;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Friend friend = new Friend();
friend.setName(cursor.getString(0));
Date date = new Date(cursor.getLong(1));
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
friend.setBirthday(cal);
Friends.add(friend);
} while (cursor.moveToNext());
}
Log.d("getAllFriends()", Friends.toString());
return Friends;
}
I bet, problem is somewhere in that SQL statement, I am not familiar with it yet, I am used to SQL language not this.
SOLVED, problem was in SQL statement as I later found out:
public void updateFriend(Friend friend) {
Log.d("UpdateFriendMethod", friend.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, friend.getName());
values.put(KEY_BIRTHDAY, friend.getBirthday().getTimeInMillis());
db.update(TABLE_Friends, values, KEY_NAME + "='" + friend.getName()
+ "'", null);
db.close();
}
Is there a simpler way to group and present data from an SQLite database than what I'm about to propose? If so, how would you improve it?
In an app I'm doing for a gym, I need to be able to record the history for 5 types of exercise classes, by date, in descending order (newest on top). In the spirit of sharing code to better understand, here is my table creation:
private static final String CREATE_TABLE_BJJ = "CREATE TABLE IF NOT EXISTS "
// TODO finish this
+ TABLE_BJJ + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BJJ_HISTORY_MOVE + " TEXT NOT NULL, " + BJJ_HISTORY_MOVECOUNT + " INTEGER NOT NULL, "
+ BJJ_HISTORY_PERFORMEDBY + " TEXT NOT NULL, " + BJJ_HISTORY_PERFORMEDTO
+ " TEXT NOT NULL, " + DATE + " datetime NOT NULL, " + UPLOADED
+ " INTEGER NOT NULL DEFAULT 0);";
this results in something like this once data gets recorded:
for the history page though, I need to somehow group all moves performed by date into one row with a sum of the number of moves performed, as in the screenshot below:
What I was thinking might work would be to populate an array with the results of a SELECT DISTINCT STATEMENT then filling an array with the results like so:
String query ="SELECT DISTINCT Date FROM BJJHistory";
ArrayList<String> dateList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Cursor cursor = database.rawQuery(query,null);
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
String datestr = sdf.format(new Date(cursor.getString(0)));
dateList.add(datestr);
}
while (cursor.moveToNext());
}
}
return cursor;
I have a custom class to hold the results:
Public class History {
public String numMoves;
public String date;
public History() {
super();
}
public History(final String numMoves, final String date) {
super();
this.numMoves = numMoves;
this.date = date;
}
}
Afterward, using the array to then create cursors to pull data back as such:
final ArrayList<History> BJJHistory = new ArrayList<History>();
for (int i = 0; dateList.size(); i++) {
final Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM BJJHistory WHERE Date LIKE '" + dateList(i).toString() + "%'") > 0, null);
if (cursor != null) {
cursor.moveToFirst();
BJJHistory.add(new History(cursor.getString(0).toString(),dateList[i].toString()))
}
lot of typing
Finally, using an array adapter to fill the listview with the resulting arraylist of history items. I would still need to use a way to implement an onclick listener that would query the database for all the items for each date, so the user could see what moves they did that date, but the main listview is more important right now.
As always, Thanks in advance!
The GROUP BY clause does what you want; the date function also helps:
SELECT COUNT(*), date("Date") FROM BJHistory GROUP BY date("Date")
I ended up getting it to work with a slightly modified version of what I posted above. For anyone interested, here's my code (which could probably be improved upon):
First, I get all the unique dates from the table:
public String[] getUniqueDates(final String tablename) {
final String query = "SELECT DISTINCT Date FROM " + tablename
+ " ORDER BY Date DESC";
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
final Cursor cursor = database.rawQuery(query, null);
String datestr = null;
final Set<String> set = new LinkedHashSet<String>();
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
// Convert the date to YYYY-MM-DD
try {
final Date dt = sourceFormat.parse(cursor.getString(0));
datestr = sdf.format(dt);
} catch (final ParseException e) {
e.printStackTrace();
}
set.add(datestr);
} while (cursor.moveToNext());
}
cursor.close();
}
return set.toArray(new String[0]);
}
Then I have a class in my Database Access class that selects the number of dates matching the date:
public String selectCount(final String date) {
String count = "";
final Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM "
+ SQLiteHelper.TABLE_BJJ + " WHERE Date LIKE '" + date
+ "%'", null);
if (cursor != null) {
cursor.moveToFirst();
count = cursor.getString(0);
cursor.close();
}
return count;
}
The meat and potatoes that puts the data into the ListView:
String[] DateArray = datasource.getUniqueDates(SQLiteHelper.TABLE_BJJ);
final History BJJHistoryArray[] = new History[DateArray.length];
for (int i = 0; i < DateArray.length; i++) {
String suffix;
if (datasource.selectCount(DateArray[i]).equals("1"))
suffix = " Move";
else
suffix = " Moves";
BJJHistoryArray[i] = new History(datasource.selectCount(DateArray[i]) + suffix,
DateArray[i]);
}
final HistoryAdapter adapter = new HistoryAdapter(this, R.layout.history_row,
BJJHistoryArray);
BJJHistory.setAdapter(adapter);
This results in the following:
When a new entry is logged with the log entry button, it refreshes the query, thus changing the number up by 1 each time.
Things to improve:
Add a parameter for the selectCount() method, so that it can be used on any table.
Try to optimize cursors, if possible.
Optimize code, if possible.
Actually I am working on this for the last 3 or 4 weeks but have not able to resolve it.
I am working on Sqlite Database in android in which I have used a date picker control in my activity Once a user sets a date then i'll stored the date into the string and then sends it to the database it is working fine but when i tried to retrieve the date on the basis of date set on date picker control then it doesn't give me the desired output it show the only a line which is opening a database on my catlog.
Database Class
//Table Definition with Columns
private static final String CREATE_MYCOMPANY =
"create table company " + " (" + "_id" + " integer primary key autoincrement, "
+ "company_date" +" date);";
//Insert Method
public long create(String str) {
ContentValues args = new ContentValues();
args.put(KEY_COMPANY_DATE, str);
return mDb.insert(MYCOMPANY, null,args);
}
//Method For Fetching the row on the basis of Date.//
public Cursor fetchdate(String datr) throws SQLException, ParseException {
Cursor mCursor =
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = " + datr, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Activity Class Code
//Date picker
DatePicker dt = (DatePicker)findViewById(R.id.datePicker1);
//Converting the Date into the string format
String day = String.valueOf(dt.getYear())+"-" +String.valueOf(dt.getMonth() + 1)
+"-"+String.valueOf(dt.getDayOfMonth());
//Method for displaying the rows of table on date basis
public void DisplayAllCmpData(){
employeeTable.open();
try{
Cursor c = employeeTable.fetchdate("2012-6-13");
if (c.moveToFirst())
{
do {
System.out.println("bool2");
DisplayCmpTitle(c);
} while (c.moveToNext());
}
}catch(Exception e){
System.out.println(e);
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
employeeTable.close();
}
//Function For Displaying the all record.//
public void DisplayCmpTitle(Cursor c)
{
System.out.println("bool");
Toast.makeText(this,
"ID: " + c.getString(0) + "\n" +
"DATE: " + c.getString(1)
, Toast.LENGTH_LONG).show();
}
Thanks for any help in advance!!!!!!
mDb.query(true, MYCOMPANY, new String[] {KEY_COMPANY_ID,
KEY_COMPANY_DATE}, KEY_COMPANY_DATE /*+" BETWEEN date('2012-6-10') AND date('2012-6-14')"*/
+ " = '" + datr+"'", null,
null, null, null, null);
I have stored the date as string in sqlite database table. What i need i i have to retrieve the values which stored in last seven days. I have tried by using following but it doesn't showing any values.
My Database function
public Cursor paymentWeek(Activity activity)
{
String[] from = { _PAYMENTID, NAME, REQUESTEDDATE, FROMAD, TOADD, EMAILBODYPAYMENT, AMOUNT};
SQLiteDatabase db = getReadableDatabase();
String orderby = REQUESTEDDATE+" DESC";
Cursor cursor = db.rawQuery("select * from " + PAYMENTTABLE + " where " + REQUESTEDDATE + " BETWEEN "
+ "date('now')" + " AND " + "date('now','-7 days')", null);
activity.startManagingCursor(cursor);
return cursor;
}
Calling function
Cursor week = db.paymentWeek(this);
String[] weekly = new String[] { PaymentAppDataBase.REQUESTEDDATE,PaymentAppDataBase.PAYMENTNAME,PaymentAppDataBase.AMOUNT };
int[] sevendays = new int[] { R.id.Date,R.id.Name,R.id.Amount };
SimpleCursorAdapter weekcursor =
new SimpleCursorAdapter(this, R.layout.listview, week, weekly, sevendays);
setListAdapter(weekcursor);
db.close();
It would be helpful if you guys sort out this problem. I get stuck over here.
try Following query to get records for last week(7 days):
"select * from " + PAYMENTTABLE + " where " + REQUESTEDDATE + "DATE_SUB( CURDATE( ) ,INTERVAL 7 DAY ) AND CURDATE( )";
You don't have to change your db design.
Just write your own convert from dateString to long method, and put it in class like DateUtil.java, then call it wherever you want to do something with date type.
The method should look like this:
public static long convertStringDateToLong(String date, String yourDateFormat) {
Long time = 0L;
try {
SimpleDateFormat df = new SimpleDateFormat(yourDateFormat);
Date d = null;
try {
d = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
time = d.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return time;
}
where yourDateFormat should be something like: "MM/dd/yyyy"