Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #77 and other race condition bugs #78

Merged
merged 3 commits into from
Dec 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "1c4b4d71bcbdb586cc4af0a0585902ca",
"entities": [
{
"tableName": "ConsumedEntries",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `productId` INTEGER NOT NULL, `amount` INTEGER NOT NULL, `date` INTEGER, `name` TEXT, FOREIGN KEY(`productId`) REFERENCES `Product`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "productId",
"columnName": "productId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "amount",
"columnName": "amount",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "date",
"columnName": "date",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": [
{
"table": "Product",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"productId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "Product",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `energy` REAL NOT NULL, `barcode` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "energy",
"columnName": "energy",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "barcode",
"columnName": "barcode",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"1c4b4d71bcbdb586cc4af0a0585902ca\")"
]
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@
*/
package org.secuso.privacyfriendlyfoodtracker.database;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Query;

import com.jjoe64.graphview.series.DataPoint;

import org.secuso.privacyfriendlyfoodtracker.ui.adapter.DatabaseEntry;

import java.sql.Date;
import java.util.List;

Expand All @@ -37,6 +40,9 @@ public interface ConsumedEntrieAndProductDao {
@Query("SELECT consumedEntries.date AS unique1, sum(product.energy*consumedEntries.amount/100) AS unique2 FROM consumedEntries INNER JOIN product ON consumedEntries.productId = product.id WHERE consumedEntries.date BETWEEN :dayst AND :dayet")
List<DateCalories> getCaloriesPeriod(final Date dayst, final Date dayet);

@Query("SELECT consumedEntries.amount AS amount, consumedEntries.id AS id,consumedEntries.name as name, product.energy as energy FROM consumedEntries INNER JOIN product ON consumedEntries.productId = product.id WHERE consumedEntries.date=:day")
LiveData<List<DatabaseEntry>> findConsumedEntriesForDate(final Date day);

static class DateCalories
{
public Date unique1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.secuso.privacyfriendlyfoodtracker.database;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
Expand Down Expand Up @@ -59,8 +60,7 @@ public interface ConsumedEntriesDao {
@Query("SELECT * FROM consumedEntries WHERE productId=:productId AND amount=:amount AND date=:date AND name=:name ")
List<ConsumedEntries> findExistingConsumedEntries( int productId, int amount, Date date, String name);

@Query("SELECT * FROM consumedEntries WHERE date=:date")
List<ConsumedEntries> findConsumedEntriesForDate(final Date date);


@Query("DELETE FROM consumedEntries")
void deleteAll();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/
package org.secuso.privacyfriendlyfoodtracker.ui;

import org.secuso.privacyfriendlyfoodtracker.database.ConsumedEntries;
import org.secuso.privacyfriendlyfoodtracker.ui.adapter.DatabaseEntry;
import org.secuso.privacyfriendlyfoodtracker.ui.adapter.DatabaseFacade;
import org.secuso.privacyfriendlyfoodtracker.ui.viewmodels.OverviewViewModel;
Expand All @@ -26,6 +27,7 @@
import android.app.AlertDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.arch.persistence.room.Database;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
Expand Down Expand Up @@ -87,8 +89,14 @@ protected void onCreate(Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarOverview);
setSupportActionBar(toolbar);

// Set up global variables
// Set the date. If no date is passed on, the system date is chosen by default.
//this NEEDS to happen before viewModel.init(), else viewmodel will load data for 1.1.1970
Intent intent = getIntent();
date = intent.getLongExtra("DATE", System.currentTimeMillis());

viewModel = ViewModelProviders.of(this).get(OverviewViewModel.class);
refreshData();
viewModel.init(getDateForActivity());

viewModel.getList().observe(this, new Observer<List<DatabaseEntry>>() {
@Override
Expand All @@ -98,10 +106,7 @@ public void onChanged(@Nullable List<DatabaseEntry> databaseEntries) {
}
});

// Set up global variables
// Set the date. If no date is passed on, the system date is chosen by default.
Intent intent = getIntent();
date = intent.getLongExtra("DATE", System.currentTimeMillis());

selectedCards = 0;

setUpFloatingActionButton();
Expand All @@ -115,7 +120,6 @@ public void onChanged(@Nullable List<DatabaseEntry> databaseEntries) {
@Override
public void onResume() {
super.onResume();
refreshData();
}

/**
Expand All @@ -139,13 +143,9 @@ public boolean onOptionsItemSelected(MenuItem item) {
}
selectedCards = 0;
toggleDeletionMenuVisibility();
refreshData();
return true;
}

private void refreshData() {
viewModel.init(getDateForActivity());
}

/**
* set the menu to say the correct things
Expand Down Expand Up @@ -345,7 +345,6 @@ public void onClick(View v) {
deleteSelectedCards();
selectedCards = 0;
toggleDeletionMenuVisibility();
refreshData();
}

});
Expand Down Expand Up @@ -395,7 +394,7 @@ private CardView createCardViewForEntry(DatabaseEntry e) {
amount.setId(View.generateViewId());
energy.setId(View.generateViewId());
calories.setId(View.generateViewId());
id.setText(e.id);
id.setText(Integer.toString(e.id));

name.setText(e.name);
amount.setText(Integer.toString(e.amount) + "g");
Expand Down Expand Up @@ -495,7 +494,6 @@ public void onClick(DialogInterface dialog, int whichButton) {
String amountField = input.getText().toString();
if(amountField.length() != 0 ){
editDatabaseEntry(amountField, entry.id);
refreshData();
}
}
});
Expand All @@ -521,12 +519,11 @@ public void onClick(DialogInterface dialog, int whichButton) {
/**
* Edit a database entry
* @param amountString the new amount
* @param idString the id of the entry
* @param id the id of the entry
* @return true if the entry was successful
*/
private void editDatabaseEntry(String amountString, String idString) {
private void editDatabaseEntry(String amountString, int id) {
int amount = Integer.parseInt(amountString);
int id = Integer.parseInt(idString);
viewModel.editEntryById(id, amount);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public class DatabaseEntry {
public float energy;
public int amount;
public String name;
public String id;
public DatabaseEntry(String id, String name, int amount, float energy){
public int id;
public DatabaseEntry(int id, String name, int amount, float energy){
this.id = id;
this.amount = amount;
this.energy = energy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,24 +154,10 @@ public List<Product> findMostCommonProducts() {
return products;
}

/**
* Returns a database entry for a specified date.
* @param date the date
* @return DatabaseEntry
*/
public List<DatabaseEntry> getEntriesForDay(java.util.Date date) {
List<DatabaseEntry> databaseEntries = new ArrayList<>();
try {
List<ConsumedEntries> res = consumedEntriesDao.findConsumedEntriesForDate(new java.sql.Date(date.getTime()));
for(ConsumedEntries consumedEntry : res) {
Product product = productDao.findProductById(consumedEntry.productId);
databaseEntries.add(new DatabaseEntry(String.valueOf(consumedEntry.id),consumedEntry.name, consumedEntry.amount, product.energy));
}

} catch (Exception e) {
Log.e("DatabaseFacade", "Error o");
}
return databaseEntries;

public LiveData<List<DatabaseEntry>> getConsumedEntriesForDay(java.util.Date date){
return consumedEntrieAndProductDao.findConsumedEntriesForDate(new java.sql.Date(date.getTime()));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,15 @@
import java.util.concurrent.Executors;

public class OverviewViewModel extends AndroidViewModel {
private MutableLiveData<List<DatabaseEntry>> list = new MutableLiveData<>();
private LiveData<List<DatabaseEntry>> list = new MutableLiveData<>();

DatabaseFacade dbHelper = null;

/**
*
* @param application

*/
public OverviewViewModel(@NonNull Application application) {
super(application);

Expand All @@ -34,13 +39,12 @@ public OverviewViewModel(@NonNull Application application) {
}
}

public void init(final Date day) {
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
list.postValue(dbHelper.getEntriesForDay(day));
}
});
/**
*
* @param day The date for which the database entries are to be fetched
* */
public void init(Date day) {
list = dbHelper.getConsumedEntriesForDay(day);
}

public LiveData<List<DatabaseEntry>> getList() {
Expand All @@ -55,4 +59,5 @@ public void deleteEntryById(int id) {
public void editEntryById(int id, int amount) {
dbHelper.editEntryById(id, amount);
}

}