You are on page 1of 36

Content

Introduction……………………………………………………………………2
Chapter I JAVA programming language ,SQLite and Android Studio….3
1.1.Java language.……………………………………………………………..3
1.2.Android Java programming language.………………………………….....4
1.3.Android SQLite database.…………………………………...………….....5
Chapter II Feed Application with Source code...………..….......................7
2.1 Connection Form….………………………………………………….……7
2.2 Registration Form………………………………………………………...10
2.3 Main Form….………………………………………………...….……….14
2.4. Add eaten foods button...….………………………………………….... .18
2.5. Add Foods Page……………….…………………………………………22
2.6 My Foods Page..……………………………………………………….…24
2.7 Recipes Page..………………………………………………………….…25
2.8 Settings Page..………………………………………………………….…28
Conclusion…..…………………………………………………………...…..34
References…………..……………………………………………………...….35

35
Introduction
Turkmenistan starts to implement the Concept of development of the digital
economy until 2025
From the beginning of this year Turkmenistan starts to implement the Concept of
development of the digital economy, designed for the period of 2019-2025,
ORIENT News Agency reports.
The concept, approved by the decree of President Gurbanguly Berdimuhamedov at
the end of November 2018, is aimed at improving the efficiency of the functioning
of all sectors of the economy and the public sphere of the country through the use
of information technologies. It contains 7 chapters reflecting the current state of the
information and communication technologies system of Turkmenistan, goals,
objectives, ways and mechanisms of their development, as well as the expected
results.
The Concept is planned to be implemented in three stages. The first stage (2019)
provides for the creation of a state authorized body, an interdepartmental
Commission composed of heads of ministries, departments and other
organizations, as well as the development of the Program for the development of
the digital economy, that is, a kind of "road map" of measures to prepare for the
transition to the digital economy.
At this stage, the technical base of economic entities will be monitored to prepare
for digitalization. It is also planned to improve the material and technical base, the
legislative platform, to take systematic measures to improve the skills of personnel.
It is planned to determine organizational issues, calculate the amount of budget
funding.
At this stage, tenders for the purchase of appropriate technical equipment will be
announced, the volume of investments will be determined, trial projects will be
launched and the possibilities of their implementation in all sectors will be
analyzed.

35
The second stage (2020-2023) provides for a broader and more comprehensive
implementation of digital communication systems, the development of "One
window" service, the introduction of digital reporting, etc.
Chapter I JAVA programming language, SQLite and
Android Studio

1.1 Java is:

 Object Oriented: In Java, everything is an Object. Java can be easily


extended since it is based on the Object model.
 Platform Independent: Unlike many other programming languages including
C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
 Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
 Secure: With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral: Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
 Portable: Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler in
Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
 Robust: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
 Multithreaded: With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature

35
allows the developers to construct interactive applications that can run
smoothly.
 Interpreted: Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
 High Performance: With the use of Just-In-Time compilers, Java enables
high performance.

Java: general-purpose language: “write code once, run anywhere”

The key: Java Virtual Machine (JVM)– Program code compiled to JVM bytecode

– JVM bytecode interpreted on JVM

1.2.Android Java programming language

Android is an open-source mobile operating system. It is a variant of Linux hence


providing extensive security, modularity and productivity at the mobile device
level. Android is developed and maintained by the organization called “Open
Headset Alliance” (OHA). OHA was established in 2007 with Google being its
foremost member. OHA includes a lot of prominent hardware and software
companies.

The recommended and convenient way of developing Android apps is using Java
programming language. Although Java is a general purpose tool, it is used in
conjunction with Android Software Development Kit (SDK) in Android Studio
environment to develop apps. Another official way is using C++ with the Native
Development Kit (NDK). This option is used for developing apps with low level
instructions such as timing sensitive drivers. With C++ and NDK, we can directly
run the app on the Android kernel hence increasing efficiency in exchange of code
length and development cost. There also exist third-party tools like Xamarin,
Crodova and React Native for developing apps. These platforms provide
convenience however a native-like performance isn‟t normally expected from the
35
apps developed by third party tools. We‟ll use the standard and official way of
developing Android apps: Java with Android SDK and we‟ll use Android Studio
Integrated Development Environment (IDE) for this job.
1.3.Android SQLite

