Skip to content

Commit 4d53606

Browse files
committed
1. Added method for inserting records with transaction.
1 parent 7297422 commit 4d53606

File tree

2 files changed

+190
-74
lines changed

2 files changed

+190
-74
lines changed

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

Lines changed: 181 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
package com.amit.db;
22

3+
import android.content.ContentValues;
34
import android.content.Context;
45
import android.database.Cursor;
5-
import android.database.DatabaseUtils;
6+
import android.database.sqlite.SQLiteStatement;
67
import android.util.Log;
78

89
import com.amit.utilities.SharedPreferenceData;
910

1011
import java.lang.reflect.Method;
1112
import java.util.ArrayList;
1213
import java.util.LinkedHashMap;
14+
import java.util.TreeSet;
1315

1416
/**
1517
* Created by AMIT JANGID
@@ -18,7 +20,7 @@
1820
* this class has method for executing db queries
1921
* like: creating table, inserting into table, deleting table, dropping table
2022
**/
21-
@SuppressWarnings({"unused", "unchecked"})
23+
@SuppressWarnings({"unused", "unchecked", "PrimitiveArrayArgumentToVarargsMethod", "ConstantConditions"})
2224
public class DBHelper
2325
{
2426
private static final String TAG = DBHelper.class.getSimpleName();
@@ -609,6 +611,11 @@ else if (double.class == method.getParameterTypes()[0])
609611
// getting double value from database
610612
method.invoke(instance, String.valueOf(cursor.getDouble(j)));
611613
}
614+
// checking if parameter type is byte array
615+
/*else if (byte[].class == method.getParameterTypes()[0])
616+
{
617+
method.invoke(instance, cursor.getBlob(j));
618+
}*/
612619
// any other data type will be get string from database
613620
else
614621
{
@@ -1012,54 +1019,171 @@ public DBHelper insertData(String tableName)
10121019
}
10131020

10141021
// checking if data was provided or not for inserting in database
1015-
if (dbDataArrayList == null || dbDataArrayList.size() > 0)
1022+
if (dbDataArrayList == null || dbDataArrayList.size() == 0)
10161023
{
10171024
Log.e(TAG, "insertData: No data provided for inserting.");
10181025
return this;
10191026
}
10201027

1021-
StringBuilder query = new StringBuilder();
1022-
StringBuilder columnName = new StringBuilder();
1023-
StringBuilder columnData = new StringBuilder();
1024-
1025-
query.append("INSERT INTO ").append(tableName).append(" (");
1028+
// content values for putting column name
1029+
// and data for inserting into database table
1030+
ContentValues contentValues = new ContentValues();
10261031

10271032
// loop for no of data to be inserted
10281033
for (int i = 0; i < dbDataArrayList.size(); i++)
10291034
{
1030-
// extracting column name and column data for array list
1031-
columnName.append(dbDataArrayList.get(i).columnName);
1035+
// adding column names and column data into content values
1036+
contentValues.put(dbDataArrayList.get(i).columnName, dbDataArrayList.get(i).columnData.toString());
1037+
}
1038+
1039+
// executing inserting statement for inserting records in table
1040+
db.getWritableDatabase().insert(tableName, null, contentValues);
1041+
dbDataArrayList = new ArrayList<>();
1042+
1043+
return this;
1044+
}
10321045

