Skip to content

Commit

Permalink
1. Added new method in db helper for inserting data in to database us…
Browse files Browse the repository at this point in the history
…ing transaction for faster data insertion and faster execution time.
  • Loading branch information
amitjangid80 committed Mar 6, 2019
1 parent 0159e65 commit cb46b91
Show file tree
Hide file tree
Showing 3 changed files with 250 additions and 12 deletions.
160 changes: 157 additions & 3 deletions app/src/main/java/com/amit/db/DBHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class DBHelper
private static final String TAG = DBHelper.class.getSimpleName();

private final Database db;

private ArrayList<DbData> dbDataArrayList = new ArrayList<>();
private ArrayList<DbColumn> dbColumnArrayList = new ArrayList<>();

Expand Down Expand Up @@ -1036,6 +1036,152 @@ public DBHelper insertData(String tableName)

return this;
}

//#region COMMENTS FOR insertDataWithTransaction method
/**
* 2019 January 09 - Wednesday - 06:49 PM
* insert data with transaction method
*
* @param tableName - name of the table where the data is to be inserted
*
* this method will insert data into table using database transaction
* this method is useful for inserting bulk records into table in less time
**/
//#endregion COMMENTS FOR insertDataWithTransaction method
@Deprecated
public DBHelper insertDataWithTransaction(String tableName)
{
if (dbDataArrayList == null || dbDataArrayList.size() == 0)
{
Log.e(TAG, "insertDataWithTransaction: Db Data was not provided. Cannot insert data in table.");
return this;
}

// tree set is used for removing duplicate column name from data array list
TreeSet<String> treeSet = new TreeSet<>();

// this array list will hold unique column name from data array list
ArrayList<String> columnsArrayList = new ArrayList<>();

// loop for removing duplicate values from data array list
// for (int i = 0; i < dbDataArrayList.size(); i++)
for (int i = 0; i < dbDataArrayList.size(); i++)
{
for (DbData item : dbDataArrayList)
{
// checking if tree set contains columns from data array list
// if not contains then adding it to columns array list
if (!treeSet.contains(item.columnName))
{
// column name not present in columns array list
// adding to columns array list and tree set
treeSet.add(item.columnName);
columnsArrayList.add(item.columnName);
}
}
}

// getting columns count for generating insert query
// and inserting records into corresponding columns
int columnCount = columnsArrayList.size();

// this string builder is used to append names of columns for the query
// for saving records into corresponding columns
StringBuilder queryBuilder = new StringBuilder();

// this string builder is used to append indexes for the query
StringBuilder indexesBuilder = new StringBuilder();

// generating insert query
queryBuilder.append("INSERT INTO ").append(tableName).append(" (");
indexesBuilder.append(" VALUES (");

// loop for generating insert query with columns name and indexes
for (int i = 0; i < columnCount; i++)
{
indexesBuilder.append("?");
queryBuilder.append(columnsArrayList.get(i));

// checking if column's count is equals to i
// if yes then appending brackets
// else appending comma
if (i == columnCount - 1)
{
queryBuilder.append(")");
indexesBuilder.append(")");
}
else
{
queryBuilder.append(" , ");
indexesBuilder.append(" , ");
}
}

// this is final query
String query = queryBuilder.toString() + indexesBuilder.toString();
Log.e(TAG, "insertDataWithTransaction: Insert query with transaction is: " + query);

// starting database transaction for inserting records
db.getWritableDatabase().beginTransaction();

// compiling insert query with indexes
SQLiteStatement statement = db.getWritableDatabase().compileStatement(query);

// this position is used for SQLite statement
// for binding data with columns
int position = 0;

// loop for inserting records with statement
for (int i = 0; i <= dbDataArrayList.size(); i++)
{
// checking if position is equals to column count
// this check will make sure that only those records get inserted
// for which the columns are passed
// irrespective of no of columns table has
// if yes then executing the statement
if (position == columnCount)
{
position = 0;
statement.execute();
statement.clearBindings();
}

// checking if i is equals to data array list's size
// if yes then breaking loop so the below code is not executed
// this check will ensure that last records are inserted
// and no index out of bound exception occurs
if (i == dbDataArrayList.size())
{
continue;
}

// increasing the position value by 1 for mapping data with column
position += 1;

// retrieving data from data array list
Object columnData = dbDataArrayList.get(i).columnData;

// checking the type of data and binding to corresponding type
if (columnData instanceof Integer)
{
statement.bindLong(position, Integer.parseInt(columnData.toString()));
}
else if (columnData instanceof String )
{
statement.bindString(position, columnData.toString());
}
else if (columnData instanceof Double || columnData instanceof Float)
{
statement.bindDouble(position, Double.parseDouble(columnData.toString()));
}
}

db.getWritableDatabase().setTransactionSuccessful();
db.getWritableDatabase().endTransaction();

dbDataArrayList = new ArrayList<>();
return this;
}