A relational database typically lives inside some kind of containing object. Often,
the container is a database management system (DBMS). (You may sometimes see
references to a relational database management system (RDBMS). For most
purposes in today’s world, most DBMSs are RDBMSs.)

A database management system such as Oracle provides functionality that goes

beyond the database itself, such as user interfaces or developer interfaces;


diagnostic, debugging, and maintenance tools; and even sophisticated data display
functionality.

In some cases, a database is part of a language, object-oriented class, or framework

that, itself, may or may not be a DBMS. For example, PHP has a database class
just as does the Android SDK (Yes, one is a language and one is an operating
system, but each can provide an object-oriented database class.)

No matter what development platform you’re using, integrating SQLite in your app
is always the same (and, indeed, this applies to any database).

1. Design your database. This is not a SQLite issue. See the sidebar, “The Critical
Database Design Step.”

2. Connect your app to the database at runtime.

3. Use the connection to add, delete, insert, or update data.

4. Use the results of the operation in your app. This may consist of refreshing the
interface by adding or removing items, or it may consist of working with the data
in a new item or anything else you and your users require. This is not a SQLite
issue.

35
There is a sort of progression in the integration of SQLite with PHP, Android/Java,

and Core Data for iOS and OS X. With PHP, you are typically working with very
visible SQLite code, and, as you will see, it is frequently procedural code for the
most part. When you get to Core Data, you’ll be working with object-oriented code
where the framework and its classes use SQLite code behind the scenes: you will
rarely write SQLite code directly, but you’re using it all the time. Android and Java
strike a middle ground so that the SQLite code is more visible than it is in Core
Data, but it’s not as visible as it is when you’re using PHP.

Although there are object-oriented ways of writing PHP code, by and large you are

working in a procedural environment. However, in today’s world, the


recommended

best practice for integrating PHP with a database is to use the PHP data object
(PDO) extension. That is an object-oriented class which encapsulates the code that
you need to work with for a database. There are versions for SQLite and other
major databases so your PDO code is relatively easy to port.

Although SQLite is integrated tightly with PHP, Android, and iOS/OS X, the
integration strategies differ somewhat. In a way, they form a logical progression.
PHP supports SQLite as an extension to the language (no longer optional as of this
writing). When you write your PHP code for SQLite, today’s best practice is to use
the PHP data object (PDO) class.

However, the rest of your code may very well be traditional procedural code: there
is no assumption that you will be writing object-oriented code throughout.

Android represents a slightly different approach to the idea of creating a general-

purpose class (android.database). In the case of Android, a specific subclass


database

provides SQLite support (android.database.sqlite) along with the generalized data

management support in android.database.


35
It’s reasonable to think of SQLite in Android as a more object-oriented
implementation than that of PHP. (This is a generalization and is not meant to
ignore—or fan—arguments.) Despite these differences in approach, the SQLite
code

Chapter II Feed Application with Source code

2.1. Connection From

import android.content.BroadcastReceiver

import android.content.Context

import android.content.Intent

import android.content.IntentFilter

import android.net.ConnectivityManager

import android.net.NetworkInfo

import androidx.lifecycle.LiveData

class ConnectionLiveData(val context: Context) : LiveData<ConnectionModel?>()


