content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model data class User( val id: String = "", val isAnonymous: Boolean = true )
Make-It-So/start/app/src/main/java/com/example/makeitso/model/User.kt
1403811906
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model import com.google.firebase.firestore.DocumentId data class Task( @DocumentId val id: String = "", val title: String = "", val priority: String = "", val dueDate: String = "", val dueTime: String = "", val description: String = "", val url: String = "", val flag: Boolean = false, val completed: Boolean = false, val userId: String = "" )
Make-It-So/start/app/src/main/java/com/example/makeitso/model/Task.kt
2245931431
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service import com.example.makeitso.model.User import kotlinx.coroutines.flow.Flow interface AccountService { val currentUserId: String val hasUser: Boolean val currentUser: Flow<User> suspend fun authenticate(email: String, password: String) suspend fun sendRecoveryEmail(email: String) suspend fun createAnonymousAccount() suspend fun linkAccount(email: String, password: String) suspend fun deleteAccount() suspend fun signOut() }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/AccountService.kt
3798216034
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.impl import com.example.makeitso.BuildConfig import com.example.makeitso.R.xml as AppConfig import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.trace import com.google.firebase.Firebase import com.google.firebase.remoteconfig.get import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.remoteConfigSettings import javax.inject.Inject import kotlinx.coroutines.tasks.await class ConfigurationServiceImpl @Inject constructor() : ConfigurationService { private val remoteConfig get() = Firebase.remoteConfig init { if (BuildConfig.DEBUG) { val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 0 } remoteConfig.setConfigSettingsAsync(configSettings) } remoteConfig.setDefaultsAsync(AppConfig.remote_config_defaults) } override suspend fun fetchConfiguration(): Boolean { return remoteConfig.fetchAndActivate().await() } override val isShowTaskEditButtonConfig: Boolean get() = remoteConfig[SHOW_TASK_EDIT_BUTTON_KEY].asBoolean() companion object { private const val SHOW_TASK_EDIT_BUTTON_KEY = "show_task_edit_button" private const val FETCH_CONFIG_TRACE = "fetchConfig" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/ConfigurationServiceImpl.kt
3212164902
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.impl import com.example.makeitso.model.service.LogService import com.google.firebase.crashlytics.crashlytics import com.google.firebase.Firebase import javax.inject.Inject class LogServiceImpl @Inject constructor() : LogService { override fun logNonFatalCrash(throwable: Throwable) = Firebase.crashlytics.recordException(throwable) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/LogServiceImpl.kt
2708706399
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.impl import com.example.makeitso.model.Task import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.StorageService import com.example.makeitso.model.service.trace import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.dataObjects import com.google.firebase.firestore.toObject import kotlinx.coroutines.ExperimentalCoroutinesApi import javax.inject.Inject import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.tasks.await class StorageServiceImpl @Inject constructor(private val firestore: FirebaseFirestore, private val auth: AccountService) : StorageService { @OptIn(ExperimentalCoroutinesApi::class) override val tasks: Flow<List<Task>> get() = auth.currentUser.flatMapLatest { user -> firestore.collection(TASK_COLLECTION).whereEqualTo(USER_ID_FIELD, user.id).dataObjects() } override suspend fun getTask(taskId: String): Task? = firestore.collection(TASK_COLLECTION).document(taskId).get().await().toObject() override suspend fun save(task: Task): String = trace(SAVE_TASK_TRACE) { val taskWithUserId = task.copy(userId = auth.currentUserId) firestore.collection(TASK_COLLECTION).add(taskWithUserId).await().id } override suspend fun update(task: Task): Unit = trace(UPDATE_TASK_TRACE) { firestore.collection(TASK_COLLECTION).document(task.id).set(task).await() } override suspend fun delete(taskId: String) { firestore.collection(TASK_COLLECTION).document(taskId).delete().await() } companion object { private const val USER_ID_FIELD = "userId" private const val TASK_COLLECTION = "tasks" private const val SAVE_TASK_TRACE = "saveTask" private const val UPDATE_TASK_TRACE = "updateTask" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/StorageServiceImpl.kt
1482793090
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.impl import com.example.makeitso.model.User import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.trace import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth import javax.inject.Inject import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await class AccountServiceImpl @Inject constructor(private val auth: FirebaseAuth) : AccountService { override val currentUserId: String get() = auth.currentUser?.uid.orEmpty() override val hasUser: Boolean get() = auth.currentUser != null override val currentUser: Flow<User> get() = callbackFlow { val listener = FirebaseAuth.AuthStateListener { auth -> this.trySend(auth.currentUser?.let { User(it.uid, it.isAnonymous) } ?: User()) } auth.addAuthStateListener(listener) awaitClose { auth.removeAuthStateListener(listener) } } override suspend fun authenticate(email: String, password: String) { auth.signInWithEmailAndPassword(email, password).await() } override suspend fun sendRecoveryEmail(email: String) { auth.sendPasswordResetEmail(email).await() } override suspend fun createAnonymousAccount() { auth.signInAnonymously().await() } override suspend fun linkAccount(email: String, password: String): Unit = trace(LINK_ACCOUNT_TRACE) { val credential = EmailAuthProvider.getCredential(email, password) auth.currentUser!!.linkWithCredential(credential).await() } override suspend fun deleteAccount() { auth.currentUser!!.delete().await() } override suspend fun signOut() { if (auth.currentUser!!.isAnonymous) { auth.currentUser!!.delete() } auth.signOut() // Sign the user back in anonymously. createAnonymousAccount() } companion object { private const val LINK_ACCOUNT_TRACE = "linkAccount" } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/impl/AccountServiceImpl.kt
2549228533
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service import com.example.makeitso.model.Task import kotlinx.coroutines.flow.Flow interface StorageService { val tasks: Flow<List<Task>> suspend fun getTask(taskId: String): Task? suspend fun save(task: Task): String suspend fun update(task: Task) suspend fun delete(taskId: String) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/StorageService.kt
3776703124
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service interface LogService { fun logNonFatalCrash(throwable: Throwable) }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/LogService.kt
1169723534
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.module import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.firestore import com.google.firebase.Firebase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object FirebaseModule { @Provides fun auth(): FirebaseAuth = Firebase.auth @Provides fun firestore(): FirebaseFirestore = Firebase.firestore }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/module/FirebaseModule.kt
126683842
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service.module import com.example.makeitso.model.service.AccountService import com.example.makeitso.model.service.ConfigurationService import com.example.makeitso.model.service.LogService import com.example.makeitso.model.service.StorageService import com.example.makeitso.model.service.impl.AccountServiceImpl import com.example.makeitso.model.service.impl.ConfigurationServiceImpl import com.example.makeitso.model.service.impl.LogServiceImpl import com.example.makeitso.model.service.impl.StorageServiceImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class ServiceModule { @Binds abstract fun provideAccountService(impl: AccountServiceImpl): AccountService @Binds abstract fun provideLogService(impl: LogServiceImpl): LogService @Binds abstract fun provideStorageService(impl: StorageServiceImpl): StorageService @Binds abstract fun provideConfigurationService(impl: ConfigurationServiceImpl): ConfigurationService }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/module/ServiceModule.kt
4097149919
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service interface ConfigurationService { suspend fun fetchConfiguration(): Boolean val isShowTaskEditButtonConfig: Boolean }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/ConfigurationService.kt
2660525166
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model.service import com.google.firebase.perf.trace import com.google.firebase.perf.metrics.Trace /** * Trace a block with Firebase performance. * * Supports both suspend and regular methods. */ inline fun <T> trace(name: String, block: Trace.() -> T): T = Trace.create(name).trace(block)
Make-It-So/start/app/src/main/java/com/example/makeitso/model/service/Performance.kt
4004830988
/* Copyright 2022 Google LLC 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 https://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.example.makeitso.model enum class Priority { None, Low, Medium, High; companion object { fun getByName(name: String?): Priority { values().forEach { priority -> if (name == priority.name) return priority } return None } fun getOptions(): List<String> { val options = mutableListOf<String>() values().forEach { priority -> options.add(priority.name) } return options } } }
Make-It-So/start/app/src/main/java/com/example/makeitso/model/Priority.kt
2868633218
package com.example.pempekarridho import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.pempekarridho", appContext.packageName) } }
pempek_arridho/app/src/androidTest/java/com/example/pempekarridho/ExampleInstrumentedTest.kt
2780013099
package com.example.pempekarridho import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
pempek_arridho/app/src/test/java/com/example/pempekarridho/ExampleUnitTest.kt
430766860
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class MainActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val btnClick: Button = findViewById(R.id.myButton) btnClick.setOnClickListener(this) } override fun onClick(v: View?) { if (v !=null) { when(v.id){ R.id.myButton -> { val pindahIntent = Intent(this, LoginPageActivity::class.java) startActivity(pindahIntent) } } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/MainActivity.kt
1252855650
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class firstpage2 : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_firstpage2) val btnClick = findViewById<Button>(R.id.fpButton2) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.fpButton2 -> { val heIntent = Intent(this, BerandaActivity::class.java) startActivity(heIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/firstpage2.kt
1399321558
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class SelamatActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_selamat) val btnClick = findViewById<Button>(R.id.myButton4) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton4 -> { val hiIntent = Intent(this, firstpage1::class.java) startActivity(hiIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/SelamatActivity.kt
737736961
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class firstpage1 : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_firstpage1) val btnClick = findViewById<Button>(R.id.myButton2) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton2 -> { val hiIntent = Intent(this, firstpage2::class.java) startActivity(hiIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/firstpage1.kt
704176085
package com.example.pempekarridho import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class BerandaActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_beranda) } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/BerandaActivity.kt
2562729939
package com.example.pempekarridho import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button class LoginPageActivity : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_page) val btnClick = findViewById<Button>(R.id.myButton1) btnClick.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.myButton1 -> { val hiIntent = Intent(this, SelamatActivity::class.java) startActivity(hiIntent) } } } }
pempek_arridho/app/src/main/java/com/example/pempekarridho/LoginPageActivity.kt
2674885604
package com.example.mynavigation import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.mynavigation", appContext.packageName) } }
MyNavigation/app/src/androidTest/java/com/example/mynavigation/ExampleInstrumentedTest.kt
3151358782
package com.example.mynavigation import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MyNavigation/app/src/test/java/com/example/mynavigation/ExampleUnitTest.kt
3044056294
package com.example.mynavigation import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.navigation.NavigationView class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration : AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar)) val navHostFragment = supportFragmentManager. findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController //Creating top level destinations //and adding them to the draw appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_recent, R.id.nav_favorites, R.id.nav_archive, R.id.nav_bin), findViewById(R.id.drawer_layout) ) setupActionBarWithNavController(navController, appBarConfiguration) findViewById<NavigationView>(R.id.nav_view)?.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
MyNavigation/app/src/main/java/com/example/mynavigation/MainActivity.kt
4038538502
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [RecentFragment.newInstance] factory method to * create an instance of this fragment. */ class RecentFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_recent, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment RecentFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = RecentFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/RecentFragment.kt
2331578904
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [SettingsFragment.newInstance] factory method to * create an instance of this fragment. */ class SettingsFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_settings, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SettingsFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = SettingsFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/SettingsFragment.kt
3791677257
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ArchiveFragment.newInstance] factory method to * create an instance of this fragment. */ class ArchiveFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_archive, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ArchiveFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ArchiveFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/ArchiveFragment.kt
2062754989
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.navigation.Navigation class HomeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home , container, false) view.findViewById<Button>(R.id.button_home)?.setOnClickListener ( Navigation.createNavigateOnClickListener(R.id.nav_home_to_content, null) ) return view } }
MyNavigation/app/src/main/java/com/example/mynavigation/HomeFragment.kt
2720406254
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [BinFragment.newInstance] factory method to * create an instance of this fragment. */ class BinFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_bin, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BinFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = BinFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/BinFragment.kt
706842281
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [FavoritesFragment.newInstance] factory method to * create an instance of this fragment. */ class FavoritesFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_favorites, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FavoritesFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = FavoritesFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/FavoritesFragment.kt
2934125883
package com.example.mynavigation import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [ContentFragment.newInstance] factory method to * create an instance of this fragment. */ class ContentFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_content, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment ContentFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = ContentFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
MyNavigation/app/src/main/java/com/example/mynavigation/ContentFragment.kt
1501119856
package com.example.hw4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.hw4", appContext.packageName) } }
hw4_m5/app/src/androidTest/java/com/example/hw4/ExampleInstrumentedTest.kt
1788569846
package com.example.hw4 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
hw4_m5/app/src/test/java/com/example/hw4/ExampleUnitTest.kt
2430224473
package com.example.hw4 data class OnBoardingModel( val title: String? = null, val desc: String? = null, val lottieAnim: Int? = null )
hw4_m5/app/src/main/java/com/example/hw4/OnBoardingModel.kt
2145399994
package com.example.hw4 import android.app.Application import androidx.room.Room import com.example.hw4.data.room.AppDatabase import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject @HiltAndroidApp class App : Application() { companion object { lateinit var appDatabase: AppDatabase } override fun onCreate() { super.onCreate() appDatabase = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build() } /*Room.databaseBuilder(applicationContext, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build()*/ }
hw4_m5/app/src/main/java/com/example/hw4/App.kt
2272700485
package com.example.hw4 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.viewModels import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.Navigation.findNavController import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import com.example.hw4.data.local.Pref import com.example.hw4.databinding.ActivityMainBinding import com.example.hw4.remote.LoveModel import com.example.hw4.remote.RetrofitService import dagger.hilt.android.AndroidEntryPoint import retrofit2.Call import retrofit2.Callback import retrofit2.Response import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var pref: Pref private lateinit var binding: ActivityMainBinding private var navController: NavController? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController if (!pref.isShow()) { navController?.navigate(R.id.onBoardingFragment) } } }
hw4_m5/app/src/main/java/com/example/hw4/MainActivity.kt
1507524381
package com.example.hw4.di import android.content.Context import android.content.SharedPreferences import androidx.room.Room import com.example.hw4.data.local.Pref import com.example.hw4.data.room.AppDatabase import com.example.hw4.data.room.LoveDao import com.example.hw4.remote.LoveApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @InstallIn(SingletonComponent::class) @Module class AppModule { @Provides fun provideApi(): LoveApi { return Retrofit.Builder().baseUrl("https://love-calculator.p.rapidapi.com/") .addConverterFactory(GsonConverterFactory.create()).build().create(LoveApi::class.java) } @Provides fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences { return context.getSharedPreferences(Pref.PREF_NAME, Context.MODE_PRIVATE) } @Provides fun providePref(sharedPreferences: SharedPreferences): Pref { return Pref(sharedPreferences) } @Provides fun provideDatabase(@ApplicationContext context: Context):AppDatabase{ return Room.databaseBuilder(context, AppDatabase::class.java, "love-file") .allowMainThreadQueries().build() } @Provides fun provideDao(appDatabase: AppDatabase):LoveDao{ return appDatabase.getDao() } }
hw4_m5/app/src/main/java/com/example/hw4/di/AppModule.kt
1637101049
package com.example.hw4 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import com.example.hw4.data.room.LoveDao import com.example.hw4.databinding.FragmentHistoryBinding import com.example.hw4.remote.LoveModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class HistoryFragment : Fragment() { @Inject lateinit var dao: LoveDao private val viewModel: LoveViewModel by viewModels() private lateinit var binding: FragmentHistoryBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHistoryBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.getGetDao().observe(viewLifecycleOwner, Observer {loveModelList -> val list = mutableListOf<LoveModel>() loveModelList?.let { list.add(it) } binding.tvListHistory.text =list.joinToString( separator = "\n", transform = { it.toString() }, prefix = "", postfix = "" ) /*list.joinToString(separator = "", prefix = "", postfix = "")*/ }) /* val list = dao.getAll() list.forEach { binding.tvListHistory.text = list.joinToString(separator = "", prefix = "", postfix = "") }*/ } } /* viewModel.getLiveLoveData(etFirstName.text.toString(), etSecondName.text.toString()) .observe(viewLifecycleOwner, Observer { tvResult.text = it.toString() })*/
hw4_m5/app/src/main/java/com/example/hw4/HistoryFragment.kt
341922323
package com.example.hw4.utils import android.content.Context import android.widget.ImageView import android.widget.Toast import androidx.fragment.app.Fragment import com.bumptech.glide.Glide fun Context.showToast(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } fun Fragment.showToast(msg: String){ Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show() } fun ImageView.loadImage(url: String?){ Glide.with(this).load(url).into(this) }
hw4_m5/app/src/main/java/com/example/hw4/utils/Ext.kt
412421294
package com.example.hw4 import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.hw4.data.room.LoveDao import com.example.hw4.remote.LoveApi import com.example.hw4.remote.LoveModel import com.example.hw4.remote.RetrofitService import retrofit2.Call import retrofit2.Callback import retrofit2.Response import javax.inject.Inject class Repository @Inject constructor(private val api: LoveApi, private val dao: LoveDao) { fun getDao(): LiveData<LoveModel>{ return dao.getAll() } fun getData(firstName: String, secondName: String): MutableLiveData<LoveModel> { val love = MutableLiveData<LoveModel>() api.getLove(firstName, secondName).enqueue(object : Callback<LoveModel> { override fun onResponse(call: Call<LoveModel>, response: Response<LoveModel>) { if (response.isSuccessful) { response.body()?.let { love.postValue(it) dao.insert(it) } } } override fun onFailure(call: Call<LoveModel>, t: Throwable) { Log.e("ololo", "onFailure:${t.message}") } }) return love } }
hw4_m5/app/src/main/java/com/example/hw4/Repository.kt
147820358
package com.example.hw4 import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.example.hw4.remote.LoveModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoveViewModel @Inject constructor(private val repository: Repository) : ViewModel() { fun getLiveLoveData(firstName: String, secondName: String): LiveData<LoveModel> { return repository.getData(firstName, secondName) } fun getGetDao(): LiveData<LoveModel>{ return repository.getDao() } }
hw4_m5/app/src/main/java/com/example/hw4/LoveViewModel.kt
829418072
package com.example.hw4 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.findNavController import com.example.hw4.databinding.FragmentHistoryBinding import com.example.hw4.databinding.FragmentMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainFragment : Fragment() { private lateinit var binding : FragmentMainBinding private val viewModel: LoveViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMainBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initClickers() } private fun initClickers() { with(binding) { btnGetLove.setOnClickListener { viewModel.getLiveLoveData(etFirstName.text.toString(), etSecondName.text.toString()) .observe(viewLifecycleOwner, Observer { tvResult.text = it.toString() }) } btnHistory.setOnClickListener { findNavController().navigate(R.id.historyFragment) } } } }
hw4_m5/app/src/main/java/com/example/hw4/MainFragment.kt
1618039045
package com.example.hw4.data.room import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.example.hw4.remote.LoveModel @Dao interface LoveDao { @Insert fun insert(lioveModel: LoveModel) /* ORDER BY fname ASC*/ @Query ("SELECT * FROM `love-table` ORDER BY fname ASC") fun getAll(): LiveData<LoveModel> }
hw4_m5/app/src/main/java/com/example/hw4/data/room/LoveDao.kt
943136451
package com.example.hw4.data.room import androidx.room.Database import androidx.room.RoomDatabase import com.example.hw4.remote.LoveModel @Database(entities = [LoveModel::class], version = 1) abstract class AppDatabase:RoomDatabase() { abstract fun getDao():LoveDao }
hw4_m5/app/src/main/java/com/example/hw4/data/room/AppDatabase.kt
2008963179
package com.example.hw4.data.local import android.content.Context import android.content.SharedPreferences import javax.inject.Inject class Pref @Inject constructor(private val preferences: SharedPreferences) { fun isShow(): Boolean { return preferences.getBoolean(SHOWED_KEY, false) } fun onShowed() { preferences.edit().putBoolean(SHOWED_KEY, true).apply() } companion object { const val PREF_NAME = "pref.name" const val SHOWED_KEY = "showed.key" } }
hw4_m5/app/src/main/java/com/example/hw4/data/local/Pref.kt
3893725485
package com.example.hw4.onboarding.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.airbnb.lottie.LottieDrawable import com.example.hw4.OnBoardingModel import com.example.hw4.R import com.example.hw4.databinding.ItemOnboardingBinding class OnBoardingAdapter(private val onClick: () -> Unit) : RecyclerView.Adapter<OnBoardingAdapter.OnBoardingViewHolder>() { private val list = arrayListOf<OnBoardingModel>( OnBoardingModel( "Have a good time", "You should take the time to help those who need you", R.raw.love2 ), OnBoardingModel( "Cherishing love", "It is no longer possible for you to cherish love", R.raw.love3 ), OnBoardingModel( "Have a breakup?", "We have the correction for you don't worry \n mayby someone is waiting for you!", R.raw.love4 ), OnBoardingModel("It's funs and many more!", "", R.raw.lovekiss) ) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OnBoardingViewHolder { return OnBoardingViewHolder( ItemOnboardingBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int = list.size override fun onBindViewHolder(holder: OnBoardingViewHolder, position: Int) { holder.bind(list[position]) } inner class OnBoardingViewHolder(private val binding: ItemOnboardingBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(onBoarding: OnBoardingModel) = with(binding) { tvTitle.text = onBoarding.title tvDesc.text = onBoarding.desc btnGetStarted.isVisible = adapterPosition == list.lastIndex onBoarding.lottieAnim?.let { ivBoard.setAnimation(onBoarding.lottieAnim) ivBoard.playAnimation() } btnGetStarted.setOnClickListener { onClick() } } } }
hw4_m5/app/src/main/java/com/example/hw4/onboarding/adapter/OnBoardingAdapter.kt
3957033754
package com.example.hw4.onboarding import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.hw4.data.local.Pref import com.example.hw4.databinding.FragmentOnBoardingBinding import com.example.hw4.onboarding.adapter.OnBoardingAdapter import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class OnBoardingFragment : Fragment() { @Inject lateinit var pref: Pref private lateinit var binding: FragmentOnBoardingBinding private val adapter = OnBoardingAdapter(this::onClick) private fun onClick() { pref.onShowed() findNavController().navigateUp() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentOnBoardingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.viewPager.adapter = adapter binding.indicator.setViewPager(binding.viewPager) } }
hw4_m5/app/src/main/java/com/example/hw4/onboarding/OnBoardingFragment.kt
962165509
package com.example.hw4.remote import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory //https://love-calculator.p.rapidapi.com/getPercentage?sname=Alice&fname=John object RetrofitService { val retrofit = Retrofit.Builder().baseUrl("https://love-calculator.p.rapidapi.com/") .addConverterFactory(GsonConverterFactory.create()).build() val api = retrofit.create(LoveApi::class.java) }
hw4_m5/app/src/main/java/com/example/hw4/remote/RetrofitService.kt
2863948930
package com.example.hw4.remote import androidx.room.Entity import androidx.room.PrimaryKey @Entity("love-table") data class LoveModel( val fname: String, val sname: String, val percentage: String, val result: String, @PrimaryKey(autoGenerate = true) var id: Int? = null ){ override fun toString(): String { return "\n$percentage \n$fname \n$sname \n$result\n" } }
hw4_m5/app/src/main/java/com/example/hw4/remote/LoveModel.kt
2939710675
package com.example.hw4.remote import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Query //https://love-calculator.p.rapidapi.com/getPercentage?sname=Alice&fname=John /* .addHeader("X-RapidAPI-Key", "62046210eamshb1039cc3a834d5ep160059jsn329f9fbbe521") .addHeader("X-RapidAPI-Host", "love-calculator.p.rapidapi.com")*/ interface LoveApi { @GET("getPercentage") fun getLove(@Query("sname")secondName:String,@Query("fname")firstName:String, @Header("X-RapidAPI-Key")key:String ="62046210eamshb1039cc3a834d5ep160059jsn329f9fbbe521", @Header("X-RapidAPI-Host")host: String="love-calculator.p.rapidapi.com"): Call<LoveModel> }
hw4_m5/app/src/main/java/com/example/hw4/remote/LoveApi.kt
2199092021
package com.theminesec.example.headless.util const val TAG = "ClientApp"
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/util/Constant.kt
2764580886
package com.theminesec.example.headless import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.model.transaction.Amount import com.theminesec.sdk.headless.model.transaction.PaymentMethod import com.theminesec.sdk.headless.ui.ThemeProvider import com.theminesec.sdk.headless.ui.UiProvider import com.theminesec.sdk.headless.ui.UiState class ClientHeadlessImpl : HeadlessActivity() { override fun provideTheme(): ThemeProvider = ClientHeadlessThemeProvider() override fun provideUi(): UiProvider = ClientUiProvider() } class ClientHeadlessThemeProvider : ThemeProvider() { override fun provideColors(darkTheme: Boolean): HeadlessColors { return if (darkTheme) { HeadlessColorsDark().copy( primary = Color(0xFFD5A23B).toArgb() ) } else { HeadlessColorsLight().copy( primary = Color(0xFFFFC145).toArgb() ) } } } class ClientUiProvider : UiProvider() { @Composable override fun AmountDisplay(amount: Amount, description: String?) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.AmountDisplay(amount, description) } } @Composable override fun AcceptanceMarkDisplay(supportedPayments: List<PaymentMethod>, showWallet: Boolean) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.AcceptanceMarkDisplay(supportedPayments, true) } } @Composable override fun AwaitCardIndicator() { Box( modifier = Modifier .fillMaxSize() .border(1.dp, Color.Red), ) { super.AwaitCardIndicator() } } @Composable override fun ProgressIndicator() { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.ProgressIndicator() } } @Composable override fun UiStateDisplay(modifier: Modifier, uiState: UiState, countdownSec: Int) { Box( modifier = Modifier.border(1.dp, Color.Red), contentAlignment = Alignment.Center ) { super.UiStateDisplay(modifier, uiState, countdownSec) } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientHeadlessImpl.kt
467447061
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, content: @Composable RowScope.() -> Unit, ) { Button( modifier = modifier .fillMaxWidth() .defaultMinSize(minHeight = 48.dp, minWidth = 72.dp), onClick = onClick, enabled = enabled, colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary, ), shape = RoundedCornerShape(size = 8.dp), content = content ) }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/Button.kt
3663776092
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Composable fun ObjectDisplay(text: String) { val formatter = remember { DateTimeFormatter.ofPattern("HH:mm:ss.SSS") } Row { Text( style = MaterialTheme.typography.labelSmall, color = Color(0xff28fe14), text = formatter.format(LocalDateTime.now()), modifier = Modifier.padding(end = 8.dp) ) Text( style = MaterialTheme.typography.labelSmall, color = Color(0xff28fe14), text = text ) } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/ObjectDisplay.kt
4280435690
package com.theminesec.example.headless.exampleHelper.component import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.theminesec.example.headless.R @Composable fun SplitSection( upperContent: @Composable () -> Unit, lowerContent: @Composable () -> Unit, ) { val density = LocalDensity.current.density val screenHeight = LocalConfiguration.current.screenHeightDp var upperColumnHeight by remember { // initial 600.dp.value * screen density mutableFloatStateOf(600 * density) } var isDragging by remember { mutableStateOf(false) } val dragState = rememberDraggableState { delta -> upperColumnHeight = (upperColumnHeight + delta) .coerceAtLeast(100 * density) .coerceAtMost((screenHeight - 100) * density) } Column(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .height((upperColumnHeight / density).dp) .padding(horizontal = 16.dp) .verticalScroll(rememberScrollState()), ) { Spacer(modifier = Modifier.height(16.dp)) Text(text = stringResource(id = R.string.app_name), style = MaterialTheme.typography.headlineMedium) Spacer(modifier = Modifier.height(16.dp)) upperContent() Spacer(modifier = Modifier.height(16.dp)) } Box( modifier = Modifier .fillMaxWidth() .background(Color.White.copy(if (isDragging) 0.3f else 0.1f)) .padding(8.dp) .draggable( orientation = Orientation.Vertical, state = dragState, onDragStarted = { isDragging = true }, onDragStopped = { isDragging = false } ), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .width(72.dp) .height(6.dp) .background(Color.White.copy(alpha = 0.4f), RoundedCornerShape(8.dp)) ) } Column( modifier = Modifier.fillMaxSize() ) { lowerContent() } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/component/SplitSection.kt
1296104619
package com.theminesec.example.headless.exampleHelper import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.theminesec.example.headless.exampleHelper.component.ObjectDisplay import com.theminesec.example.headless.exampleHelper.component.SplitSection import com.theminesec.example.headless.exampleHelper.theme.MsExampleTheme @Composable fun HelperLayout( content: @Composable ColumnScope.() -> Unit, ) { MsExampleTheme { val viewModel: HelperViewModel = viewModel() val messages by viewModel.messages.collectAsState() val lazyListState = rememberLazyListState() val snackbarHostState = remember { SnackbarHostState() } val localFocusManager = LocalFocusManager.current // scroll to bottom when new message comes in LaunchedEffect(messages) { lazyListState.animateScrollToItem((messages.size - 1).coerceAtLeast(0)) } Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Scaffold( modifier = Modifier.fillMaxSize(), snackbarHost = { SnackbarHost(snackbarHostState) } ) { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding) .pointerInput(Unit) { detectTapGestures(onTap = { localFocusManager.clearFocus() }) }, ) { SplitSection( upperContent = { Column( verticalArrangement = Arrangement.spacedBy(16.dp) ) { content() } }, lowerContent = { Box(modifier = Modifier.fillMaxSize()) { LazyColumn( state = lazyListState, modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues( start = 16.dp, top = 56.dp, end = 16.dp, bottom = 16.dp ) ) { items(messages) { msg -> ObjectDisplay(msg) } } Button( onClick = { viewModel.clearLog() }, modifier = Modifier .align(Alignment.TopEnd) .defaultMinSize(minHeight = 40.dp, minWidth = 64.dp) .padding(8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = MaterialTheme.colorScheme.background.copy(0.6f), contentColor = Color.White.copy(0.8f) ), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.4f)), shape = RoundedCornerShape(8.dp) ) { Text(text = "Clear") } } } ) } } } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/HelperLayout.kt
1401251652
package com.theminesec.example.headless.exampleHelper.theme import android.app.Activity import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView val ShamrockGreen = Color(0xff2BD659) val SlateGray = Color(0xff64748b) val CatalinaBlue = Color(0xff101A2D) @Composable fun MsExampleTheme(content: @Composable () -> Unit) { val colorScheme = darkColorScheme( primary = ShamrockGreen, onPrimary = CatalinaBlue, secondary = SlateGray, background = CatalinaBlue, onBackground = Color.White ) val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.background.toArgb() } } MaterialTheme( colorScheme = colorScheme, typography = Type, content = content ) }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/theme/Theme.kt
1288871276
package com.theminesec.example.headless.exampleHelper.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.sp import com.theminesec.example.headless.R // Set of Material typography styles to start with private val jetBrainMono = FontFamily( Font(R.font.jbm_medium) ) private val defaultTypography = Typography() val Type = Typography( displayLarge = defaultTypography.displayLarge.copy(fontFamily = jetBrainMono), displayMedium = defaultTypography.displayMedium.copy(fontFamily = jetBrainMono), displaySmall = defaultTypography.displaySmall.copy(fontFamily = jetBrainMono), headlineLarge = defaultTypography.headlineLarge.copy(fontFamily = jetBrainMono), headlineMedium = defaultTypography.headlineMedium.copy(fontFamily = jetBrainMono), headlineSmall = defaultTypography.headlineSmall.copy(fontFamily = jetBrainMono), titleLarge = defaultTypography.titleLarge.copy(fontFamily = jetBrainMono), titleMedium = defaultTypography.titleMedium.copy(fontFamily = jetBrainMono), titleSmall = defaultTypography.titleSmall.copy(fontFamily = jetBrainMono), bodyLarge = defaultTypography.bodyLarge.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), bodyMedium = defaultTypography.bodyMedium.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), bodySmall = defaultTypography.bodySmall.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), labelLarge = defaultTypography.labelLarge.copy(fontFamily = jetBrainMono, fontSize = 12.sp), labelMedium = defaultTypography.labelMedium.copy(fontFamily = jetBrainMono, fontSize = 10.sp), labelSmall = defaultTypography.labelSmall.copy(fontFamily = jetBrainMono, fontSize = 10.sp, lineHeight = 12.sp), )
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/theme/Type.kt
3634738681
package com.theminesec.example.headless.exampleHelper import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.theminesec.example.headless.util.TAG import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import ulid.ULID class HelperViewModel : ViewModel() { // for demo setups private val _messages: MutableStateFlow<List<String>> = MutableStateFlow(emptyList()) val messages: StateFlow<List<String>> = _messages fun writeMessage(message: String) = viewModelScope.launch { val temp = _messages.value .toMutableList() .apply { add("==> $message") } _messages.emit(temp) } fun clearLog() = viewModelScope.launch { _messages.emit(emptyList()) } // demo part var posReference by mutableStateOf(ULID.randomULID()) val currency by mutableStateOf("HKD") var amountStr by mutableStateOf("2") private set fun handleInputAmt(incomingStr: String) { Log.d(TAG, "incoming: $incomingStr") if (incomingStr.length > 12) return if (incomingStr.count { c -> c == '.' } > 1) return incomingStr.split(".").getOrNull(1)?.let { afterDecimal -> if (afterDecimal.length > 2) return } amountStr = incomingStr.filter { c -> c.isDigit() || c == '.' } } fun resetRandomPosReference() { posReference = ULID.randomULID() } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/HelperViewModel.kt
2864784091
package com.theminesec.example.headless import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.* import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.lifecycleScope import com.google.gson.* import com.theminesec.example.headless.exampleHelper.HelperLayout import com.theminesec.example.headless.exampleHelper.HelperViewModel import com.theminesec.example.headless.exampleHelper.component.Button import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.HeadlessService import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.transaction.* import kotlinx.coroutines.launch import java.lang.reflect.Type import java.math.BigDecimal import java.time.Instant import java.util.* class ClientMain : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val viewModel: HelperViewModel by viewModels() var completedSaleTranId: String? by mutableStateOf(null) var completedSalePosReference: String? by mutableStateOf(null) var completedSaleRequestId: String? by mutableStateOf(null) var completedRefundTranId: String? by mutableStateOf(null) val gson = GsonBuilder() .registerTypeAdapter(Instant::class.java, object : JsonSerializer<Instant> { override fun serialize(p0: Instant?, p1: Type?, p2: JsonSerializationContext?): JsonElement = JsonPrimitive(p0?.toString()) }) .setPrettyPrinting().create() val launcher = registerForActivityResult( HeadlessActivity.contract(ClientHeadlessImpl::class.java) ) { viewModel.writeMessage("${it.javaClass.simpleName} \n${gson.toJson(it)}") viewModel.resetRandomPosReference() when (it) { is WrappedResult.Success -> { if (it.value.tranType == TranType.SALE) { completedSaleTranId = it.value.tranId completedSalePosReference = it.value.posReference completedSaleRequestId = it.value.actions.firstOrNull()?.requestId } if (it.value.tranType == TranType.REFUND) { completedRefundTranId = it.value.tranId } } is WrappedResult.Failure -> { viewModel.writeMessage("Failed") } } } setContent { HelperLayout { Button(onClick = { val sdkInitResp = (application as ClientApp).sdkInitResp viewModel.writeMessage("sdkInitResp: $sdkInitResp}") }) { Text(text = "SDK init status") } Button(onClick = { lifecycleScope.launch { val res = HeadlessSetup.initialSetup(this@ClientMain) viewModel.writeMessage("initialSetup: $res") } }) { Text(text = "Initial setups (download Keys)") } HorizontalDivider() Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp) ) { OutlinedTextField( modifier = Modifier.weight(1f), label = { Text(text = "Currency") }, value = viewModel.currency, onValueChange = {}, enabled = false ) OutlinedTextField( modifier = Modifier.weight(1f), label = { Text(text = "Amount") }, value = viewModel.amountStr, onValueChange = viewModel::handleInputAmt, isError = viewModel.amountStr.isEmpty(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) ) } OutlinedTextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = "POS message ID") }, value = viewModel.posReference, onValueChange = { viewModel.posReference = it }, ) TextButton( onClick = { viewModel.resetRandomPosReference() }, modifier = Modifier.fillMaxWidth() ) { Icon(imageVector = Icons.Default.Refresh, contentDescription = null) Spacer(modifier = Modifier.size(4.dp)) Text(text = "Set random POS message ID") } Button(onClick = { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( viewModel.amountStr.toBigDecimal(), Currency.getInstance(viewModel.currency), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = listOf(PaymentMethod.VISA, PaymentMethod.MASTERCARD), description = "description 123", posReference = viewModel.posReference, forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) }) { Text(text = "PoiRequest.ActionNew") } HorizontalDivider() Text(text = "With UI\nActivity result launcher", style = MaterialTheme.typography.titleLarge) Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionVoid(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (full amt)") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it, Amount(BigDecimal("0.5"), Currency.getInstance(viewModel.currency))) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (partial amt)") } Button(onClick = { completedRefundTranId?.let { val action = PoiRequest.ActionVoid(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid (using refund tran id)") } Button(onClick = { completedSaleTranId?.let { val query = PoiRequest.Query(Referencable.TranId(it)) launcher.launch(query) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.Query (TranId)") } Button(onClick = { completedSalePosReference?.let { val query = PoiRequest.Query(Referencable.PosReference(it)) launcher.launch(query) } ?: viewModel.writeMessage("No pos ref") }) { Text(text = "PoiRequest.Query (PosReference)") } Button(onClick = { completedSaleRequestId?.let { val query = PoiRequest.Query(Referencable.RequestId(it)) launcher.launch(query) } ?: viewModel.writeMessage("No poi req id") }) { Text(text = "PoiRequest.Query (RequestId)") } HorizontalDivider() Text(text = "Without UI\nSuspended API", style = MaterialTheme.typography.titleLarge) Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionVoid(it) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (full amt)") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it, Amount(BigDecimal("0.5"), Currency.getInstance(viewModel.currency))) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (partial amt)") } Button(onClick = { completedSaleTranId?.let { val query = Referencable.TranId(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.Query (TranId)") } Button(onClick = { completedSalePosReference?.let { val query = Referencable.PosReference(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No pos ref") }) { Text(text = "PoiRequest.Query (PosReference)") } Button(onClick = { completedSaleRequestId?.let { val query = Referencable.RequestId(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No req id") }) { Text(text = "PoiRequest.Query (RequestId)") } } } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientMain.kt
2697151192
package com.theminesec.example.headless import android.app.Application import android.util.Log import com.theminesec.example.headless.util.TAG import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.setup.SdkInitResp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ClientApp : Application() { private val appScope = CoroutineScope(Dispatchers.Main) var sdkInitResp: WrappedResult<SdkInitResp>? = null private set override fun onCreate() { super.onCreate() appScope.launch { val clientAppInitRes = HeadlessSetup.initSoftPos(this@ClientApp, "public-test.license") Log.d(TAG, "$clientAppInitRes") sdkInitResp = clientAppInitRes } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientApp.kt
1986727748
package com.theminesec.example.headless_xml const val TAG = "HL/ ClientAppXml"
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/Constant.kt
3393612312
package com.theminesec.example.headless_xml import android.annotation.SuppressLint import android.content.ContentResolver import android.content.Context import android.graphics.Color import android.graphics.SurfaceTexture import android.media.MediaPlayer import android.net.Uri import android.util.Log import android.view.LayoutInflater import android.view.Surface import android.view.TextureView import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.LinearLayout.LayoutParams import android.widget.TextView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.DataBindingUtil import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.theminesec.example.headless_xml.databinding.CompAmountDisplayBinding import com.theminesec.example.headless_xml.databinding.CompOrSignatureScreenBinding import com.theminesec.example.headless_xml.databinding.CompOrUiStateDisplayBinding import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.model.transaction.Amount import com.theminesec.sdk.headless.model.transaction.PaymentMethod import com.theminesec.sdk.headless.model.transaction.WalletType import com.theminesec.sdk.headless.ui.* import com.theminesec.sdk.headless.ui.component.SignaturePad import com.theminesec.sdk.headless.ui.component.SignatureState import com.theminesec.sdk.headless.ui.component.resource.getImageRes import kotlinx.coroutines.launch class ClientHeadlessImpl : HeadlessActivity() { override fun provideTheme(): ThemeProvider { return ClientThemeProvider() } private val provider = ClientViewProvider() override fun provideUi(): UiProvider { return UiProvider( amountView = provider, progressIndicatorView = provider, awaitCardIndicatorView = provider, acceptanceMarksView = provider, signatureScreenView = provider, uiStateDisplayView = provider ) } } @SuppressLint("SetTextI18n") class ClientViewProvider : AmountView, ProgressIndicatorView, AwaitCardIndicatorView, AcceptanceMarksView, SignatureScreenView, UiStateDisplayView { private fun Int.intToDp(context: Context): Int = (this * context.resources.displayMetrics.density).toInt() override fun createAmountView(context: Context, amount: Amount, description: String?): View { val inflater = LayoutInflater.from(context) return DataBindingUtil.inflate<CompAmountDisplayBinding>(inflater, R.layout.comp_amount_display, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT ) this.amount = amount.value.toString() this.description = "dummy description" } .root // return LinearLayout(context).apply { // orientation = LinearLayout.VERTICAL // layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) // addView(TextView(context) // .apply { // textSize = 30F // textAlignment = TEXT_ALIGNMENT_CENTER // text = "Total amount here" // }) // addView(TextView(context) // .apply { // textSize = 40F // textAlignment = TEXT_ALIGNMENT_CENTER // text = "${amount.currency.currencyCode}${amount.value}" // }) // } } override fun createAwaitCardIndicatorView(context: Context): View { val mediaPlayer = MediaPlayer() return TextureView(context).apply { surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { val videoUri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(context.packageName) .appendPath("${R.raw.demo_await}") .build() mediaPlayer.apply { setDataSource(context, videoUri) setSurface(Surface(surface)) isLooping = true prepareAsync() setOnPreparedListener { start() } } } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = true override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} } } } override fun createAcceptanceMarksView(context: Context, supportedPayments: List<PaymentMethod>, showWallet: Boolean): View { return LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL val iconLp = LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, ).apply { marginEnd = 16.intToDp(context) } supportedPayments.forEach { pm -> addView(ImageView(context).apply { setImageResource(pm.getImageRes()).apply { layoutParams = iconLp } }) } if (showWallet) { addView(ImageView(context).apply { setImageResource(WalletType.APPLE_PAY.getImageRes()) }) } } } override fun createProgressIndicatorView(context: Context): View { val mediaPlayer = MediaPlayer() return TextureView(context).apply { surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { val videoUri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(context.packageName) .appendPath("${R.raw.demo_processing}") .build() mediaPlayer.apply { setDataSource(context, videoUri) setSurface(Surface(surface)) isLooping = true prepareAsync() setOnPreparedListener { start() } } } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = true override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} } } // return CircularProgressIndicator(context).apply { // layoutParams = LayoutParams( // LayoutParams.MATCH_PARENT, // LayoutParams.MATCH_PARENT // ) // indicatorSize = 200.intToDp(context) // trackThickness = 8.intToDp(context) // isIndeterminate = true // trackColor = Color.TRANSPARENT // setIndicatorColor(Color.parseColor("#FFD503")) // isVisible = true // } } override fun createSignatureView( context: Context, amount: Amount?, maskedAccount: String?, paymentMethod: PaymentMethod?, approvalCode: String?, signatureState: SignatureState, onConfirm: () -> Unit ): View { val inflater = LayoutInflater.from(context) val binding = DataBindingUtil.inflate<CompOrSignatureScreenBinding>(inflater, R.layout.comp_or_signature_screen, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT ) this.amount = amount this.maskedAccount = maskedAccount this.paymentMethod = paymentMethod this.approvalCode = approvalCode } binding.composeViewSignaturePad.apply { setViewCompositionStrategy(ViewCompositionStrategy.Default) setContent { SignaturePad(state = signatureState) } } binding.btnClear.apply { (context as LifecycleOwner).lifecycleScope.launch { signatureState.signatureLines.collect { isEnabled = it.isNotEmpty() } } setOnClickListener { signatureState.clearSignatureLines() } } binding.btnConfirm.apply { (context as LifecycleOwner).lifecycleScope.launch { signatureState.signatureLines.collect { isEnabled = it.isNotEmpty() } } setOnClickListener { onConfirm() } } return binding.root } private var tv: TextView? = null override fun createUiStateDisplayView( context: Context, uiState: UiState, ): View { val inflater = LayoutInflater.from(context) val binding = DataBindingUtil.inflate<CompOrUiStateDisplayBinding>(inflater, R.layout.comp_or_ui_state_display, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT ) } tv = binding.tvCountdown binding.tvTitle.text = context.getString(uiState.getTitleRes()) binding.tvDesc.text = context.getString(uiState.getDescriptionRes()) when (uiState) { is UiState.Awaiting -> { binding.tvCountdown.visibility = View.VISIBLE binding.containerPms.visibility = View.VISIBLE binding.containerPms.addView(createAcceptanceMarksView(context, uiState.supportedPayments, showWallet = true)) } is UiState.Processing -> { binding.tvCountdown.visibility = View.VISIBLE } else -> { binding.tvCountdown.visibility = View.GONE } } return binding.root } override fun onCountdownUpdate(countdownSec: Int) { Log.d(TAG, "xml onCountdownUpdate: $countdownSec") tv?.text = "${countdownSec}s" } } class ClientThemeProvider : ThemeProvider() { override fun provideColors(darkTheme: Boolean): HeadlessColors { return HeadlessColorsLight().copy( primary = Color.parseColor("#FFD503"), foreground = Color.parseColor("#333333"), mutedForeground = Color.parseColor("#4E3C2E") ) } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientHeadlessImpl.kt
1173905042
package com.theminesec.example.headless_xml import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import kotlin.reflect.KProperty class ContentViewBindingDelegate<in R : AppCompatActivity, out T : ViewDataBinding>( @LayoutRes private val layoutRes: Int, ) { private var binding: T? = null operator fun getValue(activity: R, property: KProperty<*>): T { if (binding == null) { binding = DataBindingUtil.setContentView<T>(activity, layoutRes).apply { lifecycleOwner = activity } } return binding!! } } fun <R : AppCompatActivity, T : ViewDataBinding> contentView( @LayoutRes layoutRes: Int, ): ContentViewBindingDelegate<R, T> = ContentViewBindingDelegate(layoutRes)
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ContentViewBindingDelegate.kt
66750436
package com.theminesec.example.headless_xml import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.theminesec.example.headless_xml.databinding.ActivityMainBinding import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.transaction.* import kotlinx.coroutines.launch import ulid.ULID import java.util.* class ClientMain : AppCompatActivity() { private val binding: ActivityMainBinding by contentView(R.layout.activity_main) private val launcher = registerForActivityResult( HeadlessActivity.contract(ClientHeadlessImpl::class.java) ) { Log.d(TAG, "onCreate: WrappedResult<Transaction>: $it}") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.view = this } fun checkInitStatus() { val sdkInitResp = (application as ClientApp).sdkInitResp Log.d(TAG, "checkInitStatus: $sdkInitResp") } fun initialSetup() = lifecycleScope.launch { val res = HeadlessSetup.initialSetup(this@ClientMain) Log.d(TAG, "setupInitial: $res") } fun launchNewSale() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "10.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = null, description = "description 123", posReference = "pos_${ULID.randomULID()}", forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) } fun launchNewSaleWithSign() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "1001.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = listOf(PaymentMethod.VISA, PaymentMethod.MASTERCARD), description = "description 123", posReference = "pos_${ULID.randomULID()}", forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) } fun launchNewSaleWrongProfile() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "20.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "wrong profile", forceFetchProfile = false ) ) } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientMain.kt
29090844
package com.theminesec.example.headless_xml import android.app.Application import android.util.Log import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.setup.SdkInitResp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ClientApp : Application() { private val appScope = CoroutineScope(Dispatchers.Main) var sdkInitResp: WrappedResult<SdkInitResp>? = null private set override fun onCreate() { super.onCreate() appScope.launch { val clientAppInitRes = HeadlessSetup.initSoftPos(this@ClientApp, "test.license") Log.d(TAG, "$clientAppInitRes") sdkInitResp = clientAppInitRes } } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientApp.kt
1378584054
package com.example.weather2 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.weather2", appContext.packageName) } }
Weather4/app/src/androidTest/java/com/example/weather2/ExampleInstrumentedTest.kt
3195131069
package com.example.weather2 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Weather4/app/src/test/java/com/example/weather2/ExampleUnitTest.kt
23970123
package com.example.weather2 import android.app.Application import androidx.room.Room import com.example.weather2.data.room.AppDatabase class App : Application() { companion object { lateinit var weatherDatabase: AppDatabase } override fun onCreate() { super.onCreate() weatherDatabase = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "weather-db").allowMainThreadQueries() .build() } }
Weather4/app/src/main/java/com/example/weather2/App.kt
955421199
package com.example.weather2.response data class Hour( val time_epoch: Long, val time: String, val temp_c: Double, val temp_f: Double, val is_day: Int, val condition: Condition, val wind_mph: Double, val wind_kph: Double, val wind_degree: Int, val wind_dir: String, val pressure_mb: Double, val pressure_in: Double, val precip_mm: Double, val precip_in: Double, val humidity: Int, val cloud: Int, val feelslike_c: Double, val feelslike_f: Double, val vis_km: Double, val vis_miles: Double, val uv: Double, val gust_mph: Double, val dayOfWeek: String, val gust_kph: Double )
Weather4/app/src/main/java/com/example/weather2/response/Hour.kt
3330487897
package com.example.weather2.response data class Astro( val sunrise: String, val sunset: String, val moonrise: String, val moonset: String, val moon_phase: String, val moon_illumination: String, val is_moon_up: Int, val is_sun_up: Int )
Weather4/app/src/main/java/com/example/weather2/response/Astro.kt
1481119331
package com.example.weather2.response data class Location( val name: String, val region: String, val country: String, val lat: Double, val lon: Double, val tz_id: String, val localtime_epoch: Long, val localtime: String )
Weather4/app/src/main/java/com/example/weather2/response/Location.kt
742086816
package com.example.weather2.response data class Day( val maxtemp_c: Double, val maxtemp_f: Double, val mintemp_c: Double, val mintemp_f: Double, val avgtemp_c: Double, val avgtemp_f: Double, val maxwind_mph: Double, val maxwind_kph: Double, val totalprecip_mm: Double, val totalprecip_in: Double, val totalsnow_cm: Double, val avgvis_km: Double, val avgvis_miles: Double, val avghumidity: Int, val daily_will_it_rain: Int, val daily_chance_of_rain: String, val daily_will_it_snow: Int, val daily_chance_of_snow: String, val condition: Condition, val uv: Double )
Weather4/app/src/main/java/com/example/weather2/response/Day.kt
854186526
package com.example.weather2.response data class Condition( val text: String, val icon: String, val code: Int )
Weather4/app/src/main/java/com/example/weather2/response/Condition.kt
3793233750
package com.example.weather2.response data class ForecastDay( val date: String, val date_epoch: Long, val day: Day, val astro: Astro, val hour: List<Hour> )
Weather4/app/src/main/java/com/example/weather2/response/ForecastDay.kt
3145390629
package com.example.weather2.response data class WeatherResponse( val location: Location, val current: Current, val forecast: Forecast )
Weather4/app/src/main/java/com/example/weather2/response/WeatherResponse.kt
1309403484
package com.example.weather2.response data class Forecast( val forecastday: List<ForecastDay> )
Weather4/app/src/main/java/com/example/weather2/response/Forecast.kt
1465842367
package com.example.weather2.response data class Current( val last_updated_epoch: Long, val last_updated: String, val temp_c: Double, val temp_f: Double, val is_day: Int, val condition: Condition, val wind_mph: Double, val wind_kph: Double, val wind_degree: Int, val wind_dir: String, val pressure_mb: Double, val pressure_in: Double, val precip_mm: Double, val precip_in: Double, val humidity: Int, val cloud: Int, val feelslike_c: Double, val feelslike_f: Double, val vis_km: Double, val vis_miles: Double, val uv: Double, val gust_mph: Double, val gust_kph: Double )
Weather4/app/src/main/java/com/example/weather2/response/Current.kt
482132337
package com.example.weather2.data import com.example.weather2.data.room.WeatherEntity import com.example.weather2.data.room.WeatherDao import com.example.weather2.response.WeatherResponse class WeatherRepository( private val api: WeatherApi, private val weatherDao: WeatherDao ) { suspend fun getWeather(location: String, days: Int, aqi: String, alerts: String): WeatherResponse { val key = "8a8b25949fec425599f92306240304" val response = api.getForecast(key, location, days, aqi, alerts) val weatherEntity = convertResponseToEntity(response) weatherDao.insert(weatherEntity) return response } suspend fun getLocalWeather(): List<WeatherEntity> { return weatherDao.getAll() } private fun convertResponseToEntity(response: WeatherResponse): WeatherEntity { val temperature = response.current.temp_c return WeatherEntity( id = 0, temperature = temperature ) } }
Weather4/app/src/main/java/com/example/weather2/data/WeatherRepository.kt
2652809028
package com.example.weather2.data.room import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class WeatherEntity( @PrimaryKey(autoGenerate = true) val id: Int, val temperature: Double, )
Weather4/app/src/main/java/com/example/weather2/data/room/WeatherEntity.kt
3011071809
package com.example.weather2.data.room import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [WeatherEntity::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun weatherDao(): WeatherDao }
Weather4/app/src/main/java/com/example/weather2/data/room/AppDatabase.kt
703339594
package com.example.weather2.data.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface WeatherDao { @Query("SELECT * FROM weatherentity") fun getAll(): List<WeatherEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(weather: WeatherEntity) @Query("DELETE FROM weatherentity") suspend fun deleteAll() }
Weather4/app/src/main/java/com/example/weather2/data/room/WeatherDao.kt
3861892863
package com.example.weather2.data import com.example.weather2.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitInstance { private val client = OkHttpClient.Builder().apply { addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) }.build() private val retrofit by lazy { Retrofit.Builder() .baseUrl(BuildConfig.API) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() } val api: WeatherApi by lazy { retrofit.create(WeatherApi::class.java) } }
Weather4/app/src/main/java/com/example/weather2/data/WeatherModule.kt
3238078207
package com.example.weather2.data import com.example.weather2.response.WeatherResponse import retrofit2.http.GET import retrofit2.http.Query interface WeatherApi { @GET("forecast.json") suspend fun getForecast( @Query("key") key: String, @Query("q") location: String, @Query("days") days: Int, @Query("aqi") aqi: String, @Query("alerts") alerts: String ): WeatherResponse }
Weather4/app/src/main/java/com/example/weather2/data/WeatherApi.kt
1520705245
package com.example.weather2.domain import com.example.weather2.data.WeatherRepository import com.example.weather2.response.WeatherResponse class GetWeatherUseCase(private val repository: WeatherRepository) { suspend fun execute(location: String, days: Int, aqi: String, alerts: String): WeatherResponse { return repository.getWeather(location, days, aqi, alerts) } }
Weather4/app/src/main/java/com/example/weather2/domain/GetWeatherUseCase.kt
2994619399
package com.example.weather2.presentation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.room.Room import com.example.weather2.data.RetrofitInstance import com.example.weather2.data.WeatherRepository import com.example.weather2.data.room.AppDatabase import com.example.weather2.data.room.WeatherDao import com.example.weather2.databinding.ActivityMainBinding import com.example.weather2.domain.GetWeatherUseCase import com.squareup.picasso.Picasso class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var viewModel: WeatherViewModel private val adapter = WeatherAdapter() private lateinit var weatherDao: WeatherDao private val locations = listOf("London", "New York", "Paris", "Moscow", "Bishkek") private var currentLocationIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) supportActionBar?.hide() setContentView(binding.root) val db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "weather-database" ).build() weatherDao = db.weatherDao() val api = RetrofitInstance.api val repository = WeatherRepository(api, weatherDao) val getWeatherUseCase = GetWeatherUseCase(repository) viewModel = ViewModelProvider(this, WeatherViewModelFactory(getWeatherUseCase))[WeatherViewModel::class.java] binding.recyclerView.adapter = adapter val days = 7 val aqi = "no" val alerts = "no" getWeatherForLocation(locations[currentLocationIndex], days, aqi, alerts) binding.arrow.setOnClickListener { currentLocationIndex = (currentLocationIndex + 1) % locations.size getWeatherForLocation(locations[currentLocationIndex], days, aqi, alerts) } } private fun getWeatherForLocation(location: String, days: Int, aqi: String, alerts: String) { viewModel.getWeather(location, days, aqi, alerts) viewModel.weatherResponse.observe(this) { response -> val hoursWithDays = response.forecast.forecastday.flatMap { day -> day.hour.map { hour -> Pair(hour, day) } } val sortedHoursWithDays = hoursWithDays.sortedBy { it.first.time_epoch } adapter.submitList(sortedHoursWithDays) val currentWeather = response.current binding.tvToday.text = "Today" binding.tvGradus.text = "${currentWeather.temp_c}°C" binding.tvWeather.text = currentWeather.condition.text binding.tvCity.text = response.location.name val iconUrl = "https:${currentWeather.condition.icon}" Picasso.get() .load(iconUrl) .into(binding.ivIcon) } } }
Weather4/app/src/main/java/com/example/weather2/presentation/MainActivity.kt
1408065212
package com.example.weather2.presentation import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.weather2.domain.GetWeatherUseCase import com.example.weather2.response.WeatherResponse import kotlinx.coroutines.launch class WeatherViewModel(private val getWeatherUseCase: GetWeatherUseCase) : ViewModel() { val weatherResponse: MutableLiveData<WeatherResponse> = MutableLiveData() fun getWeather(location: String, days: Int, aqi: String, alerts: String) { viewModelScope.launch { val response = getWeatherUseCase.execute(location, days, aqi, alerts) weatherResponse.postValue(response) } } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherViewModel.kt
1818535401
package com.example.weather2.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.weather2.domain.GetWeatherUseCase class WeatherViewModelFactory(private val getWeatherUseCase: GetWeatherUseCase) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(WeatherViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return WeatherViewModel(getWeatherUseCase) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherViewModelFactory.kt
146194160
package com.example.weather2.presentation import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.weather2.databinding.ItemWeatherBinding import com.example.weather2.response.Hour import com.example.weather2.response.ForecastDay import java.text.SimpleDateFormat import java.util.* class WeatherAdapter : ListAdapter<Pair<Hour, ForecastDay>, WeatherAdapter.WeatherViewHolder>( DiffCallback() ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherViewHolder { val binding = ItemWeatherBinding.inflate(LayoutInflater.from(parent.context), parent, false) return WeatherViewHolder(binding) } override fun onBindViewHolder(holder: WeatherViewHolder, position: Int) { val currentItem = getItem(position) holder.bind(currentItem.first, currentItem.second) } inner class WeatherViewHolder(private val binding: ItemWeatherBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(hour: Hour, forecastDay: ForecastDay) { binding.apply { if (hour.time.endsWith("00:00")) { tvDay.text = getDayOfWeek(forecastDay.date) } else { tvDay.text = "" } tvTime.text = getTime(hour.time) tvGradusRv.text = "${hour.temp_c}C" tvWeatherRv.text = hour.condition.text } } private fun getDayOfWeek(date: String): String { val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val date = format.parse(date) val formatDayOfWeek = SimpleDateFormat("EEEE", Locale.getDefault()) return formatDayOfWeek.format(date) } private fun getTime(time: String): String { val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) val date = format.parse(time) val formatTime = SimpleDateFormat("HH:mm", Locale.getDefault()) return formatTime.format(date) } } class DiffCallback : DiffUtil.ItemCallback<Pair<Hour, ForecastDay>>() { override fun areItemsTheSame(oldItem: Pair<Hour, ForecastDay>, newItem: Pair<Hour, ForecastDay>) = oldItem.first.time_epoch == newItem.first.time_epoch override fun areContentsTheSame(oldItem: Pair<Hour, ForecastDay>, newItem: Pair<Hour, ForecastDay>) = oldItem == newItem } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherAdapter.kt
1765411561
package com.example.assignment11_2 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.assignment11_2", appContext.packageName) } }
Android-advance-11_2-Food-app/app/src/androidTest/java/com/example/assignment11_2/ExampleInstrumentedTest.kt
1806943946
package com.example.assignment11_2 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Android-advance-11_2-Food-app/app/src/test/java/com/example/assignment11_2/ExampleUnitTest.kt
2044569577
package com.example.assignment11_2.viewmodel import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.example.assignment11_2.model.Food import com.example.assignment11_2.repository.FoodRepository import kotlinx.coroutines.launch import java.lang.IllegalArgumentException class FoodViewModel (app : Application):ViewModel(){ private val foodRepository : FoodRepository = FoodRepository(app) class FoodViewModelFactory(private val application: Application) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(FoodViewModel::class.java)) { return FoodViewModel(application) as T } throw IllegalArgumentException("Unable construct viewModel") } } fun insertFood(food: Food) = viewModelScope.launch { foodRepository.insertFood(food) } fun updateFood(food: Food)=viewModelScope.launch { foodRepository.updateFood(food) } fun deleteFood(id:Int)=viewModelScope.launch { foodRepository.deleteFood(id) } fun getAllFoods():LiveData<List<Food>> = foodRepository.getAllFood() }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/viewmodel/FoodViewModel.kt
2195392715
package com.example.assignment11_2.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.assignment11_2.database.dao.FoodDao import com.example.assignment11_2.model.Food @Database(entities = [Food::class], version = 1) abstract class FoodDatabase : RoomDatabase() { abstract fun getFoodDao(): FoodDao companion object { @Volatile private var instance: FoodDatabase? = null fun getInstance(context: Context): FoodDatabase { if (instance == null) { instance = Room.databaseBuilder(context, FoodDatabase::class.java, "FoodDatabase").build() } return instance!! } } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/database/FoodDatabase.kt
2252223949
package com.example.assignment11_2.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update import com.example.assignment11_2.model.Food @Dao interface FoodDao { @Insert suspend fun insertFood(food: Food) @Update suspend fun updateFood(food: Food) @Query("DELETE FROM food_table WHERE id = :id") suspend fun deleteFood(id: Int) @Query("SELECT * FROM food_table") fun getAllFoods():LiveData<List<Food>> @Query("SELECT * FROM food_table WHERE name_col=:name") fun getFoodByName(name:String):LiveData<List<Food>> }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/database/dao/FoodDao.kt
1069914359
package com.example.assignment11_2.repository import android.app.Application import androidx.lifecycle.LiveData import com.example.assignment11_2.database.FoodDatabase import com.example.assignment11_2.database.dao.FoodDao import com.example.assignment11_2.model.Food class FoodRepository(app : Application) { private val foodDao : FoodDao init{ val foodDatabase: FoodDatabase = FoodDatabase.getInstance(app) foodDao = foodDatabase.getFoodDao() } suspend fun insertFood(food: Food) = foodDao.insertFood(food) suspend fun updateFood(food: Food) = foodDao.updateFood(food) suspend fun deleteFood(id : Int) = foodDao.deleteFood(id) fun getAllFood():LiveData<List<Food>> = foodDao.getAllFoods() }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/repository/FoodRepository.kt
3132148080
package com.example.assignment11_2.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.assignment10.R class FoodDetailFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_food_detail, container, false) } companion object { @JvmStatic fun newInstance(param1: String, param2: String) = FoodDetailFragment().apply { arguments = Bundle().apply { // putString(ARG_PARAM1, param1) // putString(ARG_PARAM2, param2) } } } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/fragments/FoodDetailFragment.kt
2352664763
package com.example.assignment11_2.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.assignment10.R import com.example.assignment10.databinding.FoodItemBinding import com.example.assignment11_2.model.Food import java.text.NumberFormat import java.util.Locale class FoodAdapter : RecyclerView.Adapter<FoodAdapter.ViewHolder>() { val foodList = listOf( Food( id = 1, name = "Hamburger testcase long text", description = "Delicious hamburger with beef patty, lettuce, tomato, and cheese", price = 5545499.3, image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRrt1EInzip1NZ71yE0yKJ99ZtDqzzO-7iqtw&s" ), Food( id = 2, name = "Pizza", description = "Tasty pizza topped with pepperoni, mushrooms, and mozzarella cheese", price = 8343443.99, image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTFESPeeQZO1U-pTrKDWKPjrF5zYvEFARa2Vg&s" ), Food( id = 3, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 1235.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 4, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12040.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 5, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 124554.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 6, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 1245124.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 7, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 123125.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 8, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12235.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 9, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12235325.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), ) inner class ViewHolder(item: View) : RecyclerView.ViewHolder(item) { private val binding: FoodItemBinding = FoodItemBinding.bind(item) val foodName = binding.tvFoodName val foodPrice = binding.tvFoodPrice val foodDescription = binding.tvFoodDescription val foodImage = binding.imgFood } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.food_item,parent,false) return ViewHolder(view) } override fun onBindViewHolder(holder: FoodAdapter.ViewHolder, position: Int) { holder.foodName.text = foodList[position].name holder.foodPrice.text = NumberFormat.getCurrencyInstance(Locale("vi", "VN")).format(foodList[position].price) holder.foodDescription.text = foodList[position].description Glide.with(holder.itemView.context).load(foodList[position].image) .error(R.drawable.img_no_available).into(holder.foodImage) } override fun getItemCount(): Int { return foodList.size } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/adapter/FoodAdapter.kt
1475620892
package com.example.assignment11_2.model import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity(tableName = "food_table") class Food( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int? = 0, @ColumnInfo(name = "name_col") var name: String = "", @ColumnInfo(name = "description_col") var description: String = "", @ColumnInfo(name = "price_col") var price: Double, @ColumnInfo(name="image-col") val image: String ) : Parcelable
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/model/Food.kt
675023753
package com.example.assignment11_2.activities import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import com.example.assignment10.R import com.example.assignment10.databinding.ActivityMainBinding import com.example.assignment11_2.adapter.FoodAdapter import com.example.assignment11_2.model.Food import com.example.assignment11_2.viewmodel.FoodViewModel class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val foodViewModel: FoodViewModel by lazy { ViewModelProvider( this, FoodViewModel.FoodViewModelFactory(this.application) )[FoodViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // RecyclerView val adapter = FoodAdapter() binding.rvFoods.layoutManager = GridLayoutManager(this,2) binding.rvFoods.adapter = adapter } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/activities/MainActivity.kt
1055992333