Skip to content
This repository was archived by the owner on Jan 10, 2025. It is now read-only.

First commit for DonutTracker app, a sample for the MAD Skills #910

Merged
merged 8 commits into from
Oct 14, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
8 changes: 8 additions & 0 deletions MADSkillsNavigationSample/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
111 changes: 111 additions & 0 deletions MADSkillsNavigationSample/app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "androidx.navigation.safeargs.kotlin"
apply plugin: 'kotlin-kapt'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"

buildFeatures {
viewBinding = true
}

defaultConfig {
applicationId "com.android.samples.navdonutcreator"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

// To inline the bytecode built with JVM target 1.8 into
// bytecode that is being built with JVM target 1.6. (e.g. navArgs)


compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}

packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
}

configurations {
ktlint
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

implementation 'androidx.fragment:fragment-ktx:1.2.5'

implementation "androidx.lifecycle:lifecycle-livedata-core-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"

implementation "androidx.room:room-runtime:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"

api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"

ktlint "com.pinterest:ktlint:0.37.2"
}


// Disable the 'paren-spacing' rule which conflicts with non-paren annotations on functional types
task ktlint(type: JavaExec, group: "verification") {
description = "Check Kotlin code style."
main = "com.pinterest.ktlint.Main"
classpath = configurations.ktlint
args "src/**/*.kt", "--disabled_rules", "paren-spacing"
}
check.dependsOn ktlint
task ktlintFormat(type: JavaExec, group: "formatting") {
description = "Fix Kotlin code style deviations."
main = "com.pinterest.ktlint.Main"
classpath = configurations.ktlint
args "-F", "src/**/*.kt", "--disabled_rules", "paren-spacing"
}
21 changes: 21 additions & 0 deletions MADSkillsNavigationSample/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# 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
43 changes: 43 additions & 0 deletions MADSkillsNavigationSample/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2020 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.samples.donuttracker">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.android.samples.donuttracker.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<nav-graph android:value="@navigation/nav_graph" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.donuttracker

import androidx.room.Entity
import androidx.room.PrimaryKey

/**
* This class holds the data that we are tracking for each donut: its name, a description, and
* a rating.
*/
@Entity
data class Donut(
@PrimaryKey(autoGenerate = true) val id: Long,
val name: String,
val description: String = "",
val rating: Int
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.donuttracker

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.android.samples.donuttracker.databinding.DonutEntryDialogBinding
import com.android.samples.donuttracker.storage.DonutDatabase
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

/**
* This dialog allows the user to enter information about a donut, either creating a new
* entry or updating an existing one.
*/
class DonutEntryDialogFragment : BottomSheetDialogFragment() {

private lateinit var donutEntryViewModel: DonutEntryViewModel

private enum class EditingState {
NEW_DONUT,
EXISTING_DONUT
}

@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val donutDao = DonutDatabase.getDatabase(requireContext()).donutDao()

donutEntryViewModel = ViewModelProvider(this, ViewModelFactory(donutDao))
.get(DonutEntryViewModel::class.java)

val binding = DonutEntryDialogBinding.bind(view)

var donut: Donut? = null
val args: DonutEntryDialogFragmentArgs by navArgs()
val editingState =
if (args.itemId > 0) EditingState.EXISTING_DONUT
else EditingState.NEW_DONUT

// If we arrived here with an itemId of >= 0, then we are editing an existing item
if (editingState == EditingState.EXISTING_DONUT) {
// Request to edit an existing item, whose id was passed in as an argument.
// Retrieve that item and populate the UI with its details
donutEntryViewModel.get(args.itemId).observe(viewLifecycleOwner) { donutItem ->
binding.name.setText(donutItem.name)
binding.description.setText(donutItem.description)
binding.ratingBar.rating = donutItem.rating.toFloat()
donut = donutItem
}
}

// When the user clicks the Done button, use the data here to either update
// an existing item or create a new one
binding.doneButton.setOnClickListener {
// Grab these now since the Fragment may go away before the setupNotification
// lambda below is called
val context = requireContext().applicationContext
val navController = findNavController()

donutEntryViewModel.addData(
donut?.id ?: 0,
binding.name.text.toString(),
binding.description.text.toString(),
binding.ratingBar.rating.toInt()
) { actualId ->
val arg = DonutEntryDialogFragmentArgs(actualId).toBundle()
val pendingIntent = navController
.createDeepLink()
.setDestination(R.id.donutEntryDialogFragment)
.setArguments(arg)
.createPendingIntent()

Notifier.postNotification(actualId, context, pendingIntent)
}
dismiss()
}

// User clicked the Cancel button; just exit the dialog without saving the data
binding.cancelButton.setOnClickListener {
dismiss()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return DonutEntryDialogBinding.inflate(inflater, container, false).root
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.samples.donuttracker

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.android.samples.donuttracker.storage.DonutDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class DonutEntryViewModel(private val donutDao: DonutDao) : ViewModel() {

private var donutLiveData: LiveData<Donut>? = null

fun get(id: Long): LiveData<Donut> {
return donutLiveData ?: liveData {
emit(donutDao.get(id))
}.also {
donutLiveData = it
}
}

fun addData(
id: Long,
name: String,
description: String,
rating: Int,
setupNotification: (Long) -> Unit
) {
val donut = Donut(id, name, description, rating)

CoroutineScope(Dispatchers.Main.immediate).launch {
var actualId = id

if (id > 0) {
update(donut)
} else {
actualId = insert(donut)
}

setupNotification(actualId)
}
}

private suspend fun insert(donut: Donut): Long {
return donutDao.insert(donut)
}

private fun update(donut: Donut) = viewModelScope.launch(Dispatchers.IO) {
donutDao.update(donut)
}
}
Loading