//#region COMMENTS FOR insertDataWithTransaction method
/**
Expand All @@ -1044,11 +1190,13 @@ public DBHelper insertData(String tableName)
*
* @param tableName - name of the table where the data is to be inserted
*
* @param dbColumnCount - total number of columns in the table you want to insert data
*
* this method will insert data into table using database transaction
* this method is useful for inserting bulk records into table in less time
**/
//#endregion COMMENTS FOR insertDataWithTransaction method
public DBHelper insertDataWithTransaction(String tableName)
public DBHelper insertDataWithTransaction(String tableName, int dbColumnCount)
{
if (dbDataArrayList == null || dbDataArrayList.size() == 0)
{
Expand All @@ -1063,10 +1211,16 @@ public DBHelper insertDataWithTransaction(String tableName)
ArrayList<String> columnsArrayList = new ArrayList<>();

// loop for removing duplicate values from data array list
for (int i = 0; i < dbDataArrayList.size(); i++)
// for (int i = 0; i < dbDataArrayList.size(); i++)
for (int i = 0; i < dbColumnCount; i++)
{
for (DbData item : dbDataArrayList)
{
if (columnsArrayList.size() == dbColumnCount)
{
break;
}

// checking if tree set contains columns from data array list
// if not contains then adding it to columns array list
if (!treeSet.contains(item.columnName))
Expand Down
31 changes: 30 additions & 1 deletion app/src/main/java/com/amit/utilities/TextUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Created By AMIT JANGID
* 2018 April 17 - Tuesday - 12:52 PM
**/
@SuppressWarnings("unused")
@SuppressWarnings({"unused", "WeakerAccess"})
public class TextUtils
{
/**
Expand Down Expand Up @@ -80,6 +80,35 @@ else if (stringToReplace.equalsIgnoreCase(""))
return Integer.parseInt(stringToReplace);
}
}

/**
* replace null method
* this method will replace null with empty space
*
* @param string - string where you want to replace null
* @return it will return empty string
**/
public static String replaceNullWithDash(String string)
{
if (string == null)
{
return "-";
}
else if (string.equalsIgnoreCase("null"))
{
return "-";
}
else if (string.equalsIgnoreCase(" "))
{
return "-";
}
else if (string.equalsIgnoreCase(""))
{
return "-";
}

return string;
}

/**
* 2018 September 14 - Friday - 12:34 PM
Expand Down
71 changes: 63 additions & 8 deletions app/src/main/java/com/amit/views/DatePickerFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,18 @@
* this class will display a date picker dialog
* it will return selected date in the format defined
**/
@SuppressWarnings({"unused", "deprecation"})
@SuppressWarnings({"unused", "deprecation", "DeprecatedIsStillUsed"})
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
private static final String TAG = DatePickerFragment.class.getSimpleName();

private Calendar calendar;
private Calendar mCalendar;

@Deprecated
private SelectedDate mSelectedDate;

private OnDateSelectedListener mOnDateSelectedListener;

private static boolean mIsCurrentDateMin;
private static String mSelectedDateFormat;

Expand All @@ -44,6 +48,7 @@ public class DatePickerFragment extends DialogFragment implements DatePickerDial
*
* @param isCurrentDateMin - pass true to set current date as minimum date else pass false.
**/
@Deprecated
public void showDatePickerDialog(@NonNull Context context, @NonNull SelectedDate selectedDate,
@NonNull String selectedDateFormat, boolean isCurrentDateMin)
{
Expand All @@ -55,15 +60,40 @@ public void showDatePickerDialog(@NonNull Context context, @NonNull SelectedDate
datePickerFragment.show(((Activity) context).getFragmentManager(), "DatePicker");
}

/**
* 2018 October 24 - Wednesday - 03:34 PM
* show date picker dialog method
*
* this method will show the date picker dialog fragment
*
* @param context - context of the application
* @param onDateSelectedListener - interface of date picker fragment for getting the selected date value
* @param selectedDateFormat - format in which you want the date.
* Example: yyyy-MM-dd hh:mm:ss
*
* @param isCurrentDateMin - pass true to set current date as minimum date else pass false.
**/
public void showDatePickerDialog(@NonNull Context context,
@NonNull OnDateSelectedListener onDateSelectedListener,
@NonNull String selectedDateFormat, boolean isCurrentDateMin)
{
mIsCurrentDateMin = isCurrentDateMin;
mSelectedDateFormat = selectedDateFormat;

DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.initializeInterface(onDateSelectedListener);
datePickerFragment.show(((Activity) context).getFragmentManager(), "DatePicker");
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Use the current date as the default date in the picker
calendar = Calendar.getInstance();
mCalendar = Calendar.getInstance();

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int year = mCalendar.get(Calendar.YEAR);
int month = mCalendar.get(Calendar.MONTH);
int day = mCalendar.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
Expand All @@ -79,25 +109,50 @@ public Dialog onCreateDialog(Bundle savedInstanceState)
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
calendar.set(year, month, dayOfMonth);
mCalendar.set(year, month, dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat(mSelectedDateFormat, Locale.getDefault());

String selectedDate = sdf.format(calendar.getTime());
String selectedDate = sdf.format(mCalendar.getTime());
Log.e(TAG, "onDateSet: selected date is: " + selectedDate);

if (mSelectedDate != null)
{
mSelectedDate.selectedDate(selectedDate);
}
else
{
Log.e(TAG, "onDateSet: selectedDate interface is null.");
}

if (mOnDateSelectedListener != null)
{
mOnDateSelectedListener.onDateSelected(selectedDate);
}
else
{
Log.e(TAG, "onDateSet: onDateSelectedListener interface is null.");
}
}

@Deprecated
private void initializeInterface(SelectedDate selectedDate)
{
this.mSelectedDate = selectedDate;
}

private void initializeInterface(OnDateSelectedListener onDateSelectedListener)
{
this.mOnDateSelectedListener = onDateSelectedListener;
}

@Deprecated
public interface SelectedDate
{
void selectedDate(String selectedDate);
}

public interface OnDateSelectedListener
{
void onDateSelected(String selectedDate);
}
}

0 comments on commit cb46b91

Please sign in to comment.