commit 1b7507e89233fef43d29ced57f37bf24e1097586 Author: H Malik Date: Tue Jul 17 16:54:27 2018 +1000 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39fb081 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..96cc43e --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..7ac24c7 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..ba7052b --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..48b26e3 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..2944ad7 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,37 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 25 + buildToolsVersion '26.0.2' + defaultConfig { + applicationId "com.example.h_mal.shift_tracker" + minSdkVersion 21 + targetSdkVersion 25 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + vectorDrawables.useSupportLibrary = true + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation 'com.android.support:support-v4:25.4.0' + implementation 'com.android.support:support-vector-drawable:25.4.0' + compile fileTree(dir: 'libs', include: ['*.jar']) + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { + exclude group: 'com.android.support', module: 'support-annotations' + }) + compile 'com.android.support:appcompat-v7:25.4.0' + compile 'com.android.support:design:25.4.0' + compile 'com.android.support.constraint:constraint-layout:1.0.2' + compile 'com.ajts.androidmads.SQLite2Excel:library:1.0.2' + + compile 'com.google.android.gms:play-services-ads:11.8.0' + testCompile 'junit:junit:4.12' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..5543844 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,25 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:\Users\h_mal\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/com/example/h_mal/shift_tracker/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/example/h_mal/shift_tracker/ExampleInstrumentedTest.java new file mode 100644 index 0000000..7887498 --- /dev/null +++ b/app/src/androidTest/java/com/example/h_mal/shift_tracker/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.example.h_mal.shift_tracker; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumentation test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("com.example.h_mal.shift_tracker", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..72e509d --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftProvider.java b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftProvider.java new file mode 100644 index 0000000..200a6cf --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftProvider.java @@ -0,0 +1,262 @@ +package com.example.h_mal.shift_tracker.Data; + +import android.content.ContentProvider; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.util.Log; + +import com.example.h_mal.shift_tracker.Data.ShiftsContract.ShiftsEntry; + +/** + * Created by h_mal on 26/12/2017. + */ + +public class ShiftProvider extends ContentProvider { + + + public static final String LOG_TAG = ShiftProvider.class.getSimpleName(); + + private static final int SHIFTS = 100; + private static final int SHIFT_ID = 101; + + private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + + + static { + + sUriMatcher.addURI(ShiftsContract.CONTENT_AUTHORITY, ShiftsContract.PATH_SHIFTS, SHIFTS); + + sUriMatcher.addURI(ShiftsContract.CONTENT_AUTHORITY, ShiftsContract.PATH_SHIFTS + "/#", SHIFT_ID); + } + + ShiftsDbHelper mDbHelper; + + public ShiftProvider() { + } + + @Override + public boolean onCreate() { + mDbHelper = new ShiftsDbHelper(getContext()); + return true; + } + + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, + String sortOrder) { + + SQLiteDatabase database = mDbHelper.getReadableDatabase(); + + Cursor cursor; + + int match = sUriMatcher.match(uri); + switch (match) { + case SHIFTS: + + cursor = database.query(ShiftsEntry.TABLE_NAME, projection, selection, selectionArgs, + null, null, sortOrder); + break; + case SHIFT_ID: + + selection = ShiftsEntry._ID + "=?"; + selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; + cursor = database.query(ShiftsEntry.TABLE_NAME, projection, selection, selectionArgs, + null, null, sortOrder); + break; + default: + throw new IllegalArgumentException("Cannot query " + uri); + } + + cursor.setNotificationUri(getContext().getContentResolver(), uri); + + return cursor; + } + + @Override + public Uri insert(Uri uri, ContentValues contentValues) { + final int match = sUriMatcher.match(uri); + switch (match) { + case SHIFTS: + return insertShift(uri, contentValues); + default: + throw new IllegalArgumentException("Insertion is not supported for " + uri); + } + } + + private Uri insertShift(Uri uri, ContentValues values) { + + String description = values.getAsString(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION); + if (description == null) { + throw new IllegalArgumentException("Description required"); + } + + String date = values.getAsString(ShiftsEntry.COLUMN_SHIFT_DATE); + if (date == null) { + throw new IllegalArgumentException("Date required"); + } + + String timeIn = values.getAsString(ShiftsEntry.COLUMN_SHIFT_TIME_IN); + if (timeIn == null) { + throw new IllegalArgumentException("Time In required"); + } + + String timeOut = values.getAsString(ShiftsEntry.COLUMN_SHIFT_TIME_OUT); + if (timeOut == null) { + throw new IllegalArgumentException("Time Out required"); + } + + Float duration = values.getAsFloat(ShiftsEntry.COLUMN_SHIFT_DURATION); + if (duration < 0) { + throw new IllegalArgumentException("Duration cannot be negative"); + } + + String shiftType = values.getAsString(ShiftsEntry.COLUMN_SHIFT_TYPE); + if (shiftType == null) { + throw new IllegalArgumentException("Shift type required"); + } + + Float shiftUnits = values.getAsFloat(ShiftsEntry.COLUMN_SHIFT_UNIT); + if (shiftUnits < 0) { + throw new IllegalArgumentException("Units cannot be negative"); + } + + Float payRate = values.getAsFloat(ShiftsEntry.COLUMN_SHIFT_PAYRATE); + if (payRate < 0) { + throw new IllegalArgumentException("Pay rate cannot be negative"); + } + + Float totalPay = values.getAsFloat(ShiftsEntry.COLUMN_SHIFT_TOTALPAY); + if (totalPay < 0) { + throw new IllegalArgumentException("Total Pay cannot be negative"); + } + + Integer breakMins = values.getAsInteger(ShiftsEntry.COLUMN_SHIFT_BREAK); + if (breakMins < 0) { + throw new IllegalArgumentException("Break cannot be negative"); + } + + SQLiteDatabase database = mDbHelper.getWritableDatabase(); + + long id = database.insert(ShiftsEntry.TABLE_NAME, null, values); + + if (id == -1) { + Log.e(LOG_TAG, "row failed " + uri); + return null; + } + + getContext().getContentResolver().notifyChange(uri, null); + + return ContentUris.withAppendedId(uri, id); + } + + @Override + public int update(Uri uri, ContentValues contentValues, String selection, + String[] selectionArgs) { + final int match = sUriMatcher.match(uri); + switch (match) { + case SHIFTS: + return updateShift(uri, contentValues, selection, selectionArgs); + case SHIFT_ID: + + selection = ShiftsEntry._ID + "=?"; + selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; + return updateShift(uri, contentValues, selection, selectionArgs); + default: + throw new IllegalArgumentException("Update is not supported for " + uri); + } + } + + + private int updateShift(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + + if (values.containsKey(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION)) { + String description = values.getAsString(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION); + if (description == null) { + throw new IllegalArgumentException("description required"); + } + } + + if (values.containsKey(ShiftsEntry.COLUMN_SHIFT_DATE)) { + String date = values.getAsString(ShiftsEntry.COLUMN_SHIFT_DATE); + if (date == null) { + throw new IllegalArgumentException("date required"); + } + } + + if (values.containsKey(ShiftsEntry.COLUMN_SHIFT_TIME_IN)) { + String timeIn = values.getAsString(ShiftsEntry.COLUMN_SHIFT_TIME_IN); + if (timeIn == null) { + throw new IllegalArgumentException("time in required"); + } + } + + if (values.containsKey(ShiftsEntry.COLUMN_SHIFT_TIME_OUT)) { + String timeOut = values.getAsString(ShiftsEntry.COLUMN_SHIFT_TIME_OUT); + if (timeOut == null) { + throw new IllegalArgumentException("time out required"); + } + } + + if (values.containsKey(ShiftsEntry.COLUMN_SHIFT_BREAK)) { + String breaks = values.getAsString(ShiftsEntry.COLUMN_SHIFT_BREAK); + if (breaks == null) { + throw new IllegalArgumentException("break required"); + } + } + + if (values.size() == 0) { + return 0; + } + + SQLiteDatabase database = mDbHelper.getWritableDatabase(); + int rowsUpdated = database.update(ShiftsEntry.TABLE_NAME, values, selection, selectionArgs); + if (rowsUpdated != 0) { + getContext().getContentResolver().notifyChange(uri, null); + } + + return rowsUpdated; + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + SQLiteDatabase database = mDbHelper.getWritableDatabase(); + + int rowsDeleted; + + final int match = sUriMatcher.match(uri); + switch (match) { + case SHIFTS: + rowsDeleted = database.delete(ShiftsEntry.TABLE_NAME, selection, selectionArgs); + break; + case SHIFT_ID: + selection = ShiftsEntry._ID + "=?"; + selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) }; + rowsDeleted = database.delete(ShiftsEntry.TABLE_NAME, selection, selectionArgs); + break; + default: + throw new IllegalArgumentException("Deletion is not supported for " + uri); + } + + if (rowsDeleted != 0) { + getContext().getContentResolver().notifyChange(uri, null); + } + + return rowsDeleted; + } + + @Override + public String getType(Uri uri) { + final int match = sUriMatcher.match(uri); + switch (match) { + case SHIFTS: + return ShiftsEntry.CONTENT_LIST_TYPE; + case SHIFT_ID: + return ShiftsEntry.CONTENT_ITEM_TYPE; + default: + throw new IllegalStateException("Unknown URI " + uri + " with match " + match); + } + } +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsContract.java b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsContract.java new file mode 100644 index 0000000..5cf3734 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsContract.java @@ -0,0 +1,60 @@ +package com.example.h_mal.shift_tracker.Data; + +import android.content.ContentResolver; +import android.net.Uri; +import android.provider.BaseColumns; + +/** + * Created by h_mal on 26/12/2017. + */ + +public class ShiftsContract { + + private ShiftsContract() {} + + public static final String CONTENT_AUTHORITY = "com.example.h_mal.shift_tracker"; + + public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); + + public static final String PATH_SHIFTS = "shifts"; + + public static final class ShiftsEntry implements BaseColumns { + + public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_SHIFTS); + + public static final String CONTENT_LIST_TYPE = + ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_SHIFTS; + + + public static final String CONTENT_ITEM_TYPE = + ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_SHIFTS; + + + public final static String TABLE_NAME = "shifts"; + + public final static String TABLE_NAME_EXPORT = "shiftsexport"; + + public final static String _ID = BaseColumns._ID; + + public final static String COLUMN_SHIFT_TYPE = "shifttype"; + + public final static String COLUMN_SHIFT_DESCRIPTION = "description"; + + public final static String COLUMN_SHIFT_DATE = "date"; + + public final static String COLUMN_SHIFT_TIME_IN = "timein"; + + public final static String COLUMN_SHIFT_TIME_OUT = "timeout"; + + public final static String COLUMN_SHIFT_BREAK = "break"; + + public final static String COLUMN_SHIFT_DURATION = "duration"; + + public final static String COLUMN_SHIFT_UNIT = "unit"; + + public final static String COLUMN_SHIFT_PAYRATE = "payrate"; + + public final static String COLUMN_SHIFT_TOTALPAY = "totalpay"; + + } +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsDbHelper.java b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsDbHelper.java new file mode 100644 index 0000000..a22b0a5 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/Data/ShiftsDbHelper.java @@ -0,0 +1,88 @@ +package com.example.h_mal.shift_tracker.Data; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import com.example.h_mal.shift_tracker.Data.ShiftsContract.ShiftsEntry; + +/** + * Created by h_mal on 26/12/2017. + */ + +public class ShiftsDbHelper extends SQLiteOpenHelper { + + public static final String LOG_TAG = ShiftsDbHelper.class.getSimpleName(); + + private static final String DATABASE_NAME = "shifts.db"; + + private static final int DATABASE_VERSION = 4; + + private static String DEFAULT_TEXT = "Hourly"; + + + public ShiftsDbHelper(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + + String SQL_CREATE_PRODUCTS_TABLE = "CREATE TABLE " + ShiftsEntry.TABLE_NAME + " (" + + ShiftsEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ShiftsEntry.COLUMN_SHIFT_DESCRIPTION + " TEXT NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_DATE + " DATE NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_TIME_IN + " TIME NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_TIME_OUT + " TIME NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_BREAK + " INTEGER NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_DURATION + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_TYPE + " TEXT NOT NULL DEFAULT " + DEFAULT_TEXT + ", " + + ShiftsEntry.COLUMN_SHIFT_UNIT + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_PAYRATE + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_TOTALPAY + " FLOAT NOT NULL DEFAULT 0)"; + + + db.execSQL(SQL_CREATE_PRODUCTS_TABLE); + db.execSQL(SQL_CREATE_PRODUCTS_TABLE_2); + } + + private static final String SQL_CREATE_PRODUCTS_TABLE_2 = "CREATE TABLE " + ShiftsEntry.TABLE_NAME_EXPORT + " (" + + ShiftsEntry.COLUMN_SHIFT_DESCRIPTION + " TEXT NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_DATE + " DATE NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_TIME_IN + " TIME NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_TIME_OUT + " TIME NOT NULL, " + + ShiftsEntry.COLUMN_SHIFT_BREAK + " INTEGER NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_DURATION + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_TYPE + " TEXT NOT NULL DEFAULT " + DEFAULT_TEXT + ", " + + ShiftsEntry.COLUMN_SHIFT_UNIT + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_PAYRATE + " FLOAT NOT NULL DEFAULT 0, " + + ShiftsEntry.COLUMN_SHIFT_TOTALPAY + " FLOAT NOT NULL DEFAULT 0)"; + + private static final String DATABASE_ALTER_1 = + "ALTER TABLE " + ShiftsEntry.TABLE_NAME + " ADD COLUMN " + + ShiftsEntry.COLUMN_SHIFT_TYPE + " TEXT NOT NULL DEFAULT " + DEFAULT_TEXT + ";"; + + private static final String DATABASE_ALTER_2 = + "ALTER TABLE " + ShiftsEntry.TABLE_NAME + " ADD COLUMN " + + ShiftsEntry.COLUMN_SHIFT_UNIT + " FLOAT NOT NULL DEFAULT 0;"; + + private static final String DATABASE_ALTER_3 = + "ALTER TABLE " + ShiftsEntry.TABLE_NAME + " ADD COLUMN " + + ShiftsEntry.COLUMN_SHIFT_PAYRATE + " FLOAT NOT NULL DEFAULT 0;"; + + private static final String DATABASE_ALTER_4 = + "ALTER TABLE " + ShiftsEntry.TABLE_NAME + " ADD COLUMN " + + ShiftsEntry.COLUMN_SHIFT_TOTALPAY + " FLOAT NOT NULL DEFAULT 0;"; + + private static final String DATABASE_UPDATE_1 = + "UPDATE " + ShiftsEntry.TABLE_NAME + " SET " + + ShiftsEntry.COLUMN_SHIFT_TYPE + " = replace( " + ShiftsEntry.COLUMN_SHIFT_TYPE + ", 'hourly', 'Hourly' )" + + " WHERE " + ShiftsEntry.COLUMN_SHIFT_TYPE + " LIKE 'hourly%'"; + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + if (oldVersion < newVersion) { + db.execSQL(SQL_CREATE_PRODUCTS_TABLE_2); + } + } +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/FilterDataFragment.java b/app/src/main/java/com/example/h_mal/shift_tracker/FilterDataFragment.java new file mode 100644 index 0000000..5c91523 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/FilterDataFragment.java @@ -0,0 +1,198 @@ +package com.example.h_mal.shift_tracker; + +import android.app.DatePickerDialog; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.Spinner; + +import com.example.h_mal.shift_tracker.Data.ShiftsContract; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static com.example.h_mal.shift_tracker.MainActivity.args; +import static com.example.h_mal.shift_tracker.MainActivity.selection; + + +public class FilterDataFragment extends Fragment { + + private String[] spinnerList = new String[]{"","Hourly","Piece Rate"}; + private List listArgs = new ArrayList(); + private EditText LocationET; + private EditText dateFromET; + private EditText dateToET; + private Spinner typeSpinner; + Calendar mcurrentDate; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View rootView = inflater.inflate(R.layout.fragment_filter_data, container, false); + MainActivity.setActionBarTitle(getString(R.string.title_activity_filter_data)); + + mcurrentDate = Calendar.getInstance(); + + LocationET = (EditText) rootView.findViewById(R.id.filterLocationEditText); + dateFromET = (EditText) rootView.findViewById(R.id.fromdateInEditText); + dateToET = (EditText) rootView.findViewById(R.id.filterDateOutEditText); + typeSpinner = (Spinner) rootView.findViewById(R.id.TypeFilterEditText); + + if(selection != null && selection.contains(" AND " + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION + " LIKE ?")){ + String str = args[2]; + str = str.replace("%", ""); + LocationET.setText(str); + } + if(selection != null && !args[0].equals("2000-01-01")){ + dateFromET.setText(args[0]); + } + + if(selection != null && args != null && !args[1].equals(String.valueOf(mcurrentDate.get(Calendar.YEAR) + "-" + + String.format("%02d", (mcurrentDate.get(Calendar.MONTH) + 1)) + "-" + + String.format("%02d", mcurrentDate.get(Calendar.DAY_OF_MONTH))))){ + dateToET.setText(args[1]); + } + + dateFromET.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //To show current date in the datepicker + + int mYear = mcurrentDate.get(Calendar.YEAR); + int mMonth = mcurrentDate.get(Calendar.MONTH); + int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); + + if(!dateFromET.getText().toString().equals("")) { + String dateString = dateFromET.getText().toString().trim(); + + mYear = Integer.parseInt(dateString.substring(0, 4)); + mMonth = Integer.parseInt(dateString.substring(5, 7)); + if (mMonth == 1){ + mMonth = 0; + }else{ + mMonth = mMonth -1; + } + + mDay = Integer.parseInt(dateString.substring(8)); + } + DatePickerDialog mDatePicker=new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { + public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) { + dateFromET.setText( + selectedyear + "-" + + String.format("%02d", (selectedmonth + 1)) + "-" + + String.format("%02d", selectedday) + ); + } + },mYear, mMonth, mDay); + mDatePicker.setTitle("Select date"); + mDatePicker.show(); } + }); + + dateToET.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //To show current date in the datepicker + Calendar mcurrentDate = Calendar.getInstance(); + int mYear = mcurrentDate.get(Calendar.YEAR); + int mMonth = mcurrentDate.get(Calendar.MONTH); + int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); + + if(!dateToET.getText().toString().equals("")) { + String dateString = dateToET.getText().toString().trim(); + + mYear = Integer.parseInt(dateString.substring(0, 4)); + mMonth = Integer.parseInt(dateString.substring(5, 7)); + if (mMonth == 1){ + mMonth = 0; + }else{ + mMonth = mMonth -1; + } + + mDay = Integer.parseInt(dateString.substring(8)); + } + + DatePickerDialog mDatePicker=new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { + public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) { + dateToET.setText( + selectedyear + "-" + + String.format("%02d", (selectedmonth + 1)) + "-" + + String.format("%02d", selectedday) + ); + } + },mYear, mMonth, mDay); + mDatePicker.setTitle("Select date"); + mDatePicker.show(); } + }); + + ArrayAdapter adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, spinnerList); + typeSpinner.setAdapter(adapter); + if(selection != null && selection.contains(" AND " + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE + " IS ?")) { + int spinnerPosition = adapter.getPosition(args[args.length-1]); + typeSpinner.setSelection(spinnerPosition); + } + + Button submit = (Button) rootView.findViewById(R.id.submitFiltered); + + submit.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + + BuildQuery(); + args = listArgs.toArray(new String[0]); + FragmentMain.NEW_LOADER = 1; + MainActivity.fragmentManager.popBackStack(); + + } + }); + + return rootView; + } + + private void BuildQuery() { + + String dateQuery = ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE + " BETWEEN ? AND ?"; + String descQuery = " AND " + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION + " LIKE ?"; + String typeQuery = " AND " + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE + " IS ?"; + + String dateFrom = "2000-01-01"; + + Date c = Calendar.getInstance().getTime(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + String dateTo = df.format(c); + + if(!TextUtils.isEmpty(dateFromET.getText().toString().trim())){ + dateFrom = dateFromET.getText().toString().trim(); + } + + if(!TextUtils.isEmpty(dateToET.getText().toString().trim())){ + dateTo = dateToET.getText().toString().trim(); + } + + selection = dateQuery; + listArgs.add(dateFrom); + listArgs.add(dateTo); + + if (!TextUtils.isEmpty(LocationET.getText().toString().trim())){ + selection = selection + descQuery; + listArgs.add("%" + LocationET.getText().toString().trim() + "%"); + } + + if (!typeSpinner.getSelectedItem().toString().equals("")){ + selection = selection + typeQuery; + listArgs.add(typeSpinner.getSelectedItem().toString()); + } + + } + +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/FragmentAddItem.java b/app/src/main/java/com/example/h_mal/shift_tracker/FragmentAddItem.java new file mode 100644 index 0000000..2b498c0 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/FragmentAddItem.java @@ -0,0 +1,622 @@ +package com.example.h_mal.shift_tracker; + +import android.app.DatePickerDialog; +import android.app.TimePickerDialog; +import android.content.ContentValues; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.Loader; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.TimePicker; +import android.widget.Toast; + +import com.example.h_mal.shift_tracker.Data.ShiftsContract; + +import java.util.Calendar; + +public class FragmentAddItem extends Fragment implements + LoaderManager.LoaderCallbacks { + + private static final int EXISTING_PRODUCT_LOADER = 0; + + private Uri mCurrentProductUri; + + public static RadioGroup mRadioGroup; + private RadioButton mRadioButtonOne; + private RadioButton mRadioButtonTwo; + private EditText mLocationEditText; + private EditText mDateEditText; + private TextView mDurationTextView; + private EditText mTimeInEditText; + private EditText mTimeOutEditText; + private EditText mBreakEditText; + private EditText mUnitEditText; + private EditText mPayRateEditText; + private TextView mTotalPayTextView; + private LinearLayout hourlyDataView; + private LinearLayout unitsHolder; + private LinearLayout durationHolder; + private LinearLayout wholeView; + private ScrollView scrollView; + private ProgressBar progressBarAI; + private int mBreaks; + + private int mDay; + private int mMonth; + private int mYear; + private int mHoursIn; + private int mMinutesIn; + private int mHoursOut; + private int mMinutesOut; + private float mUnits; + private float mPayRate; + private String mType; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View rootView = inflater.inflate(R.layout.fragment_add_item, container, false); + setHasOptionsMenu(true); + + progressBarAI = (ProgressBar) rootView.findViewById(R.id.pd_ai); + scrollView = (ScrollView) rootView.findViewById(R.id.total_view); + mRadioGroup = (RadioGroup) rootView.findViewById(R.id.rg); + mRadioButtonOne = (RadioButton) rootView.findViewById(R.id.hourly); + mRadioButtonTwo = (RadioButton) rootView.findViewById(R.id.piecerate); + mLocationEditText = (EditText) rootView.findViewById(R.id.locationEditText); + mDateEditText = (EditText) rootView.findViewById(R.id.dateEditText); + mTimeInEditText = (EditText) rootView.findViewById(R.id.timeInEditText); + mBreakEditText = (EditText) rootView.findViewById(R.id.breakEditText); + mTimeOutEditText = (EditText) rootView.findViewById(R.id.timeOutEditText); + mDurationTextView = (TextView) rootView.findViewById(R.id.ShiftDuration); + mUnitEditText = (EditText) rootView.findViewById(R.id.unitET); + mPayRateEditText = (EditText) rootView.findViewById(R.id.payrateET); + mTotalPayTextView = (TextView) rootView.findViewById(R.id.totalpayval); + + hourlyDataView = (LinearLayout) rootView.findViewById(R.id.hourly_data_holder); + unitsHolder = (LinearLayout) rootView.findViewById(R.id.units_holder); + durationHolder = (LinearLayout) rootView.findViewById(R.id.duration_holder); + wholeView = (LinearLayout) rootView.findViewById(R.id.whole_view); + + mPayRate = 0.0f; + mUnits = 0.0f; + + final Bundle b = getArguments(); + if(b != null) { + mCurrentProductUri = Uri.parse(b.getString("uri")); + } + + if (mCurrentProductUri == null) { + MainActivity.setActionBarTitle(getString(R.string.add_item_title)); + wholeView.setVisibility(View.GONE); + } else { + MainActivity.setActionBarTitle(getString(R.string.edit_item_title)); + getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this); + } + + mBreakEditText.setHint("insert break in minutes"); + + mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(RadioGroup radioGroup, int i) { + if (mRadioButtonOne.isChecked()){ + mType = mRadioButtonOne.getText().toString(); + wholeView.setVisibility(View.VISIBLE); + unitsHolder.setVisibility(View.GONE); + hourlyDataView.setVisibility(View.VISIBLE); + durationHolder.setVisibility(View.VISIBLE); + }else if(mRadioButtonTwo.isChecked()){ + mType = mRadioButtonTwo.getText().toString(); + wholeView.setVisibility(View.VISIBLE); + unitsHolder.setVisibility(View.VISIBLE); + hourlyDataView.setVisibility(View.GONE); + durationHolder.setVisibility(View.GONE); + } + } + }); + + mDateEditText.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + //To show current date in the datepicker + if(TextUtils.isEmpty(mDateEditText.getText().toString().trim())) { + Calendar mcurrentDate = Calendar.getInstance(); + mYear = mcurrentDate.get(Calendar.YEAR); + mMonth = mcurrentDate.get(Calendar.MONTH); + mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); + }else{ + String dateString = mDateEditText.getText().toString().trim(); + + mYear = Integer.parseInt(dateString.substring(0, 4)); + mMonth = Integer.parseInt(dateString.substring(5, 7)); + if (mMonth == 1){ + mMonth = 0; + }else{ + mMonth = mMonth -1; + } + + mDay = Integer.parseInt(dateString.substring(8)); + } + DatePickerDialog mDatePicker=new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { + public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) { + mDateEditText.setText( + selectedyear + "-" + + String.format("%02d", (selectedmonth = selectedmonth + 1)) +"-" + + String.format("%02d", selectedday) + ); + setDate(selectedyear, selectedmonth, selectedday); + } + },mYear, mMonth, mDay); + mDatePicker.setTitle("Select date"); + mDatePicker.show(); } + }); + + mTimeInEditText.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (mTimeInEditText.getText().toString().equals("")) { + Calendar mcurrentTime = Calendar.getInstance(); + mHoursIn = mcurrentTime.get(Calendar.HOUR_OF_DAY); + mMinutesIn = mcurrentTime.get(Calendar.MINUTE); + } else { + mHoursIn = Integer.parseInt((mTimeInEditText.getText().toString().subSequence(0,2)).toString()); + mMinutesIn = Integer.parseInt((mTimeInEditText.getText().toString().subSequence(3,5)).toString()); + } + TimePickerDialog mTimePicker; + mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() { + @Override + public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { + String ddTime = String.format("%02d", selectedHour) + ":" + String.format("%02d", selectedMinute); + setTime(selectedMinute, selectedHour); + mTimeInEditText.setText(ddTime); + } + }, mHoursIn, mMinutesIn, true);//Yes 24 hour time + mTimePicker.setTitle("Select Time"); + mTimePicker.show(); + + } + }); + + mTimeOutEditText.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (mTimeOutEditText.getText().toString().equals("")) { + Calendar mcurrentTime = Calendar.getInstance(); + mHoursOut = mcurrentTime.get(Calendar.HOUR_OF_DAY); + mMinutesOut = mcurrentTime.get(Calendar.MINUTE); + }else { + mHoursOut = Integer.parseInt((mTimeOutEditText.getText().toString().subSequence(0,2)).toString()); + mMinutesOut = Integer.parseInt((mTimeOutEditText.getText().toString().subSequence(3,5)).toString()); + } + TimePickerDialog mTimePicker; + mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() { + @Override + public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { + String ddTime = String.format("%02d", selectedHour) + ":" + String.format("%02d", selectedMinute); + setTime2(selectedMinute,selectedHour); + mTimeOutEditText.setText(ddTime); + } + }, mHoursOut, mMinutesOut, true);//Yes 24 hour time + mTimePicker.setTitle("Select Time"); + mTimePicker.show(); + } + }); + + mTimeInEditText.addTextChangedListener(new TextWatcher() + { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) + { + + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int aft ) + { + + } + + @Override + public void afterTextChanged(Editable s) + { + setDuration(); + calculateTotalPay(); + } + }); + + mTimeOutEditText.addTextChangedListener(new TextWatcher() + { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) + { + + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int aft ) + { + + } + + @Override + public void afterTextChanged(Editable s) + { + setDuration(); + calculateTotalPay(); + } + }); + + mBreakEditText.addTextChangedListener(new TextWatcher() + { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) + { + + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int aft ) + { + + } + + @Override + public void afterTextChanged(Editable s) + { + setDuration(); + calculateTotalPay(); + } + }); + + mUnitEditText.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void afterTextChanged(Editable editable) { +// if(mRadioButtonTwo.isChecked()) { +// mUnits = 0.0f; +// if (!mUnitEditText.getText().toString().equals("")){ +// mUnits = Float.parseFloat(mUnitEditText.getText().toString()); +// } +// mPayRate = 0.0f; +// if (!mPayRateEditText.getText().toString().equals("")){ +// mPayRate = Float.parseFloat(mPayRateEditText.getText().toString()); +// } +// Float total = mPayRate * mUnits; +// mTotalPayTextView.setText(String.valueOf(total)); +// } + calculateTotalPay(); + + } + }); + + mPayRateEditText.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + + } + + @Override + public void afterTextChanged(Editable editable) { + calculateTotalPay(); + } + + }); + + Button SubmitProduct = (Button) rootView.findViewById(R.id.submit); + + SubmitProduct.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + saveProduct(); + + } + }); + + return rootView; + } + + private void calculateTotalPay(){ + Float total = 0.0f; + mPayRate = 0.0f; + if(mRadioButtonTwo.isChecked()) { + mUnits = 0.0f; + if (!mUnitEditText.getText().toString().equals("")) { + mUnits = Float.parseFloat(mUnitEditText.getText().toString()); + } + if (!mPayRateEditText.getText().toString().equals("")) { + mPayRate = Float.parseFloat(mPayRateEditText.getText().toString()); + } + total = mPayRate * mUnits; + mTotalPayTextView.setText(String.valueOf(total)); + } else if(mRadioButtonOne.isChecked()){ + if (!mPayRateEditText.getText().toString().equals("")){ + mPayRate = Float.parseFloat(mPayRateEditText.getText().toString()); + total = mPayRate * calculateDuration(mHoursIn,mMinutesIn,mHoursOut,mMinutesOut,mBreaks); + } + } + mTotalPayTextView.setText(String.format("%.2f",total)); + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + super.onCreateOptionsMenu(menu, inflater); + menu.clear(); + } + + private void saveProduct() { + + String typeString = mType; + String descriptionString = mLocationEditText.getText().toString().trim(); + if (TextUtils.isEmpty(descriptionString)) { + Toast.makeText(getContext(), "please insert Location", Toast.LENGTH_SHORT).show(); + return; + } + String dateString = mDateEditText.getText().toString().trim(); + if (TextUtils.isEmpty(dateString)) { + Toast.makeText(getContext(), "please insert Date", Toast.LENGTH_SHORT).show(); + return; + } + String timeInString = ""; + String timeOutString = ""; + int breaks = 0; + float units = 0; + float duration = 0; + float payRate = 0; + String payRateString = mPayRateEditText.getText().toString().trim(); + if (!TextUtils.isEmpty(payRateString)) { + payRate = Float.parseFloat(payRateString); + } + float totalPay = 0; + if (typeString.equals("Hourly")) { + timeInString = mTimeInEditText.getText().toString().trim(); + if (TextUtils.isEmpty(timeInString)) { + Toast.makeText(getContext(), "please insert Time in", Toast.LENGTH_SHORT).show(); + return; + } + timeOutString = mTimeOutEditText.getText().toString().trim(); + if (TextUtils.isEmpty(timeOutString)) { + Toast.makeText(getContext(), "please insert Time out", Toast.LENGTH_SHORT).show(); + return; + } + String breakMins = mBreakEditText.getText().toString().trim(); + if (!TextUtils.isEmpty(breakMins)) { + breaks = Integer.parseInt(breakMins); + if(((float)breaks / 60) > calculateDurationWithoutBreak(mHoursIn, mMinutesIn, mHoursOut, mMinutesOut)){ + Toast.makeText(getContext(), "Break larger than duration", Toast.LENGTH_SHORT).show(); + return; + } + } + duration = calculateDuration(mHoursIn, mMinutesIn, mHoursOut, mMinutesOut, breaks); + totalPay = duration * payRate; + }else if(typeString.equals("Piece Rate")){ + String unitsString = mUnitEditText.getText().toString().trim(); + if (TextUtils.isEmpty(unitsString) || Float.parseFloat(unitsString) <= 0) { + Toast.makeText(getContext(), "Insert Units", Toast.LENGTH_SHORT).show(); + return; + }else{ + units = Float.parseFloat(unitsString); + } + duration = 0; + totalPay = units * payRate; + } + + ContentValues values = new ContentValues(); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE, typeString); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, descriptionString); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE, dateString); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_IN, timeInString); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_OUT, timeOutString); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DURATION, duration); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_BREAK, breaks); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_UNIT, units); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_PAYRATE, payRate); + values.put(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TOTALPAY, totalPay); + + if (mCurrentProductUri == null) { + + Uri newUri = getActivity().getContentResolver().insert(ShiftsContract.ShiftsEntry.CONTENT_URI, values); + + if (newUri == null) { + Toast.makeText(getContext(), getString(R.string.insert_item_failed), + Toast.LENGTH_SHORT).show(); + + } else { + + Toast.makeText(getContext(), getString(R.string.insert_item_successful), + Toast.LENGTH_SHORT).show(); + } + } else { + int rowsAffected = getActivity().getContentResolver().update(mCurrentProductUri, values, null, null); + + if (rowsAffected == 0) { + Toast.makeText(getContext(), getString(R.string.update_item_failed), + Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(getContext(), getString(R.string.update_item_successful), + Toast.LENGTH_SHORT).show(); + } + } + + (MainActivity.fragmentManager).popBackStack("main",0); + } + + private void setDuration (){ + Calendar mcurrentTime = Calendar.getInstance(); + mBreaks = 0; + if (!mBreakEditText.getText().toString().equals("")){ + mBreaks = Integer.parseInt(mBreakEditText.getText().toString()); + } + if (mTimeOutEditText.getText().toString().equals("")) { + mHoursOut = mcurrentTime.get(Calendar.HOUR_OF_DAY); + mMinutesOut = mcurrentTime.get(Calendar.MINUTE); + }else { + mHoursOut = Integer.parseInt((mTimeOutEditText.getText().toString().subSequence(0,2)).toString()); + mMinutesOut = Integer.parseInt((mTimeOutEditText.getText().toString().subSequence(3,5)).toString()); + } + if (mTimeInEditText.getText().toString().equals("")) { + mHoursIn = mcurrentTime.get(Calendar.HOUR_OF_DAY); + mMinutesIn = mcurrentTime.get(Calendar.MINUTE); + } else { + mHoursIn = Integer.parseInt((mTimeInEditText.getText().toString().subSequence(0,2)).toString()); + mMinutesIn = Integer.parseInt((mTimeInEditText.getText().toString().subSequence(3,5)).toString()); + } + mDurationTextView.setText(calculateDuration(mHoursIn,mMinutesIn,mHoursOut,mMinutesOut,mBreaks) + " hours"); + } + + private void setDate (int year, int month, int day){ + mYear = year; + mMonth = month; + mDay = day; + } + + + private void setTime (int minutes, int hours){ + mMinutesIn = minutes; + mHoursIn = hours; + + } + + private void setTime2 (int minutes, int hours){ + mMinutesOut = minutes; + mHoursOut = hours; + + } + + private float calculateDuration (int hoursIn, int minutesIn, int hoursOut, int minutesOut, int breaks){ + float duration; + if (hoursOut > hoursIn){ + duration = (((float)hoursOut + ((float)minutesOut/60)) - ((float) hoursIn + ((float)minutesIn/60))) - ((float)breaks / 60); + }else{ + duration = ((((float)hoursOut + ((float)minutesOut/60)) - ((float)hoursIn + ((float)minutesIn/60))) - ((float)breaks / 60) + 24); + } + + String s = String.format("%.2f",duration); + return Float.parseFloat(s); + } + + private float calculateDurationWithoutBreak (int hoursIn, int minutesIn, int hoursOut, int minutesOut){ + float duration; + if (hoursOut > hoursIn){ + duration = (((float)hoursOut + ((float)minutesOut/60)) - ((float) hoursIn + ((float)minutesIn/60))); + }else{ + duration = ((((float)hoursOut + ((float)minutesOut/60)) - ((float)hoursIn + ((float)minutesIn/60))) + 24); + } + + String s = String.format("%.2f",duration); + return Float.parseFloat(s); + } + + + @Override + public Loader onCreateLoader(int id, Bundle args) { + progressBarAI.setVisibility(View.VISIBLE); + scrollView.setVisibility(View.GONE); + String[] projection = { + ShiftsContract.ShiftsEntry._ID, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_IN, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_OUT, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_BREAK, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DURATION, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_PAYRATE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_UNIT, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TOTALPAY,}; + + return new android.support.v4.content.CursorLoader(getContext(),mCurrentProductUri, + projection,null,null,null); + } + + @Override + public void onLoadFinished(Loader loader, Cursor cursor) { + progressBarAI.setVisibility(View.GONE); + scrollView.setVisibility(View.VISIBLE); + if (cursor == null || cursor.getCount() < 1) { + return; + } + + if (cursor.moveToFirst()) { + int descriptionColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION); + int dateColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE); + int timeInColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_IN); + int timeOutColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_OUT); + int breakColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_BREAK); + int durationColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DURATION); + int typeColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE); + int unitColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_UNIT); + int payrateColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_PAYRATE); + int totalPayColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TOTALPAY); + + String type = cursor.getString(typeColumnIndex); + String description = cursor.getString(descriptionColumnIndex); + String date = cursor.getString(dateColumnIndex); + String timeIn = cursor.getString(timeInColumnIndex); + String timeOut = cursor.getString(timeOutColumnIndex); + int breaks = cursor.getInt(breakColumnIndex); + float duration = cursor.getFloat(durationColumnIndex); + float unit = cursor.getFloat(unitColumnIndex); + float payrate = cursor.getFloat(payrateColumnIndex); + float totalPay = cursor.getFloat(totalPayColumnIndex); + + mLocationEditText.setText(description); + mDateEditText.setText(date); + if (type.equals("Hourly") || type.equals("hourly")) { + mRadioButtonOne.setChecked(true); + mRadioButtonTwo.setChecked(false); + mTimeInEditText.setText(timeIn); + mTimeOutEditText.setText(timeOut); + mBreakEditText.setText(Integer.toString(breaks)); + mDurationTextView.setText(String.format("%.2f", duration) + " Hours"); + } else if (type.equals("Piece Rate")) { + mRadioButtonOne.setChecked(false); + mRadioButtonTwo.setChecked(true); + mUnitEditText.setText(Float.toString(unit)); + } + mPayRateEditText.setText(String.format("%.2f", payrate)); + mTotalPayTextView.setText(String.format("%.2f", totalPay)); + + } + } + + @Override + public void onLoaderReset(Loader loader) { + + } + + +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/FragmentMain.java b/app/src/main/java/com/example/h_mal/shift_tracker/FragmentMain.java new file mode 100644 index 0000000..67995bd --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/FragmentMain.java @@ -0,0 +1,529 @@ +package com.example.h_mal.shift_tracker; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ContentValues; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.os.Bundle; +import android.os.Environment; +import android.os.StrictMode; +import android.support.design.widget.FloatingActionButton; +import android.support.v4.app.ActivityCompat; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.Loader; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ListView; +import android.widget.Toast; + +import com.ajts.androidmads.library.SQLiteToExcel; +import com.example.h_mal.shift_tracker.Data.ShiftsContract.ShiftsEntry; +import com.example.h_mal.shift_tracker.Data.ShiftsDbHelper; + +import java.io.File; + +import static com.example.h_mal.shift_tracker.MainActivity.args; +import static com.example.h_mal.shift_tracker.MainActivity.filter; +import static com.example.h_mal.shift_tracker.MainActivity.selection; +import static com.example.h_mal.shift_tracker.MainActivity.sortOrder; + + +public class FragmentMain extends Fragment implements + LoaderManager.LoaderCallbacks{ + + public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1; + + private static final int DEFAULT_LOADER = 0; + public static int NEW_LOADER = 0; + + ShiftsCursorAdapter mCursorAdapter; + ShiftsDbHelper shiftsDbhelper; + LoaderManager.LoaderCallbacks defaultLoaderCallback; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View rootView = inflater.inflate(R.layout.fragment_main, container, false); + setHasOptionsMenu(true); + + MainActivity.setActionBarTitle(getString(R.string.app_name)); + + filter = getActivity().getSharedPreferences("PREFS", 0); + sortOrder = filter.getString("Filter",null); + + defaultLoaderCallback = this; + + ListView productListView = (ListView) rootView.findViewById(R.id.list_item_view); + + View emptyView = rootView.findViewById(R.id.empty_view); + productListView.setEmptyView(emptyView); + + mCursorAdapter = new ShiftsCursorAdapter((MainActivity) getActivity(), null); + productListView.setAdapter(mCursorAdapter); + + getLoaderManager().initLoader(DEFAULT_LOADER, null, defaultLoaderCallback); + + FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab1); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + FragmentTransaction fragmentTransaction = (MainActivity.fragmentManager).beginTransaction(); + fragmentTransaction.replace(R.id.container,new FragmentAddItem()).addToBackStack("additem").commit(); + } + }); + + return rootView; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + + case R.id.delete_all: + deleteAllProducts(); + return true; + + case R.id.help: + new AlertDialog.Builder(getContext()) + .setTitle("Help & Support:") + .setView(R.layout.dialog_layout) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + } + }).create().show(); + return true; + + case R.id.filter_data: + FragmentTransaction fragmentTransaction = (MainActivity.fragmentManager).beginTransaction(); + fragmentTransaction.replace(R.id.container,new FilterDataFragment()).addToBackStack("filterdata").commit(); + return true; + + case R.id.sort_data: + sortData(); + return true; + + case R.id.clear_filter: + args = null; + selection = null; + NEW_LOADER = 0; + getLoaderManager().restartLoader(DEFAULT_LOADER, null, this); + return true; + case R.id.export_data: + if(checkStoragePermissions(getActivity())){ + new AlertDialog.Builder(getContext()) + .setTitle("Export?") + .setMessage("Exporting current filtered data. Continue?") + .setNegativeButton(android.R.string.no, null) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + ExportData(); + } + }).create().show(); + }else{ + Toast.makeText(getContext(), "Storage permissions required", Toast.LENGTH_SHORT).show(); + } + return true; + case R.id.action_favorite: + new AlertDialog.Builder(getContext()) + .setTitle("Info:") + .setMessage(retrieveInfo()) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + } + }).create().show(); + return true; + } + + return super.onOptionsItemSelected(item); + } + + private void sortData(){ + final String[] grpname = {"Added","Date","Name"}; + final String[] sortQuery = {""}; + int checkedItem = -1; + + if(sortOrder != null && sortOrder.contains(ShiftsEntry._ID)){ + checkedItem = 0; + sortQuery[0] = ShiftsEntry._ID; + }else if(sortOrder != null && sortOrder.contains(ShiftsEntry.COLUMN_SHIFT_DATE)){ + checkedItem = 1; + sortQuery[0] = ShiftsEntry.COLUMN_SHIFT_DATE; + }else if(sortOrder != null && sortOrder.contains(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION)){ + checkedItem = 2; + sortQuery[0] = ShiftsEntry.COLUMN_SHIFT_DESCRIPTION; + } + + AlertDialog.Builder alt_bld = new AlertDialog.Builder(getContext()); + //alt_bld.setIcon(R.drawable.icon); + alt_bld.setTitle("Sort by:"); + alt_bld.setSingleChoiceItems(grpname, checkedItem, new DialogInterface + .OnClickListener() { + public void onClick(DialogInterface dialog, int item) { + + switch (item) { + case 0: + sortQuery[0] = ShiftsEntry._ID; + return; + case 1: + sortQuery[0] = ShiftsEntry.COLUMN_SHIFT_DATE; + return; + case 2: + sortQuery[0] = ShiftsEntry.COLUMN_SHIFT_DESCRIPTION; + } + + } + }).setPositiveButton("Ascending", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + sortOrder = sortQuery[0] + " ASC"; + filter.edit().putString("Filter",sortOrder).apply(); + getLoaderManager().restartLoader(DEFAULT_LOADER, null, defaultLoaderCallback); + dialog.dismiss(); + } + }).setNegativeButton("Descending", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + sortOrder = sortQuery[0] + " DESC"; + filter.edit().putString("Filter",sortOrder).apply(); + getLoaderManager().restartLoader(DEFAULT_LOADER, null, defaultLoaderCallback); + dialog.dismiss(); + } + }); + AlertDialog alert = alt_bld.create(); + alert.show(); + } + + private void deleteAllProducts() { + new AlertDialog.Builder(getContext()) + .setTitle("Delete?") + .setMessage("Are you sure you want to delete all date?") + .setNegativeButton(android.R.string.no, null) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface arg0, int arg1) { + int rowsDeleted = getActivity().getContentResolver().delete(ShiftsEntry.CONTENT_URI, null, null); + Toast.makeText(getContext(), rowsDeleted + " Items Deleted", Toast.LENGTH_SHORT).show(); + } + }).create().show(); + } + + @Override + public void onResume() { + super.onResume(); + if(NEW_LOADER > DEFAULT_LOADER) { + getLoaderManager().restartLoader(DEFAULT_LOADER, null, defaultLoaderCallback); + System.out.println("reloading loader"); + } + } + + private void ExportData() { + + int permission = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE); + + if (permission != PackageManager.PERMISSION_GRANTED) { + Toast.makeText(getContext(), "Storage permissions not granted", Toast.LENGTH_SHORT).show(); + return; + } + + + shiftsDbhelper = new ShiftsDbHelper(getContext()); + SQLiteDatabase database = shiftsDbhelper.getWritableDatabase(); + + String[] projection_export = { + ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, + ShiftsEntry.COLUMN_SHIFT_DATE, + ShiftsEntry.COLUMN_SHIFT_TIME_IN, + ShiftsEntry.COLUMN_SHIFT_TIME_OUT, + ShiftsEntry.COLUMN_SHIFT_BREAK, + ShiftsEntry.COLUMN_SHIFT_DURATION, + ShiftsEntry.COLUMN_SHIFT_TYPE, + ShiftsEntry.COLUMN_SHIFT_UNIT, + ShiftsEntry.COLUMN_SHIFT_PAYRATE, + ShiftsEntry.COLUMN_SHIFT_TOTALPAY}; + Cursor cursor = getActivity().getContentResolver().query( + ShiftsEntry.CONTENT_URI, + projection_export, + selection, + args, + sortOrder); + + database.delete(ShiftsEntry.TABLE_NAME_EXPORT,null,null); + + float totalDuration = 0.00f; + float totalUnits = 0.00f; + float totalPay= 0.00f; + + try { + while (cursor.moveToNext()) { + final String descriptionColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION)); + final String dateColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DATE)); + final String timeInColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TIME_IN)); + final String timeOutColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TIME_OUT)); + final Float durationColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DURATION)); + final Integer breakOutColumnIndex = cursor.getInt(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_BREAK)); + final String typeColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TYPE)); + final Float unitColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_UNIT)); + final Float payrateColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_PAYRATE)); + final Float totalpayColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TOTALPAY)); + + totalUnits = totalUnits + unitColumnIndex; + totalDuration = totalDuration + durationColumnIndex; + totalPay = totalPay + totalpayColumnIndex; + + ContentValues values = new ContentValues(); + values.put(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, descriptionColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_DATE, dateColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_TIME_IN, timeInColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_TIME_OUT, timeOutColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_BREAK, breakOutColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_DURATION, durationColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_TYPE, typeColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_UNIT, unitColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_PAYRATE, payrateColumnIndex); + values.put(ShiftsEntry.COLUMN_SHIFT_TOTALPAY, totalpayColumnIndex); + + database.insert(ShiftsEntry.TABLE_NAME_EXPORT, null, values); + + } + } finally { + ContentValues values = new ContentValues(); + values.put(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, ""); + values.put(ShiftsEntry.COLUMN_SHIFT_DATE, ""); + values.put(ShiftsEntry.COLUMN_SHIFT_TIME_IN, ""); + values.put(ShiftsEntry.COLUMN_SHIFT_TIME_OUT, ""); + values.put(ShiftsEntry.COLUMN_SHIFT_BREAK, "Total duration:"); + values.put(ShiftsEntry.COLUMN_SHIFT_DURATION, totalDuration); + values.put(ShiftsEntry.COLUMN_SHIFT_TYPE, "Total units:"); + values.put(ShiftsEntry.COLUMN_SHIFT_UNIT, totalUnits); + values.put(ShiftsEntry.COLUMN_SHIFT_PAYRATE, "Total pay:"); + values.put(ShiftsEntry.COLUMN_SHIFT_TOTALPAY, totalPay); + + database.insert(ShiftsEntry.TABLE_NAME_EXPORT, null, values); + cursor.close(); + } + + + final String savePath = Environment.getExternalStorageDirectory() + "/ShifttrackerTemp"; + File file = new File(savePath); + if (!file.exists()) { + file.mkdirs(); + } + SQLiteToExcel sqLiteToExcel = new SQLiteToExcel(getContext(), "shifts.db",savePath); + + sqLiteToExcel.exportSingleTable("shiftsexport","shifthistory.xls", new SQLiteToExcel.ExportListener() { + @Override + public void onStart() { + + } + @Override + public void onCompleted(String filePath) { + Toast.makeText(getContext(), filePath, Toast.LENGTH_SHORT).show(); + Uri newPath = Uri.parse("file://" + savePath + "/" +"shifthistory.xls"); + + StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); + StrictMode.setVmPolicy(builder.build()); + + Intent emailintent = new Intent(Intent.ACTION_SEND); + + emailintent.setType("application/vnd.ms-excel"); + emailintent.putExtra(Intent.EXTRA_SUBJECT, "historic shifts"); + emailintent.putExtra(Intent.EXTRA_TEXT, "I'm email body."); + emailintent.putExtra(Intent.EXTRA_STREAM,newPath); + + startActivity(Intent.createChooser(emailintent, "Send Email")); + } + @Override + public void onError(Exception e) { + System.out.println("Error msg: " + e); + Toast.makeText(getContext(), "Failed to Export data", Toast.LENGTH_SHORT).show(); + } + }); + } + + private String retrieveInfo(){ + String[] projection = { + ShiftsEntry._ID, + ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, + ShiftsEntry.COLUMN_SHIFT_DATE, + ShiftsEntry.COLUMN_SHIFT_TIME_IN, + ShiftsEntry.COLUMN_SHIFT_TIME_OUT, + ShiftsEntry.COLUMN_SHIFT_BREAK, + ShiftsEntry.COLUMN_SHIFT_DURATION, + ShiftsEntry.COLUMN_SHIFT_TYPE, + ShiftsEntry.COLUMN_SHIFT_UNIT, + ShiftsEntry.COLUMN_SHIFT_PAYRATE, + ShiftsEntry.COLUMN_SHIFT_TOTALPAY}; + Cursor cursor = getActivity().getContentResolver().query( + ShiftsEntry.CONTENT_URI, + projection, + selection, + args, + sortOrder); + float totalDuration = 0.0f; + int countOfTypeH = 0; + int countOfTypeP = 0; + float totalUnits = 0; + float totalPay = 0; + int lines = 0; + try { + while (cursor.moveToNext()) { + final Float durationColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DURATION)); + final String typeColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TYPE)); + final Float unitColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_UNIT)); + final Float totalpayColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TOTALPAY)); + + totalDuration = totalDuration + durationColumnIndex; + if (typeColumnIndex.contains("Hourly")){ + countOfTypeH = countOfTypeH + 1; + }else if (typeColumnIndex.contains("Piece")){ + countOfTypeP = countOfTypeP +1; + } + totalUnits= totalUnits + unitColumnIndex; + totalPay = totalPay + totalpayColumnIndex; + } + } finally { + + if ((cursor != null) && (cursor.getCount() > 0)) { + lines = cursor.getCount(); + cursor.close(); + } + + } + + return buildInfoString(totalDuration,countOfTypeH,countOfTypeP,totalUnits,totalPay,lines); + } + + public String buildInfoString(float totalDuration, int countOfTypeH, int countOfTypeP, float totalUnits, float totalPay, int lines){ + String textString; + textString = lines + " Shifts"; + if (countOfTypeH != 0 && countOfTypeP != 0){ + textString = textString + " (" + countOfTypeH + " Hourly" + "/" + countOfTypeP + " Piece Rate)"; + } + if(countOfTypeH != 0){ + textString = textString + + "\n" + "Total Hours: " + String.format("%.2f",totalDuration); + } + if(countOfTypeP != 0){ + textString = textString + + "\n" + "Total Units: " + String.format("%.2f",totalUnits); + } + + if (totalPay != 0){ + textString = textString + + "\n" + "Total Pay: " + "$" + String.format("%.2f",totalPay); + } + + return textString; + } + + @Override + public Loader onCreateLoader(int i, Bundle bundle) { + String[] projection = { + ShiftsEntry._ID, + ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, + ShiftsEntry.COLUMN_SHIFT_DATE, + ShiftsEntry.COLUMN_SHIFT_TIME_IN, + ShiftsEntry.COLUMN_SHIFT_TIME_OUT, + ShiftsEntry.COLUMN_SHIFT_BREAK, + ShiftsEntry.COLUMN_SHIFT_DURATION, + ShiftsEntry.COLUMN_SHIFT_TYPE, + ShiftsEntry.COLUMN_SHIFT_PAYRATE, + ShiftsEntry.COLUMN_SHIFT_UNIT, + ShiftsEntry.COLUMN_SHIFT_TOTALPAY,}; + + return new android.support.v4.content.CursorLoader(getContext(), + ShiftsEntry.CONTENT_URI, + projection, + selection, + args, + sortOrder); + } + + @Override + public void onLoadFinished(Loader loader, Cursor cursor) { + mCursorAdapter.swapCursor(cursor); + } + + @Override + public void onLoaderReset(Loader loader) { + mCursorAdapter.swapCursor(null); + } + + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + System.out.println("request code" + requestCode); + switch (requestCode) { + case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { + if (grantResults.length > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + exportDialog(); + }else{ + Toast.makeText(getContext(), "Storage Permissions denied", Toast.LENGTH_SHORT).show(); + } + } + } + } + + public void exportDialog(){ + new AlertDialog.Builder(getContext()) + .setTitle("Export?") + .setMessage("Exporting current filtered data. Continue?") + .setNegativeButton(android.R.string.no, null) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + ExportData(); + } + }).create().show(); + } +// // Storage Permissions +// private static final int REQUEST_EXTERNAL_STORAGE = 1; +// private static String[] PERMISSIONS_STORAGE = { +// Manifest.permission.READ_EXTERNAL_STORAGE, +// Manifest.permission.WRITE_EXTERNAL_STORAGE +// }; +// /** +// * Checks if the app has permission to write to device storage +// * +// * If the app does not has permission then the user will be prompted to grant permissions +// * +// * @param activity +// */ +// public static void verifyStoragePermissions(Activity activity) { +// // Check if we have write permission +// int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); +// +// if (permission != PackageManager.PERMISSION_GRANTED) { +// // We don't have permission so prompt the user +// ActivityCompat.requestPermissions( +// activity, +// PERMISSIONS_STORAGE, +// REQUEST_EXTERNAL_STORAGE +// ); +// } +// } + + public static boolean checkStoragePermissions(Activity activity){ + boolean status = false; + int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); + + if (permission == PackageManager.PERMISSION_GRANTED ){ + status = true; + } + + return status; + } + +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/FurtherInfoFragment.java b/app/src/main/java/com/example/h_mal/shift_tracker/FurtherInfoFragment.java new file mode 100644 index 0000000..cd76d12 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/FurtherInfoFragment.java @@ -0,0 +1,184 @@ +package com.example.h_mal.shift_tracker; + +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.Loader; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.example.h_mal.shift_tracker.Data.ShiftsContract; + + +public class FurtherInfoFragment extends Fragment implements + LoaderManager.LoaderCallbacks { + + private static final int DEFAULT_LOADER = 0; + + private TextView typeTV; + private TextView descriptionTV; + private TextView dateTV; + private TextView times; + private TextView breakTV; + private TextView durationTV; + private TextView unitsTV; + private TextView payRateTV; + private TextView totalPayTV; + private LinearLayout hourlyDetailHolder; + private LinearLayout unitsHolder; + private LinearLayout wholeView; + private ProgressBar progressBarFI; + private Button editButton; + + private Uri CurrentUri; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View rootView = inflater.inflate(R.layout.fragment_futher_info, container, false); + + MainActivity.setActionBarTitle(getString(R.string.further_info_title)); + + setHasOptionsMenu(true); + + progressBarFI = (ProgressBar) rootView.findViewById(R.id.progressBar_info); + wholeView = (LinearLayout) rootView.findViewById(R.id.further_info_view); + typeTV = (TextView)rootView.findViewById(R.id.details_shift); + descriptionTV = (TextView)rootView.findViewById(R.id.details_desc); + dateTV = (TextView)rootView.findViewById(R.id.details_date); + times = (TextView)rootView.findViewById(R.id.details_time); + breakTV = (TextView)rootView.findViewById(R.id.details_breaks); + durationTV = (TextView)rootView.findViewById(R.id.details_duration); + unitsTV = (TextView)rootView.findViewById(R.id.details_units); + payRateTV = (TextView)rootView.findViewById(R.id.details_pay_rate); + totalPayTV = (TextView)rootView.findViewById(R.id.details_totalpay); + editButton = (Button) rootView.findViewById(R.id.details_edit); + hourlyDetailHolder = (LinearLayout) rootView.findViewById(R.id.details_hourly_details); + unitsHolder = (LinearLayout) rootView.findViewById(R.id.details_units_holder); + + final Bundle b = getArguments(); + CurrentUri = Uri.parse(b.getString("uri")); + + getLoaderManager().initLoader(DEFAULT_LOADER, null, this); + + editButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + FragmentTransaction fragmentTransaction = (MainActivity.fragmentManager).beginTransaction(); + Fragment fragment = new FragmentAddItem(); + fragment.setArguments(b); + fragmentTransaction.replace(R.id.container,fragment).addToBackStack("additem").commit(); + } + }); + + + return rootView; + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + super.onCreateOptionsMenu(menu, inflater); + menu.clear(); + } + + @Override + public Loader onCreateLoader(int id, Bundle args) { + progressBarFI.setVisibility(View.VISIBLE); + wholeView.setVisibility(View.GONE); + String[] projection = { + ShiftsContract.ShiftsEntry._ID, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_IN, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_OUT, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_BREAK, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DURATION, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_PAYRATE, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_UNIT, + ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TOTALPAY,}; + + return new android.support.v4.content.CursorLoader(getContext(),CurrentUri, + projection,null,null,null); + } + + @Override + public void onLoadFinished(android.support.v4.content.Loader loader, Cursor cursor) { + progressBarFI.setVisibility(View.GONE); + wholeView.setVisibility(View.VISIBLE); + if (cursor == null || cursor.getCount() < 1) { + return; + } + + if (cursor.moveToFirst()) { + int descriptionColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DESCRIPTION); + int dateColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DATE); + int timeInColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_IN); + int timeOutColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TIME_OUT); + int breakColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_BREAK); + int durationColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_DURATION); + int typeColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TYPE); + int unitColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_UNIT); + int payrateColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_PAYRATE); + int totalPayColumnIndex = cursor.getColumnIndex(ShiftsContract.ShiftsEntry.COLUMN_SHIFT_TOTALPAY); + + String type = cursor.getString(typeColumnIndex); + String description = cursor.getString(descriptionColumnIndex); + String date = cursor.getString(dateColumnIndex); + String timeIn = cursor.getString(timeInColumnIndex); + String timeOut = cursor.getString(timeOutColumnIndex); + int breaks = cursor.getInt(breakColumnIndex); + float duration = cursor.getFloat(durationColumnIndex); + float unit = cursor.getFloat(unitColumnIndex); + float payrate = cursor.getFloat(payrateColumnIndex); + float totalPay = cursor.getFloat(totalPayColumnIndex); + + String durationString = ShiftsCursorAdapter.timeValues(duration)[0] + " Hours " + ShiftsCursorAdapter.timeValues(duration)[1] + " Minutes "; + if(breaks != 0){ + durationString = durationString + " (+ " + Integer.toString(breaks) + " minutes break)"; + } + + typeTV.setText(type); + descriptionTV.setText(description); + dateTV.setText(date); + String totalPaid = ""; + String currency = "$"; + if(type.equals("Hourly")){ + hourlyDetailHolder.setVisibility(View.VISIBLE); + unitsHolder.setVisibility(View.GONE); + times.setText(timeIn + " - " + timeOut); + breakTV.setText(Integer.toString(breaks) + "mins"); + durationTV.setText(durationString); + totalPaid = String.format("%.2f",duration) + " Hours @ " + currency + String.format("%.2f",payrate) + " per Hour" + "\n" + + "Equals: " + currency + String.format("%.2f",totalPay); + }else if(type.equals("Piece Rate")){ + hourlyDetailHolder.setVisibility(View.GONE); + unitsHolder.setVisibility(View.VISIBLE); + unitsTV.setText(String.format("%.2f",unit)); + totalPaid = String.format("%.2f",unit) + " Units @ " + currency + String.format("%.2f",payrate) + " per Unit" + "\n" + + "Equals: " + currency + String.format("%.2f",totalPay); + } + + payRateTV.setText(String.format("%.2f",payrate)); + totalPayTV.setText(totalPaid); + + } + } + + @Override + public void onLoaderReset(android.support.v4.content.Loader loader) { + + } + +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/MainActivity.java b/app/src/main/java/com/example/h_mal/shift_tracker/MainActivity.java new file mode 100644 index 0000000..712b4e0 --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/MainActivity.java @@ -0,0 +1,236 @@ +package com.example.h_mal.shift_tracker; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.support.v4.app.ActivityCompat; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.Menu; +import android.view.View; +import android.widget.ProgressBar; + +import com.google.android.gms.ads.AdListener; +import com.google.android.gms.ads.AdRequest; +import com.google.android.gms.ads.AdView; +import com.google.android.gms.ads.MobileAds; + +import java.util.List; + +public class MainActivity extends AppCompatActivity { + + public static SharedPreferences filter; + public static Context context; + static String sortOrder; + public static String selection; + public static String[] args; + private static Toolbar toolbar; + public static FragmentManager fragmentManager; + private AdView adView; + private ProgressBar progressBar; + private String currentFragment; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main_view); + + verifyStoragePermissions(this); + + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + fragmentManager = getSupportFragmentManager(); + FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); + fragmentTransaction.replace(R.id.container,new FragmentMain()).addToBackStack("main").commit(); + + progressBar = (ProgressBar) findViewById(R.id.progressBar2); + + fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { + @Override + public void onBackStackChanged() { + List f = fragmentManager.getFragments(); + Fragment frag = f.get(0); + currentFragment = frag.getClass().getSimpleName(); + } + }); + + // Initialize the Mobile Ads SDK. + MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713"); + + // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in + // values/strings.xml. + adView = (AdView) findViewById(R.id.adView); + adView.setAdListener(new AdListener(){ + @Override + public void onAdOpened() { + // Code to be executed when an ad opens an overlay that + // covers the screen. + } + + @Override + public void onAdLeftApplication() { + // Code to be executed when the user has left the app. + } + + @Override + public void onAdClosed() { + // Code to be executed when when the user is about to return + // to the app after tapping on an ad. + } + @Override + public void onAdFailedToLoad(int i) { + super.onAdFailedToLoad(i); + progressBar.setVisibility(View.GONE); + } + + @Override + public void onAdLoaded() { + super.onAdLoaded(); + progressBar.setVisibility(View.GONE); + } + }); + // Create an ad request. Check your logcat output for the hashed device ID to + // get test ads on a physical device. e.g. + // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device." + + AdRequest adRequest = new AdRequest.Builder() + .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) + .build(); + + // Start loading the ad in the background. + adView.loadAd(adRequest); + + } + public static void setActionBarTitle(String title){ + toolbar.setTitle(title); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_main, menu); + return true; + } + + @Override + public void onBackPressed() { + + switch (currentFragment) { + case "FragmentMain": + new AlertDialog.Builder(this) + .setTitle("Leave?") + .setMessage("Are you sure you want to exit Farmr?") + .setNegativeButton(android.R.string.no, null) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + Intent intent = new Intent(Intent.ACTION_MAIN); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.addCategory(Intent.CATEGORY_HOME); + startActivity(intent); + finish(); + System.exit(0); + } + }).create().show(); + return; + case "FragmentAddItem": + if(FragmentAddItem.mRadioGroup.getCheckedRadioButtonId() == -1) { + fragmentManager.popBackStack(); + }else{ + new AlertDialog.Builder(this) + .setTitle("Discard Changes?") + .setMessage("Are you sure you want to discard changes?") + .setNegativeButton(android.R.string.no, null) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface arg0, int arg1) { + fragmentManager.popBackStack(); + } + }).create().show(); + + } + return; + default: + if (fragmentManager.getBackStackEntryCount() > 1) { + fragmentManager.popBackStack(); + } + } + + } + + // Storage Permissions + private static final int REQUEST_EXTERNAL_STORAGE = 1; + private static String[] PERMISSIONS_STORAGE = { + Manifest.permission.READ_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE + }; + /** + * Checks if the app has permission to write to device storage + * + * If the app does not has permission then the user will be prompted to grant permissions + * + * @param activity + */ + public static void verifyStoragePermissions(Activity activity) { + // Check if we have write permission + int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); + + if (permission != PackageManager.PERMISSION_GRANTED) { + // We don't have permission so prompt the user + ActivityCompat.requestPermissions( + activity, + PERMISSIONS_STORAGE, + REQUEST_EXTERNAL_STORAGE + ); + } + } + + +// @Override +// protected void onUserLeaveHint() { +// super.onUserLeaveHint(); +// +// Intent intent = getIntent(); +// String activity = intent.getStringExtra("activity"); +// +// if (activity == null || !activity.equals("first") || !activity.equals("firsttime")) { +// NavUtils.navigateUpFromSameTask(MainActivity.this); +// } else { +// getIntent().removeExtra("activity"); +// } +// +// } + +// @Override +// protected void onPause() { +// super.onPause(); +// // If the screen is off then the device has been locked +// PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); +// boolean isScreenOn; +// if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { +// isScreenOn = powerManager.isInteractive(); +// } else { +// isScreenOn = powerManager.isScreenOn(); +// } +// +// if (!isScreenOn) { +// Intent intent = getIntent(); +// String activity = intent.getStringExtra("activity"); +// if (activity == null || !activity.equals("first") || !activity.equals("firsttime")){ +// NavUtils.navigateUpFromSameTask(MainActivity.this); +// }else { +// getIntent().removeExtra("activity"); +// } +// System.out.println("mainactivity"); +// } +// } +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/ShiftsCursorAdapter.java b/app/src/main/java/com/example/h_mal/shift_tracker/ShiftsCursorAdapter.java new file mode 100644 index 0000000..560f6ba --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/ShiftsCursorAdapter.java @@ -0,0 +1,171 @@ +package com.example.h_mal.shift_tracker; + +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.support.v4.app.FragmentTransaction; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import com.example.h_mal.shift_tracker.Data.ShiftProvider; +import com.example.h_mal.shift_tracker.Data.ShiftsContract.ShiftsEntry; + +/** + * Created by h_mal on 26/12/2017. + */ + +public class ShiftsCursorAdapter extends CursorAdapter { + + private final MainActivity activity; + + private Context mContext; + + ShiftProvider shiftProvider; + + public ShiftsCursorAdapter(MainActivity context, Cursor c) { + super(context, c, 0); + this.activity = context; + } + + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return LayoutInflater.from(context).inflate(R.layout.list_item_1, parent, false); + } + + + + @Override + public void bindView(View view, Context context, Cursor cursor) { + mContext = context; + + TextView descriptionTextView = (TextView) view.findViewById(R.id.location); + TextView dateTextView = (TextView) view.findViewById(R.id.date); + TextView totalPay = (TextView) view.findViewById(R.id.total_pay); + TextView hoursView = (TextView) view.findViewById(R.id.hours); + TextView h = (TextView) view.findViewById(R.id.h); + TextView minutesView = (TextView) view.findViewById(R.id.minutes); + TextView m = (TextView) view.findViewById(R.id.m); + ImageView editView = (ImageView) view.findViewById(R.id.imageView); + + h.setText("h"); + m.setText("m"); + + final String typeColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TYPE)); + final String descriptionColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DESCRIPTION)); + final String dateColumnIndex = cursor.getString(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DATE)); + final Float durationColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_DURATION)); + final Float unitsColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_UNIT)); + final Float totalpayColumnIndex = cursor.getFloat(cursor.getColumnIndexOrThrow(ShiftsEntry.COLUMN_SHIFT_TOTALPAY)); + + descriptionTextView.setText(descriptionColumnIndex); + dateTextView.setText(newDate(dateColumnIndex)); + totalPay.setText(String.format("%.2f",totalpayColumnIndex)); + + if (typeColumnIndex.equals("Piece Rate") && durationColumnIndex == 0){ + hoursView.setText(String.valueOf(unitsColumnIndex)); + h.setText(""); + minutesView.setText(""); + m.setText("pcs"); + }else +// if(typeColumnIndex.equals("Hourly") || typeColumnIndex.equals("hourly")) + { + hoursView.setText(timeValues(durationColumnIndex)[0]); + minutesView.setText(timeValues(durationColumnIndex)[1]); + } + + final long ID = cursor.getLong(cursor.getColumnIndexOrThrow(ShiftsEntry._ID)); + final Uri currentProductUri = ContentUris.withAppendedId(ShiftsEntry.CONTENT_URI, ID); + + final Bundle b = new Bundle(); + b.putString("uri",String.valueOf(currentProductUri)); + + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { +// activity.clickOnViewItem(ID); + FragmentTransaction fragmentTransaction = (MainActivity.fragmentManager).beginTransaction(); + FurtherInfoFragment fragment2 = new FurtherInfoFragment(); + fragment2.setArguments(b); + fragmentTransaction.replace(R.id.container,fragment2).addToBackStack("furtherinfo").commit(); + } + }); + + editView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + FragmentTransaction fragmentTransaction = (MainActivity.fragmentManager).beginTransaction(); + FragmentAddItem fragment3 = new FragmentAddItem(); + fragment3.setArguments(b); + fragmentTransaction.replace(R.id.container,fragment3).addToBackStack("additem").commit(); + } + }); + + view.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View view) { + System.out.println("long click: " + ID); + + android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext); + builder.setMessage("Are you sure you want to delete"); + builder.setPositiveButton("delete", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + deleteProduct(ID); + } + }); + builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + + if (dialog != null) { + dialog.dismiss(); + } + } + }); + + android.app.AlertDialog alertDialog = builder.create(); + alertDialog.show(); + return true; + } + }); + + } + + private void deleteProduct(Long id) { + String[] args = new String [] {String.valueOf(id)}; +// String whereClause = String.format(ShiftsEntry._ID + " in (%s)", new Object[] { TextUtils.join(",", Collections.nCopies(args.length, "?")) }); //for deleting multiple lines + + mContext.getContentResolver().delete(ShiftsEntry.CONTENT_URI, ShiftsEntry._ID + "=?", args); + } + + private String newDate(String dateString){ + + String returnString = "01/01/2010"; + + String year = dateString.substring(0, 4); + String month = dateString.substring(5, 7); + String day = dateString.substring(8); + + returnString = day + "-" + month + "-" + year; + + return returnString; + } + + public static String[] timeValues(Float duration){ + + int hours = (int) Math.floor(duration); + int minutes = (int) ((duration - hours)*60); + + String hoursString = hours + ""; + String minutesString = String.format("%02d", minutes); + + return new String[]{hoursString,minutesString}; + } + +} diff --git a/app/src/main/java/com/example/h_mal/shift_tracker/SplashScreen.java b/app/src/main/java/com/example/h_mal/shift_tracker/SplashScreen.java new file mode 100644 index 0000000..130fdfb --- /dev/null +++ b/app/src/main/java/com/example/h_mal/shift_tracker/SplashScreen.java @@ -0,0 +1,46 @@ +package com.example.h_mal.shift_tracker; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.support.v4.app.ActivityOptionsCompat; +import android.widget.RelativeLayout; + +/** + * Created by h_mal on 27/06/2017. + */ + +public class SplashScreen extends Activity { + + // Splash screen timer + private static int SPLASH_TIME_OUT = 2000; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_splash); + + final Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.hyperspace_jump, android.R.anim.fade_out).toBundle(); + + final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.splash_layout); + + final Intent i = new Intent(SplashScreen.this,MainActivity.class); + i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); + + new Handler().postDelayed(new Runnable() { + + @Override + public void run() { + // This method will be executed once the timer is over + // Start your app main activity +// startActivity(i,bundle); + startActivity(i); + overridePendingTransition(android.R.anim.fade_in,R.anim.hyperspace_jump); +// finish(); + } + }, SPLASH_TIME_OUT); + } + + +} \ No newline at end of file diff --git a/app/src/main/res/anim/hyperspace_jump.xml b/app/src/main/res/anim/hyperspace_jump.xml new file mode 100644 index 0000000..af06e59 --- /dev/null +++ b/app/src/main/res/anim/hyperspace_jump.xml @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/add.png b/app/src/main/res/drawable/add.png new file mode 100644 index 0000000..a14e890 Binary files /dev/null and b/app/src/main/res/drawable/add.png differ diff --git a/app/src/main/res/drawable/farm.jpg b/app/src/main/res/drawable/farm.jpg new file mode 100644 index 0000000..290da71 Binary files /dev/null and b/app/src/main/res/drawable/farm.jpg differ diff --git a/app/src/main/res/drawable/farmr.jpg b/app/src/main/res/drawable/farmr.jpg new file mode 100644 index 0000000..cfa734d Binary files /dev/null and b/app/src/main/res/drawable/farmr.jpg differ diff --git a/app/src/main/res/drawable/ic_info_black_24dp.xml b/app/src/main/res/drawable/ic_info_black_24dp.xml new file mode 100644 index 0000000..34b8202 --- /dev/null +++ b/app/src/main/res/drawable/ic_info_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_notifications_black_24dp.xml b/app/src/main/res/drawable/ic_notifications_black_24dp.xml new file mode 100644 index 0000000..e3400cf --- /dev/null +++ b/app/src/main/res/drawable/ic_notifications_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_sync_black_24dp.xml b/app/src/main/res/drawable/ic_sync_black_24dp.xml new file mode 100644 index 0000000..5a283aa --- /dev/null +++ b/app/src/main/res/drawable/ic_sync_black_24dp.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/image_i_64.png b/app/src/main/res/drawable/image_i_64.png new file mode 100644 index 0000000..bcf9700 Binary files /dev/null and b/app/src/main/res/drawable/image_i_64.png differ diff --git a/app/src/main/res/drawable/img_i_full.png b/app/src/main/res/drawable/img_i_full.png new file mode 100644 index 0000000..97c195c Binary files /dev/null and b/app/src/main/res/drawable/img_i_full.png differ diff --git a/app/src/main/res/drawable/info.png b/app/src/main/res/drawable/info.png new file mode 100644 index 0000000..97c195c Binary files /dev/null and b/app/src/main/res/drawable/info.png differ diff --git a/app/src/main/res/layout/activity_splash.xml b/app/src/main/res/layout/activity_splash.xml new file mode 100644 index 0000000..8db7e41 --- /dev/null +++ b/app/src/main/res/layout/activity_splash.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_layout.xml b/app/src/main/res/layout/dialog_layout.xml new file mode 100644 index 0000000..0107d7f --- /dev/null +++ b/app/src/main/res/layout/dialog_layout.xml @@ -0,0 +1,180 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_add_item.xml b/app/src/main/res/layout/fragment_add_item.xml new file mode 100644 index 0000000..10d1cee --- /dev/null +++ b/app/src/main/res/layout/fragment_add_item.xml @@ -0,0 +1,328 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +