content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.pruebaapp 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) } }
perfil_Confiapp/app/src/test/java/com/example/pruebaapp/ExampleUnitTest.kt
3810225908
package com.example.pruebaapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.pruebaapp.fragments.RegistroFragment class RegistroRContrasenaActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registro_rcontrasena) // Crear una instancia del fragmento que deseas inflar val fragment = RegistroFragment() // Iniciar una transacción de fragmentos val transaction = supportFragmentManager.beginTransaction() // Reemplazar el contenido del FragmentContainer con el fragmento transaction.replace(R.id.fragmentContainerRegistroRContraseña, fragment) // Confirmar la transacción transaction.commit() } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/RegistroRContrasenaActivity.kt
4127483142
package com.example.pruebaapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.example.pruebaapp.data.SharedPreferencesManager import com.example.pruebaapp.databinding.ActivityMainBinding import com.example.pruebaapp.fragments.InicioFragment import com.example.pruebaapp.fragments.NoticiasFragment import com.example.pruebaapp.fragments.NotificacionesFragment import com.example.pruebaapp.fragments.PerfilFragment import com.google.android.material.bottomnavigation.BottomNavigationView private const val NUM_PAGES = 4 class MainActivity : AppCompatActivity() { lateinit var cadena: String; var cadena2 = ""; val miConst = "Esto es una cadena."; private lateinit var sharedPre: SharedPreferencesManager private lateinit var bottomNavigationView: BottomNavigationView private lateinit var viewPager: ViewPager2 private lateinit var adapter: MainActivity.ScreenSlidePagerAdapter ///Binding, extendemos binding con ":" del activity, aparece automáticamente la clase private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ///Binding binding = ActivityMainBinding.inflate(LayoutInflater.from(this)) ///Require context setContentView(binding.root) bottomNavigationView = binding.navigationBar viewPager = binding.viewPagerPrincipal viewPager.isUserInputEnabled = true Toast.makeText(this, "Hola Mundo", Toast.LENGTH_SHORT).show() //val valor = sharedPre.getUser() //intent.getBooleanExtra() Para pasar booleanos //val textView = binding.textView.setText(valor) //Toast.makeText(this, "Bienvenido ", Toast.LENGTH_SHORT).show(); //findViewById<Button>(R.id.button_1).setOnClickListener{ //val input = findViewById<TextInputEditText>(R.id.textInputEditText).text; //} adapter = ScreenSlidePagerAdapter(supportFragmentManager, lifecycle) //val pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager, lifecycle) viewPager.adapter = adapter bottomNavigationView.setOnNavigationItemSelectedListener { item -> //currentItem = 0 when (item.itemId) { R.id.menu_item_inicio -> viewPager.setCurrentItem(0, true) R.id.menu_item_Noticias -> viewPager.setCurrentItem(1, true) R.id.menu_item_Notificaciones -> viewPager.setCurrentItem(2, true) R.id.menu_item_Perfil -> viewPager.setCurrentItem(3, true) } true } ///Para sincronizar el viewPager y el bottomNavigationView viewPager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback(){ override fun onPageSelected(position: Int) { super.onPageSelected(position) val menuItem = bottomNavigationView.menu.getItem(position) bottomNavigationView.selectedItemId = menuItem.itemId } }) /*loadFragmentInicio(InicioFragment()) bottomNavigationView.setOnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.menu_item_inicio -> { // Lógica para la primera opción del menú loadFragment(InicioFragment()) return@setOnNavigationItemSelectedListener true } R.id.menu_item_Noticias -> { // Lógica para la segunda opción del menú loadFragment(NoticiasFragment()) return@setOnNavigationItemSelectedListener true } R.id.menu_item_Notificaciones -> { // Lógica para la segunda opción del menú loadFragment(NotificacionesFragment()) return@setOnNavigationItemSelectedListener true } R.id.menu_item_Perfil -> { // Lógica para la segunda opción del menú loadFragment(PerfilFragment()) return@setOnNavigationItemSelectedListener true } // Agregar más casos según sea necesario else -> false } }*/ } override fun onBackPressed() { if (viewPager.currentItem == 0) { val alertDialog = AlertDialog.Builder(this) alertDialog.setTitle("¿Cerrar la aplicación?") alertDialog.setMessage("¿Estás seguro de que quieres salir de la aplicación?") alertDialog.setPositiveButton("Sí") { _, _ -> super.onBackPressed() // Cierra la aplicación } alertDialog.setNegativeButton("No") { dialog, _ -> dialog.dismiss() // Cancela la acción } alertDialog.show() }else { // Otherwise, select the previous step. viewPager.currentItem = viewPager.currentItem - 1 } /*private fun loadFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.fragmentMainContainerView, fragment) //transaction.addToBackStack(null) // Opcional: para habilitar la navegación hacia atrás transaction.commit() } private fun loadFragmentInicio(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.fragmentMainContainerView, fragment) //transaction.addToBackStack(null) // Opcional: para habilitar la navegación hacia atrás transaction.commit() }*/ } private inner class ScreenSlidePagerAdapter(fa: FragmentManager, li: Lifecycle) : FragmentStateAdapter(fa, li) { override fun getItemCount(): Int { return NUM_PAGES } override fun createFragment(position: Int): Fragment { return when (position) { 0 -> InicioFragment() 1 -> NoticiasFragment() 2 -> NotificacionesFragment() 3 -> PerfilFragment() // Agrega más fragments según sea necesario else -> InicioFragment() //else -> throw IllegalArgumentException("Invalid position") } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/MainActivity.kt
1144129020
package com.example.pruebaapp.fragments import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.text.Editable import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.Toast //import androidx.databinding.DataBindingUtil import androidx.viewbinding.ViewBinding import com.example.pruebaapp.MainActivity import com.example.pruebaapp.R import com.example.pruebaapp.RegistroRContrasenaActivity import com.example.pruebaapp.data.SharedPreferencesManager import com.example.pruebaapp.databinding.FragmentLoginBinding ///Binding: Primero modficar el bluid.gradle (Module:app) y dentro de android al final buildFeatures { // viewBinding true // } //} private lateinit var binding: ResultProfileBinding /** * A simple [Fragment] subclass. * Use the [LoginFragment.newInstance] factory method to * create an instance of this fragment. */ class LoginFragment : Fragment() { //Binding en fragments private var _binding:FragmentLoginBinding? = null private val binding get() = _binding!! ///sharedPreferences private lateinit var sharedPre: SharedPreferencesManager lateinit var buttonOpenActivity : Button /*override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) }*/ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { /*by lazy { DataBindingUtil.inflate(LayoutInflater, R.layout.fragment_login, ) }*/ // ---> Para activities se usa así sharedPre = SharedPreferencesManager(requireContext()) val userrrr = sharedPre.getUser() val boolll = sharedPre.getBool() Toast.makeText(activity, boolll.toString(), Toast.LENGTH_SHORT).show() Toast.makeText(activity, userrrr, Toast.LENGTH_SHORT).show() _binding = FragmentLoginBinding.inflate(inflater, container, false) //val view = DataBindingUtil.inflate(R.layout.fragment_login, container, false) val buttonOpenRegisterActivity = binding.registroButton val user = binding.userInput val pass = binding.passInput buttonOpenActivity = binding.inicioButton buttonOpenActivity.setOnClickListener { val u = user.text.toString() val p = pass.text.toString() // ---> Guardar datos del usuario con SharedPreferences para Activities sharedPre.saveUser(u, p) sharedPre.saveBool() validar(u, p) } buttonOpenRegisterActivity.setOnClickListener { val intent1 = Intent(activity, RegistroRContrasenaActivity::class.java) startActivity(intent1) } return binding.root } fun validar(u: String, p: String) { if (u == sharedPre.getUser() && p == sharedPre.getPass() ) { val intent = Intent(activity, MainActivity::class.java) //intent.putExtra("user", u) startActivity(intent) }else{ Toast.makeText(activity, "Usuario o contraseña incorrectos", Toast.LENGTH_SHORT).show(); } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/LoginFragment.kt
899993318
package com.example.pruebaapp.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.pruebaapp.R // 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 [PerfilFragment.newInstance] factory method to * create an instance of this fragment. */ class PerfilFragment : 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_perfil, 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 PerfilFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = PerfilFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/PerfilFragment.kt
2371741707
package com.example.pruebaapp.fragments import android.content.Intent 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 com.example.pruebaapp.MainActivity import com.example.pruebaapp.R // 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 [MenorLoginFragment.newInstance] factory method to * create an instance of this fragment. */ class MenorLoginFragment : 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? { val view = inflater.inflate(R.layout.fragment_menor_login, container, false) val buttonOpenActivity = view.findViewById<Button>(R.id.menorLoginButton) buttonOpenActivity.setOnClickListener { val intent = Intent(activity, MainActivity::class.java) startActivity(intent) } return view } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/MenorLoginFragment.kt
3803177417
package com.example.pruebaapp.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Spinner import android.widget.Toast import com.example.pruebaapp.R // 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 [RegistroFragment.newInstance] factory method to * create an instance of this fragment. */ class RegistroFragment : 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 val view = inflater.inflate(R.layout.fragment_registro, container, false) val spinner = view.findViewById<Spinner>(R.id.tipoDocumentoList) // Datos de ejemplo para el Spinner val items = arrayOf("Cédula de Ciudadanía", "Cédula de Extrajería", "Pasaporte") // Crear un adaptador para el Spinner val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, items) // Establecer el diseño del adaptador para el Spinner adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Asignar el adaptador al Spinner spinner.adapter = adapter // Manejar eventos de selección (igual que en el ejemplo anterior) spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val selectedItem = items[position] Toast.makeText(requireContext(), "Seleccionaste: $selectedItem", Toast.LENGTH_SHORT).show() } override fun onNothingSelected(parent: AdapterView<*>?) { // Acción a realizar cuando no se selecciona ningún elemento } } return view } 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 RegistroFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = RegistroFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/RegistroFragment.kt
1579377044
package com.example.pruebaapp.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.pruebaapp.R // 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 [NotificacionesFragment.newInstance] factory method to * create an instance of this fragment. */ class NotificacionesFragment : 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_notificaciones, 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 NotificacionesFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = NotificacionesFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/NotificacionesFragment.kt
2493668378
package com.example.pruebaapp.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.pruebaapp.R // 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 [NoticiasFragment.newInstance] factory method to * create an instance of this fragment. */ class NoticiasFragment : 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_noticias, 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 NoticiasFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = NoticiasFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/NoticiasFragment.kt
2469106349
package com.example.pruebaapp.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.pruebaapp.R // 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 [InicioFragment.newInstance] factory method to * create an instance of this fragment. */ class InicioFragment : 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_inicio, 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 InicioFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = InicioFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/fragments/InicioFragment.kt
1839539315
package com.example.pruebaapp import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.example.pruebaapp.fragments.LoginFragment import com.example.pruebaapp.fragments.MenorLoginFragment import com.google.android.material.tabs.TabLayout /** * The number of pages (wizard steps) to show in this demo. */ private const val NUM_PAGES = 2 class LoginActivity : FragmentActivity() { /** * The pager widget, which handles animation and allows swiping horizontally * to access previous and next wizard steps. */ private lateinit var viewPager: ViewPager2 private lateinit var tabLayout: TabLayout private lateinit var adapter: ScreenSlidePagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) // Instantiate a ViewPager2 and a PagerAdapter. viewPager = findViewById(R.id.loginViewPager) tabLayout = findViewById(R.id.indicador) // The pager adapter, which provides the pages to the view pager widget. adapter = ScreenSlidePagerAdapter(supportFragmentManager, lifecycle) //val tutor = tabLayout.addTab(tabLayout.newTab().setText(" Tutor ")) //val menor = tabLayout.addTab(tabLayout.newTab().setText(" Menor ")) viewPager.adapter = adapter tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab?) { if (tab != null) viewPager.currentItem = tab.position } override fun onTabUnselected(tab: TabLayout.Tab?) { } override fun onTabReselected(tab: TabLayout.Tab?) { } }) viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) tabLayout.selectTab(tabLayout.getTabAt(position)) } }) /*val registroButton = findViewById<Button>(R.id.registroButton) registroButton.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } val inicioButton = findViewById<ButtonR.id.inicioButton) inicioButton.setOnClickListener { val intent1 = Intent(this, MainActivity::class.java) startActivity(intent1) }*/ } override fun onBackPressed() { if (viewPager.currentItem == 0) { // If the user is currently looking at the first step, allow the system to handle // the Back button. This calls finish() on this activity and pops the back stack. super.onBackPressed() } else { // Otherwise, select the previous step. viewPager.currentItem = viewPager.currentItem - 1 } } /** * A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in * sequence. */ private inner class ScreenSlidePagerAdapter(fa: FragmentManager, li: Lifecycle) : FragmentStateAdapter(fa, li) { override fun getItemCount(): Int { return NUM_PAGES } override fun createFragment(position: Int): Fragment { return if (position == 0) LoginFragment() else MenorLoginFragment() } } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/LoginActivity.kt
3130740752
package com.example.pruebaapp.data import android.content.Context import android.content.SharedPreferences import androidx.core.content.contentValuesOf class SharedPreferencesManager(private val context: Context) { private val name_DB = "myDataBase" private val sharedPreferences : SharedPreferences by lazy { ///Solamente para el teléfono en el que se esta usando la aplicación (nombre de la db y el segundo el modo en que se va a manejar la base de datos) context.getSharedPreferences(name_DB, Context.MODE_PRIVATE) } // Función para almacenar los datos fun saveUser(user: String, pass: String){ //Asignar una edición al SharedPreferences (editar) val editor = sharedPreferences.edit() //Asignar el Token o Clave editor.putString("saveUser", user) editor.putString("savePass", pass) //Aplicar cambios editor.apply() } fun saveBool(){ val editor = sharedPreferences.edit() editor.putBoolean("myBool", true) editor.apply() } // Función para mostrar los datos fun getUser(): String{ // Retornar la clave que identifica el contenido de las SharedPreferences return sharedPreferences.getString("saveUser", "Empty").toString() } fun getPass(): String{ // Retornar la clave que identifica el contenido de las SharedPreferences return sharedPreferences.getString("savePass", "Empty").toString() } fun getBool(): Boolean{ return sharedPreferences.getBoolean("myBool", false) } // Crear función para obtener los datos del registro y así poder ingresar en el Inicio de Sesión // (Usuario o Cédula & Contraseña) fun saveRegistro(){ } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/data/SharedPreferencesManager.kt
1020159316
package com.example.pruebaapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.example.pruebaapp.data.SharedPreferencesManager class SplashActivity : AppCompatActivity() { private lateinit var sharedPref: SharedPreferencesManager private val SPLASH_TIME_OUT: Long = 1500 // 1,5 segundos de demora override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) sharedPref = SharedPreferencesManager(this) ///Hacemos la vcalidacion boolean para inicio de sesion Handler().postDelayed({ if (userLog()){ // Este código se ejecutará después de SPLASH_TIME_OUT val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }else{ val intent1 = Intent(this, LoginActivity::class.java) startActivity(intent1) } }, SPLASH_TIME_OUT); } private fun userLog(): Boolean{ return sharedPref.getBool() } }
perfil_Confiapp/app/src/main/java/com/example/pruebaapp/SplashActivity.kt
2262296627
package com.example.ejercicios 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.ejercicios", appContext.packageName) } }
EjerciciosApp/app/src/androidTest/java/com/example/ejercicios/ExampleInstrumentedTest.kt
1959604247
package com.example.ejercicios 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) } }
EjerciciosApp/app/src/test/java/com/example/ejercicios/ExampleUnitTest.kt
4109861379
package com.example.ejercicios.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
EjerciciosApp/app/src/main/java/com/example/ejercicios/ui/theme/Color.kt
4053240194
package com.example.ejercicios.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun EjerciciosTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
EjerciciosApp/app/src/main/java/com/example/ejercicios/ui/theme/Theme.kt
4007869682
package com.example.ejercicios.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
EjerciciosApp/app/src/main/java/com/example/ejercicios/ui/theme/Type.kt
391025426
package com.example.ejercicios import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView class EstadisticasAdapter(context: Context, estadisticas: ArrayList<ArrayList<String>>) : ArrayAdapter<ArrayList<String>>(context, 0, estadisticas) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val estadistica = getItem(position) ?: arrayListOf("", "", "") val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_estadistica, parent, false) val nombreTextView: TextView = view.findViewById(R.id.nombreTextView) val valorTextView: TextView = view.findViewById(R.id.valorTextView) val unidadTextView: TextView = view.findViewById(R.id.unidadTextView) nombreTextView.text = estadistica[0] valorTextView.text = estadistica[1] + estadistica[2] // Unir valor y unidad unidadTextView.text = "" // Dejar unidad vacía return view } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/EstadisticasAdapter.kt
149617938
package com.example.ejercicios import android.app.Activity import android.content.DialogInterface import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.ContextMenu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ImageButton import android.widget.LinearLayout import android.widget.ListView import android.widget.PopupMenu import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.compose.ui.unit.dp import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar class MainActivity : AppCompatActivity() { lateinit var adaptador: ArrayAdapter<ArrayList<String>> val theCallback = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) crearTabla() adaptador = EstadisticasAdapter(this, estadisticasArray) val estadisticasListView = findViewById<ListView>(R.id.lv_estadisticas) estadisticasListView.adapter = adaptador adaptador.notifyDataSetChanged() registerForContextMenu(estadisticasListView) val floatingButton = findViewById<FloatingActionButton>(R.id.floatingActionButton) floatingButton.setOnClickListener{ val popupMenu = PopupMenu(this, it) popupMenu.menuInflater.inflate(R.menu.popup_menu_float, popupMenu.menu) popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.action_create_routine -> { irActividad(NuevaRutina::class.java) true } R.id.action_create_exercise -> { irActividad(NuevoEjercicio::class.java) true } R.id.action_create_equipment -> { irActividad(NuevoEquipamiento::class.java) true } else -> false } } popupMenu.show() } } override fun onCreateContextMenu( menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo? ) { super.onCreateContextMenu(menu, v, menuInfo) val inflater = menuInflater inflater.inflate(R.menu.estadisticas_menu, menu) val info = menuInfo as AdapterView.AdapterContextMenuInfo val posicion = info.position estadisticaSeleccionada = posicion } override fun onContextItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.mi_editar_estadistica -> { editarEstadistica(adaptador) return true } else -> super.onContextItemSelected(item) } } fun editarEstadistica(adaptador: ArrayAdapter<ArrayList<String>>){ val builder = AlertDialog.Builder(this) val input = EditText(this) input.setText(estadisticasArray[estadisticaSeleccionada][1]) builder.setView(input) builder.setTitle("Editar estadística") builder.setPositiveButton("Aceptar") { dialog, which -> estadisticasArray[estadisticaSeleccionada][1] = input.text.toString() adaptador.notifyDataSetChanged() } builder.setNegativeButton("Cancelar") { dialog, which -> dialog.cancel() } builder.show() } private fun actualizarTabla(){ } private fun crearTabla() { val tableLayout = findViewById<TableLayout>(R.id.tablaCalendario) var contador = 1 for(i in 1 until 6){ val fila = tableLayout.getChildAt(i) as TableRow for (j in 0 until 7){ val celda = fila.getChildAt(j) as LinearLayout val textView = celda.findViewById<TextView>(R.id.tv_dia_boton) val mesAcabado = contador > 31 if (mesAcabado){ contador = 1 } val debeTenerRightMargin = j < 6 if (debeTenerRightMargin){ val layoutParams = celda.layoutParams as LinearLayout.LayoutParams val density = resources.displayMetrics.density val marginDp =7 val marginPx = (marginDp * density).toInt() layoutParams.rightMargin = marginPx } textView.text = contador.toString() contador++ } } var fila = tableLayout.getChildAt(1) as TableRow var celda = fila.getChildAt(0) as LinearLayout var imgBtn = celda.findViewById<ImageButton>(R.id.btn_calendario) var textView = celda.findViewById<TextView>(R.id.tv_dia_boton) textView.setTextColor(Color.parseColor("#CCCCCC")) imgBtn.setBackgroundResource(R.drawable.gray_square_button) fila = tableLayout.getChildAt(5) as TableRow celda = fila.getChildAt(3) as LinearLayout imgBtn = celda.findViewById<ImageButton>(R.id.btn_calendario) imgBtn.setBackgroundResource(R.drawable.gray_square_button) textView = celda.findViewById<TextView>(R.id.tv_dia_boton) textView.setTextColor(Color.parseColor("#CCCCCC")) fila = tableLayout.getChildAt(5) as TableRow celda = fila.getChildAt(4) as LinearLayout imgBtn = celda.findViewById<ImageButton>(R.id.btn_calendario) imgBtn.setBackgroundResource(R.drawable.gray_square_button) textView = celda.findViewById<TextView>(R.id.tv_dia_boton) textView.setTextColor(Color.parseColor("#CCCCCC")) fila = tableLayout.getChildAt(5) as TableRow celda = fila.getChildAt(5) as LinearLayout imgBtn = celda.findViewById<ImageButton>(R.id.btn_calendario) imgBtn.setBackgroundResource(R.drawable.gray_square_button) textView = celda.findViewById<TextView>(R.id.tv_dia_boton) textView.setTextColor(Color.parseColor("#CCCCCC")) fila = tableLayout.getChildAt(5) as TableRow celda = fila.getChildAt(6) as LinearLayout imgBtn = celda.findViewById<ImageButton>(R.id.btn_calendario) imgBtn.setBackgroundResource(R.drawable.gray_square_button) textView = celda.findViewById<TextView>(R.id.tv_dia_boton) textView.setTextColor(Color.parseColor("#CCCCCC")) } fun mostrarSnackbar(texto: String) { val snack = Snackbar.make( findViewById(R.id.id_activity_main), texto, Snackbar.LENGTH_LONG ) snack.show() } fun irActividad( clase: Class<*>){ val intent = Intent(this, clase) theCallback.launch(intent) } companion object{ val estadisticasArray = arrayListOf( arrayListOf("Peso inicial", "70", "kg"), arrayListOf("Peso final", "65", "kg"), arrayListOf("Altura", "165", "cm") ) var estadisticaSeleccionada = 0 } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/MainActivity.kt
1063859182
package com.example.ejercicios import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.modelos.Equipamiento class AdaptadorTodosEquipamientos ( private val contexto: NuevoEjercicio, private val lista: ArrayList<Equipamiento>, private val recyclerView: RecyclerView ) : RecyclerView.Adapter< AdaptadorTodosEquipamientos.MyViewHolder>() { inner class MyViewHolder (view: View) : RecyclerView.ViewHolder(view) { val nombreEquipamiento: TextView init { nombreEquipamiento = view.findViewById(R.id.tv_seleccionar_ejercicio) } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): AdaptadorTodosEquipamientos.MyViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate( R.layout.tarjeta_seleccionar_ejercicio, parent, false ) return MyViewHolder(itemView) } override fun onBindViewHolder(holder: AdaptadorTodosEquipamientos.MyViewHolder, position: Int) { val equipamientoActual = this.lista[position] holder.nombreEquipamiento.text = equipamientoActual.nombre val imageButton = holder.itemView.findViewById<ImageButton>(R.id.imButton_seleccionar_ejercicio) imageButton.setOnClickListener{ NuevoEjercicio.equipamientos_disponibles.removeAt(position) NuevoEjercicio.equipamiento_seleccionados.add(equipamientoActual) notifyDataSetChanged() contexto.adaptadorEquipamientosSeleccinados.notifyDataSetChanged() } } override fun getItemCount(): Int { return this.lista.size } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/AdaptadorTodosEquipamientos.kt
4044869934
package com.example.ejercicios.firestore_database import com.example.ejercicios.modelos.Rutina import com.google.firebase.firestore.FirebaseFirestore class FirestoreRutina { private val db = FirebaseFirestore.getInstance() private val rutinasColeccion = db.collection("rutinas") fun crearRutina(nuevaRutina: Rutina){ val datosRutina = hashMapOf( "nombre" to nuevaRutina.nombre, "descripcion" to nuevaRutina.descripcion, "caloriasQuemadas" to nuevaRutina.caloriasQuemadas, "fecha" to nuevaRutina.fecha, "ejercicios" to nuevaRutina.ejercicios ) rutinasColeccion .add(datosRutina) .addOnSuccessListener { documentReference -> val rutinaId = documentReference.id nuevaRutina.id = rutinaId } .addOnFailureListener { } } fun eliminarRutina(){ } fun editarRutina(){ } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/firestore_database/FirestoreRutina.kt
2093252168
package com.example.ejercicios.firestore_database import com.example.ejercicios.modelos.Equipamiento import com.google.firebase.firestore.FirebaseFirestore class FirestoreEquipamiento { private val db = FirebaseFirestore.getInstance() private val equipamientoColeccion = db.collection("equipamiento") fun crearEquipamiento(nuevoEquipamiento: Equipamiento){ val datosEquipamiento = hashMapOf( "nombre" to nuevoEquipamiento.nombre, "descripcion" to nuevoEquipamiento.descripcion, ) equipamientoColeccion .add(datosEquipamiento) .addOnSuccessListener { documentReference -> val equipamientoId = documentReference.id nuevoEquipamiento.id = equipamientoId } .addOnFailureListener { } } fun eliminarEquipamiento(){ } fun editarEquipamiento(){ } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/firestore_database/FirestoreEquipamiento.kt
1717281058
package com.example.ejercicios.firestore_database import com.example.ejercicios.modelos.Ejercicio import com.google.firebase.firestore.FirebaseFirestore class FirestoreEjercicio { private val db = FirebaseFirestore.getInstance() private val ejerciciosColeccion = db.collection("ejercicios") fun crearEjercicio(nuevoEjercicio: Ejercicio){ val datosEjercicio = hashMapOf( "nombre" to nuevoEjercicio.nombre, "descripcion" to nuevoEjercicio.descripcion, "sets" to nuevoEjercicio.sets, "duracion" to nuevoEjercicio.duracion, //Validar que acepta nulls "repeticiones" to nuevoEjercicio.repeticiones, "pesoUtilizado" to nuevoEjercicio.pesoUtilizadoKg, "nivelDificultad" to nuevoEjercicio.nivelDificultad, "equipamiento" to nuevoEjercicio.equipamiento ) ejerciciosColeccion .add(datosEjercicio) .addOnSuccessListener { documentReference -> val ejercicioId = documentReference.id nuevoEjercicio.id = ejercicioId } .addOnFailureListener { } } fun eliminarEjercicio(){ } fun editarEjercicio(){ } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/firestore_database/FirestoreEjercicio.kt
61006389
package com.example.ejercicios.modelos class Equipamiento ( var id: String, var nombre: String, var descripcion: String ){ companion object{ val arreglo_equipamiento = arrayListOf<Equipamiento>() fun incializarEquipamientos(){ arreglo_equipamiento.add( Equipamiento( "", "Mancuerna", "Es una mancuerna" ) ) arreglo_equipamiento.add( Equipamiento( "", "Cuerda de salta", "Está hecha de plástico" ) ) } } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/modelos/Equipamiento.kt
4252322374
package com.example.ejercicios.modelos class Rutina ( var id: String, var nombre: String, var descripcion: String, var caloriasQuemadas: Double, var fecha: String, var ejercicios: ArrayList<Ejercicio> ){ }
EjerciciosApp/app/src/main/java/com/example/ejercicios/modelos/Rutina.kt
809266482
package com.example.ejercicios.modelos import com.google.common.collect.Sets class Ejercicio ( var id: String, var nombre: String, var descripcion: String, var sets: Long?, var duracion: Long?, var repeticiones: Long?, var pesoUtilizadoKg: Double?, var nivelDificultad: Long, // del 1 al 3 var equipamiento: ArrayList<Equipamiento> ) { }
EjerciciosApp/app/src/main/java/com/example/ejercicios/modelos/Ejercicio.kt
2411151716
package com.example.ejercicios import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.firestore_database.FirestoreEjercicio import com.example.ejercicios.modelos.Ejercicio import com.example.ejercicios.modelos.Equipamiento import com.google.android.material.snackbar.Snackbar import com.google.firebase.firestore.QueryDocumentSnapshot import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class NuevoEjercicio : AppCompatActivity() { lateinit var adaptadorEquipamientosSeleccinados: AdaptadorEquipamientoSeleccionado lateinit var adaptadorEquipamientosDisponibles: AdaptadorTodosEquipamientos private val firestoreEjercicio = FirestoreEjercicio() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nuevo_ejercicio) rv_equipamientos_seleccionados() rv_seleccionar_equipamientos() val db = Firebase.firestore val equipamientoExistente = db.collection("equipamiento") equipamientos_disponibles.clear() adaptadorEquipamientosDisponibles.notifyDataSetChanged() equipamientoExistente .get() .addOnSuccessListener {result -> for (document in result) { anadirAArregloEquipamiento(document) adaptadorEquipamientosDisponibles.notifyDataSetChanged() } } .addOnFailureListener { // Errores } adaptadorEquipamientosDisponibles.notifyDataSetChanged() val botonGuardar = findViewById<Button>(R.id.btn_guardar_ejercicio) botonGuardar.setOnClickListener { val input_titulo_ejercicio = findViewById<EditText>(R.id.input_titulo_ejercicio) val tituloEjercicio = if (input_titulo_ejercicio.text.isNotEmpty()) { input_titulo_ejercicio.text.toString() } else { mostrarSnackbar("Llene el campo Título") null } val input_cantidad_sets = findViewById<EditText>(R.id.input_cantidad_sets) val cantidadSets = if (input_cantidad_sets.text.isNotEmpty()) { input_cantidad_sets.text.toString().toLong() } else { mostrarSnackbar("Llene la cantidad de sets") null } val input_repeticiones = findViewById<EditText>(R.id.input_repeticiones) val tituloRepeticiones = if (input_repeticiones.text.isNotEmpty()) { input_repeticiones.text.toString().toLong() } else { mostrarSnackbar("Llene las repeticiones") null } val input_descripcion = findViewById<EditText>(R.id.input_descripcion_ejercicio) val tituloDescripcion = if (input_descripcion.text.isNotEmpty()) { input_descripcion.text.toString() } else { mostrarSnackbar("Llene el campo Descripción") null } if (tituloEjercicio !=null && cantidadSets != null && tituloRepeticiones != null && tituloDescripcion != null){ val nuevoEjercicio = Ejercicio( "", tituloEjercicio, tituloDescripcion, cantidadSets, null, tituloRepeticiones, 0.0, 1, equipamiento_seleccionados ) firestoreEjercicio.crearEjercicio(nuevoEjercicio) setResult(RESULT_OK) finish() } } val botonCancelar = findViewById<Button>(R.id.btn_cancelar_ejercicio) botonCancelar.setOnClickListener { finish() } } fun rv_equipamientos_seleccionados(){ val rv_equipamiento = findViewById<RecyclerView>(R.id.rv_equipamientos_seleccionados) adaptadorEquipamientosSeleccinados = AdaptadorEquipamientoSeleccionado( this, equipamiento_seleccionados, rv_equipamiento ) rv_equipamiento.adapter = adaptadorEquipamientosSeleccinados rv_equipamiento.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator() rv_equipamiento.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false) adaptadorEquipamientosSeleccinados.notifyDataSetChanged() } fun rv_seleccionar_equipamientos(){ val rv_equipamientos = findViewById<RecyclerView>(R.id.rv_todos_equipamiento) adaptadorEquipamientosDisponibles = AdaptadorTodosEquipamientos( this, equipamientos_disponibles, rv_equipamientos ) rv_equipamientos.adapter = adaptadorEquipamientosDisponibles rv_equipamientos.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator() rv_equipamientos.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this) adaptadorEquipamientosDisponibles.notifyDataSetChanged() } fun anadirAArregloEquipamiento( equipamiento: QueryDocumentSnapshot ){ val id = equipamiento.id val nuevoEquipamiento = Equipamiento( id, equipamiento.data["nombre"] as String, equipamiento.data["descripcion"] as String ) equipamientos_disponibles.add(nuevoEquipamiento) } fun mostrarSnackbar(texto: String) { val snack = Snackbar.make( findViewById(R.id.id_layout_nuevo_ejercicio), texto, Snackbar.LENGTH_LONG ) snack.show() } companion object{ var equipamiento_seleccionados = arrayListOf<Equipamiento>() var equipamientos_disponibles = arrayListOf<Equipamiento>() fun agregar_disponibles(){ equipamientos_disponibles.add( Equipamiento( "", "Mancuerna", "Es una mancuer a") ) equipamientos_disponibles.add( Equipamiento( "", "Cuerda de saltar", "Es una cuerda de saltar" ) ) } } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/NuevoEjercicio.kt
3937699622
package com.example.ejercicios import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.modelos.Ejercicio class AdaptadorTodosEjercicios ( private val contexto: NuevaRutina, private val lista: ArrayList<Ejercicio>, private val recyclerView: RecyclerView ) : RecyclerView.Adapter< AdaptadorTodosEjercicios.MyViewHolder>() { inner class MyViewHolder (view: View) : RecyclerView.ViewHolder(view) { val nombreEjercicio: TextView init { nombreEjercicio = view.findViewById(R.id.tv_seleccionar_ejercicio) } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): AdaptadorTodosEjercicios.MyViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate( R.layout.tarjeta_seleccionar_ejercicio, parent, false ) return MyViewHolder(itemView) } override fun onBindViewHolder(holder: AdaptadorTodosEjercicios.MyViewHolder, position: Int) { val ejercicioActual = this.lista[position] holder.nombreEjercicio.text = ejercicioActual.nombre val imageButton = holder.itemView.findViewById<ImageButton>(R.id.imButton_seleccionar_ejercicio) imageButton.setOnClickListener{ NuevaRutina.ejercicios_disponibles.removeAt(position) NuevaRutina.ejercicios_seleccionados.add(ejercicioActual) notifyDataSetChanged() contexto.adaptadorEjerciciosSeleccinados.notifyDataSetChanged() } } override fun getItemCount(): Int { return this.lista.size } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/AdaptadorTodosEjercicios.kt
2978378940
package com.example.ejercicios import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.modelos.Ejercicio class AdaptadorEjerciciosSeleccionados ( private val contexto: NuevaRutina, private val lista: ArrayList<Ejercicio>, private val recyclerView: RecyclerView ) : RecyclerView.Adapter< AdaptadorEjerciciosSeleccionados.MyViewHolder>() { inner class MyViewHolder (view: View) : RecyclerView.ViewHolder(view) { val nombreEjercicio: TextView init { nombreEjercicio = view.findViewById(R.id.tv_nombre_equino) } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): AdaptadorEjerciciosSeleccionados.MyViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate( R.layout.tarjeta_universal, parent, false ) return MyViewHolder(itemView) } override fun getItemCount(): Int { return this.lista.size } override fun onBindViewHolder(holder: AdaptadorEjerciciosSeleccionados.MyViewHolder, position: Int) { val ejercicioActual = this.lista[position] holder.nombreEjercicio.text = ejercicioActual.nombre val imageButton = holder.itemView.findViewById<ImageButton>(R.id.imButton_eliminar_ejercicio) imageButton.setOnClickListener{ NuevaRutina.ejercicios_seleccionados.removeAt(position) NuevaRutina.ejercicios_disponibles.add(ejercicioActual) notifyDataSetChanged() contexto.adaptadorEjerciciosDisponibles.notifyDataSetChanged() } } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/AdaptadorEjerciciosSeleccionados.kt
2331474340
package com.example.ejercicios import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.modelos.Equipamiento class AdaptadorEquipamientoSeleccionado ( private val contexto: NuevoEjercicio, private val lista: ArrayList<Equipamiento>, private val recyclerView: RecyclerView ) : RecyclerView.Adapter< AdaptadorEquipamientoSeleccionado.MyViewHolder>() { inner class MyViewHolder (view: View) : RecyclerView.ViewHolder(view) { val nombreEquipamiento: TextView init { nombreEquipamiento = view.findViewById(R.id.tv_nombre_equino) } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): AdaptadorEquipamientoSeleccionado.MyViewHolder { val itemView = LayoutInflater .from(parent.context) .inflate( R.layout.tarjeta_universal, parent, false ) return MyViewHolder(itemView) } override fun onBindViewHolder( holder: AdaptadorEquipamientoSeleccionado.MyViewHolder, position: Int ) { val equipamientoActual = this.lista[position] holder.nombreEquipamiento.text = equipamientoActual.nombre val imageButton = holder.itemView.findViewById<ImageButton>(R.id.imButton_eliminar_ejercicio) imageButton.setOnClickListener{ NuevoEjercicio.equipamiento_seleccionados.removeAt(position) NuevoEjercicio.equipamientos_disponibles.add(equipamientoActual) notifyDataSetChanged() contexto.adaptadorEquipamientosDisponibles.notifyDataSetChanged() } } override fun getItemCount(): Int { return this.lista.size } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/AdaptadorEquipamientoSeleccionado.kt
645305524
package com.example.ejercicios import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import com.example.ejercicios.firestore_database.FirestoreEjercicio import com.example.ejercicios.firestore_database.FirestoreEquipamiento import com.example.ejercicios.modelos.Equipamiento import com.google.android.material.snackbar.Snackbar class NuevoEquipamiento : AppCompatActivity() { private val firestoreEquipamiento = FirestoreEquipamiento() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nuevo_equipamiento) val botonGuardar = findViewById<Button>(R.id.btn_guardar_equipamiento) botonGuardar.setOnClickListener { val input_titulo_equipamiento = findViewById<EditText>(R.id.input_titulo_equipamiento) val tituloEquipamiento = if (input_titulo_equipamiento.text.isNotEmpty()) { input_titulo_equipamiento.text.toString() } else { mostrarSnackbar("Llene el campo Título") null } val input_descripcion = findViewById<EditText>(R.id.input_descripcion_equipamiento) val inpuDescripcion = if (input_descripcion.text.isNotEmpty()) { input_descripcion.text.toString() } else { mostrarSnackbar("Llene el campo Descripción") null } if (tituloEquipamiento !=null && inpuDescripcion != null ){ val nuevoEquipamiento = Equipamiento( "", tituloEquipamiento, inpuDescripcion ) firestoreEquipamiento.crearEquipamiento(nuevoEquipamiento) setResult(RESULT_OK) finish() } } val botonCancelar = findViewById<Button>(R.id.btn_cancelar_equipamiento) botonCancelar.setOnClickListener { finish() } } fun mostrarSnackbar(texto: String) { val snack = Snackbar.make( findViewById(R.id.id_layout_nuevo_ejercicio), texto, Snackbar.LENGTH_LONG ) snack.show() } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/NuevoEquipamiento.kt
1467263256
package com.example.ejercicios import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.RadioButton import android.widget.RadioGroup import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.ejercicios.firestore_database.FirestoreRutina import com.example.ejercicios.modelos.Ejercicio import com.example.ejercicios.modelos.Rutina import com.google.android.material.snackbar.Snackbar import com.google.firebase.firestore.QueryDocumentSnapshot import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class NuevaRutina : AppCompatActivity() { lateinit var adaptadorEjerciciosSeleccinados: AdaptadorEjerciciosSeleccionados lateinit var adaptadorEjerciciosDisponibles: AdaptadorTodosEjercicios private val firestoreRutina = FirestoreRutina() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nueva_rutina) rv_ejercicios_seleccionados() rv_seleccionar_ejercicios() val db = Firebase.firestore val ejerciciosExistentes = db.collection("ejercicios") ejercicios_disponibles.clear() adaptadorEjerciciosDisponibles.notifyDataSetChanged() ejerciciosExistentes .get() .addOnSuccessListener {result -> for (document in result) { anadirAArregloEjercicio(document) adaptadorEjerciciosDisponibles.notifyDataSetChanged() } } .addOnFailureListener { // Errores } adaptadorEjerciciosDisponibles.notifyDataSetChanged() val botonGuardar = findViewById<Button>(R.id.btn_guardar_rutina) botonGuardar.setOnClickListener { val input_titulo_rutina = findViewById<EditText>(R.id.input_titulo_rutina) val tituloRutina = if (input_titulo_rutina.text.isNotEmpty()) { input_titulo_rutina.text.toString() } else { mostrarSnackbar("Llene el campo Nombre") null } val radioGroup = findViewById<RadioGroup>(R.id.rg_dia_semana) val dia_seleccionado = radioGroup.checkedRadioButtonId val selection = findViewById<RadioButton>(dia_seleccionado)?.text?.toString() ?: run { mostrarSnackbar("Debe seleccionar un día de la semana") null } val inputDescripcion = findViewById<EditText>(R.id.input_descripcion_rutina) val descripcionRutina = if (inputDescripcion.text.isNotEmpty()) { inputDescripcion.text.toString() } else { mostrarSnackbar("Asigne una descripción") null } if (tituloRutina !=null && selection != null && descripcionRutina != null){ val nuevaRutina = Rutina( "", tituloRutina, descripcionRutina, 0.0, selection, ejercicios_seleccionados ) firestoreRutina.crearRutina(nuevaRutina) setResult(RESULT_OK) finish() } } val botonCancelar = findViewById<Button>(R.id.btn_cancelar_rutina) botonCancelar.setOnClickListener { finish() } } fun rv_ejercicios_seleccionados(){ val rv_ejercicios = findViewById<RecyclerView>(R.id.rv_ejercicios_seleccionar) adaptadorEjerciciosSeleccinados = AdaptadorEjerciciosSeleccionados( this, ejercicios_seleccionados, rv_ejercicios ) rv_ejercicios.adapter = adaptadorEjerciciosSeleccinados rv_ejercicios.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator() rv_ejercicios.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false) adaptadorEjerciciosSeleccinados.notifyDataSetChanged() } fun rv_seleccionar_ejercicios(){ val rv_ejercicios = findViewById<RecyclerView>(R.id.rv_todos_ejercicio) adaptadorEjerciciosDisponibles = AdaptadorTodosEjercicios( this, ejercicios_disponibles, rv_ejercicios ) rv_ejercicios.adapter = adaptadorEjerciciosDisponibles rv_ejercicios.itemAnimator = androidx.recyclerview.widget.DefaultItemAnimator() rv_ejercicios.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this) adaptadorEjerciciosDisponibles.notifyDataSetChanged() } fun anadirAArregloEjercicio( ejercicio: QueryDocumentSnapshot ){ val id = ejercicio.id val nuevoEjercicio = Ejercicio( id, ejercicio.data["nombre"] as String, ejercicio.data["descripcion"] as String, ejercicio.data["sets"] as Long, ejercicio.data["duracion"] as Long?, ejercicio.data["repeticiones"] as Long, ejercicio.data["pesoUtilizado"] as Double, ejercicio.data["nivelDificultad"] as Long, NuevoEjercicio.equipamientos_disponibles ) ejercicios_disponibles.add(nuevoEjercicio) } fun mostrarSnackbar(texto: String) { val snack = Snackbar.make( findViewById(R.id.id_layout_nueva_rutina), texto, Snackbar.LENGTH_LONG ) snack.show() } companion object{ var ejercicios_disponibles = arrayListOf<Ejercicio>() var ejercicios_seleccionados = arrayListOf<Ejercicio>() } }
EjerciciosApp/app/src/main/java/com/example/ejercicios/NuevaRutina.kt
3420342310
package com.radchuk.mornhouse 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.radchuk.mornhouse", appContext.packageName) } }
MornHouse/app/src/androidTest/java/com/radchuk/mornhouse/ExampleInstrumentedTest.kt
2289820077
package com.radchuk.mornhouse 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) } }
MornHouse/app/src/test/java/com/radchuk/mornhouse/ExampleUnitTest.kt
1966922574
package com.radchuk.mornhouse.ui.mainactivity import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.radchuk.mornhouse.data.model.Fact import com.radchuk.mornhouse.repository.FactRepository import kotlinx.coroutines.launch class FactViewModel(private val repository: FactRepository) : ViewModel() { fun insertFact(fact: Fact) { viewModelScope.launch { repository.insertFact(fact) } } suspend fun getAllFacts() = repository.getAllFacts() }
MornHouse/app/src/main/java/com/radchuk/mornhouse/ui/mainactivity/FactViewModel.kt
3209441448
package com.radchuk.mornhouse.ui.mainactivity import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.radchuk.mornhouse.R import com.radchuk.mornhouse.local.FactApiService import com.radchuk.mornhouse.local.FactRepositoryRemote import com.radchuk.mornhouse.databinding.ActivityMainBinding import com.radchuk.mornhouse.data.db.AppDatabase import com.radchuk.mornhouse.data.model.Fact import com.radchuk.mornhouse.repository.FactRepository import com.radchuk.mornhouse.ui.adapter.FactHistoryAdapter import com.radchuk.mornhouse.ui.detailactivity.DetailActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var viewModel: FactViewModel private lateinit var historyAdapter: FactHistoryAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val repository = FactRepository( AppDatabase.getInstance(application).factDao() ) viewModel = ViewModelProvider(this, FactViewModelFactory(repository)).get(FactViewModel::class.java) historyAdapter = FactHistoryAdapter(emptyList()) { navigateToDetailScreen(it) } binding.historyRecyclerView.layoutManager = LinearLayoutManager(this) binding.historyRecyclerView.adapter = historyAdapter binding.getFactButton.setOnClickListener { val number = binding.numberEditText.text.toString().toIntOrNull() if (number != null) { getFact(number) }else{ Toast.makeText(this, getString(R.string.enter_a_number), Toast.LENGTH_SHORT).show() } } binding.getRandomFactButton.setOnClickListener { getRandomFact() } loadHistory() } private fun getFact(number: Int) { MainScope().launch(Dispatchers.Main) { val factText = withContext(Dispatchers.IO) { FactRepositoryRemote(FactApiService.apiClient).getFactByNumber(number) } navigateToDetailScreen(Fact(number = number, text = factText)) viewModel.insertFact(Fact(number = number, text = factText)) updateHistory() } } private fun getRandomFact() { MainScope().launch(Dispatchers.Main) { val factText = withContext(Dispatchers.IO) { FactRepositoryRemote(FactApiService.apiClient).getRandomFact() } val number = factText.split(" ").get(0).toInt() navigateToDetailScreen(Fact(number = number, text = factText)) viewModel.insertFact(Fact(number = number, text = factText)) updateHistory() } } private fun loadHistory() { MainScope().launch(Dispatchers.Main) { val history = withContext(Dispatchers.IO) { viewModel.getAllFacts() } historyAdapter = FactHistoryAdapter(history) { navigateToDetailScreen(it) } binding.historyRecyclerView.adapter = historyAdapter } } private fun updateHistory() { MainScope().launch(Dispatchers.Main) { val history = withContext(Dispatchers.IO) { viewModel.getAllFacts() } historyAdapter.updateData(history) } } private fun navigateToDetailScreen(fact: Fact) { val intent = Intent(this, DetailActivity::class.java) intent.putExtra(DetailActivity.EXTRA_FACT, fact) startActivity(intent) } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/ui/mainactivity/MainActivity.kt
1563638596
package com.radchuk.mornhouse.ui.mainactivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.radchuk.mornhouse.repository.FactRepository class FactViewModelFactory(private val repository: FactRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.getConstructor(FactRepository::class.java).newInstance(repository) } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/ui/mainactivity/FactViewModelFactory.kt
4208125409
package com.radchuk.mornhouse.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.radchuk.mornhouse.R import com.radchuk.mornhouse.data.model.Fact class FactHistoryAdapter( private var history: List<Fact>, private val onItemClick: (Fact) -> Unit ) : RecyclerView.Adapter<FactHistoryAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_fact_history, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val fact = history[position] holder.bind(fact) holder.itemView.setOnClickListener { onItemClick(fact) } } override fun getItemCount(): Int = history.size fun updateData(newHistory: List<Fact>) { history = newHistory notifyDataSetChanged() } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(fact: Fact) { itemView.findViewById<TextView>(R.id.historyNumberTextView).text = fact.number.toString() itemView.findViewById<TextView>(R.id.historyPreviewTextView).text = fact.text } } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/ui/adapter/FactHistoryAdapter.kt
3188707766
package com.radchuk.mornhouse.ui.detailactivity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.radchuk.mornhouse.databinding.ActivityDetailBinding import com.radchuk.mornhouse.data.model.Fact class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding companion object { const val EXTRA_FACT = "extra_fact" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) val fact = intent.getParcelableExtra<Fact>(EXTRA_FACT) fact?.let { binding.detailNumberTextView.text = it.number.toString() binding.detailFactTextView.text = it.text } binding.imageButtonBack.setOnClickListener { this.finish() } } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/ui/detailactivity/DetailActivity.kt
122592378
package com.radchuk.mornhouse.repository import com.radchuk.mornhouse.data.dao.FactDao import com.radchuk.mornhouse.data.model.Fact class FactRepository(private val factDao: FactDao) { suspend fun insertFact(fact: Fact) { factDao.insertFact(fact) } suspend fun getAllFacts(): List<Fact> { return factDao.getAllFacts() } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/repository/FactRepository.kt
2806040474
package com.radchuk.mornhouse.local class FactRepositoryRemote(private val apiClient: FactApiClient) { suspend fun getFactByNumber(number: Int): String { return apiClient.getFactByNumber(number) } suspend fun getRandomFact(): String { return apiClient.getRandomFact() } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/local/FactRepositoryRemote.kt
1179023911
package com.radchuk.mornhouse.local import retrofit2.Retrofit import retrofit2.converter.scalars.ScalarsConverterFactory object FactApiService { private const val BASE_URL = "http://numbersapi.com/" val apiClient: FactApiClient = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()) .build() .create(FactApiClient::class.java) }
MornHouse/app/src/main/java/com/radchuk/mornhouse/local/FactApiService.kt
2415430281
package com.radchuk.mornhouse.local import retrofit2.http.GET import retrofit2.http.Path interface FactApiClient { @GET("{number}") suspend fun getFactByNumber(@Path("number") number: Int): String @GET("random/math") suspend fun getRandomFact(): String }
MornHouse/app/src/main/java/com/radchuk/mornhouse/local/FactApiClient.kt
3279710788
package com.radchuk.mornhouse.data.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.radchuk.mornhouse.data.model.Fact @Dao interface FactDao { @Insert suspend fun insertFact(fact: Fact) @Query("SELECT * FROM facts ORDER BY id DESC") suspend fun getAllFacts(): List<Fact> }
MornHouse/app/src/main/java/com/radchuk/mornhouse/data/dao/FactDao.kt
1063905762
package com.radchuk.mornhouse.data.model import android.os.Parcel import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "facts") data class Fact( @PrimaryKey(autoGenerate = true) val id: Long = 0, val number: Int, val text: String ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readLong(), parcel.readInt(), parcel.readString() ?: "" ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeLong(id) parcel.writeInt(number) parcel.writeString(text) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<Fact> { override fun createFromParcel(parcel: Parcel): Fact { return Fact(parcel) } override fun newArray(size: Int): Array<Fact?> { return arrayOfNulls(size) } } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/data/model/Fact.kt
2102356454
package com.radchuk.mornhouse.data.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.radchuk.mornhouse.data.dao.FactDao import com.radchuk.mornhouse.data.model.Fact @Database(entities = [Fact::class], version = 2, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun factDao(): FactDao companion object { private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, "fact-database") .build() } } }
MornHouse/app/src/main/java/com/radchuk/mornhouse/data/db/AppDatabase.kt
1512139006
package com.stochastictinkr.resourcescope import org.junit.jupiter.api.assertThrows import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class ResourceReceiverKtTest { @Test fun `ResourceReceiver or should return the value if available`() { val receiver: ResourceReceiver<Int, Int?> = ResourceReceiver<Int, Int> { value, _ -> accepted(value) } or null val transferResult = TransferResult<Int?>() with(receiver) { transferResult.receive(1) { } } assertTrue(transferResult.isSuccess) assertEquals(1, transferResult.value) } @Test fun `default ResourceReceiver fails if no value is available`() { val receiver: ResourceReceiver<Int, Int?> = ResourceReceiver<Int, Int> { value, _ -> accepted(value) } val transferResult = TransferResult<Int?>() with(receiver) { transferResult.noValue { "No value was found" } } assertFalse(transferResult.isSuccess) assertThrows<IllegalStateException> { assertNull(transferResult.value) } } @Test fun `ResourceReceiver or should return the alternative value if no value availiable`() { val receiver: ResourceReceiver<Int, Int?> = ResourceReceiver<Int, Int> { value, _ -> accepted(value) } or null val transferResult = TransferResult<Int?>() with(receiver) { transferResult.noValue { "No value was found" } } assertFalse(transferResult.isSuccess) assertNull(transferResult.value) } @Test fun `ResourceReceiver orElse should perform the alternative action if no value availiable`() { val receiver: ResourceReceiver<Int, Int?> = ResourceReceiver<Int, Int> { value, _ -> accepted(value) } orElse { rejected(-1) } val transferResult = TransferResult<Int?>() with(receiver) { transferResult.noValue { "No value was found" } } assertFalse { transferResult.isSuccess } assertEquals(-1, transferResult.value) } }
resourcescope/src/test/kotlin/com/stochastictinkr/resourcescope/ResourceReceiverKtTest.kt
3579943552
package com.stochastictinkr.resourcescope import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import kotlin.test.Test import kotlin.test.assertFailsWith import kotlin.test.assertNull import kotlin.test.assertTrue class ResourceScopeTest { @Test fun `initializeResource should return a Resource`() { val scope = ResourceScope() val resource = scope.initializeResource({ 1 }, {}) assertNotNull(resource) } @Test fun `constructCloseable should return a Resource`() { val scope = ResourceScope() val resource = scope.constructClosable { AutoCloseable { } } assertNotNull(resource) } @Test fun `constructCloseable should call close in destructor`() { val scope = ResourceScope() var closed = false val resource = scope.constructClosable { AutoCloseable { closed = true } } resource.close() assertTrue(closed) } @Test fun `resource value should be from the constructor`() { val scope = ResourceScope() val resource = scope.initializeResource({ 1 }, {}) assertEquals(1, resource.value) } @Test fun `resource can be manually closed`() { val scope = ResourceScope() val resource = scope.initializeResource({ 1 }, {}) resource.close() assertNull(resource.valueOrNull()) } @Test fun `initializeResource should throw if scope is closed`() { val scope = ResourceScope() scope.close() assertFailsWith<IllegalStateException> { scope.initializeResource({ 1 }, {}) } } @Test fun `initializeResource should throw if constructor throws`() { val scope = ResourceScope() assertFailsWith<RuntimeException> { scope.initializeResource({ throw RuntimeException() }, {}) } } @Test fun `resources should be closed when scope is closed`() { val scope = ResourceScope() val closed = mutableListOf<Int>() scope.initializeResource({ 1 }, { closed.add(it) }) scope.close() assertEquals(listOf(1), closed) } @Test fun `resources should be closed in reverse order of initialization`() { val scope = ResourceScope() val closed = mutableListOf<Int>() scope.initializeResource({ 1 }, { closed.add(it) }) scope.initializeResource({ 2 }, { closed.add(it) }) scope.initializeResource({ 3 }, { closed.add(it) }) scope.close() assertEquals(listOf(3, 2, 1), closed) } @Test fun `resources should be closed in reverse order of initialization even if some fail`() { val scope = ResourceScope() val closed = mutableListOf<Int>() scope.initializeResource({ 1 }, { closed.add(it) }) scope.initializeResource({ 2 }, { throw RuntimeException() }) scope.initializeResource({ 3 }, { closed.add(it) }) assertFailsWith<RuntimeException> { scope.close() } assertEquals(listOf(3, 1), closed) } @Test fun `resources can be transferred`() { val scope1 = ResourceScope() val scope2 = ResourceScope() val resource = scope1.initializeResource({ 1 }, {}) val transferred = scope2 takeOwnershipOf resource assertEquals(1, transferred.value) scope1.close() scope2.close() } @Test fun `transferred resources should only be closed by the new scope`() { val scope1 = ResourceScope() val scope2 = ResourceScope() val closed = mutableListOf<Int>() val resource = scope1.initializeResource({ 1 }, { closed.add(it) }) val transferred = scope2 takeOwnershipOf resource assertEquals(1, transferred.value) scope1.close() assertTrue(closed.isEmpty()) scope2.close() assertEquals(listOf(1), closed) } @Test fun `resource can be transferred via releaseTo and ownershipReceiver`() { val scope1 = ResourceScope() val scope2 = ResourceScope() val closed = mutableListOf<Int>() val resource = scope1.initializeResource({ 1 }, { closed.add(it) }) val transferred = resource releaseTo scope2.ownershipReceiver() assertEquals(1, transferred.value) scope1.close() assertTrue(closed.isEmpty()) scope2.close() assertEquals(listOf(1), closed) } @Test fun `releasing a closed resource should throw`() { val scope1 = ResourceScope() val scope2 = ResourceScope() val resource = scope1.initializeResource({ 1 }, {}) resource.close() assertFailsWith<IllegalStateException> { resource releaseTo scope2.ownershipReceiver() } } @Test fun `resources can be removed`() { val scope = ResourceScope() val closed = mutableListOf<Int>() val resource = scope.initializeResource({ 1 }, { closed.add(it) }) scope.remove(resource) scope.close() assertTrue(closed.isEmpty()) } @Test fun `removed resources should not be closed`() { val scope = ResourceScope() val closed = mutableListOf<Int>() val resource = scope.initializeResource({ 1 }, { closed.add(it) }) scope.remove(resource) scope.close() assertTrue(closed.isEmpty()) } @Test fun `removed resources can be added back`() { val scope = ResourceScope() val closed = mutableListOf<Int>() val resource = scope.initializeResource({ 1 }, { closed.add(it) }) scope.remove(resource) scope.takeOwnershipOf(resource) scope.close() assertEquals(listOf(1), closed) } // DSL tests @Test fun `resourceScope should define usable scope`() { resourceScope { val resource = construct { 1 } finally { } assertEquals(1, resource.value) } } @Test fun `finally can take a function reference`() { var closed = false fun close() { closed = true } resourceScope { construct { 1 } finally ::close } assertTrue(closed) } @Test fun `resource valueOrNull should be null if scope is closed`() { val resource = resourceScope { construct { 1 } finally { } } assertNull(resource.valueOrNull()) } @Test fun `resource valueOrNull should be value if scope is not closed`() { resourceScope { val valueOrNull = (construct { 1 } finally { }).valueOrNull() assertEquals(1, valueOrNull) } } @Test fun `resourceScope should close resources`() { val closed = mutableListOf<Int>() resourceScope { construct { 1 } finally { closed.add(this) } construct { 2 } finally { closed.add(this) } construct { 3 } finally { closed.add(this) } } assertEquals(listOf(3, 2, 1), closed) } @Test fun `then should act on resource`() { val configured = mutableListOf<Int>() val closed = mutableListOf<Int>() resourceScope { construct { 1 } then { configured.add(this) } finally { closed.add(this) } assertEquals(listOf(1), configured) assertTrue(closed.isEmpty()) } assertEquals(listOf(1), closed) } @Test fun `then can be chained`() { val configured = mutableListOf<Int>() val closed = mutableListOf<Int>() resourceScope { construct { 1 } then { configured.add(this) } then { configured.add(this) } finally { closed.add(this) } assertEquals(listOf(1, 1), configured) assertTrue(closed.isEmpty()) } assertEquals(listOf(1), closed) } @Test fun `takeOwnershipOf works on foreign resources`() { val scope1 = ResourceScope() val scope2 = ResourceScope() val resource = scope1.initializeResource({ 1 }, {}) // This bypasses the optimization of takeOwnershipOf in ResourceScopeImpl val resourceDelegate = object : Resource<Int> by resource {} val transferred = scope2.takeOwnershipOf(resourceDelegate) assertEquals(1, transferred.value) scope1.close() scope2.close() } @Test fun `destructuring of Resource works as expected`() { resourceScope { val (value, resource) = construct { 1 } finally { } assertEquals(1, value) assertEquals(1, resource.value) } } }
resourcescope/src/test/kotlin/com/stochastictinkr/resourcescope/ResourceScopeTest.kt
384543118
package com.stochastictinkr.resourcescope.internal import kotlin.test.Test import kotlin.test.assertFailsWith import kotlin.test.assertTrue class ResourceImplTest { @Test fun `value on uninitialized resource should throw`() { // This test is the only way to get 100% coverage on ResourceImpl, since this case is not possible in practice. val resource = ResourceImpl<Int>(ResourceScopeImpl()) assertFailsWith<IllegalStateException> { resource.value }.message?.contains("Access to uninitialized resource")?.let { assertTrue(it) } } }
resourcescope/src/test/kotlin/com/stochastictinkr/resourcescope/internal/ResourceImplTest.kt
57414926
package com.stochastictinkr.resourcescope import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class TransferResultTest { @Test fun `uninitialized result should behave as expected`() { val result = TransferResult<Int>() assertFalse(result.isSuccess) assertFailsWith<IllegalStateException> { result.value } assertFailsWith<IllegalStateException> { result.valueOrNull() } } @Test fun `accepted result should behave as expected`() { val result = TransferResult<Int>() result.accepted(1) assertTrue(result.isSuccess) assertEquals(1, result.value) assertEquals(1, result.valueOrNull()) } @Test fun `rejected result should behave as expected`() { val result = TransferResult<Int>() result.rejected(1) assertFalse(result.isSuccess) assertEquals(1, result.value) assertEquals(1, result.valueOrNull()) } @Test fun `failed result should behave as expected`() { val result = TransferResult<Int>() result.failed(RuntimeException()) assertFalse(result.isSuccess) assertFailsWith<RuntimeException> { result.value } assertNull(result.valueOrNull()) } }
resourcescope/src/test/kotlin/com/stochastictinkr/resourcescope/TransferResultTest.kt
2929816392
package com.stochastictinkr.resourcescope /** * Defines a resource constructor. See [construct] for more details. */ @ResourceBuilderDsl data class ResourceConstructor<V>(val constructor: () -> V, val configure: (V.() -> Unit)? = null) { /** * Configures the resource after it is constructed. * * @param configure the configuration function * @return a new [ResourceConstructor] with the specified configuration */ infix fun then(configure: V.() -> Unit) = copy( configure = this.configure?.let { existing -> { existing() configure() } } ?: { configure() } ) }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/ResourceConstructor.kt
1383283662
package com.stochastictinkr.resourcescope /** * Defines a resource constructor. This is the first step in creating a resource. * * Once a resource constructor is defined, it can be configured with an optional [then] and added to * a resource scope with [ResourceScope.finally]. * * example: * ``` * class MyResource(var value: Long = 0) { * companion object { * fun acquireMyResource() { ... } * } * fun destroy() { ... } * } * * resourceScope { * val resource = construct { MyResource() } then { value = acquireMyResource() } finally { destroy() } * // use resource * // resource is destroyed when resourceScope is closed * } * ``` */ @ResourceBuilderDsl fun <V> construct(constructor: () -> V) = ResourceConstructor(constructor)
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/Construct.kt
1905624661
package com.stochastictinkr.resourcescope /** * Resource builder DSL marker. */ @DslMarker annotation class ResourceBuilderDsl
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/ResourceBuilderDsl.kt
1418689029
package com.stochastictinkr.resourcescope /** * A ResourceReceiver is a function that receives a resource value and a destructor action. * * The receiver can accept the resource value and destructor, reject the resource value, or * reject the resource value with an exception. */ fun interface ResourceReceiver<V, out R> { /** * Receives the resource value and destructor. * Implementations of this method must call exactly one of the following methods exactly once: * * [TransferResult.accepted] - The resource was successfully acquired. The ResourceReceiver is now responsible for closing the resource. * This should only be called when the receiver has successfully taken ownership of the resource. * * [TransferResult.rejected] - The resource was not acquired, but the request was not an error. The ResourceReceiver does not take ownership of the resource. * * [TransferResult.failed] - The resource was not acquired, and the request was an error. The ResourceReceiver does not take ownership of the resource. */ fun TransferResult<in R>.receive(value: V, destructor: V.() -> Unit) /** * Called when the resource value is not available. This can happen if the resource was already closed, or if the resource was not initialized. * Implementations of this method must call exactly one of the following methods exactly once: * * [TransferResult.rejected] - The result value to use when the resource is not available. * * [TransferResult.failed] - The exception to throw when the resource is not available. * * The default implementation throws an IllegalStateException. * * @param lazyMessage a function that returns the message which conveys why the resource is not available. */ fun TransferResult<in R>.noValue(lazyMessage: () -> Any): Unit = failed(IllegalStateException(lazyMessage().toString())) } /** * Create a ResourceReceiver with the `noValue` function replaced with the rejection with the specified value. * * Example usage: * ``` * val resource = constructor { 1 } finally { close(this) } * val result = resource.releaseTo(ResourceReceiver<Int, Int> { value, _ -> accepted(value) } or 0) * ``` * */ infix fun <V, R> ResourceReceiver<V, R>.or(noValueResult: R) = orElse { rejected(noValueResult) } /** * Create a ResourceReceiver with the `noValue` function replaced with the given function. * * Example usage: * ``` * val resource = constructor { 1 } finally { close(this) } * val result = resource.releaseTo(ResourceReceiver<Int, Int> { value, _ -> accepted(value) } orElse { rejected(0) }) * ``` */ infix fun <V, R> ResourceReceiver<V, R>.orElse(noValueFun: TransferResult<in R>.(lazyMessage: () -> Any) -> Unit): ResourceReceiver<V, R> { val outer = this return object : ResourceReceiver<V, R> by (outer) { override fun TransferResult<in R>.noValue(lazyMessage: () -> Any) { noValueFun(lazyMessage) } } }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/ResourceReceiver.kt
87024633
package com.stochastictinkr.resourcescope import com.stochastictinkr.resourcescope.internal.ResourceScopeImpl import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.reflect.KFunction0 /** * A scope of managed resources. * * Resources can be created by calling [initializeResource], or by using the [ResourceConstructor] DSL. * Resources are destroyed when the scope is closed, in the reverse order of when they were added to the scope. * * Resources can be transferred between scopes by calling [takeOwnershipOf] or by using the [ownershipReceiver]. * * Resources can be removed from the scope by calling [remove]. This will prevent the resource from being closed when the scope is closed. * * @see Resource */ interface ResourceScope : AutoCloseable { /** * Creates a resource that is managed by this scope. * * @param constructor the resource constructor * @return the created resource */ fun <V> initializeResource(constructor: () -> V, destructor: (V) -> Unit): Resource<V> /** * Creates a resource that is managed by this scope. The resource will be closed by calling [AutoCloseable.close]. * * @param constructor the resource constructor * @return the created resource */ fun <V : AutoCloseable> constructClosable(constructor: () -> V): Resource<V> = initializeResource(constructor) { it.close() } /** * Creates a resource that is managed by this scope. The resource will be closed by calling the [destructor]. * * @see [construct] for example usage. * @receiver the resource constructor created by [construct] * @return the created resource */ @ResourceBuilderDsl infix fun <V> ResourceConstructor<V>.finally(destructor: V.() -> Unit): Resource<V> = initializeResource(constructor, destructor).also { configure?.invoke(it.value) } /** * Creates a resource that is managed by this scope. The resource will be closed by calling the [destructor]. * This overload is useful when the destructor is a function reference that is global. * * @see [construct] for example usage. * @receiver the resource constructor created by [construct] * @return the created resource */ @ResourceBuilderDsl infix fun <V> ResourceConstructor<V>.finally(destructor: KFunction0<Unit>): Resource<V> = finally { destructor() } /** * Takes ownership of the specified resource. * The resource will be removed from its current scope, and added to this scope. * If the resource is already managed by this scope, it will be returned as-is, and no changes will be made. * * @param resource the resource to be transferred. * @return a potentially new resource that is managed by this scope. * @throws IllegalStateException if this scope is already closed. * */ infix fun <V> takeOwnershipOf(resource: Resource<V>): Resource<V> /** * Removes the specified resource from this scope. The resource will need to be closed manually. * * @param resource the resource to be removed. * @throws IllegalArgumentException if the resource is not managed by this scope. * @throws IllegalStateException if this scope is already closed. */ fun remove(resource: Resource<*>) /** * A receiver that takes ownership of a resource and returns a new resource. */ fun <V> ownershipReceiver(): ResourceReceiver<V, Resource<V>> /** * Closes this scope, and all resources managed by this scope. */ override fun close() } /** * Creates and uses a [ResourceScope], and closes it when the block completes. */ @OptIn(ExperimentalContracts::class) inline fun <R> resourceScope(block: ResourceScope.() -> R): R { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return ResourceScope().use(block) } /** * Creates a [ResourceScope]. The caller is responsible for closing the scope. */ fun ResourceScope(): ResourceScope = ResourceScopeImpl()
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/ResourceScope.kt
4225409141
package com.stochastictinkr.resourcescope.internal import com.stochastictinkr.resourcescope.Resource import com.stochastictinkr.resourcescope.ResourceReceiver import com.stochastictinkr.resourcescope.ResourceScope import java.util.LinkedList import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * A thread safe implementation of [ResourceScope]. */ internal class ResourceScopeImpl : ResourceScope { /** * A lock used to synchronize access to the state of this scope. */ private val lock = ReentrantLock() /** * Possible states of this scope. */ private sealed interface State /** * Represents an open scope, with a list of resources. */ private class Open : State { val resources = LinkedList<ResourceImpl<*>>() } /** * Represents a closed scope. */ private data object Closed : State /** * The current state of this scope. Initialized to [Open]. */ private var state: State = Open() override fun <V> initializeResource(constructor: () -> V, destructor: (V) -> Unit): Resource<V> { // Ordering is important here. We want to push the resource to the stack before initializing it. // This ensures that there is no window where the resource is initialized but not yet pushed to the stack. val resource = ResourceImpl<V>(this) push(resource) val initialize = try { resource.initialize(constructor, destructor) } catch (ex: Throwable) { // Remove from the stack since initialization failed. remove(resource) throw ex } if (!initialize) { // Remove from the stack since initialization failed. remove(resource) } return resource } /** * Pushes a cleanup to the top of the stack. */ private fun <V> push(resource: ResourceImpl<V>) { lock.withLock { val currentState = state check(currentState is Open) { "Cleanup Scope is closed." } currentState.resources.addFirst(resource) } } override fun remove(resource: Resource<*>) { lock.withLock { val currentState = state check(currentState is Open) { "Cleanup Scope is closed." } check(currentState.resources.remove(resource)) { "Cleanup is not in this scope" } (resource as ResourceImpl).releasedFrom(this) } } override fun close() { val currentState: State? lock.withLock { currentState = this.state this.state = Closed } if (currentState is Open) { var exception: Throwable? = null val cleanups = currentState.resources while (true) { try { cleanups.pollFirst()?.scopeClosing(this) ?: break } catch (ex: Throwable) { try { exception?.let(ex::addSuppressed) exception = ex } catch (yikes: Throwable) { yikes.printStackTrace() } } } exception?.let { throw it } } } internal fun <V> resourceClosing(cleanup: ResourceImpl<V>) { lock.withLock { (state as? Open)?.resources?.remove(cleanup) } } override fun <V> takeOwnershipOf(resource: Resource<V>): Resource<V> { // already own if (resource.scope === this) return resource // in-place if (resource is ResourceImpl) { lock.withLock { val currentState = state check(currentState is Open) { "Cleanup Scope is closed." } currentState.resources.addFirst(resource) resource.movingScope(this) } return resource } // allocate a new resource impl, and attempt to move it over. return resource.releaseTo(ownershipReceiver()) } override fun <V> ownershipReceiver() = ResourceReceiver<V, Resource<V>> { value, destructor -> val resource = ResourceImpl(this@ResourceScopeImpl, value, destructor) push(resource) accepted(resource) } }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/internal/ResourceScopeImpl.kt
1838155758
package com.stochastictinkr.resourcescope.internal import com.stochastictinkr.resourcescope.Resource import com.stochastictinkr.resourcescope.ResourceReceiver import com.stochastictinkr.resourcescope.TransferResult import com.stochastictinkr.resourcescope.or /** * A thread safe implementation of [Resource] that is managed by a [ResourceScopeImpl]. * * @param V the type of the resource * @param scope the scope that manages this resource * @param state the current state of the resource, or the resource itself. * @param destructor the action to be performed when the resource is closed. */ internal class ResourceImpl<V>( scope: ResourceScopeImpl, private var state: Any? = Uninitialized, private var destructor: ((V) -> Unit)? = null, ) : Resource<V> { /** * Represents an uninitialized resource. */ private data object Uninitialized /** * Represents a closed resource. */ private data object Closed /** * A lock used to synchronize access to the resource value. */ private inline fun <R> withLock(action: () -> R): R = synchronized(this, action) /** * Initializes the state of this resource. * * @param constructor the function that produces the resource value. * @param destructor the action to be performed if the resource fails to initialize. * @return true if the resource was successfully initialized, or false otherwise. * @throws Throwable if the resource fails to initialize. * @throws IllegalStateException if the resource is already initialized. */ internal fun initialize(constructor: () -> V, destructor: (V) -> Unit) = withLock { check(state == Uninitialized) { "Attempt to reinitialize resource" } this.destructor = destructor try { state = constructor() } catch (ex: Throwable) { withActiveResource(state) { destructor(it) } state = Closed throw ex } state != Closed } override var scope: ResourceScopeImpl? = scope private set override val value: V get() = sendState(state) { value, _ -> accepted(value) }.value override fun valueOrNull(): V? = sendState(state, ResourceReceiver<V, V?> { value, _ -> accepted(value) } or null).value /** * Executes the specified action with the given resource value if it is active. */ private inline fun <R> withActiveResource(state: Any?, crossinline action: (V) -> R): R? = sendState(state, (ResourceReceiver { value, _ -> accepted(action(value)) } or null)).value /** * Closes this resource, and removes it from its owning scope. */ override fun close(): Unit = withLock { try { // Remove the resource from the scope before closing it. scope?.resourceClosing(this) } finally { scope = null // Close the resource. val previousState = state state = Closed // Perform the destructor action if the resource was active. destroy(previousState) } } private fun destroy(state: Any?) { withActiveResource(state) { destructor?.let { destroy -> destroy(it) } } } /** * Removes this resource from its owning scope. */ private fun removeFromScope() { try { scope?.remove(this) } finally { scope = null } } internal fun releasedFrom(parentScope: ResourceScopeImpl) = withLock { check(scope === parentScope) { "Releasing resource from the wrong scope" } scope = null } /** * Releases this resource to the specified receiver, changing the state of this resource to [Closed] if the * transfer is successful. */ override fun <R> releaseTo(target: ResourceReceiver<V, R>): R = withLock { val result = sendState(state, target) if (result.isSuccess) { state = Closed removeFromScope() } result.value } /** * Sends the current state of this resource to the specified receiver. */ private fun <R> sendState(state: Any?, receiver: ResourceReceiver<V, R>): TransferResult<R> = TransferResult<R>() .also { result -> receiver.run { when (state) { Uninitialized -> result.noValue { "Access to uninitialized resource" } Closed -> result.noValue { "Access to closed resource" } else -> @Suppress("UNCHECKED_CAST") (result.receive(state as V, destructor!!)) } } } /** * Close this resource due to an owner scope closing. */ internal fun scopeClosing(closingScope: ResourceScopeImpl) = withLock { check(scope === closingScope) { "Closing Cleanup from the wrong CleanupScope" } scope = null val previousState = state state = Closed destroy(previousState) } /** * Moves this resource to a new owning scope. */ internal fun movingScope(newScope: ResourceScopeImpl) = withLock { removeFromScope() scope = newScope } }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/internal/ResourceImpl.kt
4219160228
package com.stochastictinkr.resourcescope /** * A resource that can managed by a [ResourceScope]. * * @param V the type of the resource */ interface Resource<V> : AutoCloseable { /** * The scope that manages this resource. */ val scope: ResourceScope? /** * The value of the resource. */ val value: V /** * The value of the resource, or `null` if the resource is closed. */ fun valueOrNull(): V? /** * Closes this resource. Calling this method more than once has no effect. */ override fun close() /** * Releases this resource to the specified [target] receiver. * The [target] receiver will receive the value of this resource, and will be responsible for closing it. * * @param target the target receiver * @return the result of the [target] receiver after receiving the value of this resource */ infix fun <R> releaseTo(target: ResourceReceiver<V, R>): R operator fun component1() = value operator fun component2() = this }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/Resource.kt
675905889
package com.stochastictinkr.resourcescope /** * The result of a resource transfer. This is used to indicate whether a resource was successfully * acquired or not. * * The result can be in one of four states: * <ul> * <li>Uninitialized: The result has not yet been set.</li> * <li>Accepted: The resource was successfully acquired.</li> * <li>Rejected: The resource was not acquired, but the request was not an error.</li> * <li>Failed: The resource was not acquired, and the request was an error.</li> * </ul> * * @param R The type of the resource. */ @Suppress("unused") class TransferResult<R> { private sealed interface NotSuccess private data object Uninitialized : NotSuccess private data class Failure(val exception: Throwable) : NotSuccess private data class Rejected(val value: Any?) : NotSuccess private var valueField: Any? = Uninitialized /** * Returns the value of the result, or null if the result was rejected or failed. * * @throws IllegalStateException if the result has not yet been set. */ fun valueOrNull(): R? { @Suppress("UNCHECKED_CAST") return when (val value = valueField) { Uninitialized -> uninitializedError() is Failure -> null is Rejected -> value.value else -> value } as R? } /** * Returns the value of the result if the transfer was accepted or rejected, or throws the * failure exception if the transfer failed. * * @throws IllegalStateException if the result has not yet been set. * @throws Throwable if the result was failure. */ val value: R get() { @Suppress("UNCHECKED_CAST") return when (val value = valueField) { Uninitialized -> uninitializedError() is Failure -> throw value.exception is Rejected -> value.value else -> value } as R } private fun uninitializedError(): Nothing = error("Result not yet initialized") /** * Returns true if the transfer was accepted or false otherwise. */ val isSuccess get() = valueField !is NotSuccess /** * Sets the transfer as successful with the given result. * @throws IllegalStateException if the result has already been set. */ fun accepted(result: R) = initializeValue { result } /** * Sets the transfer as rejected with the given result. * @throws IllegalStateException if the result has already been set. */ fun rejected(result: R) = initializeValue { Rejected(result) } /** * Sets the transfer as failed with the given exception. * @throws IllegalStateException if the result has already been set. */ fun failed(failure: Throwable) = initializeValue { Failure(failure) } /** * Sets the result value if it has not yet been set. * @throws IllegalStateException if the result has already been set. */ private inline fun initializeValue(value: () -> Any?) { check(valueField == Uninitialized) { "Can not change result once set." } valueField = value() } }
resourcescope/src/main/kotlin/com/stochastictinkr/resourcescope/TransferResult.kt
4243348672
package com.example.beepkeep 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.beepkeep", appContext.packageName) } }
BeepKeep/app/src/androidTest/java/com/example/beepkeep/ExampleInstrumentedTest.kt
2044742493
package com.example.beepkeep 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) } }
BeepKeep/app/src/test/java/com/example/beepkeep/ExampleUnitTest.kt
1909633563
package com.example.compose import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6750A4) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFE9DDFF) val md_theme_light_onPrimaryContainer = Color(0xFF23005C) val md_theme_light_secondary = Color(0xFF006A63) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFF71F7EB) val md_theme_light_onSecondaryContainer = Color(0xFF00201D) val md_theme_light_tertiary = Color(0xFF2B5EA7) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFD7E3FF) val md_theme_light_onTertiaryContainer = Color(0xFF001B3F) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFF8FDFF) val md_theme_light_onBackground = Color(0xFF001F25) val md_theme_light_surface = Color(0xFFF8FDFF) val md_theme_light_onSurface = Color(0xFF001F25) val md_theme_light_surfaceVariant = Color(0xFFE7E0EB) val md_theme_light_onSurfaceVariant = Color(0xFF49454E) val md_theme_light_outline = Color(0xFF7A757F) val md_theme_light_inverseOnSurface = Color(0xFFD6F6FF) val md_theme_light_inverseSurface = Color(0xFF00363F) val md_theme_light_inversePrimary = Color(0xFFD0BCFF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF6750A4) val md_theme_light_outlineVariant = Color(0xFFCAC4CF) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFD0BCFF) val md_theme_dark_onPrimary = Color(0xFF381E72) val md_theme_dark_primaryContainer = Color(0xFF4F378A) val md_theme_dark_onPrimaryContainer = Color(0xFFE9DDFF) val md_theme_dark_secondary = Color(0xFF50DBCF) val md_theme_dark_onSecondary = Color(0xFF003733) val md_theme_dark_secondaryContainer = Color(0xFF00504B) val md_theme_dark_onSecondaryContainer = Color(0xFF71F7EB) val md_theme_dark_tertiary = Color(0xFFABC7FF) val md_theme_dark_onTertiary = Color(0xFF002F65) val md_theme_dark_tertiaryContainer = Color(0xFF02458E) val md_theme_dark_onTertiaryContainer = Color(0xFFD7E3FF) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF001F25) val md_theme_dark_onBackground = Color(0xFFA6EEFF) val md_theme_dark_surface = Color(0xFF001F25) val md_theme_dark_onSurface = Color(0xFFA6EEFF) val md_theme_dark_surfaceVariant = Color(0xFF49454E) val md_theme_dark_onSurfaceVariant = Color(0xFFCAC4CF) val md_theme_dark_outline = Color(0xFF948F99) val md_theme_dark_inverseOnSurface = Color(0xFF001F25) val md_theme_dark_inverseSurface = Color(0xFFA6EEFF) val md_theme_dark_inversePrimary = Color(0xFF6750A4) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFD0BCFF) val md_theme_dark_outlineVariant = Color(0xFF49454E) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFFA18ED1)
BeepKeep/app/src/main/java/com/example/beepkeep/ui/theme/Color.kt
741190434
package com.example.compose import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun BeepKeepTheme( useDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit ) { val colors = if (!useDarkTheme) { LightColors } else { DarkColors } MaterialTheme( colorScheme = colors, content = content ) }
BeepKeep/app/src/main/java/com/example/beepkeep/ui/theme/Theme.kt
567218178
package com.example.beepkeep.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
BeepKeep/app/src/main/java/com/example/beepkeep/ui/theme/Type.kt
974527493
package com.example.beepkeep import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.compose.BeepKeepTheme @Composable fun BPEntryBox(modifier: Modifier = Modifier) { Box( modifier = Modifier .padding(16.dp) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .padding(16.dp) ) { SystolicRow() DiastolicRow() PulseRow() Button( onClick = { /*TODO*/ }, modifier = Modifier .align(Alignment.End) .padding(16.dp) ) { Text(text = "Submit") } } } } @Preview @Composable fun BeepKeepPreview() { BeepKeepTheme(useDarkTheme = false) { Surface( color = MaterialTheme.colorScheme.background ) { BPEntryBox() } } } @Preview @Composable fun BeepKeepDarkThemePreview() { BeepKeepTheme(useDarkTheme = true) { Surface( color = MaterialTheme.colorScheme.background ) { BPEntryBox() } } }
BeepKeep/app/src/main/java/com/example/beepkeep/BPEntry.kt
1643922634
package com.example.beepkeep import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.AlertDialogDefaults.shape import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextFieldColors import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.compose.BeepKeepTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BeepKeepTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { BeepKeepApp() } } } } } @Composable fun BeepKeepApp() { Column { Spacer(modifier = Modifier .fillMaxWidth() .size(64.dp) ) TitleBox(modifier = Modifier .align(Alignment.CenterHorizontally) ) BPEntryBox(modifier = Modifier.weight(2f)) Spacer(modifier = Modifier.weight(1f)) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SystolicRow() { var systolicText by remember { mutableStateOf("") } var systolicColor: Color by remember { mutableStateOf(Color.Gray) } if (systolicText.isNotBlank()) { systolicColor = when (systolicText.toInt()){ in 20 .. 119 -> Color.Green in 120 .. 139 -> Color.Yellow in 140 .. 180 -> Color.Red else -> Color.Gray } } else { systolicColor = Color.Transparent } Row { Box( modifier = Modifier .size(20.dp) .clip(shape) .background(systolicColor) .align(Alignment.CenterVertically) ) Spacer(modifier = Modifier.weight(1f)) OutlinedTextField( value = systolicText, onValueChange = { systolicText = it }, label = { Text("Systolic") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier .padding(end = 8.dp) ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DiastolicRow() { var diastolicText by remember { mutableStateOf("") } var diastolicColor: Color by remember { mutableStateOf(Color.Gray) } if (diastolicText.isNotBlank()) { diastolicColor = when (diastolicText.toInt()){ in 1 .. 79 -> Color.Green in 80 .. 90 -> Color.Yellow in 90 .. 120 -> Color.Red else -> Color.Gray } } else { diastolicColor = Color.Transparent } Row { Box( modifier = Modifier .size(20.dp) .clip(shape) .background(diastolicColor) .align(Alignment.CenterVertically) ) Spacer(modifier = Modifier.weight(1f)) OutlinedTextField( value = diastolicText, onValueChange = { diastolicText = it }, label = { Text("Diastolic") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier .padding(end = 8.dp) ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun PulseRow() { var pulseText by remember { mutableStateOf("") } var pulseColor: Color by remember { mutableStateOf(Color.Gray) } if (pulseText.isNotBlank()) { pulseColor = when (pulseText.toInt()){ in 0 .. 79 -> Color.Green in 80 .. 90 -> Color.Yellow in 90 .. 120 -> Color.Red else -> Color.Gray } } Row { Spacer(modifier = Modifier.weight(1f)) OutlinedTextField( value = pulseText, onValueChange = { pulseText = it }, label = { Text("Pulse") }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier .padding(end = 8.dp) ) } } @Preview @Composable fun BeepKeepAppPreview() { BeepKeepTheme(useDarkTheme = false) { Surface( color = MaterialTheme.colorScheme.background ) { BeepKeepApp() } } } @Preview @Composable fun BeepKeepAppDarkThemePreview() { BeepKeepTheme(useDarkTheme = true) { Surface( color = MaterialTheme.colorScheme.background ) { BeepKeepApp() } } }
BeepKeep/app/src/main/java/com/example/beepkeep/MainActivity.kt
115641343
package com.example.beepkeep import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text 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.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.compose.BeepKeepTheme @Composable fun TitleBox( modifier: Modifier = Modifier, titleMargin: Dp = 8.dp, // Adjust spacing as needed subtitleColor: Color = Color.Gray, // Customize subtitle color ) { Box( modifier = modifier.padding(16.dp), contentAlignment = Alignment.Center, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .padding(16.dp) ) { Text( text = "BeepKeep", style = MaterialTheme.typography.headlineLarge, modifier = Modifier.padding(bottom = titleMargin) ) Text( text = "The app where you keep your beep", style = MaterialTheme.typography.bodyMedium, color = subtitleColor ) } } } @Preview(showBackground = true) @Composable fun TitleBoxPreview() { BeepKeepTheme(useDarkTheme = false) { Surface( color = MaterialTheme.colorScheme.background ) { TitleBox() } } } @Preview(showBackground = true) @Composable fun TitleBoxPreviewDarkTheme() { BeepKeepTheme(useDarkTheme = true) { Surface( color = MaterialTheme.colorScheme.background ) { TitleBox() } } }
BeepKeep/app/src/main/java/com/example/beepkeep/TitleBox.kt
1489832079
package com.example.beepkeep import androidx.compose.foundation.layout.Row import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.beepkeep.model.Entry import com.example.beepkeep.model.SampleRepo import com.example.compose.BeepKeepTheme @Composable fun LargeNumberColumn() { LazyColumn { items(SampleRepo.entries) { entry -> NumberRow(entry = entry) } } } @Composable fun NumberRow(entry: Entry) { Row { Text(text = entry.systolic.toString(), modifier = Modifier.weight(1f)) Text(text = entry.diastolic.toString(), modifier = Modifier.weight(1f)) Text(text = entry.pulse.toString(), modifier = Modifier.weight(1f)) } } @Preview(showBackground = true) @Composable fun LargeNumberColumnPreview() { BeepKeepTheme(useDarkTheme = false) { Surface( color = MaterialTheme.colorScheme.background ) { LargeNumberColumn() } } } @Preview(showBackground = true) @Composable fun LargeNumberColumnPreviewDarkTheme() { BeepKeepTheme(useDarkTheme = true) { Surface( color = MaterialTheme.colorScheme.background ) { LargeNumberColumn() } } }
BeepKeep/app/src/main/java/com/example/beepkeep/BPHistory.kt
3359994851
package com.example.beepkeep.model import androidx.annotation.StringRes data class Entry( val systolic: Int, val diastolic: Int, val pulse: Int )
BeepKeep/app/src/main/java/com/example/beepkeep/model/Entry.kt
3554269625
package com.example.beepkeep.model object SampleRepo { val entries = listOf( Entry( systolic = 120, diastolic = 89, pulse = 78 ), Entry( systolic = 134, diastolic = 92, pulse = 100 ), Entry( systolic = 118, diastolic = 85, pulse = 83 ), Entry( systolic = 90, diastolic = 89, pulse = 78 ), Entry( systolic = 127, diastolic = 80, pulse = 78 ), Entry( systolic = 111, diastolic = 78, pulse = 78 ) ) }
BeepKeep/app/src/main/java/com/example/beepkeep/model/SampleRepo.kt
2821983265
package net.iessochoa.hectormanuelgelardosabater.practica5 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("net.iessochoa.hectormanuelgelardosabater.practica5", appContext.packageName) } }
Practica5_Parte6/app/src/androidTest/java/net/iessochoa/hectormanuelgelardosabater/practica5/ExampleInstrumentedTest.kt
369434787
package net.iessochoa.hectormanuelgelardosabater.practica5 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) } }
Practica5_Parte6/app/src/test/java/net/iessochoa/hectormanuelgelardosabater/practica5/ExampleUnitTest.kt
3451736225
package ViewModel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.switchMap import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import model.Tarea import repository.Repository class AppViewModel(application: Application) : AndroidViewModel(application) { //creamos el LiveData de tipo Booleano. Representa nuestro filtro //private val soloSinPagarLiveData= MutableLiveData<Boolean>(false) //repositorio private val repositorio:Repository //liveData de lista de tareas var tareasLiveData :LiveData<List<Tarea>> //private val estadoLiveData = MutableLiveData<Int>(3) //LiveData que cuando se modifique un filtro cambia el tareasLiveData val SOLO_SIN_PAGAR="SOLO_SIN_PAGAR" val ESTADO="ESTADO" val PRIORIDAD="PRIORIDAD" private val filtrosLiveData by lazy {//inicio tardío val mutableMap = mutableMapOf<String, Any?>( SOLO_SIN_PAGAR to false, ESTADO to 3, PRIORIDAD to 3 ) MutableLiveData(mutableMap) } //inicio ViewModel init { //inicia repositorio Repository(getApplication<Application>().applicationContext) repositorio=Repository //tareasLiveData=soloSinPagarLiveData.switchMap {soloSinPagar-> //Repository.getTareasFiltroSinPagar(soloSinPagar)} tareasLiveData=filtrosLiveData.switchMap{ mapFiltro -> val aplicarSinPagar = mapFiltro!![SOLO_SIN_PAGAR] as Boolean var estado = mapFiltro!![ESTADO] as Int val prioridad = mapFiltro!![PRIORIDAD] as Int //Devuelve el resultado del when when {//trae toda la lista de tareas (!aplicarSinPagar && (estado == 3) && (prioridad ==3)) -> repositorio.getAllTareas() //Sólo filtra por ESTADO (!aplicarSinPagar && (estado != 3) && (prioridad ==3)) -> repositorio.getTareasFiltroEstado(estado) //Sólo filtra SINPAGAR (aplicarSinPagar && (estado == 3) && (prioridad ==3)) -> repositorio.getTareasFiltroSinPagar(aplicarSinPagar) //Filtra por ambos (!aplicarSinPagar && (estado == 3) && (prioridad !==3)) -> repositorio.getTareasFiltroPrioridad(prioridad) (aplicarSinPagar && (estado != 3) && (prioridad == 3)) -> repositorio.getTareasFiltroSinPagarEstado(aplicarSinPagar, estado) (!aplicarSinPagar && (estado != 3) && (prioridad !== 3)) -> repositorio.getTareasFiltroEstadoPrioridad(estado, prioridad) (aplicarSinPagar && (estado == 3) && (prioridad !== 3)) -> repositorio.getTareasFiltroSinPagarPrioridad(aplicarSinPagar, prioridad, estado) else -> repositorio.getTareasFiltroSinPagarPrioridadEstado(aplicarSinPagar, estado, prioridad) } } } /** * activa el LiveData del filtro */ //fun setSoloSinPagar(soloSinPagar:Boolean){soloSinPagarLiveData.value=soloSinPagar} fun addTarea(tarea: Tarea) = viewModelScope.launch(Dispatchers.IO) { Repository.addTarea(tarea)} //lanzamos el borrado por corrutina fun delTarea(tarea: Tarea) = viewModelScope.launch(Dispatchers.IO){ Repository.delTarea(tarea)} //fun setEstado(estado: Int){estadoLiveData.value=estado} /** * Modifica el Map filtrosLiveData el elemento "SOLO_SIN_PAGAR" * que activará el Transformations de TareasLiveData */ fun setSoloSinPagar(soloSinPagar: Boolean) { //recuperamos el map val mapa = filtrosLiveData.value //modificamos el filtro mapa!![SOLO_SIN_PAGAR] = soloSinPagar //activamos el LiveData filtrosLiveData.value = mapa } /** * Modifica el Map filtrosLiveData el elemento "ESTADO" * que activará el Transformations de TareasLiveData lo *llamamos cuando cambia el RadioButton */ fun setEstado(estado: Int) { //recuperamos el map val mapa = filtrosLiveData.value //modificamos el filtro mapa!![ESTADO] = estado //activamos el LiveData filtrosLiveData.value = mapa } fun setPrioridad(prioridad: Int) { // Recuperamos el map val mapa = filtrosLiveData.value?.toMutableMap() // Modificamos el filtro mapa?.set(PRIORIDAD, prioridad) // Activamos el LiveData filtrosLiveData.value = mapa } }
Practica5_Parte6/app/src/main/java/ViewModel/AppViewModel.kt
579612047
package repository import android.app.Application import android.content.Context import model.Tarea import model.db.TareasDao import model.db.TareasDataBase object Repository { //instancia al modelo //private lateinit var modelTareas: ModelTempTareas private lateinit var modelTareas: TareasDao //private val listaTareas = mutableListOf<Tarea>() //el context suele ser necesario para recuperar datos private lateinit var application: Application //inicio del objeto singleton operator fun invoke(context: Context) { this.application = context.applicationContext as Application //iniciamos el modelo //ModelTempTareas(application) //modelTareas = ModelTempTareas // iniciamos BD modelTareas = TareasDataBase.getDatabase(application).tareasDao() } fun getTareasFiltroSinPagar (soloSinPagar:Boolean) = modelTareas.getTareasFiltroSinPagar(soloSinPagar) suspend fun addTarea(tarea: Tarea) = modelTareas.addTarea(tarea) suspend fun delTarea(tarea: Tarea) = modelTareas.delTarea(tarea) fun getTareasFiltroEstado(estado: Int) = modelTareas.getTareasFiltroEstado(estado) fun getTareasFiltroSinPagarEstado(soloSinPagar:Boolean, estado:Int)= modelTareas.getTareasFiltroSinPagarEstado(soloSinPagar,estado) fun getAllTareas() = modelTareas.getAllTareas() fun getTareasFiltroPrioridad(prioridad: Int) = modelTareas.getTareasFiltroPrioridad(prioridad) fun getTareasFiltroEstadoPrioridad(estado: Int, prioridad: Int) = modelTareas.getTareasFiltroEstadoPrioridad(estado, prioridad) fun getTareasFiltroSinPagarPrioridadEstado(soloSinPagar:Boolean, estado:Int, prioridad:Int)= modelTareas.getTareasFiltroSinPagarPrioridadEstado(soloSinPagar,estado, prioridad) fun getTareasFiltroSinPagarPrioridad(soloSinPagar: Boolean, prioridad: Int, estado: Int)= modelTareas.getTareasFiltroSinPagarPrioridad(soloSinPagar, prioridad) }
Practica5_Parte6/app/src/main/java/repository/Repository.kt
488709180
package net.iessochoa.hectormanuelgelardosabater.practica5.ui import ViewModel.AppViewModel import android.app.AlertDialog import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import model.Tarea import net.iessochoa.hectormanuelgelardosabater.practica5.R import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.FragmentListaBinding import net.iessochoa.hectormanuelgelardosabater.practica5.ui.adapters.TareasAdapter /** * A simple [Fragment] subclass as the default destination in the navigation. */ class ListaFragment : Fragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) { TODO("Not yet implemented") } private var _binding: FragmentListaBinding? = null private val viewModel: AppViewModel by activityViewModels() lateinit var tareasAdapter: TareasAdapter // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onResume() { super.onResume() PreferenceManager.getDefaultSharedPreferences(requireContext()).registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() PreferenceManager.getDefaultSharedPreferences(requireContext()).unregisterOnSharedPreferenceChangeListener(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentListaBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) iniciaRecyclerView() iniciaCRUD() viewModel.tareasLiveData.observe(viewLifecycleOwner, Observer<List<Tarea>> { lista -> //actualizaLista(lista) tareasAdapter.setLista(lista) }) iniciaFiltros() iniciaFiltrosEstado() iniciaSpPrioridad() viewModel.tareasLiveData.observe(viewLifecycleOwner, Observer<List<Tarea>> { lista -> actualizaLista(lista) }) viewModel.tareasLiveData.observe(viewLifecycleOwner, Observer<List<Tarea>> { listaFiltrada -> // Actualizar el RecyclerView con la nueva lista filtrada actualizaLista(listaFiltrada) }) } private fun iniciaCRUD(){ binding.fabNuevo.setOnClickListener { //creamos acción enviamos argumento nulo porque queremos crear NuevaTarea val action=ListaFragmentDirections.actionEditar(null) findNavController().navigate(action) } tareasAdapter.onTareaClickListener = object : TareasAdapter.OnTareaClickListener { //**************Editar Tarea************* override fun onTareaClick(tarea: Tarea?) { //creamos la acción y enviamos como argumento la tarea para editarla val action = ListaFragmentDirections.actionEditar(tarea) findNavController().navigate(action) } //***********Borrar Tarea************ override fun onTareaBorrarClick(tarea: Tarea?) { //borramos directamente la tarea //viewModel.delTarea(tarea!!) borrarTarea(tarea!!) } override fun onEstadoIconClick(tarea: Tarea?) { // Lógica cuando se hace clic en el icono de estado de la tarea } } } private fun obtenColorPreferencias():Int{ //cogemos el primer color si no hay ninguno seleccionado val colorPorDefecto=resources.getStringArray(R.array.color_values)[0] //recuperamos el color actual val color= PreferenceManager.getDefaultSharedPreferences(requireContext()).getString(MainActivity.PREF_COLOR_PRIORIDAD, colorPorDefecto) return Color.parseColor(color) } private fun iniciaSpPrioridad() { ArrayAdapter.createFromResource( //contexto suele ser la Activity requireContext(), //array de strings R.array.prioridad, //layout para mostrar el elemento seleccionado R.layout.spinner_items).also { adapter -> // Layout para mostrar la apariencia de la lista adapter.setDropDownViewResource(R.layout.spinner_items) // asignamos el adaptador al spinner binding.spPrioridad.adapter = adapter binding.spPrioridad.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, v: View?, posicion: Int, id: Long) { viewModel.setPrioridad(posicion) } override fun onNothingSelected(p0: AdapterView<*>?) { } } } } fun borrarTarea(tarea:Tarea){ AlertDialog.Builder(activity as Context) .setTitle(getString(R.string.atencion)) //recuerda: todo el texto en string.xml .setMessage("Desea borrar la Tarea ${tarea.id}?") //acción si pulsa si .setPositiveButton(getString(R.string.aceptar)){_,_-> //borramos la tarea viewModel.delTarea(tarea) //cerramos el dialogo //v.dismiss() } //accion si pulsa no .setNegativeButton(getString(R.string.cancelar)){v,_->v.dismiss()} .setCancelable(false) .create() .show() } private fun iniciaRecyclerView() { //creamos el adaptador tareasAdapter = TareasAdapter() tareasAdapter.colorPrioridadAlta=obtenColorPreferencias() with(binding.rvTareas) { //Creamos el layoutManager layoutManager = LinearLayoutManager(activity) //le asignamos el adaptador adapter = tareasAdapter } } private fun iniciaFiltros(){ binding.swSinPagar.setOnCheckedChangeListener( ) { _,isChecked-> //actualiza el LiveData SoloSinPagarLiveData que a su vez modifica tareasLiveData //mediante el Transformation viewModel.setSoloSinPagar(isChecked)} } private fun iniciaFiltrosEstado() { //listener de radioGroup binding.rgFiltrarEstado.setOnCheckedChangeListener { _, checkedId -> val estado = when (checkedId) { // IDs de cada RadioButton R.id.rgbAbiertas -> 0 // Abierta R.id.rgbEnCurso -> 1 // En curso R.id.rgbCerrada -> 2 // Cerrada else -> 3 // Recuperar toda la lista de tareas } viewModel.setEstado(estado) } //iniciamos a abierto binding.rgFiltrarEstado.check(R.id.rbAbierta) } private fun actualizaLista(lista: List<Tarea>?) { //creamos un string modificable val listaString = buildString { lista?.forEach() { //añadimos al final del string append( "${it.id}-${it.tecnico}-${ //mostramos un trozo de la descripción if (it.descripcion.length < 21) it.descripcion else it.descripcion.subSequence(0, 20) }-${ if (it.pagado) "SI-PAGADO" else "NO-PAGADO" }-" + when (it.estado) { 0 -> "ABIERTA" 1 -> "EN_CURSO" else -> "CERRADA" } + "\n" ) } } // binding.tvListaTareas.setText(listaString) } override fun onDestroyView() { super.onDestroyView() _binding = null } } private fun Any.setBackgroundColor(color: Int) { }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/ui/ListaFragment.kt
1867880833
package net.iessochoa.hectormanuelgelardosabater.practica5.ui import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.navigation.fragment.findNavController import net.iessochoa.hectormanuelgelardosabater.practica5.R import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { companion object{ val PREF_NOMBRE = "nombre" val PREF_COLOR_PRIORIDAD = "color_prioridad" val PREF_AVISO_NUEVAS = "aviso_nuevas" } private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val navController = findNavController(R.id.nav_host_fragment_content_main) appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_prueba -> actionPrueba() R.id.action_settings -> actionSettings() else -> super.onOptionsItemSelected(item) } } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } fun actionPrueba():Boolean{ Toast.makeText(this,"Prueba de menú", Toast.LENGTH_SHORT).show() return true } private fun actionSettings(): Boolean { findNavController(R.id.nav_host_fragment_content_main).navigate(R.id.settingsFragment) binding.icEnvio.visibility = View.INVISIBLE//ocultar el icono return true } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/ui/MainActivity.kt
3953237128
package net.iessochoa.hectormanuelgelardosabater.practica5.ui.adapters; import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.ItemTareaBinding import model.Tarea import net.iessochoa.hectormanuelgelardosabater.practica5.R class TareasAdapter(): RecyclerView.Adapter<TareasAdapter.TareaViewHolder>() { var colorPrioridadAlta :Int=Color.TRANSPARENT var listaTareas: List<Tarea>? = null var onTareaClickListener:OnTareaClickListener?=null private var ABIERTA = 0 private var EN_CURSO = 1 private var CERRADA = 2 fun setLista(lista: List<Tarea>) { listaTareas = lista //notifica al adaptador que hay cambios y tiene que redibujar el ReciclerView notifyDataSetChanged() } inner class TareaViewHolder(val binding: ItemTareaBinding) : RecyclerView.ViewHolder(binding.root){ init { //inicio del click de icono borrar binding.ivBorrar.setOnClickListener(){ //recuperamos la tarea de la lista val tarea=listaTareas?.get(this.adapterPosition) //llamamos al evento borrar que estará definido en el fragment onTareaClickListener?.onTareaBorrarClick(tarea) } //inicio del click sobre el Layout(constraintlayout) binding.root.setOnClickListener(){ val tarea=listaTareas?.get(this.adapterPosition) onTareaClickListener?.onTareaClick(tarea) } binding.ivEstado.setOnClickListener(){ val tarea=listaTareas?.get(this.adapterPosition) if (tarea != null) { val nuevoEstado = cambiarEstado(tarea.estado) tarea.estado = nuevoEstado notifyDataSetChanged() onTareaClickListener?.onEstadoIconClick(tarea) } } } } private fun cambiarEstado(estadoActual: Int): Int { return when (estadoActual) { ABIERTA -> EN_CURSO EN_CURSO -> CERRADA CERRADA -> ABIERTA else -> ABIERTA // Valor por defecto, si no es ninguno de los anteriores } } //tamaño de la lista override fun getItemCount(): Int = listaTareas?.size?:0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TareaViewHolder { //utilizamos binding, en otro caso hay que indicar el item.xml. Para más detalles puedes verlo en la documentación val binding = ItemTareaBinding .inflate(LayoutInflater.from(parent.context), parent, false) return TareaViewHolder(binding) } override fun onBindViewHolder(tareaViewHolder: TareaViewHolder, pos: Int) { //Nos pasan la posición del item a mostrar en el viewHolder with(tareaViewHolder) { //cogemos la tarea a mostrar y rellenamos los campos del ViewHolder with(listaTareas!!.get(pos)) { binding.tvId.text = id.toString() binding.tvDescripcion.text = descripcion binding.tvTecnico.text = tecnico binding.rbValoracion.rating = valoracionCliente //mostramos el icono en función del estado binding.ivEstado.setImageResource( when (estado) { 0 -> R.drawable.ic_abierto 1 -> R.drawable.ic_encurso else -> R.drawable.ic_cerrado } ) //cambiamos el color de fondo si la prioridad es alta binding.cvItem.setBackgroundColor( if (prioridad == 2)//prioridad alta colorPrioridadAlta else Color.TRANSPARENT ) } } } fun actualizaRecyclerColor(color:Int){ colorPrioridadAlta=color notifyDataSetChanged() } interface OnTareaClickListener{ //editar tarea que contiene el ViewHolder fun onTareaClick(tarea:Tarea?) //borrar tarea que contiene el ViewHolder fun onTareaBorrarClick(tarea:Tarea?) fun onEstadoIconClick(tarea: Tarea?) } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/ui/adapters/TareasAdapter.kt
1958236814
package net.iessochoa.hectormanuelgelardosabater.practica5.ui import ViewModel.AppViewModel import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.transition.TransitionInflater import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.SeekBar import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.core.view.updatePadding import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.preference.PreferenceManager import com.google.android.material.snackbar.Snackbar import model.Tarea import net.iessochoa.hectormanuelgelardosabater.practica5.R import net.iessochoa.hectormanuelgelardosabater.practica5.VerFoto import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.FragmentTareaBinding /** * A simple [Fragment] subclass as the second destination in the navigation. */ class TareaFragment : Fragment() { private var _binding: FragmentTareaBinding? = null val args: TareaFragmentArgs by navArgs() private val viewModel: AppViewModel by activityViewModels() var uriFoto="" //petición de foto de la galería private val solicitudFotoGallery = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { //uri de la foto elegida val uri = result.data?.data //mostramos la foto binding.ivFoto.setImageURI(uri) //guardamos la uri uriFoto = uri.toString() } } //será una tarea nueva si no hay argumento val esNuevo by lazy { args.tarea == null } private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentTareaBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.ivHacerFoto.setOnClickListener { abrirFotoFragment() } binding.root.setOnApplyWindowInsetsListener { view, insets -> view.updatePadding(bottom = insets.systemWindowInsetBottom) insets } /* binding.ivFoto.setOnClickListener { // Configurar la transición de ampliación val action = TareaFragmentDirections.actionTareaFragmentToVerFotoFragment(uriFoto) findNavController().navigate(action) // Aplicar la transición /* exitTransition = transition reenterTransition = transition // Ampliar la imagen val detalleFragmento = VerFotoFragment.newInstance(uriFoto) // Pasa la URI de la foto activity?.supportFragmentManager ?.beginTransaction() ?.replace(R.id.fragment_ver_foto, detalleFragmento) ?.addToBackStack(null) ?.commit()*/ }*/ //Iniciamos las funciones iniciaSpCategoria() iniciaSpPrioridad() iniciaSwPagado() iniciaRgEstado() iniciaSbHoras() iniciaIvBuscarFoto() iniciaFabGuardar() //si es nueva tarea o es una edicion if (esNuevo) {//nueva tarea //cambiamos el título de la ventana (requireActivity() as AppCompatActivity).supportActionBar?.title = "Nueva tarea" iniciaTecnico() } else iniciaTarea(args.tarea!!) } /** * Carga los valores de la tarea a editar */ private fun iniciaTarea(tarea: Tarea) { if (tarea == null) { // Si la tarea es nula, mostramos "Nueva Tarea" (requireActivity() as AppCompatActivity).supportActionBar?.title = "Nueva Tarea" } else { // Si hay una tarea, mostramos su número de tarea (requireActivity() as AppCompatActivity).supportActionBar?.title = "Tarea ${tarea.id}" } binding.spCategoria.setSelection(tarea.categoria) binding.spPrioridad.setSelection(tarea.prioridad) binding.swPagado.isChecked = tarea.pagado binding.rgEstado.check( when (tarea.estado) { 0 -> R.id.rbAbierta 1 -> R.id.rgbEnCurso else -> R.id.rgbCerrada } ) binding.sbHoras.progress = tarea.horasTrabajo binding.rtbValoracion.rating = tarea.valoracionCliente binding.etTecnico.setText(tarea.tecnico) binding.etDescripcion.setText(tarea.descripcion) if (!tarea.fotoUri.isNullOrEmpty()) binding.ivFoto.setImageURI(tarea.fotoUri.toUri()) uriFoto=tarea.fotoUri //cambiamos el título (requireActivity() as AppCompatActivity).supportActionBar?.title = "Tarea ${tarea.id}" } private fun abrirFotoFragment() { // Navega al FotoFragment findNavController().navigate(TareaFragmentDirections.actionTareaFragmentToFotoFragment()) } /*private fun guardaTarea() { //recuperamos los datos val categoria = binding.spCategoria.selectedItemPosition val prioridad = binding.spPrioridad.selectedItemPosition val pagado = binding.swPagado.isChecked val estado = when (binding.rgEstado.checkedRadioButtonId) { R.id.rbAbierta -> 0 R.id.rgbEnCurso -> 1 else -> 2 } val horas = binding.sbHoras.progress val valoracion = binding.rtbValoracion.rating val tecnico = binding.etTecnico.text.toString() val descripcion = binding.etDescripcion.text.toString() //creamos la tarea: si es nueva, generamos un id, en otro caso le asignamos su id val tarea = if (esNuevo) Tarea( categoria,prioridad,pagado,estado,horas,valoracion,tecnico,descripcion,uriFoto) else Tarea( args.tarea!!.id,categoria,prioridad,pagado,estado,horas,valoracion,tecnico,descripcion,uriFoto) //guardamos la tarea desde el viewmodel viewModel.addTarea(tarea) //salimos de editarFragment findNavController().popBackStack() }*/ private fun guardaTarea() { //recuperamos los datos //guardamos la tarea desde el viewmodel viewModel.addTarea(creaTarea()) //salimos de editarFragment findNavController().popBackStack() } private fun creaTarea():Tarea{ val categoria=binding.spCategoria.selectedItemPosition val prioridad=binding.spPrioridad.selectedItemPosition val pagado=binding.swPagado.isChecked val estado=when (binding.rgEstado.checkedRadioButtonId) { R.id.rbAbierta -> 0 R.id.rgbEnCurso -> 1 else -> 2 } val horas=binding.sbHoras.progress val valoracion=binding.rtbValoracion.rating val tecnico=binding.etTecnico.text.toString() val descripcion=binding.etDescripcion.text.toString() //creamos la tarea: si es nueva, generamos un id, en otro caso le asignamos su id val tarea = if(esNuevo) Tarea(categoria,prioridad,pagado,estado,horas,valoracion,tecnico,descripcion, uriFoto) else//venimos de hacer foto Tarea(args.tarea!!.id,categoria,prioridad,pagado,estado,horas,valoracion,tecnico,descripcion, uriFoto) return tarea } private fun iniciaFabGuardar() { binding.fabGuardar.setOnClickListener { if (binding.etTecnico.text.toString().isEmpty() || binding.etDescripcion.text.toString() .isEmpty() ) { // muestraMensajeError() val mensaje = "Los campos no pueden estar vacios" Snackbar.make(binding.root, mensaje, Snackbar.LENGTH_LONG).setAction("Action", null) .show() } else guardaTarea() } } private fun iniciaSpCategoria() { ArrayAdapter.createFromResource( //contexto suele ser la Activity requireContext(), //array de strings R.array.categoria, //layout para mostrar el elemento seleccionado R.layout.spinner_items ).also { adapter -> // Layout para mostrar la apariencia de la lista adapter.setDropDownViewResource(R.layout.spinner_items) // asignamos el adaptador al spinner binding.spCategoria.adapter = adapter } binding.spCategoria.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, posicion: Int, id: Long ) { //recuperamos el valor val valor = binding.spCategoria.getItemAtPosition(posicion) //creamos el mensaje desde el recurso string parametrizado val mensaje = getString(R.string.mensaje_categoria, valor) //mostramos el mensaje donde "binding.root" es el ContrainLayout principal Snackbar.make(binding.root, mensaje, Snackbar.LENGTH_LONG) .setAction("Action", null).show() } override fun onNothingSelected(parent: AdapterView<*>?) { // Manejar evento cuando no se selecciona nada en el Spinner } } } private fun iniciaRgEstado() { //listener de radioGroup binding.rgEstado.setOnCheckedChangeListener { _, checkedId -> val imagen = when (checkedId) {//el id del RadioButton seleccionado //id del cada RadioButon R.id.rbAbierta -> R.drawable.ic_abierto R.id.rgbEnCurso -> R.drawable.ic_encurso else -> R.drawable.ic_cerrado } binding.ivEstado.setImageResource(imagen) } //iniciamos a abierto binding.rgEstado.check(R.id.rbAbierta) } private fun iniciaSwPagado() { binding.swPagado.setOnCheckedChangeListener { _, isChecked -> //cambiamos el icono si está marcado o no el switch val imagen = if (isChecked) R.drawable.ic_pagado else R.drawable.ic_no_pagado //asignamos la imagen desde recursos binding.ivPagado.setImageResource(imagen) } //iniciamos a valor false binding.swPagado.isChecked = false binding.ivPagado.setImageResource(R.drawable.ic_no_pagado) } private fun iniciaSpPrioridad() { ArrayAdapter.createFromResource( //contexto suele ser la Activity requireContext(), //array de strings R.array.prioridad, //layout para mostrar el elemento seleccionado R.layout.spinner_items ).also { adapter -> // Layout para mostrar la apariencia de la lista adapter.setDropDownViewResource(R.layout.spinner_items) // asignamos el adaptador al spinner binding.spPrioridad.adapter = adapter } binding.spPrioridad.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, v: View?, posicion: Int, id: Long) { //el array son 3 elementos y "alta" ocupa la tercera posición if (posicion == 2) { binding.clytTarea.setBackgroundColor(requireContext().getColor(R.color.prioridad_alta)) } else {//si no es prioridad alta quitamos el color binding.clytTarea.setBackgroundColor(Color.TRANSPARENT) } } override fun onNothingSelected(p0: AdapterView<*>?) { binding.clytTarea.setBackgroundColor(Color.TRANSPARENT) } } } private fun iniciaSbHoras() { //asignamos el evento binding.sbHoras.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(p0: SeekBar?, progreso: Int, p2: Boolean) { //Mostramos el progreso en el textview binding.tvHoras.text = getString(R.string.horas_trabajadas, progreso) } override fun onStartTrackingTouch(p0: SeekBar?) { } override fun onStopTrackingTouch(p0: SeekBar?) { } }) //inicio del progreso binding.sbHoras.progress = 0 binding.tvHoras.text = getString(R.string.horas_trabajadas, 0) } private fun buscarFoto() { //Toast.makeText(requireContext(), "Buscando la foto...", Toast.LENGTH_SHORT).show() val intent = Intent( Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI ) intent.type = "image/*" solicitudFotoGallery.launch(intent) } fun iniciaIvBuscarFoto() { binding.ivBuscarFoto.setOnClickListener() { when { //si tenemos los permisos permisosAceptados() -> buscarFoto() //no tenemos los permisos y los solicitamos else -> solicitudPermisosLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } } } private val solicitudPermisosLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission has been granted. buscarFoto() } else { // Permission request was denied. explicarPermisos() } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun iniciaTecnico() { //recuperamos las preferencias val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) //recuperamos el nombre del usuario val tecnico = sharedPreferences.getString(MainActivity.PREF_NOMBRE, "") //lo asignamos binding.etTecnico.setText(tecnico) } fun permisosAceptados() = ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED fun explicarPermisos() { AlertDialog.Builder(activity as Context) .setTitle(android.R.string.dialog_alert_title) //TODO:recuerda: el texto en string.xml .setMessage("Es necesario el permiso de \"Lectura de fichero\" para mostrar una foto.\nDesea aceptar los permisos?") //acción si pulsa si .setPositiveButton(android.R.string.ok) { v, _ -> //Solicitamos los permisos de nuevo solicitudPermisosLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) //cerramos el dialogo v.dismiss() } //accion si pulsa no .setNegativeButton(android.R.string.cancel) { v, _ -> v.dismiss() } .setCancelable(false) .create() .show() } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/ui/TareaFragment.kt
1396752210
package net.iessochoa.hectormanuelgelardosabater.practica5 import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.FragmentVerFotoBinding class VerFoto : Fragment() { private var _binding: FragmentVerFotoBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentVerFotoBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fotoUri = arguments?.getString("fotoUri") binding.ivVerFoto.setImageURI(Uri.parse(fotoUri)) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/ui/verFoto.kt
493613253
package net.iessochoa.hectormanuelgelardosabater.practica5 import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.root_preferences, rootKey) //buscamos la preferencia val buildVersion: Preference? = findPreference("buildVersion") //definimos la accion para la preferencia buildVersion?.setOnPreferenceClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://portal.edu.gva.es/03013224/"))) //hay que devolver booleano para indicar si se acepta el cambio o no false } val telefonoContactoPreference: Preference? = findPreference("telefonoContacto") telefonoContactoPreference?.setOnPreferenceClickListener { // Número de teléfono al que quieres llamar val phoneNumber = "tel:966912260" // Creamos un Intent con la acción ACTION_DIAL y la URI del número de teléfono val dialIntent = Intent(Intent.ACTION_DIAL, Uri.parse(phoneNumber)) // Iniciamos la actividad del teléfono startActivity(dialIntent) // Devolvemos true para indicar que se acepta el cambio true } } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/SettingsFragment.kt
4085966446
package net.iessochoa.hectormanuelgelardosabater.practica5 import android.app.AlertDialog import android.content.pm.PackageManager import android.graphics.Insets.add import android.os.Build import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import net.iessochoa.hectormanuelgelardosabater.practica5.databinding.FragmentFotoBinding import android.util.Log import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import android.Manifest import android.annotation.SuppressLint import android.content.ContentValues import android.icu.text.SimpleDateFormat import android.net.Uri import android.provider.MediaStore import android.widget.Toast import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.core.content.ContentProviderCompat.requireContext import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import java.util.Locale class FotoFragment : Fragment() { private var _binding: FragmentFotoBinding? = null private var uriFoto: Uri?=null private val binding get() = _binding!! val args: FotoFragmentArgs by navArgs() //Array con los permisos necesarios private val PERMISOS_REQUERIDOS = mutableListOf ( Manifest.permission.CAMERA).apply { //si la versión de Android es menor o igual a la 9 pedimos el permiso de escritura if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() private var imageCapture: ImageCapture? = null companion object { private const val TAG = "Practica5_CameraX" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentFotoBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Configurar el OnClickListener para el botón redondo binding.btCapturaFoto.setOnClickListener { // Llamar al método para capturar la foto takePhoto() } binding.ivMuestra.setOnClickListener(){ var tarea=args.tarea?.copy(fotoUri =uriFoto.toString()) val action = FotoFragmentDirections.actionFotoFragmentToTareaFragment(tarea) findNavController().navigate(action) } if (allPermissionsGranted()) { startCamera() } else { solicitudPermisosLauncher.launch(PERMISOS_REQUERIDOS) } } @SuppressLint("SuspiciousIndentation") private fun takePhoto() { // Get a stable reference of the modifiable image capture use case val imageCapture = imageCapture ?: return // Create time stamped name and MediaStore entry. val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) // val name = "practica5_1" val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") //funiona en versiones superiores a Android 9 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + getString(R.string.app_name)) } } // Create output options object which contains file + metadata val outputOptions = ImageCapture.OutputFileOptions .Builder( requireActivity().contentResolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues ) .build() // Set up image capture listener, which is triggered after photo has // been taken imageCapture.takePicture( outputOptions, ContextCompat.getMainExecutor(requireContext()), object : ImageCapture.OnImageSavedCallback { override fun onError(exc: ImageCaptureException) { Log.e(TAG, "Photo capture failed: ${exc.message}", exc) } override fun onImageSaved(output: ImageCapture.OutputFileResults) { val msg = "Photo capture succeeded:${output.savedUri}" Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show() Log.d(TAG, msg) binding.ivMuestra.setImageURI(output.savedUri) uriFoto=output.savedUri } } ) } private fun allPermissionsGranted() = PERMISOS_REQUERIDOS.all { ContextCompat.checkSelfPermission(requireContext(), it) == PackageManager.PERMISSION_GRANTED } private fun startCamera() { //Se usa para vincular el ciclo de vida de las cámaras al propietario del ciclo de vida. val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext()) //Agrega un elemento Runnable como primer argumento cameraProviderFuture.addListener({ // Esto se usa para vincular el ciclo de vida de nuestra cámara al LifecycleOwner dentro del proceso de la aplicación val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() //Inicializa nuestro objeto Preview, // llama a su compilación, obtén un proveedor de plataforma desde el visor y, // luego, configúralo en la vista previa. val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(binding.viewFinder.surfaceProvider) } imageCapture = ImageCapture.Builder().build() // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle( this, cameraSelector, preview, imageCapture ) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } //segundo argumento }, ContextCompat.getMainExecutor(requireContext())) } //Permite lanzar la solicitud de permisos al sistema operativo y actuar según el usuario //los acepte o no val solicitudPermisosLauncher = registerForActivityResult( //realizamos una solicitud de multiples permisos ActivityResultContracts.RequestMultiplePermissions() ) { isGranted: Map<String, Boolean> -> if (allPermissionsGranted()) { //Si tenemos los permisos, iniciamos la cámara startCamera() } else { // Si no tenemos los permisos. Explicamos al usuario explicarPermisos() } } fun explicarPermisos() { AlertDialog.Builder(requireContext()) .setTitle(android.R.string.dialog_alert_title) //TODO:recuerda: el texto en string.xml .setMessage("Son necesarios los permisos para hacer una foto.\nDesea aceptar los permisos?") //acción si pulsa si .setPositiveButton(android.R.string.ok) { v, _ -> //Solicitamos los permisos de nuevo solicitudPermisosLauncher.launch(PERMISOS_REQUERIDOS) //cerramos el dialogo v.dismiss() } //accion si pulsa no .setNegativeButton(android.R.string.cancel) { v, _ -> v.dismiss() //cerramos el fragment requireActivity().onBackPressedDispatcher.onBackPressed() } .setCancelable(false) .create() .show() } }
Practica5_Parte6/app/src/main/java/net/iessochoa/hectormanuelgelardosabater/practica5/FotoFragment.kt
799100906
package model import android.net.Uri import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Entity(tableName = "tareas") @Parcelize data class Tarea( @PrimaryKey(autoGenerate = true) var id:Long?=null,//id único val categoria:Int, val prioridad:Int, val pagado:Boolean, var estado:Int, val horasTrabajo:Int, val valoracionCliente:Float, val tecnico:String, val descripcion:String, val fotoUri: String ):Parcelable { //segundo constructor que genera id nuevo constructor( categoria:Int, prioridad:Int, pagado:Boolean, estado:Int, horasTrabajo:Int, valoracionCliente:Float, tecnico:String, descripcion:String, fotoUri: String ):this(null,categoria,prioridad,pagado,estado,horasTrabajo,valoracionCliente, tecnico, descripcion,fotoUri) {} companion object { var idContador = 1L//iniciamos contador de tareas private fun generateId(): Long { return idContador++//sumamos uno al contador } } //dos tareas son iguales cuando su id es igual. // Facilita la búsqueda en un arrayList override fun equals(other: Any?): Boolean { return (other is Tarea)&&(this.id == other?.id) } }
Practica5_Parte6/app/src/main/java/model/Tarea.kt
4278321457
package model.temp import android.app.Application import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import model.Tarea import kotlin.random.Random object ModelTempTareas { //lista de tareas private val tareas = ArrayList<Tarea>() //LiveData para observar en la vista los cambios en la lista private val tareasLiveData = MutableLiveData<List<Tarea>>(tareas) //el context que suele ser necesario en acceso a datos private lateinit var application: Application //Permite iniciar el objeto Singleton operator fun invoke(context: Context) { this.application = context.applicationContext as Application //iniciaPruebaTareas() //Lanzamos una corrutina GlobalScope.launch { iniciaPruebaTareas() } } /** * devuelve un LiveData en vez de MutableLiveData para evitar su modificación en las capas superiores */ fun getAllTareas(): LiveData<List<Tarea>> { tareasLiveData.value= tareas return tareasLiveData } /** * añade una tarea, si existe (id iguales) la sustituye * y si no la añade. Posteriormente actualiza el LiveData * que permitirá avisar a quien esté observando */ fun addTarea(tarea: Tarea) { val pos = tareas.indexOf(tarea) if (pos < 0) {//si no existe tareas.add(tarea) } else { //si existe se sustituye tareas.set(pos, tarea) } //actualiza el LiveData tareasLiveData.value = tareas } /** * Borra una tarea y actualiza el LiveData * para avisar a los observadores */ suspend fun delTarea(tarea: Tarea) { // Thread.sleep(50000) tareas.remove(tarea) //tareasLiveData.value = tareas tareasLiveData.postValue(tareas) } /** * Crea unas Tareas de prueba de forma aleatoria. */ suspend fun iniciaPruebaTareas() { val tecnicos = listOf( "Pepe Gotero", "Sacarino Pómez", "Mortadelo Fernández", "Filemón López", "Zipi Climent", "Zape Gómez" ) lateinit var tarea: Tarea (1..10).forEach({ tarea = Tarea( (0..4).random(), (0..2).random(), Random.nextBoolean(), (0..2).random(), (0..30).random(), (0..5).random().toFloat(), tecnicos.random(), "tarea $it Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat ligula et vehicula mattis. \n Etiam tristique ornare lacinia. Vestibulum lacus magna, dignissim et tempor id, convallis sed augue", "" ) tareas.add(tarea) }) //actualizamos el LiveData tareasLiveData.postValue(tareas) } /** * Varios filtros: */ fun getTareasFiltroSinPagarEstado(soloSinPagar:Boolean, estado:Int): MutableLiveData<List<Tarea>> { //devuelve el LiveData con la lista filtrada tareasLiveData.value=tareas.filter { !it.pagado && it.estado==estado } as ArrayList<Tarea> return tareasLiveData } fun getTareasFiltroSinPagar(soloSinPagar:Boolean): LiveData<List<Tarea>> { //devuelve el LiveData con la lista filtrada o entera tareasLiveData.value=if(soloSinPagar) tareas.filter { !it.pagado } as ArrayList<Tarea> else tareas return tareasLiveData } fun getTareasFiltroEstado(estado: Int): LiveData<List<Tarea>> { /*tareasLiveData.value = if(estado != 3) tareas.filter { it.estado == estado } as ArrayList<Tarea> else tareas*/ val estadosFiltrados = when (estado) { 0 -> tareas.filter { it.estado == 0 } as ArrayList<Tarea> 1 -> tareas.filter { it.estado == 1 } as ArrayList<Tarea> 2 -> tareas.filter { it.estado == 2 } as ArrayList<Tarea> else -> tareas } tareasLiveData.value = estadosFiltrados return tareasLiveData } }
Practica5_Parte6/app/src/main/java/model/temp/ModelTempTareas.kt
2210990546
package model.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import model.Tarea @Dao interface TareasDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addTarea(tarea: Tarea) @Delete suspend fun delTarea(tarea: Tarea) @Query("SELECT * FROM tareas ") fun getAllTareas(): LiveData<List<Tarea>> @Query("SELECT * FROM tareas WHERE pagado!= :soloSinPagar") fun getTareasFiltroSinPagar(soloSinPagar:Boolean):LiveData<List<Tarea>> @Query("SELECT * FROM tareas WHERE estado= :estado") fun getTareasFiltroEstado(estado:Int):LiveData<List<Tarea>> @Query("SELECT * FROM tareas WHERE (pagado= :soloSinPagar) AND(estado= :estado)") fun getTareasFiltroSinPagarEstado(soloSinPagar:Boolean, estado:Int):LiveData<List<Tarea>> //Filtro Prioridad @Query("SELECT * FROM tareas WHERE prioridad = :prioridad") fun getTareasFiltroPrioridad(prioridad: Int): LiveData<List<Tarea>> //Filtro Prioridad y pago @Query("SELECT * FROM tareas WHERE (pagado != :soloSinPagar) AND (prioridad = :prioridad)") fun getTareasFiltroSinPagarPrioridad(soloSinPagar:Boolean, prioridad:Int): LiveData<List<Tarea>> // Filtro prioridad y estado @Query("SELECT * FROM tareas WHERE (estado = :estado) AND (prioridad = :prioridad)") fun getTareasFiltroEstadoPrioridad (estado: Int, prioridad: Int): LiveData<List<Tarea>> //Filtro Prioridad, estado y pagado @Query("SELECT * FROM tareas WHERE (pagado != :soloSinPagar) AND (estado = :estado) AND (prioridad = :prioridad)") fun getTareasFiltroSinPagarPrioridadEstado(prioridad: Boolean, soloSinPagar: Int, estado: Int ): LiveData<List<Tarea>> }
Practica5_Parte6/app/src/main/java/model/db/TareasDao.kt
503299792
package model.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.sqlite.db.SupportSQLiteDatabase import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import model.Tarea import kotlin.random.Random @Database(entities = arrayOf(Tarea::class), version = 1, exportSchema = false) public abstract class TareasDataBase : RoomDatabase() { abstract fun tareasDao(): TareasDao companion object { // Singleton prevents multiple instances of database opening at the // same time. @Volatile private var INSTANCE: TareasDataBase? = null fun getDatabase(context: Context): TareasDataBase { // if the INSTANCE is not null, then return it, // if it is, then create the database return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, TareasDataBase::class.java, "tareas_database" ) .addCallback(InicioDbCallback()) .build() INSTANCE = instance // return instance instance } } } //***************CallBack****************************** /** * Permite iniciar la base de datos con Tareas */ private class InicioDbCallback() : RoomDatabase.Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) INSTANCE?.let { database -> GlobalScope.launch { cargarDatabase(database.tareasDao()) } } } //Iniciamos la base de datos con Tareas de ejemplo private suspend fun cargarDatabase(tareasDao: TareasDao) { val tecnicos = listOf( "Pepe Gotero", "Sacarino Pómez", "Mortadelo Fernández", "Filemón López", "Zipi Climent", "Zape Gómez" ) lateinit var tarea: Tarea (1..15).forEach({ tarea = Tarea( (0..4).random(), (0..2).random(), Random.nextBoolean(), (0..2).random(), (0..30).random(), (0..5).random().toFloat(), tecnicos.random(), "tarea $it realizada por el técnico \nLorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat ligula et vehicula mattis. Etiam tristique ornare lacinia. Vestibulum lacus magna, dignissim et tempor id, convallis sed augue", "" ) tareasDao.addTarea(tarea) }) } } }
Practica5_Parte6/app/src/main/java/model/db/TareasDataBase.kt
4021184340
package hr.marintolic.chatsample.database.user import hr.marintolic.chatsample.EnvironmentVariables import hr.marintolic.chatsample.database.user.model.User import hr.marintolic.chatsample.database.user.model.Users import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction /** * Used to connect to the user database and perform transactions. */ object UserDatabase { /** * The default list of users that the app will add at launch if such do not already exist. */ private val defaultChatUsers = listOf( User( username = "Stanley", password = "password" ), User( username = "Maurice", password = "password" ), User( username = "Laura", password = "password" ), User( username = "Susan", password = "password" ), ) /** * The user database. */ private val userDatabase: Database = createDatabase() /** * Initializes the database. */ internal fun initialize() { createUserTable() addDefaultUsers() } /** * Adds the default users to the database if such do not already exist. */ private fun addDefaultUsers() { defaultChatUsers.forEach { val doesUserExist = getUser(it.username) != null if (!doesUserExist) insertUser(it) } } /** * Initializes the database. * * Call this function only once as multiple calls to it will create memory leaks. * * @return The database containing users. */ private fun createDatabase(): Database { // Map<K,V>.getValue() will cause a crash if no such value exists, which is preferable to a silent failure here val dbName = EnvironmentVariables.chatSampleUserDbName val dbUserName = EnvironmentVariables.chatSampleUserDbUserName val dbUserPassword = EnvironmentVariables.chatSampleUserDbUserPassword val jdbcUrl = createJdbcUrl( dbName = dbName ) return Database.connect( url = jdbcUrl, driver = DRIVER_CLASS_NAME, user = dbUserName, password = dbUserPassword ) } /** * Creates a Jdbc PostgreSQL URL from a templated string. * * @param dbName The name of the database. * @param host Where the database is hosted on. The default is [DEFAULT_HOST]. * @param port The port used to connect to the database. The default is [DEFAULT_PORT]. * * @return The resulting Jdbc URL. */ private fun createJdbcUrl( dbName: String, host: String = DEFAULT_HOST, port: String = DEFAULT_PORT ) = "jdbc:postgresql://$host:$port/$dbName" /** * Creates a table of users if such doesn't exist. */ private fun createUserTable() { transaction(userDatabase) { SchemaUtils.create(Users) } } /** * Inserts a new user into the database. * * @param user The user to be inserted into the database. */ internal fun insertUser(user: User) { transaction { Users.insert { it[username] = user.username it[password] = user.password } } } /** * Updates an existing user's information in the database. * * @param user The user whose information will be updated. */ internal fun updateUser(user: User) { transaction { Users.update { it[username] = user.username it[password] = user.password } } } /** * Fetches a user by username from the database if such exists. * * @param username The name of the user to be fetched. * * @return The user data if such exists, null otherwise. */ internal fun getUser(username: String): User? { return transaction { Users.selectAll().where { Users.username eq username } .map { User( username = it[Users.username], password = it[Users.password], ) }.firstOrNull() } } /** * The name of the database driver. */ private const val DRIVER_CLASS_NAME = "org.postgresql.Driver" /** * The default host for the database. */ private const val DEFAULT_HOST = "localhost" /** * The default port for the database. */ private const val DEFAULT_PORT = "5432" } /** * Checks to see if the given user credentials are valid or not. * * @receiver The user whose credentials are to be validated. * * @return True if the credentials are valid, false otherwise. */ internal fun User.areCredentialsValid(): Boolean { val storedUser = UserDatabase.getUser(this.username) ?: return false return storedUser.password == this.password }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/database/user/UserDatabase.kt
1767326248
package hr.marintolic.chatsample.database.user.model import org.jetbrains.exposed.sql.Table /** * A table of users for the database. */ object Users : Table() { /** * The name for the column containing the usernames. */ private const val USERNAME = "username" /** * The name for the column containing the passwords. */ private const val PASSWORD = "password" /** * The username for the given user. * @see [User] */ val username = varchar(name = USERNAME, length = 20) /** * The password for the given user. * @see [User] */ val password = varchar(PASSWORD, length = 128) /** * Set the table primary key to be the user's username. */ override val primaryKey = PrimaryKey(username) }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/database/user/model/Users.kt
2131649304
package hr.marintolic.chatsample.database.user.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Represents a user's login information. * * @property username The username a user uses to log-in. * @property password The password the user uses to log-in. */ @Serializable internal data class User( @SerialName("username") val username: String, @SerialName("password") val password: String, )
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/database/user/model/User.kt
1676646245
package hr.marintolic.chatsample import SERVER_HOST import SERVER_PORT import hr.marintolic.chatsample.database.user.UserDatabase import hr.marintolic.chatsample.plugins.auth.installAuthenticationPlugin import hr.marintolic.chatsample.plugins.contentnegotiation.installContentNegotiation import hr.marintolic.chatsample.plugins.routing.routingModule import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* /** * The main entry point of the server application. */ fun main() { embeddedServer( factory = Netty, port = SERVER_PORT, host = SERVER_HOST, module = Application::root ).start(wait = true) } /** * The root function of the application, contains all other modules and performs the installation of plugins. */ private fun Application.root() { // Initialize the user database initUserDatabase() // Install plugins first installPlugins() // Call root module rootModule() } /** * The root module containing all other submodules. */ private fun Application.rootModule() { routingModule() } /** * Installs necessary plugins. */ private fun Application.installPlugins() { installAuthenticationPlugin() installContentNegotiation() } /** * Initializes the user database. */ private fun initUserDatabase() { UserDatabase.initialize() }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/Application.kt
2365300232
package hr.marintolic.chatsample.plugins.contentnegotiation import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.* /** * Configures content negotiation. */ internal fun Application.installContentNegotiation() { install(ContentNegotiation){ json() } }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/plugins/contentnegotiation/ContentNegotiation.kt
3639773544
package hr.marintolic.chatsample.plugins.auth import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import hr.marintolic.chatsample.EnvironmentVariables import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.response.* /** * Installs and sets up authentication. */ internal fun Application.installAuthenticationPlugin() { install(Authentication) { jwtAuth() } } /** * Sets up JWT authentication. */ private fun AuthenticationConfig.jwtAuth() { jwt("auth-jwt") { realm = EnvironmentVariables.jwtRealm verifier( JWT.require(Algorithm.HMAC256(EnvironmentVariables.jwtSecret)) .withAudience(EnvironmentVariables.jwtAudience) .withIssuer(EnvironmentVariables.jwtIssuer) .build() ) // Responds to requests without a token or containing bad ones challenge { _, _ -> call.respond(HttpStatusCode.Unauthorized, "Invalid or expired token.") } // Validates JWT tokens validate { credential -> if (credential.payload.getClaim("username").asString() != "") { JWTPrincipal(credential.payload) } else { null } } } }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/plugins/auth/Auth.kt
2178750701
package hr.marintolic.chatsample.plugins.routing import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import hr.marintolic.chatsample.EnvironmentVariables import hr.marintolic.chatsample.database.user.areCredentialsValid import hr.marintolic.chatsample.database.user.model.User import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* /** * The routing for unauthorized users. */ internal fun Application.routingUnauthorized() { routing { homeRoute() loginRoute() } } /** * Represents the home route with the url subdirectory [HOME_SUBDIRECTORY]. */ private fun Routing.homeRoute() { get(HOME_SUBDIRECTORY) { call.respondText { "Greetings from GDG Osijek!" } } } /** * Represents the login route with the url subdirectory [LOGIN_SUBDIRECTORY]. */ private fun Routing.loginRoute() { post(LOGIN_SUBDIRECTORY) { try { val user = call.receive<User>() if (user.areCredentialsValid()) { val jwtToken = JWT.create() .withAudience(EnvironmentVariables.jwtAudience) .withIssuer(EnvironmentVariables.jwtIssuer) .withClaim("username", user.username) .sign(Algorithm.HMAC256(EnvironmentVariables.jwtSecret)) call.respond(hashMapOf("token" to jwtToken)) } else { call.respond(HttpStatusCode.Unauthorized) } } catch (exception: Exception) { exception.printStackTrace() call.respond(HttpStatusCode.InternalServerError) } } } /** * The subdirectory for the home page. */ private const val HOME_SUBDIRECTORY = "/" /** * The subdirectory for the login page. */ private const val LOGIN_SUBDIRECTORY = "/login"
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/plugins/routing/RoutingUnauthorized.kt
161756204
package hr.marintolic.chatsample.plugins.routing import io.ktor.server.application.* /** * The root level routing module containing submodules both for authorized and unauthorized users. */ internal fun Application.routingModule(){ routingUnauthorized() routingAuthorizedUsers() }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/plugins/routing/RoutingModule.kt
1524878012
package hr.marintolic.chatsample.plugins.routing import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.response.* import io.ktor.server.routing.* /** * The routing for authorized users. */ internal fun Application.routingAuthorizedUsers() { routing { chatRoute() } } /** * Represents the chat home page route with the subdirectory [AUTHORIZED_SUBDIRECTORY]/[CHAT_SUBDIRECTORY]. */ internal fun Routing.chatRoute() { authenticate("auth-jwt") { get("/$AUTHORIZED_SUBDIRECTORY/$CHAT_SUBDIRECTORY") { val principal = call.principal<JWTPrincipal>() ?: return@get call.respond(HttpStatusCode.InternalServerError) val username = principal.payload.getClaim("username").asString() // TODO implement call.respondText { "hi $username, this hasn't yet been implemented!" } } } } /** * Represents a subdirectory used for logged-in users. */ private const val AUTHORIZED_SUBDIRECTORY = "authorized" /** * Represents a subdirectory used for the chat home page. */ private const val CHAT_SUBDIRECTORY = "chat"
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/plugins/routing/RoutingAuthorized.kt
453773509
package hr.marintolic.chatsample /** * Contains environment variables. */ internal object EnvironmentVariables { /** * The JWT secret used to generate tokens. */ val jwtSecret = System.getenv("CHAT_SAMPLE_JWT_SECRET") /** * JWT issuer information. */ val jwtIssuer = System.getenv("CHAT_SAMPLE_JWT_ISSUER") /** * JWT audience information. */ val jwtAudience = System.getenv("CHAT_SAMPLE_JWT_AUDIENCE") /** * JWT realm information. */ val jwtRealm = System.getenv("CHAT_SAMPLE_JWT_REALM") /** * The name of the database holding user information. */ val chatSampleUserDbName = System.getenv("CHAT_SAMPLE_USER_DB_NAME") /** * The name of the user with privileges to the user database. */ val chatSampleUserDbUserName = System.getenv("CHAT_SAMPLE_USER_DB_USER_NAME") /** * The password of the user with the privileges to the user database. */ val chatSampleUserDbUserPassword = System.getenv("CHAT_SAMPLE_USER_DB_USER_PASSWORD") }
Chat-Sample-Ktor-Compose-Multiplatform/server/src/main/kotlin/hr/marintolic/chatsample/EnvironmentVariables.kt
1993800714
import platform.UIKit.UIDevice class IOSPlatform: Platform { override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion } actual fun getPlatform(): Platform = IOSPlatform()
Chat-Sample-Ktor-Compose-Multiplatform/shared/src/iosMain/kotlin/Platform.ios.kt
110407275
interface Platform { val name: String } expect fun getPlatform(): Platform
Chat-Sample-Ktor-Compose-Multiplatform/shared/src/commonMain/kotlin/Platform.kt
960794953
/** * The host address of the server. */ const val SERVER_HOST = "0.0.0.0" /** * The port the server listens to. */ const val SERVER_PORT = 8080
Chat-Sample-Ktor-Compose-Multiplatform/shared/src/commonMain/kotlin/Constants.kt
2118225574
class Greeting { private val platform = getPlatform() fun greet(): String { return "Hello, ${platform.name}!" } }
Chat-Sample-Ktor-Compose-Multiplatform/shared/src/commonMain/kotlin/Greeting.kt
2562376394