Skip to content

Commit b480f8a

Browse files
committed
1. Added method for getting max value of a field.
2. Added method for just executing a query.
1 parent dbed041 commit b480f8a

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

app/src/main/java/com/amit/db/DBHelper.java

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,4 +571,92 @@ public boolean isTableExists(String tableName)
571571
return false;
572572
}
573573
}
574+
575+
/**
576+
* 2018 August 13 - Monday - 12:34 PM
577+
* get max field method
578+
*
579+
* this method will get max value of the field in the table
580+
*
581+
* @param field - primary key of the table to get the max value or
582+
* an integer field of the table to get the max value
583+
*
584+
* @param tableName - table name from where you need to get max value
585+
*
586+
* @return - max value of the field passed
587+
**/
588+
public int getMaxId(String field, String tableName)
589+
{
590+
try
591+
{
592+
if (field != null && field.length() != 0)
593+
{
594+
if (tableName.length() == 0)
595+
{
596+
Log.e(TAG, "getMaxId: table name is required which was not passed");
597+
return 0;
598+
}
599+
600+
String query = "SELECT MAX(" + field + ") AS ID FROM " + tableName;
601+
Cursor cursor = db.getReadableDatabase().rawQuery(query, null);
602+
603+
if (cursor != null)
604+
{
605+
cursor.moveToFirst();
606+
int id = cursor.getInt(cursor.getColumnIndex("ID"));
607+
608+
cursor.close();
609+
return id;
610+
}
611+
else
612+
{
613+
return 0;
614+
}
615+
}
616+
else
617+
{
618+
return 0;
619+
}
620+
}
621+
catch (Exception e)
622+
{
623+
Log.e(TAG, "getMaxId: exception while getting max field from table:\n");
624+
e.printStackTrace();
625+
return 0;
626+
}
627+
}
628+
629+
/**
630+
* 2018 August 20 - Monday - 04:01 PM
631+
* execute query method
632+
*
633+
* this method is used to execute a query
634+
* this method will return true if the query is executed successfully
635+
*
636+
* @param query - query that you want to execute without getting any particular result.
637+
*
638+
* @return - true if query was successful
639+
* false if query was not successful.
640+
**/
641+
public boolean executeQuery(String query)
642+
{
643+
try
644+
{
645+
if (query != null && !query.equalsIgnoreCase(""))
646+
{
647+
db.getWritableDatabase().execSQL(query);
648+
return true;
649+
}
650+
else
651+
{
652+
return false;
653+
}
654+
}
655+
catch (Exception ex)
656+
{
657+
Log.e(TAG, "executeQuery: exception while executing query:\n");
658+
ex.printStackTrace();
659+
return false;
660+
}
661+
}
574662
}

0 commit comments

Comments
 (0)