Skip to content

Commit

Permalink
Fixed database crashes and operation on main thread.
Browse files Browse the repository at this point in the history
Added temporary fix to #76. It's missing a propper check if the country code is supported.
Allowed calls on main thread for now to improve stability and reduce crashes. When the database call structure has been redone, this should be switched off again.
Fixes #75, Fixes #65 (fixed with the key generation change)
  • Loading branch information
Kamuno committed May 14, 2020
1 parent 9d350ea commit b8d529d
Show file tree
Hide file tree
Showing 10 changed files with 176 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public static ApplicationDatabase getInstance(final Context context) throws Exce

sInstance = Room.databaseBuilder(context.getApplicationContext(),ApplicationDatabase.class, DATABASE_NAME)
.openHelperFactory(factory)
.allowMainThreadQueries()
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ public interface ConsumedEntriesDao {
@Query("SELECT * FROM consumedEntries WHERE date=:date")
List<ConsumedEntries> findConsumedEntriesForDate(final Date date);


@Query("DELETE FROM consumedEntries")
void deleteAll();
}
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 All @@ -24,6 +25,7 @@

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

/**
* Includes methods that offer abstract access to the app database to manage products.
Expand All @@ -45,17 +47,14 @@ public interface ProductDao {
void deleteAll();

@Query("SELECT * FROM product")
List<Product> getAllProducts();
LiveData<List<Product>> getAllProducts();

@Query("SELECT * FROM product WHERE id=:id")
Product findProductById(final int id);


@Query("SELECT * FROM product WHERE name=:name AND energy=:energy AND barcode=:barcode")
List<Product> findExistingProducts(String name, float energy, String barcode);

@Query("SELECT * FROM product WHERE name LIKE :name")
List<Product> findProductsByName(String name);


}
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,9 @@ public ProductApiService getProductApiService(String languageCode) {
}

private ProductApiService createProductApiService() {
String languageCode = Locale.getDefault().getLanguage();
if (languageCode == "de") {
languageCode = "de";
} else {
String languageCode = Locale.getDefault().getCountry();
// TODO: check if it supported -> https://world.openfoodfacts.org/data/taxonomies/countries.json
if (languageCode.equals("")) {
languageCode = "world";
}
productApiService = createProductApiService(languageCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@

import org.secuso.privacyfriendlyfoodtracker.ui.adapter.DatabaseEntry;
import org.secuso.privacyfriendlyfoodtracker.ui.adapter.DatabaseFacade;
import org.secuso.privacyfriendlyfoodtracker.ui.viewmodels.OverviewViewModel;
import org.secuso.privacyfriendlyfoodtracker.ui.viewmodels.SharedStatisticViewModel;
import org.secuso.privacyfriendlyfoodtracker.ui.views.CheckableCardView;
import org.secuso.privacyfriendlyfoodtracker.R;

import android.app.AlertDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.CardView;
import android.text.InputFilter;
Expand Down Expand Up @@ -68,6 +74,8 @@ public class OverviewActivity extends AppCompatActivity {
// I.e. if more than 0 cards are selected, the user should be able to delete them
private int selectedCards;

private OverviewViewModel viewModel;

/**
* sets up the activity
* @param savedInstanceState the saved instance state
Expand All @@ -79,6 +87,17 @@ protected void onCreate(Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarOverview);
setSupportActionBar(toolbar);

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

viewModel.getList().observe(this, new Observer<List<DatabaseEntry>>() {
@Override
public void onChanged(@Nullable List<DatabaseEntry> databaseEntries) {
refreshFoodList(databaseEntries);
refreshTotalCalorieCounter(databaseEntries);
}
});

// Set up global variables
// Set the date. If no date is passed on, the system date is chosen by default.
Intent intent = getIntent();
Expand All @@ -96,8 +115,7 @@ protected void onCreate(Bundle savedInstanceState) {
@Override
public void onResume() {
super.onResume();
refreshFoodList();
refreshTotalCalorieCounter();
refreshData();
}

/**
Expand All @@ -121,10 +139,14 @@ public boolean onOptionsItemSelected(MenuItem item) {
}
selectedCards = 0;
toggleDeletionMenuVisibility();
refreshTotalCalorieCounter();
refreshData();
return true;
}

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

/**
* set the menu to say the correct things
* @param menu the menu
Expand Down Expand Up @@ -224,8 +246,7 @@ private void deleteSelectedCards() {
if (c.isChecked()) {
TextView idView = (TextView) c.getChildAt(1);
String id = idView.getText().toString();
DatabaseFacade facade = getDbFacade();
facade.deleteEntryById(Integer.parseInt(id));
viewModel.deleteEntryById(Integer.parseInt(id));
cardsToRemove.add(v);
}
}
Expand All @@ -245,37 +266,21 @@ private ViewGroup getEntryList() {
return foodlist;
}

/**
* creates a database facade that can be used to call database functions
*
* @return a DatabaseFacade object
*/
private DatabaseFacade getDbFacade() {
DatabaseFacade facade;
try {
facade = new DatabaseFacade(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return facade;
}

/**
* Refreshes the calorie counter at the top of the activity.
* Recounts calories for all Entries of the day.
*/
private void refreshTotalCalorieCounter() {
private void refreshTotalCalorieCounter(@Nullable List<DatabaseEntry> entries) {
BigDecimal totalCalories = new BigDecimal("0");
TextView heading = this.findViewById(R.id.overviewHeading);
String cal = getString(R.string.total_calories);
Date d = getDateForActivity();
String formattedDate = getFormattedDate(d);
DatabaseFacade facade = getDbFacade();
DatabaseEntry[] entries = facade.getEntriesForDay(d);
for (DatabaseEntry e : entries) {
totalCalories = totalCalories.add( BigDecimal.valueOf(e.energy * e.amount/ 100) );
// totalCalories += (e.energy * e.amount) / 100;
if(entries != null) {
for (DatabaseEntry e : entries) {
totalCalories = totalCalories.add(BigDecimal.valueOf(e.energy * e.amount / 100));
// totalCalories += (e.energy * e.amount) / 100;
}
}
heading.setText(String.format(Locale.ENGLISH, " %s: %.2f %s", formattedDate, totalCalories, cal));
}
Expand Down Expand Up @@ -340,7 +345,7 @@ public void onClick(View v) {
deleteSelectedCards();
selectedCards = 0;
toggleDeletionMenuVisibility();
refreshTotalCalorieCounter();
refreshData();
}

});
Expand Down Expand Up @@ -489,9 +494,8 @@ public void onClick(View v) {
public void onClick(DialogInterface dialog, int whichButton) {
String amountField = input.getText().toString();
if(amountField.length() != 0 ){
boolean result = editDatabaseEntry(amountField, entry.id);
refreshFoodList();
refreshTotalCalorieCounter();
editDatabaseEntry(amountField, entry.id);
refreshData();
}
}
});
Expand Down Expand Up @@ -520,22 +524,17 @@ public void onClick(DialogInterface dialog, int whichButton) {
* @param idString the id of the entry
* @return true if the entry was successful
*/
private boolean editDatabaseEntry(String amountString, String idString) {
DatabaseFacade facade = getDbFacade();
private void editDatabaseEntry(String amountString, String idString) {
int amount = Integer.parseInt(amountString);
int id = Integer.parseInt(idString);
return facade.editEntryById(id, amount);
viewModel.editEntryById(id, amount);
}

/**
* refresh the list of entries
*/
private void refreshFoodList() {
Date d = getDateForActivity();
DatabaseFacade facade = getDbFacade();
// Fix Issue #53
if(facade != null) {
DatabaseEntry[] entries = facade.getEntriesForDay(d);
private void refreshFoodList(List<DatabaseEntry> entries) {
if(entries != null) {
ViewGroup foodList = getEntryList();
foodList.removeAllViews();
for (DatabaseEntry e : entries) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// search in the local db first
System.out.println(s.toString());
SearchResultAdapter newAdapter = new SearchResultAdapter(databaseFacade.getProductByName(s.toString()));
SearchResultAdapter newAdapter = new SearchResultAdapter(
databaseFacade.getProductByName(s.toString())
);
foodList.setAdapter(newAdapter);
}

Expand Down
Loading

0 comments on commit b8d529d

Please sign in to comment.