1033-
if (dbDataArrayList.get(i).blobData != null)
1046+
//#region COMMENTS FOR insertDataWithTransaction method
1047+
/**
1048+
* 2019 January 09 - Wednesday - 06:49 PM
1049+
* insert data with transaction method
1050+
*
1051+
* @param tableName - name of the table where the data is to be inserted
1052+
*
1053+
* this method will insert data into table using database transaction
1054+
* this method is useful for inserting bulk records into table in less time
1055+
**/
1056+
//#endregion COMMENTS FOR insertDataWithTransaction method
1057+
public DBHelper insertDataWithTransaction(String tableName)
1058+
{
1059+
if (dbDataArrayList == null || dbDataArrayList.size() == 0)
1060+
{
1061+
Log.e(TAG, "insertDataWithTransaction: Db Data was not provided. Cannot insert data in table.");
1062+
return this;
1063+
}
1064+
1065+
// tree set is used for removing duplicate column name from data array list
1066+
TreeSet<String> treeSet = new TreeSet<>();
1067+
1068+
// this array list will hold unique column name from data array list
1069+
ArrayList<String> columnsArrayList = new ArrayList<>();
1070+
1071+
// loop for removing duplicate values from data array list
1072+
for (int i = 0; i < dbDataArrayList.size(); i++)
1073+
{
1074+
for (DbData item : dbDataArrayList)
1075+
{
1076+
// checking if tree set contains columns from data array list
1077+
// if not contains then adding it to columns array list
1078+
if (!treeSet.contains(item.columnName))
1079+
{
1080+
// column name not present in columns array list
1081+
// adding to columns array list and tree set
1082+
treeSet.add(item.columnName);
1083+
columnsArrayList.add(item.columnName);
1084+
}
1085+
}
1086+
}
1087+
1088+
// getting columns count for generating insert query
1089+
// and inserting records into corresponding columns
1090+
int columnCount = columnsArrayList.size();
1091+
1092+
// this string builder is used to append names of columns for the query
1093+
// for saving records into corresponding columns
1094+
StringBuilder queryBuilder = new StringBuilder();
1095+
1096+
// this string builder is used to append indexes for the query
1097+
StringBuilder indexesBuilder = new StringBuilder();
1098+
1099+
// generating insert query
1100+
queryBuilder.append("INSERT INTO ").append(tableName).append(" (");
1101+
indexesBuilder.append(" VALUES (");
1102+
1103+
// loop for generating insert query with columns name and indexes
1104+
for (int i = 0; i < columnCount; i++)
1105+
{
1106+
indexesBuilder.append("?");
1107+
queryBuilder.append(columnsArrayList.get(i));
1108+
1109+
// checking if column's count is equals to i
1110+
// if yes then appending brackets
1111+
// else appending comma
1112+
if (i == columnCount - 1)
10341113
{
1035-
columnData.append(dbDataArrayList.get(i).blobData);
1114+
queryBuilder.append(")");
1115+
indexesBuilder.append(")");
10361116
}
1037-
else if (dbDataArrayList.get(i).columnData != null)
1117+
else
10381118
{
1039-
columnData.append(dbDataArrayList.get(i).columnData);
1119+
queryBuilder.append(" , ");
1120+
indexesBuilder.append(" , ");
10401121
}
1122+
}
1123+
1124+
// this is final query
1125+
String query = queryBuilder.toString() + indexesBuilder.toString();
1126+
Log.e(TAG, "insertDataWithTransaction: Insert query with transaction is: " + query);
1127+
1128+
// starting database transaction for inserting records
1129+
db.getWritableDatabase().beginTransaction();
1130+
1131+
// compiling insert query with indexes
1132+
SQLiteStatement statement = db.getWritableDatabase().compileStatement(query);
1133+
1134+
// this position is used for SQLite statement
1135+
// for binding data with columns
1136+
int position = 0;
10411137

1042-
// checking if the loop is at the end of data array list
1043-
// if yes then appending bracket at end of the query for columns and datas
1044-
// else appending comma between two columns and data
1045-
if (i == dbDataArrayList.size() - 1)
1138+
// loop for inserting records with statement
1139+
for (int i = 0; i <= dbDataArrayList.size(); i++)
1140+
{
1141+
// checking if position is equals to column count
1142+
// this check will make sure that only those records get inserted
1143+
// for which the columns are passed
1144+
// irrespective of no of columns table has
1145+
// if yes then executing the statement
1146+
if (position == columnCount)
10461147
{
1047-
columnName.append(")");
1048-
columnData.append(")");
1148+
position = 0;
1149+
statement.execute();
1150+
statement.clearBindings();
10491151
}
1050-
else
1152+
1153+
// checking if i is equals to data array list's size
1154+
// if yes then breaking loop so the below code is not executed
1155+
// this check will ensure that last records are inserted
1156+
// and no index out of bound exception occurs
1157+
if (i == dbDataArrayList.size())
1158+
{
1159+
continue;
1160+
}
1161+
1162+
// increasing the position value by 1 for mapping data with column
1163+
position += 1;
1164+
1165+
// retrieving data from data array list
1166+
Object columnData = dbDataArrayList.get(i).columnData;
1167+
1168+
// checking the type of data and binding to corresponding type
1169+
if (columnData instanceof Integer)
10511170
{
1052-
columnName.append(" , ");
1053-
columnData.append(" , ");
1171+
statement.bindLong(position, Integer.parseInt(columnData.toString()));
1172+
}
1173+
else if (columnData instanceof String )
1174+
{
1175+
statement.bindString(position, columnData.toString());
1176+
}
1177+
else if (columnData instanceof Double || columnData instanceof Float)
1178+
{
1179+
statement.bindDouble(position, Double.parseDouble(columnData.toString()));
10541180
}
10551181
}
10561182

1057-
query.append(columnName.toString()).append(" VALUES (").append(columnData.toString());
1058-
Log.e(TAG, "insertData: Insert query is: " + query.toString());
1183+
db.getWritableDatabase().setTransactionSuccessful();
1184+
db.getWritableDatabase().endTransaction();
10591185

1060-
db.getWritableDatabase().execSQL(query.toString());
10611186
dbDataArrayList = new ArrayList<>();
1062-
10631187
return this;
10641188
}
10651189