{

override fun onActive() {

super.onActive()

val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)

context.registerReceiver(networkReceiver, filter)

override fun onInactive() {

super.onInactive()

35
context.unregisterReceiver(networkReceiver)

val WIFI_DATA = 0

val MOBILE_DATA = 0

private val networkReceiver: BroadcastReceiver = object : BroadcastReceiver()


{

override fun onReceive(context: Context, intent: Intent) {

if (intent.extras != null) {

val activeNetwork =

intent.extras![ConnectivityManager.EXTRA_NETWORK_INFO] asNetworkInfo?

val isConnected = activeNetwork != null &&

activeNetwork.isConnectedOrConnecting

if (isConnected) {

when (activeNetwork!!.type) {

ConnectivityManager.TYPE_WIFI ->
postValue(ConnectionModel(WIFI_DATA, true))

ConnectivityManager.TYPE_MOBILE -> postValue(

ConnectionModel(

MOBILE_DATA,

true ) ) } }

else {

postValue(ConnectionModel(0, false))

35
}

} })

35
2.2. Registration From

import android.content.SharedPreferences
import com.feedapp.app.ui.activities.SearchActivity
import com.feedapp.app.util.SP_GUIDE_HOME
import com.feedapp.app.util.SP_INTRO_SHOWED
import javax.inject.Inject
class SharedPrefsHelper @Inject internal constructor(

private val sp: SharedPreferences) {


companion object {
private const val SP_CAUTION_DIALOG = "ShouldShowCautionDialog"
private const val SP_KEY_INTRO_PRODUCTS = "productsUi"
}
fun saveDontAskDownloadDB() =
sp.edit().putBoolean(SearchActivity.SP_KEY_LOCALE_ASK,

35
false).commit()
fun saveLocalDBDownloaded(code: String) =
sp.edit()

putString(SearchActivity.SP_KEY_LOCALE_SEARCH, code).commit()
fun shouldAskDownloadDB() =
sp.getBoolean(SearchActivity.SP_KEY_LOCALE_ASK, true)
fun isIntroShowed() = sp.getBoolean(SP_INTRO_SHOWED, false)

fun isHomeGuideShowed(): Boolean =sp.getBoolean(SP_GUIDE_HOME, false)


fun saveIntroductionPassed() {
sp.edit().putBoolean(SP_INTRO_SHOWED, true).apply()
}
fun saveHomeUiGuideShowed() =
sp.edit().putBoolean(SP_GUIDE_HOME, true).commit()
fun getLocalSearchPreferred() =
sp.getString(SearchActivity.SP_KEY_LOCALE_SEARCH, null)
fun setLocalSearchPreferred(code: String?) =
sp.edit().putString(SearchActivity.SP_KEY_LOCALE_SEARCH, code).commit()
fun shouldShowCautionDialog(): Boolean =
sp.getBoolean(SP_CAUTION_DIALOG, true)
fun saveShowedCautionDialog() =
sp.edit().putBoolean(SP_CAUTION_DIALOG, false).commit()
fun isProductsUiGuideShowed() =
sp.getBoolean(SP_KEY_INTRO_PRODUCTS, false)
fun saveProductsUiGuideShowed() =
sp.edit().putBoolean(SP_KEY_INTRO_PRODUCTS, true).apply()
}

@Component(

modules =

35
[

AndroidSupportInjectionModule::class,

ActivitiesBuilderModule::class,

AppModule::class,

ViewModelFactoryModule::class

interface AppComponent : AndroidInjector<AppDelegate> {

@Component.Builder

interface Builder {

@BindsInstance

fun application(application: Application): Builder

fun build(): AppComponent

javax.inject.Singleton

class ViewModelProviderFactory @Inject

constructor(private val viewModels: MutableMap<Class<out ViewModel>,


Provider<ViewModel>>) :

ViewModelProvider.Factory {

override fun <T : ViewModel> create(modelClass: Class<T>): T {

val creator = viewModels[modelClass]

35
?: viewModels.asIterable().firstOrNull
{ modelClass.isAssignableFrom(it.key) }?.value

?: throw IllegalArgumentException("unknown model class $modelClass")

return try {

creator.get() as T

} catch (e: Exception) {

throw RuntimeException(e)

35
35
2.3. Main From

import androidx.lifecycle.ViewModel
import com.feedapp.app.di.other.ViewModelKey
import com.feedapp.app.viewModels.HomeViewModel
import com.feedapp.app.viewModels.MyMealsViewModel
import com.feedapp.app.viewModels.RecipeSearchViewModel
import com.feedapp.app.viewModels.SettingsViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
abstract class HomeActivityVMModules {

35
@Binds
@IntoMap
@ViewModelKey(HomeViewModel::class)
internal abstract fun bindHomeViewModel(homeViewModel:
HomeViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(MyMealsViewModel::class)
internal abstract fun bindMyMealsViewModel(myMealsViewModel:
MyMealsViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(RecipeSearchViewModel::class)
internal abstract fun
bindRecipeSearchViewModelModule(recipeSearchViewModel:
RecipeSearchViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(SettingsViewModel::class)
internal abstract fun bindSettingsVM(settingsViewModel: SettingsViewModel):
ViewModel
}

class IntroductionViewModel @Inject internal constructor(

private val userRepository: UserRepository,

private val introductionRepository: IntroductionRepository,

private val spHelper: SharedPrefsHelper

) : ViewModel() {

val goal: LiveData<UserGoal> = introductionRepository.goal

35
val applied: MutableLiveData<Boolean> = introductionRepository.applied

private val _valuesInvalid = MutableLiveData<Event<Boolean>>()

val valuesInvalid: LiveData<Event<Boolean>>

get() = _valuesInvalid

private val _progressBar = MutableLiveData<Event<Boolean>>()

val progressBar: LiveData<Event<Boolean>>

get() = _progressBar

suspend fun saveUser() = coroutineScope {

val user = introductionRepository.createUser()

spHelper.saveIntroductionPassed()

user?.let {

userRepository.saveUser(it) } }

private fun showInvalidToast(itemId: Boolean) {

_valuesInvalid.value = Event(itemId)

fun showProgressBar(itemId: Boolean) {

_progressBar.postValue(Event(itemId))

fun canUnblockButton(length: Int, length1: Int, notEmpty: Boolean): Boolean =

introductionRepository.canUnblockButton(length, length1, notEmpty)

fun areHeightWeightInvalid(text: String, text1: String): Boolean {

val are = introductionRepository.areHeightWeightInvalid(text, text1)

if (!are) { showInvalidToast(true) } return are }


35
suspend fun ifUserExists() = userRepository.ifUserExists()

fun chooseGoal(goal: UserGoal) = introductionRepository.chooseGoal(goal)

fun setWeightValue(toString: String) =


introductionRepository.setWeightValue(toString)

fun setAgeValue(toString: String) =


introductionRepository.setAgeValue(toString)

fun setHeightValue(toString: String) =


introductionRepository.setHeightValue(toString)

35
2.4. Add eaten foods button

import androidx.lifecycle.LiveData

import androidx.lifecycle.MutableLiveData

import androidx.lifecycle.ViewModel

import androidx.lifecycle.viewModelScope

import com.feedapp.app.data.models.BasicNutrientType

import com.feedapp.app.data.models.calculations.RecipesDetailsCalculator

import com.feedapp.app.data.models.user.User

import com.feedapp.app.data.repositories.DayRepository

import com.feedapp.app.data.repositories.RecipeSearchRepository
35
import com.feedapp.app.data.repositories.UserRepository

import kotlinx.coroutines.Dispatchers.IO

import kotlinx.coroutines.launch

import javax.inject.Inject

class DetailedRecipeViewModel @Inject constructor(

private val recipeSearchRepository: RecipeSearchRepository,

userRepository: UserRepository,

private val dayRepository: DayRepository,

private val recipesDetailsCalculator: RecipesDetailsCalculator

):

ViewModel() {

val user: LiveData<User?> = userRepository.user

val mealTypePosition = MutableLiveData(0)

val isSearching: LiveData<Boolean> = recipeSearchRepository.isSearching

val recipeDetailed = recipeSearchRepository.recipeDetailed

init
{ mealTypePosition.postValue(recipesDetailsCalculator.getMealTypeByCurrent
Time().code) }

fun searchDetailedInfo(id: Int) = recipeSearchRepository.searchDetails(id)

fun observeRecipesDetailed() =
recipeSearchRepository.observeRecipesDetailed()

fun checkCredits(credits: String?, sourceName: String?, sourceUrl: String?) =

recipeSearchRepository.checkCredits(credits, sourceName, sourceUrl)

35
fun getDailyPercentage(type: BasicNutrientType): Pair<Int, Int> {

return user.value?.let {

val amount = recipeDetailed.value?.nutrition?.getAmountByNutrient(type)

recipesDetailsCalculator.getDailyPercentage(type, it, amount)

} ?: Pair(0, 0) }

// save recipe as consumed product

fun trackRecipe(servings: Int?, mealType: Int?) =

viewModelScope.launch(IO) {

recipeDetailed.value?.let {

dayRepository.saveRecipeToDay(

it,

servings ?: 1,

mealType ?: 0

) } }

fun isServingsCorrect(servings: String): Boolean =

recipesDetailsCalculator.checkServingsAmount(servings)

fun getDropDownInitialText() =

recipesDetailsCalculator.getDropDownInitialText(mealTypePosition.value)

fun startSearching() {

recipeSearchRepository.startSearching()

35
35
2.5. Add Foods Page

import androidx.lifecycle.ViewModel

import androidx.lifecycle.viewModelScope

import com.feedapp.app.data.repositories.FoodRepository

import kotlinx.coroutines.Dispatchers.IO

import kotlinx.coroutines.launch

import javax.inject.Inject

class AddCustomProductViewModel @Inject internal constructor(private val


foodRepository: FoodRepository) :

ViewModel() {

fun exceeds(gramsInOnePortion: Float, nutrient: Float): Boolean =

gramsInOnePortion < nutrient && gramsInOnePortion != 0f

fun getMultiplier(gramsInOnePortion: Float): Float = 100 / gramsInOnePortion

fun getCalories(caloriesInOnePortion: Float, hundredMultiplier: Float) =

foodRepository.getCalories(caloriesInOnePortion, hundredMultiplier)

fun getEnergy(caloriesInHundredGrams: Float) =


foodRepository.getEnergy(caloriesInHundredGrams)

fun saveProduct(

name: String,

energy: Float,

proteinsInHundred: Float,

fatsInHundred: Float,

carbsInHundred: Float,

35
sugar: Float,

sFats: Float,

uFats: Float,

tFats: Float

) = viewModelScope.launch(IO) {

foodRepository.saveProduct(

name, energy, proteinsInHundred, fatsInHundred,

carbsInHundred, sugar, sFats, uFats, tFats ) }}

35
2.6 My Foods Page

import androidx.lifecycle.LiveData

import androidx.lifecycle.MutableLiveData

import androidx.lifecycle.ViewModel

import com.feedapp.app.data.models.FoodProduct

import com.feedapp.app.data.repositories.FoodRepository

import javax.inject.Inject

class MyMealsViewModel @Inject

internal constructor(

private val foodRepository: FoodRepository

) : ViewModel() {

init { // get custom products from room db

foodRepository.getCustomProducts() }

val myProducts: LiveData<ArrayList<FoodProduct>> =


foodRepository.myProducts

val isTextNoMealsVisible = MutableLiveData(false)

val isProgressBarVisible = MutableLiveData(true)

fun deleteCustomProduct(

foodProduct: FoodProduct

){

foodRepository.deleteProduct(foodProduct)

} fun refreshCustomProducts() {

foodRepository.updateProducts() }

35
fun isProductsEmpty(): Boolean {

return myProducts.value != null && myProducts.value!!.isEmpty() } }

2.7 Recipes Page

import android.content.SharedPreferences

import androidx.lifecycle.LiveData

import androidx.lifecycle.viewModelScope

import com.feedapp.app.data.api.models.recipesearch.RecipeSearchModel

import com.feedapp.app.data.models.day.MealType

import com.feedapp.app.data.repositories.RecipeSearchRepository

35
import com.feedapp.app.data.repositories.UserRepository

import com.feedapp.app.util.USER_RECIPES_SEARCHES_MAX

import com.feedapp.app.util.getDayDate

import kotlinx.coroutines.Dispatchers.IO

import kotlinx.coroutines.launch

import java.util.*

import javax.inject.Inject

class RecipeSearchViewModel @Inject constructor(

private val calendar: Calendar,

private val sp: SharedPreferences,

private val recipeSearchRepository: RecipeSearchRepository,

private val userRepository: UserRepository

) : ViewModel() {

val isConnected = MutableLiveData(true)

val isSearching: LiveData<Boolean> = recipeSearchRepository.isSearching

val hasSearched = MutableLiveData(false)

val isRecipesEmpty: LiveData<Boolean> =


recipeSearchRepository.isRecipesEmpty

val searchRecipes: LiveData<RecipeSearchModel> =


recipeSearchRepository.searchRecipes

val recipesBreakfast: LiveData<RecipeSearchModel> =


recipeSearchRepository.recipesBreakfast

val recipesLunch: LiveData<RecipeSearchModel> =


recipeSearchRepository.recipesLunch
35
val recipesSnack: LiveData<RecipeSearchModel> =
recipeSearchRepository.recipesSnack

val recipesDinner: LiveData<RecipeSearchModel> =


recipeSearchRepository.recipesDinner

init { updateIntoleranceAndDiet() }

fun updateIntoleranceAndDiet() =

viewModelScope.launch(IO) {

val user = userRepository.user.value

user?.let {

recipeSearchRepository.updateIntoleranceAndDiet(user.intolerance, user.diet) }

private fun searchRecipeWithType(query: String, mealType: MealType) =

recipeSearchRepository.searchRecipeWithType(query, mealType)

fun areRecipesLimitReached(): Boolean {

val date = calendar.time.getDayDate()

val searchesInDay = sp.getInt(date.toJson(), 1)

date.toJson()?.let { incrementSearches(it, searchesInDay) }

if (searchesInDay <= USER_RECIPES_SEARCHES_MAX) {

return false }

return true }

private fun incrementSearches(date: String, searchesInDay: Int) {

sp.edit().putInt(date, searchesInDay + 1).apply() }

fun searchRecipe(query: String) {

searchStarted()

35
recipeSearchRepository.searchRecipe(query) }

fun loadDefaultRecipes() {

if (isConnected.value == true) {

viewModelScope.launch(IO) {

for (type in MealType.values()) searchRecipeWithType(type.toString(), type)


} } }

private fun searchStarted() {

hasSearched.postValue(true) }

fun isConnected(): Boolean {

return isConnected.value != null && isConnected.value!! } }

35
2.8 Settings Page

import androidx.lifecycle.LiveData

import androidx.lifecycle.MutableLiveData

import androidx.lifecycle.ViewModel

import androidx.lifecycle.viewModelScope

import com.feedapp.app.data.interfaces.BasicOperationCallback

import com.feedapp.app.data.interfaces.UserDeleteCallback

import com.feedapp.app.data.models.BasicNutrientType

import com.feedapp.app.data.models.BasicNutrientType.*

import kotlinx.coroutines.Dispatchers.IO

import kotlinx.coroutines.launch

import java.io.File

import java.io.FileOutputStream

import java.net.URL

import javax.inject.Inject

enum class Operation { SUCCESS, FAILED}

class SettingsViewModel @Inject internal constructor(

private val userRepository: UserRepository,

private val recentDelegate: RecentDelegate

) : ViewModel() { val status = MutableLiveData(DataResponseStatus.NONE)

var user: LiveData<User?> = userRepository.user

private val _toastDatabase = MutableLiveData<Event<Operation>>()

35
val toastDatabase: LiveData<Event<Operation>> get() = _toastDatabase

private val toastDelete = MutableLiveData<Event<UserDeleteOperation>>()

private val firebaseReauth = MutableLiveData<Event<Boolean>>()

val toast: LiveData<Event<UserDeleteOperation>> get() = toastDelete

val reauth: LiveData<Event<Boolean>> get() = firebaseReauth

fun saveNewValue(newValueToSave: String, type: BasicNutrientType) =

viewModelScope.launch(IO) { user.value?.let {

val callback = object : BasicOperationCallback {

override fun onSuccess() {

status.postValue(DataResponseStatus.SUCCESS) }

override fun onFailure() {

status.postValue(DataResponseStatus.FAILED)

} }
userRepository.updateNutrient(newValueToSave, type, callback)

} }

fun saveMeasure(metric: Boolean) = viewModelScope.launch(IO) {

userRepository.saveMeasure(metric)

status.postValue(DataResponseStatus.SUCCESS) }

fun deleteAllData(listener: UserDeleteCallback) = viewModelScope.launch(IO)


{ try {

userRepository.deleteFirebaseAccount(object :

UserDeleteCallback { override fun onDeletionSuccess() {

listener.onDeletionSuccess() }

35
override fun onDeletionError() {

listener.onDeletionError()

toastDeletion(UserDeleteOperation.FAILED) }

override fun reauthRequired() {

toastDeletion(UserDeleteOperation.REAUTH)

firebaseReauth(true) } })

} catch (e: Exception) {

e.printStackTrace()

toastDeletion(UserDeleteOperation.FAILED) } }

private fun toastDeletion(itemId: UserDeleteOperation) {

toastDelete.value = Event(itemId) }

private fun firebaseReauth(itemId: Boolean) {

firebaseReauth.value = Event(itemId) }

fun saveIntolerance(intoleranceList: List<String>) {

viewModelScope.launch(IO) {

userRepository.saveIntolerance(intoleranceList)

status.postValue(DataResponseStatus.SUCCESS) } }

fun saveDiet(dietList: List<String>) {

viewModelScope.launch(IO) {

userRepository.saveDiet(dietList)

status.postValue(DataResponseStatus.SUCCESS) } }

35
fun deleteRecentProducts() = viewModelScope.launch(IO) {

recentDelegate.deleteRecentProducts() }

fun getNutrientValue(nutrient: BasicNutrientType): String {

return when (nutrient) {

PROTEINS -> user.value?.proteinsNeeded.toString()

FATS -> user.value?.fatsNeeded.toString()

CARBS -> user.value?.carbsNeeded.toString()

CALORIES -> user.value?.caloriesNeeded.toString() } }

fun downloadDatabase(

filePath: String,

code: String,

listener: BasicOperationCallback

) = viewModelScope.launch(IO) {

fun download(link: String, path: String) {

try { URL(link).openStream().use { input ->

FileOutputStream(File(path)).use { output ->

input.copyTo(output)

_toastDatabase.postValue(Event(Operation.SUCCESS)) } }

} catch (e: Exception) {

e.printStackTrace()

_toastDatabase.postValue(Event(Operation.FAILED))

listener.onFailure() } }

LocalDBUrls.getURLByCode(code)?.let { download(it, filePath) } }}


35
35
Conclusion

Nowadays everyone are increasingly in control over the decisions that


influence their health and wellness, and the practices they learn all through
childhood and young adulthood can bear on into their adult lives. So we present to
you a system that lets know and keep educated about the food you have devoured
throughout the day and help you in sifting the fats, carbs and protein admissions
for the same. When you go to a specialist of nutirician, at that point she
will ask you your own subtle elements identified with body and wellbeing,
for example, your age, your tallness, your weight the system here goes about
as a nutritionist. The system ascertains your calorie and eating routine,

likewise creates BMI in light of gave points of interest and afterward the
AI (Artificial Intelligence) expert will likewise counsel you about what should
your admission in your eating regimen and what should you overlook so as to keep
yourself solid by means of your eating routine.

The system demonstrates you the eating regimen you overwhelmed by a graphical
portrayal of the aggregate calories and aggregate amount of utilization. The
client is permitted to check his past eating routine propensities by choosing
the coveted date. The most imperative module which has the AI working
behind leads the client what nourishment should he or she expend dealing with his
BMI and right now devoured things, giving the yields which are extremely exact
and solid.

35
REFERENCES

1. Gurbanguly Berdimuhamedov Book I "Ösüşiň täze belentliklerine tarap "


Ashgabat, 2008
2. Gurbanguly Berdimuhamedov Book II "Ösüşiň täze belentliklerine tarap"
Ashgabat, 2009
3. Gurbanguly Berdimuhamedov "Garaşsyzlyga guwanmak, halky, watany
söýmek bagtdyr." Ashgabat, 2007
4. Gurbanguly Berdimuhamedov. "Türkmenistanyň durmuş-ykdysady ösüşiniň
döwlet kadalaşdyrylyşy ". Curriculum for undergraduate students. Volume I.
Turkmen State Publishing House, Ashgabat, 2010
5. C. Horstmann, Big Java Late Objects, Wiley, 2013. https://library.ohio-
state.edu/record=b7175998~S7
6. J. Bloch, Effective Java, 3rd ed., Addison–Wesley, 2018.
https://library.ohio-
7. 7state.edu/record=b8555335~S7
8. R. Gallardo, S. Hommel, S. Kannan, J. Gordon, and S.B. Zakhour, The Java
Tutorial: A Short Course on the Basics, Addison-Wesley, 6th ed., 2015.
https://library.ohio-state.edu/record=b8554781~S7
9. C. Collins, M. Galpin, and M. Kaeppler, Android in Practice, Manning,
2011. https://library.ohio-state.edu/record=b8534164~S7M.L. Sichitiu,
2011,
http://www.ece.ncsu.edu/wireless/MadeInWALAN/AndroidTutorial/PPTs/
10.javaReview.ppt
11. Oracle, https://docs.oracle.com/javase/8/docs/api/index.html

35

You might also like