@@ -1068,16 +1192,23 @@ else if (dbDataArrayList.get(i).columnData != null)
10681192
* 2019 January 08 - Tuesday - 04:28 PM
10691193
* update data method
10701194
*
1071-
* @param tableName - name of the table on which update query is to be performed
1195+
* @param tableName - name of the table on which update query is to be performed
10721196
*
1073-
* @param columnName - name of the column to check whether the record is present so the data is updated
1197+
* @param whereClause - name of the column to check whether the record is present so the data is updated
1198+
* pass this parameter in the way given in example below
1199+
* Ex: code = ? or ID = ? etc // this is important
10741200
*
1075-
* @param columnData - data of the column name provided to check if record is present for data update
1201+
* @param whereArgs - data of the column name provided to check if record is present for data update
1202+
* here you need to pass the data for the corresponding where clause
1203+
* Ex: 1 or 2 etc
10761204
*
10771205
* this method will update records of the table in database
1206+
* this method uses database's update method for updating records
1207+
*
1208+
* parameter whereClause and whereArgs must be passed in the form given
10781209
**/
10791210
//#endregion COMMENTS FOR updateData method
1080-
public DBHelper updateData(String tableName, String columnName, String columnData)
1211+
public DBHelper updateData(String tableName, String whereClause, String whereArgs)
10811212
{
10821213
// checking if table name was provided or not
10831214
if (tableName == null || tableName.isEmpty())
@@ -1087,14 +1218,14 @@ public DBHelper updateData(String tableName, String columnName, String columnDat
10871218
}
10881219

10891220
// checking if column name was provided or not
1090-
if (columnName == null || columnName.isEmpty())
1221+
if (whereClause == null || whereClause.isEmpty())
10911222
{
10921223
Log.e(TAG, "updateData: Column name was null or empty.");
10931224
return this;
10941225
}
10951226

10961227
// checking if column data was provided or not
1097-
if (columnData == null || columnData.isEmpty())
1228+
if (whereArgs == null || whereArgs.isEmpty())
10981229
{
10991230
Log.e(TAG, "updateData: Column data was null or empty.");
11001231
return this;
@@ -1107,40 +1238,18 @@ public DBHelper updateData(String tableName, String columnName, String columnDat
11071238
return this;
11081239
}
11091240

1110-
StringBuilder query = new StringBuilder();
1111-
query.append("UPDATE ").append(tableName).append(" SET ");
1241+
// content values for putting column name
1242+
// and data for inserting into database table
1243+
ContentValues contentValues = new ContentValues();
11121244

11131245
// loop for no of data provided
11141246
for (int i = 0; i < dbDataArrayList.size(); i++)
11151247
{
1116-
query.append(dbDataArrayList.get(i).columnName)
1117-
.append(" = ");
1118-
1119-
if (dbDataArrayList.get(i).blobData != null)
1120-
{
1121-
query.append(dbDataArrayList.get(i).blobData);
1122-
}
1123-
else if (dbDataArrayList.get(i).columnData != null)
1124-
{
1125-
query.append(dbDataArrayList.get(i).columnData);
1126-
}
1127-
1128-
// checking if loop is not at end of the data array list
1129-
// if not then appending comma between two columns
1130-
if (i != dbDataArrayList.size() - 1)
1131-
{
1132-
query.append(" , ");
1133-
}
1248+
// adding column names and column data into content values
1249+
contentValues.put(dbDataArrayList.get(i).columnName, dbDataArrayList.get(i).columnData.toString());
11341250
}
11351251

1136-
query.append(" WHERE ")
1137-
.append(columnName)
1138-
.append(" = ")
1139-
.append(DatabaseUtils.sqlEscapeString(columnData));
1140-
1141-
Log.e(TAG, "updateData: Update query is: " + query.toString());
1142-
1143-
db.getWritableDatabase().execSQL(query.toString());
1252+
db.getWritableDatabase().update(tableName, contentValues, whereClause, new String[]{whereArgs});
11441253
dbDataArrayList = new ArrayList<>();
11451254

11461255
return this;
@@ -1204,6 +1313,7 @@ public boolean deleteTable(String tableName)
12041313
//#endregion COMMENTS FOR getAllRecords method
12051314
public <T> ArrayList<T> getAllRecords(String tableName, boolean isAscending,
12061315
String orderByColumnName, Class<T> tClass)
1316+
12071317
{
12081318
try
12091319
{
@@ -1296,6 +1406,11 @@ else if (double.class == method.getParameterTypes()[0])
12961406
// getting double value from database
12971407
method.invoke(instance, String.valueOf(cursor.getDouble(j)));
12981408
}
1409+
// checking if parameter type is byte array
1410+
/*else if (byte[].class == method.getParameterTypes()[0])
1411+
{
1412+
method.invoke(instance, cursor.getBlob(j));
1413+
}*/
12991414
// any other data type will be get string from database
13001415
else
13011416
{
@@ -1463,6 +1578,11 @@ else if (double.class == method.getParameterTypes()[0])
14631578
// getting double value from database
14641579
method.invoke(instance, String.valueOf(cursor.getDouble(j)));
14651580
}
1581+
// checking if parameter type is byte array
1582+
/*else if (byte[].class == method.getParameterTypes()[0])
1583+
{
1584+
method.invoke(instance, cursor.getBlob(j));
1585+
}*/
14661586
// any other data type will be get string from database
14671587
else
14681588
{

0 commit comments

Comments
 (0)