path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantCategoryFragment.kt | 1093867302 | package com.andy.kotlindelivery.fragments.restaurant
import android.app.Activity
import android.os.Bundle
import android.util.Log
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.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.CategoriasProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
class RestaurantCategoryFragment : Fragment() {
var TAG = "RestaurantCategoryFragment"
var categoriasProvider: CategoriasProviders? = null
var sharedPref: SharedPref? = null
var usuario: Usuario? = null
var myView: View? = null
var imageViewCategory: ImageView? =null
var editTextCategory: EditText? = null
var buttonCrearCategory: Button? = null
private var imageFile: File? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_restaurant_category, container, false)
sharedPref = SharedPref(requireActivity())
imageViewCategory = myView?.findViewById(R.id.image_view_category)
editTextCategory = myView?.findViewById(R.id.edittxt_category)
buttonCrearCategory = myView?.findViewById(R.id.btn_create_category)
getUserFromSession()
categoriasProvider = CategoriasProviders(usuario?.sessionToken!!)
Log.d(TAG, "Usuario con Token: ${usuario?.sessionToken!!}")
imageViewCategory?.setOnClickListener{ selectImage() }
buttonCrearCategory?.setOnClickListener { createCategory() }
return myView
}
/////FUNCION QUE INICIA LA CREACION DE LA CATEGORIA
private fun createCategory() {
val categoria = editTextCategory?.text.toString()
if(imageFile != null){
val category = Categoria(nombre = categoria)
Log.d(TAG, "Categoria: $category")
categoriasProvider?.create(imageFile!!, category)?.enqueue(object : Callback<ResponseHttp> {
override fun onResponse(call: Call<ResponseHttp>, response: Response<ResponseHttp>) {
Log.d(TAG, "RESPONSE: $response")
Log.d(TAG, "BODY: ${response.body()}")
if(response.body()?.isSucces == true){
clearForm()
}
Toast.makeText(requireContext(), response.body()?.message, Toast.LENGTH_LONG).show()
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d(TAG, "Error: ${t.message}")
Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show()
}
})
} else {
Toast.makeText(requireContext(), "Selecciona una imagen", Toast.LENGTH_LONG).show()
}
}
///////////////////////////////////////
private fun clearForm(){
editTextCategory?.setText("")
imageFile = null
imageViewCategory?.setImageResource(R.drawable.ic_image)
}
//////////FUNCIONES DE SESION
private fun getUserFromSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $usuario")
}
}
//////////////////////////////////////
///////////SELECCIONAR IMAGEN
private val startImageForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
if(resultCode == Activity.RESULT_OK){
val fileUri = data?.data
imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor
imageViewCategory?.setImageURI(fileUri)
} else if (resultCode == ImagePicker.RESULT_ERROR){
Toast.makeText(requireContext(), ImagePicker.getError(data), Toast.LENGTH_LONG).show()
}
else {
Toast.makeText(requireContext(), "Tarea se cancelo", Toast.LENGTH_LONG).show()
}
}
private fun selectImage() {
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080,1080)
.createIntent { intent ->
startImageForResult.launch(intent)
}
}
//////////////////////////////////
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantOrdersFragment.kt | 436715949 | package com.andy.kotlindelivery.fragments.restaurant
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andy.kotlindelivery.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 [RestaurantOrdersFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class RestaurantOrdersFragment : 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_restaurant_orders, 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 RestaurantOrdersFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
RestaurantOrdersFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/delivery/DeliveryOrdersFragment.kt | 3196194907 | package com.andy.kotlindelivery.fragments.delivery
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andy.kotlindelivery.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 [DeliveryOrdersFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class DeliveryOrdersFragment : 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_delivery_orders, 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 DeliveryOrdersFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
DeliveryOrdersFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientOrderFragment.kt | 2576615231 | package com.andy.kotlindelivery.fragments.client
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andy.kotlindelivery.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 [ClientOrderaFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ClientOrderFragment : 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_client_order, 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 ClientOrderaFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ClientOrderFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientCategoriesFragment.kt | 3404397954 | package com.andy.kotlindelivery.fragments.client
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.shopping_bag.ClientShoppingBagActivity
import com.andy.kotlindelivery.adapters.CategoriasAdapters
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.CategoriasProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ClientCategoriesFragment : Fragment() {
val gson = Gson()
var TAG = "ClientCategoriesFragment"
var myView: View? = null
var recyclerViewCategorias: RecyclerView? = null
var categoriasProvider: CategoriasProviders? = null
var adapter: CategoriasAdapters? = null
var usuario: Usuario? = null
var sharedPref: SharedPref? = null
var categorias = ArrayList<Categoria>()
var toolbar: Toolbar? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_client_categories, container, false)
setHasOptionsMenu(true)
toolbar = myView?.findViewById(R.id.toolbar)
toolbar?.setTitleTextColor(ContextCompat.getColor(requireContext(), R.color.black))
toolbar?.title = "Categorias"
(activity as AppCompatActivity).setSupportActionBar(toolbar)
recyclerViewCategorias = myView?.findViewById(R.id.recyclerview_categorias)
recyclerViewCategorias?.layoutManager = LinearLayoutManager(requireContext())
sharedPref = SharedPref(requireActivity())
getUserFromSession()
categoriasProvider = CategoriasProviders(usuario?.sessionToken!!)
Log.d(TAG, "categoriasProvider : ${usuario?.sessionToken!!}")
getCategorias()
return myView
}
////////
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_shopping_bag, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.item_shopping_bag){
goToShoppingBag()
}
return super.onOptionsItemSelected(item)
}
private fun goToShoppingBag(){
val i = Intent(requireContext(), ClientShoppingBagActivity::class.java)
startActivity(i)
}
////////////////////////////////////////////////////
private fun getCategorias(){
Log.d(TAG, "getCategorias() : ${categoriasProvider}")
categoriasProvider?.getAll()?.enqueue(object: Callback<ArrayList<Categoria>> {
override fun onResponse(call: Call<ArrayList<Categoria>>, response: Response<ArrayList<Categoria>>
) {
if(response.body() != null){
categorias = response.body()!!
adapter = CategoriasAdapters(requireActivity(), categorias)
recyclerViewCategorias?.adapter = adapter
}
}
override fun onFailure(call: Call<ArrayList<Categoria>>, t: Throwable) {
Log.d(TAG, "Error: ${t.message}")
Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show()
}
})
}
private fun getUserFromSession() {
//val sharedPref = SharedPref(this,)
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $usuario")
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/client/ClientProfileFragment.kt | 640256822 | package com.andy.kotlindelivery.fragments.client
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.MainActivity
import com.andy.kotlindelivery.activities.SelectRolesActivity
import com.andy.kotlindelivery.activities.client.update.ClientUpdateActivity
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
import com.google.gson.Gson
import de.hdodenhof.circleimageview.CircleImageView
class ClientProfileFragment : Fragment() {
var myView: View? = null
var buttonSeleccinarRol : Button? = null
var buttonUpdateProfile : Button? = null
var circleImageUser:CircleImageView? = null
var textViewNombre: TextView? = null
var textViewCorreo: TextView? = null
var textViewTelefono: TextView? = null
var imageViewLogout: ImageView?= null
var sharedPref: SharedPref? =null
var usuario: Usuario? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_client_profile, container, false)
sharedPref = SharedPref(requireActivity())
buttonSeleccinarRol = myView?.findViewById(R.id.btn_select_rol)
buttonUpdateProfile = myView?.findViewById(R.id.btn_update_profile)
textViewNombre = myView?.findViewById(R.id.textview_name)
textViewCorreo = myView?.findViewById(R.id.textview_email)
textViewTelefono= myView?.findViewById(R.id.textview_phone)
circleImageUser = myView?.findViewById(R.id.circle_image_user)
imageViewLogout = myView?.findViewById(R.id.imageview_logout)
buttonSeleccinarRol?.setOnClickListener { goToRolSelect() }
buttonUpdateProfile?.setOnClickListener { goToUpdate() }
imageViewLogout?.setOnClickListener { logout() }
getUserFormSession()
textViewNombre?.text = "${usuario?.nombre} ${usuario?.apellido}"
textViewCorreo?.text = usuario?.email
textViewTelefono?.text = usuario?.telefono
if(!usuario?.image.isNullOrBlank()){
Glide.with(requireContext()).load(usuario?.image).into(circleImageUser!!)
}
return myView
}
private fun getUserFormSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d("Fragment Client Profile", "Usuario: $usuario")
}
}
private fun goToUpdate(){
val i = Intent(requireContext(), ClientUpdateActivity::class.java)
startActivity(i)
}
private fun logout(){
sharedPref?.remove("user")
val i = Intent(requireContext(), MainActivity::class.java)
startActivity(i)
}
private fun goToRolSelect() {
val i = Intent(requireContext(), SelectRolesActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/UsuariosProviders.kt | 1826269683 | package com.andy.kotlindelivery.providers
import com.andy.kotlindelivery.api.ApiRoutes
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.routers.UsuariosRoutes
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import java.io.File
class UsuariosProviders(val token: String? = null) {
private var usuariosRoutes: UsuariosRoutes? = null
private var usuariosRoutesToken: UsuariosRoutes? = null
init {
val api =ApiRoutes()
usuariosRoutes =api.getUsuariosRoutes()
if(token != null){
usuariosRoutesToken = api.getUsuariosRoutesGetToken(token!!)
}
}
fun register(usuario: Usuario): Call<ResponseHttp>?{
return usuariosRoutes?.register(usuario)
}
fun login(email: String, contrasena:String): Call<ResponseHttp>?{
return usuariosRoutes?.login(email, contrasena)
}
fun update(file:File, usuario: Usuario):Call<ResponseHttp>? {
val reqFile = RequestBody.create(MediaType.parse("image/*"), file)
val image = MultipartBody.Part.createFormData("image", file.name, reqFile)
val requestBody = RequestBody.create(MediaType.parse("text/plain"), usuario.toJson())
return usuariosRoutesToken?.update(image, requestBody, token!!)
}
fun updateWhitoutImage(usuario: Usuario): Call<ResponseHttp>?{
return usuariosRoutesToken?.updateWithoutImage(usuario, token!!)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/ProductosProviders.kt | 1434426178 | package com.andy.kotlindelivery.providers
import com.andy.kotlindelivery.api.ApiRoutes
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.routers.CategoriasRoutes
import com.andy.kotlindelivery.routers.ProductosRoutes
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import java.io.File
class ProductosProviders(val token: String) {
private var productosRoutes: ProductosRoutes? = null
init {
val api = ApiRoutes()
productosRoutes = api.getProductosRoutes(token)
}
fun findByCategoria(idCategoria: String): Call<ArrayList<Producto>> ?{
return productosRoutes?.findByCategoria(idCategoria, token)
}
fun create(files: List<File>, producto: Producto): Call<ResponseHttp>? {
val images = arrayOfNulls< MultipartBody.Part>(files.size)
for (i in 0 until files.size) {
val reqFile = RequestBody.create(MediaType.parse("image/*"), files[i])
images[i] = MultipartBody.Part.createFormData("image", files[i].name, reqFile)
}
val requestBody = RequestBody.create(MediaType.parse("text/plain"), producto.toJson())
return productosRoutes?.create(images, requestBody, token!!)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/providers/CategoriasProviders.kt | 1845768753 | package com.andy.kotlindelivery.providers
import com.andy.kotlindelivery.api.ApiRoutes
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.routers.CategoriasRoutes
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import java.io.File
class CategoriasProviders(val token: String) {
private var categoriasRoutes: CategoriasRoutes? = null
init {
val api = ApiRoutes()
categoriasRoutes = api.getCategoriasRoutesGetToken(token)
}
fun getAll(): Call<ArrayList<Categoria>> ?{
return categoriasRoutes?.getAll(token)
}
fun create(file: File, categoria: Categoria): Call<ResponseHttp>? {
val reqFile = RequestBody.create(MediaType.parse("image/*"), file)
val image = MultipartBody.Part.createFormData("image", file.name, reqFile)
val requestBody = RequestBody.create(MediaType.parse("text/plain"), categoria.toJson())
return categoriasRoutes?.create(image, requestBody, token!!)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/utils/SharedPref.kt | 1144079281 | package com.andy.kotlindelivery.utils
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import com.google.gson.Gson
class SharedPref(activity:Activity) {
private var prefs: SharedPreferences? = null
init {
prefs = activity.getSharedPreferences("com.andy.kotlindelivery", Context.MODE_PRIVATE)
}
//metodo que guarda la sesion
fun save(key:String, objeto: Any) {
try{
val gson = Gson()
val json = gson.toJson(objeto)
with(prefs?.edit()) {
this?.putString(key, json)
this?.commit()
}
}catch (e: Exception) {
Log.d("ERROR", "Err: ${e.message}")
}
}
//metodo que obtiene la data del metodo save()
fun getData(key: String): String? {
val data = prefs?.getString(key, "")
return data
}
// FUNCION PARA CERRAR SESION
fun remove(key: String){
prefs?.edit()?.remove(key)?.apply()
}
}
|
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Rol.kt | 3544019830 | package com.andy.kotlindelivery.models
import com.google.gson.annotations.SerializedName
class Rol (
@SerializedName("id") val id: String,
@SerializedName("nombre") val nombre: String,
@SerializedName("imagen") val imagen: String,
@SerializedName("ruta") val ruta: String
){
override fun toString(): String {
return "Rol(id='$id', nombre='$nombre', imagen='$imagen', ruta='$ruta')"
}
}
|
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Categoria.kt | 645518434 | package com.andy.kotlindelivery.models
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
class Categoria(
val id: String? = null,
val nombre: String,
val image: String? = null
) {
fun toJson(): String {
return Gson().toJson(this)
}
override fun toString(): String {
//return "Categoria(id=$id, nombre=$nombre, image=$image)"
return nombre
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/ResponseHttp.kt | 290894754 | package com.andy.kotlindelivery.models
import com.google.gson.JsonObject
import com.google.gson.annotations.SerializedName
class ResponseHttp(
@SerializedName("message") val message : String,
@SerializedName("succes") val isSucces : Boolean,
@SerializedName("data") val data : JsonObject,
@SerializedName("error") val error : String,
) {
override fun toString(): String {
return "ResponseHttp(message='$message', isSucces=$isSucces, data=$data, error='$error')"
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Producto.kt | 728315161 | package com.andy.kotlindelivery.models
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
class Producto(
@SerializedName("id") val id: String? = null,
@SerializedName("nombre") val nombre: String,
@SerializedName("descripcion") val descripcion: String,
@SerializedName("precio") val precio: Double,
@SerializedName("image1") val imagen1: String? = null,
@SerializedName("image2") val imagen2: String? = null,
@SerializedName("image3") val imagen3: String? = null,
@SerializedName("id_categoria") val idCategoria: String,
@SerializedName("quantity") var quantity: Int? = null,
) {
fun toJson(): String {
return Gson().toJson(this)
}
override fun toString(): String {
return "Producto(id=$id, nombre='$nombre', descripcion='$descripcion', precio=$precio, imagen1=$imagen1, imagen2=$imagen2, imagen3=$imagen3, idCategoria='$idCategoria', quantity=$quantity)"
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/models/Usuario.kt | 2859392721 | package com.andy.kotlindelivery.models
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
class Usuario (
@SerializedName("id") var id : String? = null,
@SerializedName("nombre") var nombre:String,
@SerializedName("apellido") var apellido : String,
@SerializedName("email") val email:String,
@SerializedName("telefono") var telefono : String,
@SerializedName("contrasena") val contrasena:String,
@SerializedName("image") var image : String? = null,
@SerializedName("session_token") val sessionToken:String? = null,
@SerializedName("is_available") val is_available : Boolean? = null,
@SerializedName("roles") val roles: ArrayList<Rol>? = null //array de objetos
) {
override fun toString(): String {
return "Usuario(id=$id, nombre='$nombre', apellido='$apellido', email='$email', telefono='$telefono', contrasena='$contrasena', image=$image, sessionToken=$sessionToken, is_available=$is_available, roles=$roles)"
}
fun toJson(): String {
return Gson().toJson(this)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/CategoriasAdapters.kt | 262881218 | package com.andy.kotlindelivery.adapters
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity
import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
class CategoriasAdapters (val context: Activity, val categorias:ArrayList<Categoria>): RecyclerView.Adapter<CategoriasAdapters.CategoriasViewHolder>() {
val sharedPref = SharedPref(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoriasViewHolder{
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_categorias, parent, false) ///instacias la vista en la que se esta trabajando
return CategoriasViewHolder(view)
}
override fun getItemCount(): Int {
return categorias.size
}
override fun onBindViewHolder(holder: CategoriasViewHolder, position: Int) {
val categoria = categorias[position] // cada una de las categorias
Log.d("Categorias adapter", "Categoiras : $categoria")
holder.textViewCategoria.text = categoria.nombre
Glide.with(context).load(categoria.image).into(holder.imageViewCategoria)
holder.itemView.setOnClickListener { goToProductos( categoria ) }
}
private fun goToProductos( categoria: Categoria) {
val i = Intent(context, ClientProductsListActivity::class.java)
i.putExtra("idCategoria", categoria.id)
context.startActivity(i)
}
class CategoriasViewHolder(view: View): RecyclerView.ViewHolder(view){
val textViewCategoria: TextView
val imageViewCategoria: ImageView
init {
textViewCategoria = view.findViewById(R.id.textview_category)
imageViewCategoria = view.findViewById(R.id.imageview_category)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/RolesAdapters.kt | 4225489925 | package com.andy.kotlindelivery.adapters
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity
import com.andy.kotlindelivery.activities.delivery.home.DeliveryHomeActivity
import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity
import com.andy.kotlindelivery.models.Rol
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
class RolesAdapters (val context: Activity, val roles:ArrayList<Rol>): RecyclerView.Adapter<RolesAdapters.RolesViewHolder>() {
val sharedPref = SharedPref(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RolesViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_roles, parent, false) ///instacias la vista en la que se esta trabajando
return RolesViewHolder(view)
}
override fun getItemCount(): Int {
return roles.size
}
override fun onBindViewHolder(holder: RolesViewHolder, position: Int) {
val rol = roles[position]
holder.textViewRol.text = rol.nombre
Glide.with(context).load(rol.imagen).into(holder.imageViewRol)
holder.itemView.setOnClickListener { goToRol( rol ) }
}
private fun goToRol(rol: Rol) {
val typeActivity = when( rol.nombre) {
"RESTAURANTE" -> RestaurantHomeActivity::class.java
"REPARTIDOR" -> DeliveryHomeActivity::class.java
else -> ClientHomeActivity::class.java
}
sharedPref.save("rol", rol.nombre)
val i = Intent(context, typeActivity)
context.startActivity(i)
}
class RolesViewHolder(view: View): RecyclerView.ViewHolder(view){
val textViewRol: TextView
val imageViewRol: ImageView
init {
textViewRol = view.findViewById(R.id.textView_rol)
imageViewRol = view.findViewById(R.id.imageView_rol)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/ProductosAdapters.kt | 4225021946 | package com.andy.kotlindelivery.adapters
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.products.details.ClientProductsDetailActivity
import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity
import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
import com.google.gson.Gson
class ProductosAdapters (val context: Activity, val productos:ArrayList<Producto>): RecyclerView.Adapter<ProductosAdapters.ProductosViewHolder>() {
val sharedPref = SharedPref(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductosViewHolder{
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_productos, parent, false) ///instacias la vista en la que se esta trabajando
return ProductosViewHolder(view)
}
override fun getItemCount(): Int {
return productos.size
}
override fun onBindViewHolder(holder: ProductosViewHolder, position: Int) {
val producto = productos[position] // cada una de las categorias
Log.d("Productos adapter", "Productos : $producto")
holder.textViewNombre.text = producto.nombre
holder.textViewPrecio.text = "$${producto.precio}"
Glide.with(context).load(producto.imagen1).into(holder.imageViewProducto)
holder.itemView.setOnClickListener { goToDetail( producto ) }
}
private fun goToDetail( producto: Producto) {
val i = Intent(context, ClientProductsDetailActivity::class.java)
i.putExtra("producto", producto.toJson())
context.startActivity(i)
}
class ProductosViewHolder(view: View): RecyclerView.ViewHolder(view){
val textViewNombre: TextView
val textViewPrecio: TextView
val imageViewProducto: ImageView
init {
textViewNombre = view.findViewById(R.id.txtview_nombre)
textViewPrecio = view.findViewById(R.id.txtview_precio)
imageViewProducto = view.findViewById(R.id.imageview_producto)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/adapters/ShoppingBagAdapters.kt | 927053026 | package com.andy.kotlindelivery.adapters
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.products.details.ClientProductsDetailActivity
import com.andy.kotlindelivery.activities.client.products.list.ClientProductsListActivity
import com.andy.kotlindelivery.activities.client.shopping_bag.ClientShoppingBagActivity
import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
import com.google.gson.Gson
import kotlin.math.sign
class ShoppingBagAdapters (val context: Activity, val productos:ArrayList<Producto>): RecyclerView.Adapter<ShoppingBagAdapters.ShoppingBagViewHolder>() {
val sharedPref = SharedPref(context)
init{
(context as ClientShoppingBagActivity).setTotal(getTotal())
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingBagViewHolder{
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_shopping_bag , parent, false) ///instacias la vista en la que se esta trabajando
return ShoppingBagViewHolder(view)
}
override fun getItemCount(): Int {
return productos.size
}
override fun onBindViewHolder(holder: ShoppingBagViewHolder, position: Int) {
val producto = productos[position] // cada una de las categorias
Log.d("Productos adapter", "Productos : $producto")
holder.textViewNombre.text = producto.nombre
holder.textViewPrecio.text = "$${producto.precio * producto.quantity!!}"
holder.textViewContador.text = "${producto.quantity}"
Glide.with(context).load(producto.imagen1).into(holder.imageViewProducto)
holder.imageViewAdd.setOnClickListener { addItem(producto, holder) }
holder.imageViewRemove.setOnClickListener { removeItem(producto, holder) }
holder.imageViewDelete.setOnClickListener { deleteProducto(position) }
// holder.itemView.setOnClickListener { goToDetail( producto ) }
}
private fun getTotal(): Double{
var total = 0.0
for(p in productos) {
total = total + (p.quantity!! + p.precio)
}
return total
}
private fun deleteProducto(position: Int) {
productos.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeRemoved(position, productos.size)
sharedPref.save("order", productos)
(context as ClientShoppingBagActivity).setTotal(getTotal())
}
///// FUNCIONES PARA INCREMENTAR Y DECREMENTAR LA CANTIDAD DE PRODUCTOS
private fun getIndexOf(idProducto: String): Int{
var pos = 0
for(p in productos)
if(p.id == idProducto){
return pos
}
pos ++
return -1
}
private fun addItem(producto: Producto, holder: ShoppingBagViewHolder){
val index = getIndexOf(producto.id!!)
producto.quantity = producto.quantity!! +1
productos[index].quantity = producto.quantity
holder.textViewContador.text = "${producto?.quantity}"
holder.textViewPrecio.text = "$${producto.quantity!! * producto.precio}"
sharedPref.save("order", productos)
(context as ClientShoppingBagActivity).setTotal(getTotal())
}
private fun removeItem(producto: Producto, holder: ShoppingBagViewHolder){
if(producto.quantity!! > 1) {
val index = getIndexOf(producto.id!!)
producto.quantity = producto.quantity!! -1
productos[index].quantity = producto.quantity
holder.textViewContador.text = "${producto?.quantity}"
holder.textViewPrecio.text = "$${producto.quantity!! * producto.precio}"
sharedPref.save("order", productos)
(context as ClientShoppingBagActivity).setTotal(getTotal())
}
}
// private fun goToDetail( producto: Producto) {
// val i = Intent(context, ClientProductsDetailActivity::class.java)
// i.putExtra("producto", producto.toJson())
// context.startActivity(i)
// }
///INICIALIZA Y ASIGNA LAS VARIABLES DEL RECYCLERVIEW
class ShoppingBagViewHolder(view: View): RecyclerView.ViewHolder(view){
val textViewNombre: TextView
val textViewPrecio: TextView
val imageViewProducto: ImageView
val textViewContador: TextView
val imageViewRemove: ImageView
val imageViewAdd: ImageView
val imageViewDelete: ImageView
init {
textViewNombre = view.findViewById(R.id.textview_nombre)
textViewPrecio = view.findViewById(R.id.textview_precio)
textViewContador = view.findViewById(R.id.textview_contador)
imageViewRemove = view.findViewById(R.id.image_remove)
imageViewAdd = view.findViewById(R.id.image_add)
imageViewDelete = view.findViewById(R.id.image_delete)
imageViewProducto = view.findViewById(R.id.imageview_producto)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/api/ApiRoutes.kt | 3213437976 | package com.andy.kotlindelivery.api
import com.andy.kotlindelivery.routers.CategoriasRoutes
import com.andy.kotlindelivery.routers.ProductosRoutes
import com.andy.kotlindelivery.routers.UsuariosRoutes
class ApiRoutes {
val API_URL = "http://192.168.100.92:3000/api/"
val retrofit = RetrofitClient()
fun getUsuariosRoutes(): UsuariosRoutes {
return retrofit.getClient(API_URL).create(UsuariosRoutes::class.java)
}
fun getUsuariosRoutesGetToken(token: String): UsuariosRoutes{
return retrofit.getClientWebToken(API_URL, token).create(UsuariosRoutes::class.java)
}
fun getCategoriasRoutesGetToken(token: String): CategoriasRoutes{
return retrofit.getClientWebToken(API_URL, token).create(CategoriasRoutes::class.java)
}
fun getProductosRoutes(token: String): ProductosRoutes{
return retrofit.getClientWebToken(API_URL, token).create(ProductosRoutes::class.java)
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/api/RetrofitClient.kt | 1260320848 | package com.andy.kotlindelivery.api
import android.annotation.SuppressLint
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RetrofitClient {
fun getClient(url: String) : Retrofit {
return Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
fun getClientWebToken(url: String, token: String): Retrofit {
val client = OkHttpClient.Builder()
client.addInterceptor{ chain ->
val request= chain.request()
val newRequest =request.newBuilder().header("Authorization", token)
chain.proceed(newRequest.build())
}
return Retrofit.Builder()
.baseUrl(url)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/restaurant/home/RestaurantHomeActivity.kt | 3069758857 | package com.andy.kotlindelivery.activities.restaurant.home
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.MainActivity
import com.andy.kotlindelivery.fragments.client.ClientProfileFragment
import com.andy.kotlindelivery.fragments.restaurant.RestaurantCategoryFragment
import com.andy.kotlindelivery.fragments.restaurant.RestaurantOrdersFragment
import com.andy.kotlindelivery.fragments.restaurant.RestaurantProductFragment
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.utils.SharedPref
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.Gson
class RestaurantHomeActivity : AppCompatActivity() {
private val TAG = "RestaurantHomeActivity"
// var buttonLogout: Button? = null
var sharedPref: SharedPref? = null
var bottomNavigation: BottomNavigationView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_restaurant_home)
sharedPref = SharedPref(this)
//Abre el fragment por defecto
openFragment(RestaurantOrdersFragment())
//buttonLogout = findViewById(R.id.btn_logout)
//buttonLogout?.setOnClickListener { logout() }
bottomNavigation = findViewById(R.id.bottom_navigation)
bottomNavigation?.setOnItemSelectedListener {
when (it.itemId){
R.id.item_home -> {
openFragment(RestaurantOrdersFragment())
true
}
R.id.item_category -> {
openFragment(RestaurantCategoryFragment())
true
}
R.id.item_product -> {
openFragment(RestaurantProductFragment())
true
}
R.id.item_profile -> {
openFragment(ClientProfileFragment())
true
}
else -> false
}
}
getUserFormSession()
}
/// barra de navegacion
private fun openFragment(fragment: Fragment){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun logout(){
sharedPref?.remove("user")
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}
private fun getUserFormSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $user")
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/MainActivity.kt | 2837446731 | package com.andy.kotlindelivery.activities
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity
import com.andy.kotlindelivery.activities.delivery.home.DeliveryHomeActivity
import com.andy.kotlindelivery.activities.restaurant.home.RestaurantHomeActivity
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.UsuariosProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
var imageViewGotoRegister: ImageView? = null
var editTxtEmail: EditText? = null
var editTxTContrasena: EditText? = null
var btnLogin: Button? = null
var usuarioProvider = UsuariosProviders()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageViewGotoRegister = findViewById(R.id.imgview_goregister)
editTxtEmail = findViewById(R.id.edittxt_email)
editTxTContrasena = findViewById(R.id.edittxt_contrasena)
btnLogin = findViewById(R.id.btn_login)
imageViewGotoRegister?.setOnClickListener{ goToRegister() }
btnLogin?.setOnClickListener { login() }
getUserFromSession()
}
private fun login(){
val email = editTxtEmail?.text.toString() //NULL POINTE EXCEPTION
val contrasena = editTxTContrasena?.text.toString()
if (isValidForm(email,contrasena)) {
usuarioProvider.login(email,contrasena)?.enqueue(object : Callback<ResponseHttp> {
override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) {
Log.d("MainActivity", "Respuesta: ${response.body()}" )
Log.d("MainActivity", "Datos enviados: ${email} " )
Log.d("MainActivity", "Datos enviados: ${contrasena} " )
if(response.body()?.isSucces == true) {
Toast.makeText(this@MainActivity, response.body()?.message, Toast.LENGTH_LONG).show()
saveUserInSession(response.body()?.data.toString())
//goToClientHome()
}
else {
Toast.makeText(this@MainActivity, "Los datos son incorrectos1", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d("MainActivity", "Hubo un error ${t.message}")
Toast.makeText(this@MainActivity, "Hubo un error ${t.message}", Toast.LENGTH_LONG).show()
}
})
} else {
Toast.makeText(this@MainActivity, "No es valido", Toast.LENGTH_LONG).show()
}
}
private fun goToClientHome() {
val i = Intent(this, ClientHomeActivity::class.java)
i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK //ELIMINA EL HISTORIAL DE PANTALLA
startActivity(i)
}
private fun goToRestaurantHome() {
val i = Intent(this, RestaurantHomeActivity::class.java)
i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
private fun goToDeliveryHome() {
val i = Intent(this, DeliveryHomeActivity::class.java)
i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
private fun goToRolSelect() {
val i = Intent(this, SelectRolesActivity::class.java)
i.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
private fun saveUserInSession(data: String) {
val sharedPreferences = SharedPref(this)
val gson = Gson()
val user = gson.fromJson(data, Usuario::class.java)
sharedPreferences.save("user", user)
if (user.roles?.size!! > 1){ //tiene mas de un rol
goToRolSelect()
} else { //tiene un rol
goToClientHome()
}
}
fun String.isEmailValid() : Boolean{
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
//Ya que la sesion ha sido iniciada nos mandara directamente a la pantalla de ClientHomeActivity
private fun getUserFromSession() {
val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
val user = gson.fromJson(sharedPref.getData("user"), Usuario::class.java)
Log.d("MainActivity","Usuario: $user")
if(!sharedPref.getData("rol").isNullOrBlank()) {
val rol = sharedPref.getData("rol")?.replace("\"", "")
Log.d("MainActivity", "Rol $rol")
when( rol ){
"RESTAURANTE" -> goToRestaurantHome()
"REPARTIDOR" -> goToDeliveryHome()
"CLIENTE" -> goToClientHome()
else -> goToClientHome()
}
}
}
}
private fun isValidForm(email:String, contrasena:String) : Boolean{
if(email.isBlank()) {
Toast.makeText(this,"Debes ingresar el email", Toast.LENGTH_LONG).show()
return false
}
if(contrasena.isBlank()) {
Toast.makeText(this,"Debes ingresar la contraseña", Toast.LENGTH_LONG).show()
return false
}
if(!email.isEmailValid()) {
return false
}
return true
}
private fun goToRegister(){
val i = Intent( this, RegisterActivity::class.java)
startActivity(i)
finish()
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/RegisterActivity.kt | 873369646 | package com.andy.kotlindelivery.activities
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.UsuariosProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class RegisterActivity : AppCompatActivity() {
var imageViewLogin: ImageView? = null
var editTxtNombre : EditText? = null
var editTxtApellido : EditText? = null
var editTxtEmailRegs : EditText? = null
var editTxtTelefono : EditText? = null
var editTxtContrasenaRegs : EditText? = null
var editTxtContrasenaConfirm : EditText? = null
var btnRegistro : Button? = null
//
var usuariosProviders = UsuariosProviders()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
imageViewLogin = findViewById(R.id.imgview_gologin)
editTxtNombre = findViewById(R.id.edittxt_nombre)
editTxtApellido = findViewById(R.id.edittxt_apellido)
editTxtEmailRegs = findViewById(R.id.edittxt_emailregister)
editTxtTelefono = findViewById(R.id.edittxt_telelfono)
editTxtContrasenaRegs = findViewById(R.id.edittxt_contrasenaregister)
editTxtContrasenaConfirm = findViewById(R.id.edittxt_contrasenaconfirm)
btnRegistro = findViewById(R.id.btn_registro)
imageViewLogin?.setOnClickListener{ gotoLogin() }
btnRegistro?.setOnClickListener { register() }
}
private fun register(){
var nombre = editTxtNombre?.text.toString()
var apellido = editTxtApellido?.text.toString()
var emailRegistro = editTxtEmailRegs?.text.toString()
var telefono = editTxtTelefono?.text.toString()
var contrasenaRegistro = editTxtContrasenaRegs?.text.toString()
var contrasenaConfirmacion = editTxtContrasenaConfirm?.text.toString()
if(isValidForm(nombre=nombre,
apellido=apellido,
emailRegistro=emailRegistro,
telefono=telefono,
contrasenaRegistro=contrasenaRegistro,
contrasenaConfirma=contrasenaConfirmacion)){
val usuario = Usuario(
nombre = nombre,
apellido = apellido,
email = emailRegistro,
telefono = telefono,
contrasena = contrasenaRegistro )
usuariosProviders.register(usuario)?.enqueue(object: Callback<ResponseHttp> {
override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp> ) {
if(response.body()?.isSucces == true) {
saveUserInSession(response.body()?.data.toString())
goToClientHome()
}
Toast.makeText(this@RegisterActivity, response.body()?.message, Toast.LENGTH_LONG).show()
Log.d( TAG, "Response: $response" )
Log.d( TAG, "Body: ${response.body()}" )
Log.d(TAG, "Los datos son: ${usuario} ")
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d(TAG, "Se produjo un error ${t.message}")
Toast.makeText(this@RegisterActivity, "Se produjo un error ${t.message}", Toast.LENGTH_LONG).show()
}
})
// Toast.makeText(this, "El formulario es valido", Toast.LENGTH_SHORT).show()
}
}
////////////////////////////////////////
private fun goToClientHome() {
//val i = Intent(this, ClientHomeActivity::class.java)
val i = Intent(this, SaveImageActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
private fun saveUserInSession(data: String) {
val sharedPreferences = SharedPref(this)
val gson = Gson()
val user = gson.fromJson(data, Usuario::class.java)
sharedPreferences.save("user", user)
}
///////////////////////////////
fun String.isEmailValid() : Boolean{
return !TextUtils.isEmpty(this) && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}
private fun isValidForm(
nombre : String,
apellido : String,
emailRegistro : String,
telefono : String,
contrasenaRegistro : String,
contrasenaConfirma : String
) : Boolean{
if(nombre.isBlank()) {
Toast.makeText(this,"Debes ingresar el nombre", Toast.LENGTH_LONG).show()
return false
}
if(apellido.isBlank()) {
Toast.makeText(this,"Debes ingresar el apellido", Toast.LENGTH_LONG).show()
return false
}
if(emailRegistro.isBlank()) {
Toast.makeText(this,"Debes ingresar el email", Toast.LENGTH_LONG).show()
return false
}
if(telefono.isBlank()) {
Toast.makeText(this,"Debes ingresar el telefono", Toast.LENGTH_LONG).show()
return false
}
if(contrasenaRegistro.isBlank()) {
Toast.makeText(this,"Debes ingresar la contraseña", Toast.LENGTH_LONG).show()
return false
}
if(contrasenaConfirma.isBlank()) {
Toast.makeText(this,"Debes volver a introducir la contraseña", Toast.LENGTH_LONG).show()
return false
}
if(!emailRegistro.isEmailValid()) {
return false
}
if(contrasenaRegistro != contrasenaConfirma) {
Toast.makeText(this,"Las contraseñas no coinciden", Toast.LENGTH_LONG).show()
}
return true
}
private fun gotoLogin() {
val i = Intent(this, MainActivity::class.java)
startActivity(i)
finish()
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/SaveImageActivity.kt | 421572402 | package com.andy.kotlindelivery.activities
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.andy.kotlindelivery.R
import com.github.dhaval2404.imagepicker.ImagePicker
import de.hdodenhof.circleimageview.CircleImageView
import java.io.File
import com.andy.kotlindelivery.activities.client.home.ClientHomeActivity
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.UsuariosProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SaveImageActivity : AppCompatActivity() {
var TAG = "SaveImageActivity"
var circleImageUser: CircleImageView? = null
var buttonNext: Button? = null
var buttonConfirm: Button? = null
private var imageFile: File? = null
var userProvider: UsuariosProviders? =null
var user: Usuario? = null
var sharedPref: SharedPref? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_save_imagectivity)
sharedPref = SharedPref(this)
getUserFormSession()
userProvider = UsuariosProviders(user?.sessionToken)
circleImageUser = findViewById(R.id.cirlce_image)
buttonConfirm = findViewById(R.id.btn_confirm)
buttonNext = findViewById(R.id.btn_next)
circleImageUser?.setOnClickListener{ selectImage() }
buttonNext?.setOnClickListener{ goToClientHome() }
buttonConfirm?.setOnClickListener{ saveImage() }
}
private fun saveImage() {
if(imageFile != null && user != null ) {
userProvider?.update(imageFile!!, user!!)?.enqueue(object : Callback<ResponseHttp> {
override fun onResponse(
call: Call<ResponseHttp>,
response: Response<ResponseHttp>
) {
Log.d(TAG, "RESPONSE: $response")
Log.d(TAG, "BODY: ${response.body()}")
saveUserInSession(response.body()?.data.toString())
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d(TAG, "Error: ${t.message}")
Toast.makeText(this@SaveImageActivity, "Error ${t.message}", Toast.LENGTH_LONG)
.show()
}
})
} else {
Toast.makeText(this@SaveImageActivity, "Los datos del usuario no pueden ser nulas", Toast.LENGTH_LONG).show()
}
}
private fun saveUserInSession(data: String) {
val gson = Gson()
val user = gson.fromJson(data, Usuario::class.java)
sharedPref?.save("user", user)
goToClientHome()
}
private fun goToClientHome() {
val i = Intent(this, ClientHomeActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK //ELIMINA EL HISTORIAL DE PANTALLA
startActivity(i)
}
private fun getUserFormSession() {
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
}
}
private val startImageForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
if(resultCode == Activity.RESULT_OK){
val fileUri = data?.data
imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor
circleImageUser?.setImageURI(fileUri)
} else if (resultCode == ImagePicker.RESULT_ERROR){
Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_LONG).show()
}
else {
Toast.makeText(this, "Tarea se cancelo", Toast.LENGTH_LONG).show()
}
}
private fun selectImage() {
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080,1080)
.createIntent { intent ->
startImageForResult.launch(intent)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/SelectRolesActivity.kt | 2319649508 | package com.andy.kotlindelivery.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.adapters.RolesAdapters
import com.andy.kotlindelivery.models.Rol
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
class SelectRolesActivity : AppCompatActivity() {
var recyclerViewRoles: RecyclerView? = null
var user: Usuario? = null
var adapter: RolesAdapters? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select_roles)
recyclerViewRoles = findViewById(R.id.recyclerview_roles)
recyclerViewRoles?.layoutManager = LinearLayoutManager(this)
getUserFromSession()
adapter = RolesAdapters(this, user?.roles!!)
recyclerViewRoles?.adapter = adapter
}
private fun getUserFromSession() {
val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
user = gson.fromJson(sharedPref.getData("user"), Usuario::class.java)
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/delivery/home/DeliveryHomeActivity.kt | 908429420 | package com.andy.kotlindelivery.activities.delivery.home
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.MainActivity
import com.andy.kotlindelivery.fragments.client.ClientProfileFragment
import com.andy.kotlindelivery.fragments.delivery.DeliveryOrdersFragment
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.utils.SharedPref
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.Gson
class DeliveryHomeActivity : AppCompatActivity() {
private val TAG = "DeliveryHomeActivity"
// var buttonLogout: Button? = null
var sharedPref: SharedPref? = null
var bottomNavigation: BottomNavigationView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_delivery_home)
sharedPref = SharedPref(this)
//Abre el fragment por defecto
openFragment(DeliveryOrdersFragment())
//buttonLogout = findViewById(R.id.btn_logout)
//buttonLogout?.setOnClickListener { logout() }
bottomNavigation = findViewById(R.id.bottom_navigation)
bottomNavigation?.setOnItemSelectedListener {
when (it.itemId){
R.id.item_orders -> {
openFragment(DeliveryOrdersFragment())
true
}
R.id.item_profile -> {
openFragment(ClientProfileFragment())
true
}
else -> false
}
}
getUserFormSession()
}
/// barra de navegacion
private fun openFragment(fragment: Fragment){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun logout(){
sharedPref?.remove("user")
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}
private fun getUserFormSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $user")
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/shopping_bag/ClientShoppingBagActivity.kt | 1304639856 | package com.andy.kotlindelivery.activities.client.shopping_bag
import android.content.res.ColorStateList
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.adapters.ShoppingBagAdapters
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class ClientShoppingBagActivity : AppCompatActivity() {
var recyclerViewShoppingBag: RecyclerView? = null
var btnNext: Button? = null
var textViewTotal: TextView? = null
var toolbar: Toolbar? = null
var adapter: ShoppingBagAdapters? = null
var sharedPref: SharedPref? = null
var gson = Gson()
var seleeccionarProducto = ArrayList<Producto>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_client_shopping_bag)
sharedPref = SharedPref(this)
recyclerViewShoppingBag = findViewById(R.id.recyclerview_shopping_bag)
btnNext = findViewById(R.id.btn_next)
textViewTotal = findViewById(R.id.textview_total)
toolbar = findViewById(R.id.toolbar)
toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black))
toolbar?.title = "Tu orden"
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true) //habilita la flecha hacia atras
recyclerViewShoppingBag?.layoutManager = LinearLayoutManager(this)
getPoductosFromSharedPref()
}
fun setTotal(total: Double){
textViewTotal?. text = "$${total}"
}
private fun getPoductosFromSharedPref(){
Log.d("getPoductosFrom", "SahredPref antes del if ${sharedPref?.getData("order")} ")
if(!sharedPref?.getData("order").isNullOrBlank()) {
val type = object: TypeToken<ArrayList<Producto>>() {}.type
seleeccionarProducto = gson.fromJson(sharedPref?.getData("order"), type)
adapter = ShoppingBagAdapters(this, seleeccionarProducto)
recyclerViewShoppingBag?.adapter = adapter
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/home/ClientHomeActivity.kt | 3310047127 | package com.andy.kotlindelivery.activities.client.home
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.activities.MainActivity
import com.andy.kotlindelivery.fragments.client.ClientCategoriesFragment
import com.andy.kotlindelivery.fragments.client.ClientOrderFragment
import com.andy.kotlindelivery.fragments.client.ClientProfileFragment
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.utils.SharedPref
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.Gson
class ClientHomeActivity : AppCompatActivity() {
private val TAG = "ClientHomeActivity"
// var buttonLogout: Button? = null
var sharedPref: SharedPref? = null
var bottomNavigation: BottomNavigationView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_client_home)
sharedPref = SharedPref(this)
//Abre el fragment por defecto
openFragment(ClientCategoriesFragment())
//buttonLogout = findViewById(R.id.btn_logout)
//buttonLogout?.setOnClickListener { logout() }
bottomNavigation = findViewById(R.id.bottom_navigation)
bottomNavigation?.setOnItemSelectedListener {
when (it.itemId){
R.id.item_home -> {
openFragment(ClientCategoriesFragment())
true
}
R.id.item_orders -> {
openFragment(ClientOrderFragment())
true
}
R.id.item_profile -> {
openFragment(ClientProfileFragment())
true
}
else -> false
}
}
getUserFromSession()
}
/// barra de navegacion
private fun openFragment(fragment: Fragment){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun logout(){
sharedPref?.remove("user")
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}
private fun getUserFromSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
val user = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $user")
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/products/details/ClientProductsDetailActivity.kt | 3648501094 | package com.andy.kotlindelivery.activities.client.products.details
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.media.Image
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.utils.SharedPref
import com.denzcoskun.imageslider.ImageSlider
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.models.SlideModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class ClientProductsDetailActivity : AppCompatActivity() {
var TAG = "ClientProductsDetailActivity"
var producto: Producto? = null
val gson = Gson()
var imagenSlider: ImageSlider? = null
var txtviewNombre: TextView? = null
var txtviewDescripcion: TextView? = null
var txtviewContador: TextView? = null
var txtviewPrecio: TextView? = null
var imageViewAdd: ImageView? = null
var imageViewRemove: ImageView? = null
var btnAddProducto: Button? = null
var contador = 1
var productoPrecio = 0.0
var sharedPref: SharedPref? = null
var seleeccionarProducto = ArrayList<Producto>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_client_products_detail)
producto = gson.fromJson(intent.getStringExtra("producto"), Producto::class.java)
//Log.d(TAG, "Producto $producto")
imagenSlider = findViewById(R.id.imageSlider)
txtviewNombre = findViewById(R.id.txtview_nombre)
txtviewDescripcion = findViewById(R.id.txtview_descripcion)
txtviewContador= findViewById(R.id.textview_contador)
txtviewPrecio = findViewById(R.id.textview_precio)
imageViewAdd= findViewById(R.id.image_add)
imageViewRemove= findViewById(R.id.image_remove)
btnAddProducto= findViewById(R.id.btn_add_product)
sharedPref = SharedPref(this)
Log.d(TAG, "SahredPref al inicio ${sharedPref?.getData("order")} ")
val imageList = ArrayList<SlideModel>()
imageList.add(SlideModel(producto?.imagen1, ScaleTypes.CENTER_CROP))
imageList.add(SlideModel(producto?.imagen2, ScaleTypes.CENTER_CROP))
imageList.add(SlideModel(producto?.imagen3, ScaleTypes.CENTER_CROP))
//Log.d(TAG, "Array de producto $imageList")
imagenSlider?.setImageList(imageList)
txtviewNombre?.text = producto?.nombre
txtviewDescripcion?.text = producto?.descripcion
txtviewPrecio?.text = "$${producto?.precio}"
imageViewAdd?.setOnClickListener { addItem() }
imageViewRemove?.setOnClickListener { removeItem() }
btnAddProducto?.setOnClickListener { addToBag() }
getPoductosFromSharedPref()
}
private fun addToBag(){
val index = getIndexOf(producto?.id!!) //indice del producto
Log.d(TAG, "addToBag ->Producto id: ${producto?.id!!}")
if(index == -1){ //este producto no existe aun en sharedpref
if(producto?.quantity == null) {
producto?.quantity = 1
}
seleeccionarProducto.add(producto!!)
} else { //ya existe el producto en shared pref y se edita la cantidad
seleeccionarProducto[index].quantity = contador
}
sharedPref?.save("order", seleeccionarProducto)
//Log.d(TAG, "sharedPref: ${sharedPref}")
Log.d(TAG, "addToBag: ${seleeccionarProducto}")
Toast.makeText(this, "Producto agregado", Toast.LENGTH_LONG).show()
}
private fun getPoductosFromSharedPref(){
Log.d("getPoductosFrom", "SahredPref antes del if ${sharedPref?.getData("order")} ")
if(!sharedPref?.getData("order").isNullOrBlank()) {
val type = object: TypeToken<ArrayList<Producto>>() {}.type
seleeccionarProducto = gson.fromJson(sharedPref?.getData("order"), type)
val index = getIndexOf(producto?.id!!)
if(index != -1){
producto?.quantity = seleeccionarProducto[index].quantity
txtviewContador?.text = "${producto?.quantity}"
productoPrecio = producto?.precio!! * producto?.quantity!!
txtviewPrecio?.text = "${productoPrecio}"
btnAddProducto?.setText("Editar producto")
btnAddProducto?.backgroundTintList = ColorStateList.valueOf(Color.RED)
}
for( p in seleeccionarProducto) {
Log.d("getPoductosFrom", "Shared pref: $p")
}
}
Log.d("getPoductosFrom", "SahredPref despues del if ${sharedPref?.getData("order")} ")
}
//METODO QUE COMPARA SI YA EXISTE EN SHARED PREF Y ASI PODER EDITAR LA CANTIDAD
private fun getIndexOf(idProducto: String): Int{
var pos = 0
for(p in seleeccionarProducto)
if(p.id == idProducto){
return pos
}
pos ++
return -1
}
private fun addItem(){
contador++
productoPrecio = producto?.precio!! * contador
producto?.quantity = contador
txtviewContador?.text = "${producto?.quantity}"
txtviewPrecio?.text = "$${productoPrecio}"
}
private fun removeItem(){
if(contador > 1) {
contador--
productoPrecio = producto?.precio!! * contador
producto?.quantity = contador
txtviewContador?.text = "${producto?.quantity}"
txtviewPrecio?.text = "$${productoPrecio}"
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/products/list/ClientProductsListActivity.kt | 1627037962 | package com.andy.kotlindelivery.activities.client.products.list
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.adapters.CategoriasAdapters
import com.andy.kotlindelivery.adapters.ProductosAdapters
import com.andy.kotlindelivery.models.Categoria
import com.andy.kotlindelivery.models.Producto
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.CategoriasProviders
import com.andy.kotlindelivery.providers.ProductosProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.google.gson.Gson
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ClientProductsListActivity : AppCompatActivity() {
var TAG = "ClientProductsListActivity"
var recyclerViewProductos: RecyclerView? = null
var adapter: ProductosAdapters? = null
var usuario: Usuario? = null
var productosProviders: ProductosProviders? = null
var productos: ArrayList<Producto> = ArrayList()
var toolbar: Toolbar? = null
var sharedPref: SharedPref? = null
var idCategoria: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_client_products_list)
idCategoria = intent.getStringExtra("idCategoria")
Log.d(TAG,"Id categoria: $idCategoria")
recyclerViewProductos = findViewById(R.id.recyclerview_productos)
recyclerViewProductos?.layoutManager = GridLayoutManager(this, 2)
toolbar =findViewById(R.id.toolbar)
toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black))
toolbar?.title = "Productos"
setSupportActionBar(toolbar)
sharedPref = SharedPref(this)
getUserFromSession()
productosProviders = ProductosProviders(usuario?.sessionToken!!)
getProductos()
}
private fun getProductos(){
productosProviders?.findByCategoria(idCategoria!!)?.enqueue(object: Callback<ArrayList<Producto>> {
override fun onResponse(
call: Call<ArrayList<Producto>>,
response: Response<ArrayList<Producto>>
) {
Log.d(TAG,"Response: ${response.body()}")
if(response.body() != null){
productos = response.body()!!
adapter = ProductosAdapters(this@ClientProductsListActivity, productos)
recyclerViewProductos?.adapter = adapter
}
}
override fun onFailure(call: Call<ArrayList<Producto>>, t: Throwable) {
Toast.makeText(this@ClientProductsListActivity, t.message, Toast.LENGTH_LONG).show()
Log.d(TAG,"Error: ${t.message}")
}
})
}
/////funciones de sesion
private fun getUserFromSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $usuario")
}
}
} |
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/activities/client/update/ClientUpdateActivity.kt | 3744052627 | package com.andy.kotlindelivery.activities.client.update
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.andy.kotlindelivery.R
import com.andy.kotlindelivery.models.ResponseHttp
import com.andy.kotlindelivery.models.Usuario
import com.andy.kotlindelivery.providers.UsuariosProviders
import com.andy.kotlindelivery.utils.SharedPref
import com.bumptech.glide.Glide
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.gson.Gson
import de.hdodenhof.circleimageview.CircleImageView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
class ClientUpdateActivity : AppCompatActivity() {
var circleImageUsuario: CircleImageView? = null
var editTextNombre: EditText? = null
var editTextApellido: EditText? = null
var editTextTelefono: EditText? = null
var buttonActualizar: Button? = null
val TAG = "Client Update Activity"
var sharedPref: SharedPref? = null
var usuario: Usuario? = null
private var imageFile: File? = null
var userProvider : UsuariosProviders? = null
var toolbar: Toolbar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_client_update)
sharedPref = SharedPref(this)
toolbar = findViewById(R.id.toolbar)
toolbar?.title = "Editar perfil"
toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.black))
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true) // nos muestra la fecla de ir hacia atras
circleImageUsuario = findViewById(R.id.circle_image_user)
editTextNombre = findViewById(R.id.edittxt_nombre)
editTextApellido = findViewById(R.id.edittxt_apellido)
editTextTelefono = findViewById(R.id.edittxt_telelfono)
buttonActualizar = findViewById(R.id.btn_update)
getUserFromSession()
userProvider = UsuariosProviders(usuario?.sessionToken)
editTextNombre?.setText(usuario?.nombre)
editTextApellido?.setText(usuario?.apellido)
editTextTelefono?.setText(usuario?.telefono)
if (!usuario?.image.isNullOrBlank()) {
Glide.with(this).load(usuario?.image).into(circleImageUsuario!!)
}
circleImageUsuario?.setOnClickListener { selectImage() }
buttonActualizar?.setOnClickListener { updateData() }
}
private fun getUserFromSession() {
//val sharedPref = SharedPref(this,)
val gson = Gson()
if (!sharedPref?.getData("user").isNullOrBlank()) {
//Si el usuario existe en sesion
usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java)
Log.d(TAG, "Usuario: $usuario")
}
}
private val startImageForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
if(resultCode == Activity.RESULT_OK){
val fileUri = data?.data
imageFile = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor
circleImageUsuario?.setImageURI(fileUri)
} else if (resultCode == ImagePicker.RESULT_ERROR){
Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_LONG).show()
}
else {
Toast.makeText(this, "Tarea se cancelo", Toast.LENGTH_LONG).show()
}
}
private fun selectImage() {
ImagePicker.with(this)
.crop()
.compress(1024)
.maxResultSize(1080,1080)
.createIntent { intent ->
startImageForResult.launch(intent)
}
}
private fun updateData() {
var nombre = editTextNombre?.text.toString()
var apellido = editTextApellido?.text.toString()
var telefono = editTextTelefono?.text.toString()
usuario?.nombre = nombre
usuario?.apellido = apellido
usuario?.telefono = telefono
if(imageFile != null) {
userProvider?.update(imageFile!!, usuario!!)?.enqueue(object : Callback<ResponseHttp> {
override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) {
Log.d(TAG, "RESPONSE: $response")
Log.d(TAG, "BODY: ${response.body()}")
Toast.makeText(this@ClientUpdateActivity, response.body()?.message, Toast.LENGTH_LONG).show()
if(response.body()?.isSucces == true){
saveUserInSession(response.body()?.data.toString())
}
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d(TAG, "Error: ${t.message}")
Toast.makeText(this@ClientUpdateActivity, "Error ${t.message}", Toast.LENGTH_LONG).show()
}
})
} else {
userProvider?.updateWhitoutImage(usuario!!)?.enqueue(object : Callback<ResponseHttp> {
override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp>) {
Log.d(TAG, "RESPONSE: $response")
Log.d(TAG, "BODY: ${response.body()}")
Toast.makeText(this@ClientUpdateActivity, response.body()?.message, Toast.LENGTH_LONG).show()
if(response.body()?.isSucces == true){
saveUserInSession(response.body()?.data.toString())
}
}
override fun onFailure(call: Call<ResponseHttp>, t: Throwable) {
Log.d(TAG, "Error: ${t.message}")
Toast.makeText(this@ClientUpdateActivity, "Error ${t.message}", Toast.LENGTH_LONG).show()
}
})
}
}
private fun saveUserInSession(data: String) {
val gson = Gson()
val user = gson.fromJson(data, Usuario::class.java)
sharedPref?.save("user", user)
}
} |
amount-counter/src/test/kotlin/com/example/TestDb.kt | 3018174946 | package com.example
import com.example.db.ProductsTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
fun getTestDb(): Database {
return Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
user = "test",
driver = "org.h2.Driver",
password = "test",
)
}
fun initTestDb(db: Database) {
transaction(db) {
SchemaUtils.create(ProductsTable)
ProductsTable.insert {
it[id] = 1L
it[uuid] = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4")
it[name] = "Diablo IV"
it[amount] = 10L
}
ProductsTable.insert {
it[id] = 2L
it[uuid] = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3")
it[name] = "Overwatch 2"
it[amount] = 1L
}
ProductsTable.insert {
it[id] = 3L
it[uuid] = UUID.fromString("d2c02017-61f7-4609-9fa0-da6887aff9c6")
it[name] = "Half-Life 3"
it[amount] = 10000L
}
ProductsTable.insert {
it[id] = 4L
it[uuid] = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc")
it[name] = "CyberPunk 2077"
it[amount] = 50L
}
ProductsTable.insert {
it[id] = 5L
it[uuid] = UUID.fromString("1603b0c2-952e-4400-89b4-49d2e3ee0e62")
it[name] = "God of War: Ragnarok"
it[amount] = 5L
}
}
}
|
amount-counter/src/test/kotlin/com/example/ApplicationTest.kt | 962364274 | package com.example
import com.example.plugins.configureMonitoring
import com.example.plugins.configureRouting
import com.example.plugins.configureSerialization
import com.example.plugins.configureSwagger
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.matchers.shouldBe
import io.ktor.client.HttpClient
import io.ktor.client.request.get
import io.ktor.http.HttpStatusCode.Companion.OK
import io.ktor.server.testing.ApplicationTestBuilder
import io.ktor.server.testing.testApplication
import org.junit.jupiter.api.Test
class ApplicationTest {
@Test
fun `app should be configured without any exceptions`() {
shouldNotThrowAny {
testApplication {
application {
val db = getTestDb()
configurePlugins()
configureRouting(db)
}
}
}
}
@Test
fun `monitoring request returns OK(200) response`() {
testApplication {
testHttpClient().get("/metrics-micrometer").status shouldBe OK
}
}
@Test
fun `swagger request returns OK(200) response`() {
testApplication {
testHttpClient().get("/docs/swagger").status shouldBe OK
}
}
private fun ApplicationTestBuilder.testHttpClient(): HttpClient {
environment {
module {
configureMonitoring()
configureSwagger()
configureSerialization()
}
}
return createClient {}
}
}
|
amount-counter/src/test/kotlin/com/example/routing/ProductRoutingTest.kt | 944924279 | package com.example.routing
import com.example.db.ProductsTable
import com.example.dto.IdsRequestDto
import com.example.getTestDb
import com.example.initTestDb
import com.example.plugins.configureSerialization
import com.example.service.PdfPrinterService
import com.example.service.ProductsService
import configureExceptionHandling
import io.kotest.assertions.assertSoftly
import io.kotest.matchers.shouldBe
import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.testing.ApplicationTestBuilder
import io.ktor.server.testing.testApplication
import io.mockk.every
import io.mockk.mockk
import kotlinx.serialization.json.Json
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Test
class ProductRoutingTest {
private val db = getTestDb().also { initTestDb(it) }
private val service = ProductsService(db)
@AfterAll
fun tearDown() {
transaction(db) {
SchemaUtils.drop(ProductsTable)
}
}
@Test
fun `get products endpoint should return correct JSON and status code OK(200)`() {
testApplication {
val expectedJson =
Json.parseToJsonElement(
"""
[
{
"id": "bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4",
"name": "Diablo IV",
"amount": 10
},
{
"id": "bf70093e-a4d4-461b-86ff-6515feee9bb3",
"name": "Overwatch 2",
"amount": 1
},
{
"id": "d2c02017-61f7-4609-9fa0-da6887aff9c6",
"name": "Half-Life 3",
"amount": 10000
},
{
"id": "a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc",
"name": "CyberPunk 2077",
"amount": 50
},
{
"id": "1603b0c2-952e-4400-89b4-49d2e3ee0e62",
"name": "God of War: Ragnarok",
"amount": 5
}
]
""",
)
assertSoftly(testHttpClient().get("/api/getProducts")) {
Json.parseToJsonElement(bodyAsText()) shouldBe expectedJson
status shouldBe HttpStatusCode.OK
}
}
}
@Test
fun `get summary endpoint should return status code OK(200)`() {
testApplication {
testHttpClient().post(
"/api/getSummary",
) {
setBody(
IdsRequestDto(
ids = listOf(
"bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4",
"bf70093e-a4d4-461b-86ff-6515feee9bb3",
"d2c02017-61f7-4609-9fa0-da6887aff9c6",
),
),
)
contentType(ContentType.Application.Json)
}.status shouldBe HttpStatusCode.OK
}
}
@Test
fun `get summary endpoint should return status code BadRequest(400) in case of not existed ids requested`() {
testApplication {
testHttpClient().post(
"/api/getSummary",
) {
setBody(
IdsRequestDto(
ids = listOf(
"bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4",
"bf70093e-a4d4-461b-86ff-6515feee9bb3",
"111111",
),
),
)
contentType(ContentType.Application.Json)
}.status shouldBe HttpStatusCode.BadRequest
}
}
@Test
fun `get summary endpoint should return status code BadRequest(400) in case ids not provided`() {
testApplication {
testHttpClient().post("/api/getSummary").status shouldBe HttpStatusCode.BadRequest
}
}
@Test
fun `get summary endpoint should return status code internal server error (500) in case ids not provided`() {
testApplication {
val pdfPrinterService = mockk<PdfPrinterService>().also {
every { it.printProductSummaryToByteArray(any()) } throws NumberFormatException()
}
testHttpClient(pdfPrinterService = pdfPrinterService).post(
"/api/getSummary",
) {
setBody(IdsRequestDto(listOf("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4")))
contentType(ContentType.Application.Json)
}.status shouldBe HttpStatusCode.InternalServerError
}
}
@Test
fun `get summary endpoint should return status code internal server error (500) in case of uncaught exception`() {
testApplication {
val productsService = mockk<ProductsService>().also {
every { it.getProductsSummary(any()) } throws NullPointerException()
}
testHttpClient(productsService = productsService).post(
"/api/getSummary",
) {
setBody(IdsRequestDto(listOf("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4")))
contentType(ContentType.Application.Json)
}.status shouldBe HttpStatusCode.InternalServerError
}
}
private fun ApplicationTestBuilder.testHttpClient(
productsService: ProductsService = service,
pdfPrinterService: PdfPrinterService = PdfPrinterService(),
): HttpClient {
environment {
module {
configureExceptionHandling()
configureSerialization()
configureProductRouting(productsService, pdfPrinterService)
}
}
return createClient {
install(ContentNegotiation) {
json()
}
}
}
}
|
amount-counter/src/test/kotlin/com/example/service/PdfPrinterServiceTest.kt | 1301350604 | package com.example.service
import com.example.model.ProductsSummary
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
class PdfPrinterServiceTest {
private val service = PdfPrinterService()
@Test
fun `pdf printer service print product summary should not throw any exceptions`() {
assertDoesNotThrow { service.printProductSummaryToByteArray(ProductsSummary(emptyList(), 10)) }
}
}
|
amount-counter/src/test/kotlin/com/example/service/ProductsServiceTest.kt | 3175392692 | package com.example.service
import com.example.db.ProductsTable
import com.example.exception.ItemsNotFoundException
import com.example.getTestDb
import com.example.initTestDb
import com.example.model.Product
import com.example.model.ProductsSummary
import io.kotest.matchers.shouldBe
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.util.UUID
class ProductsServiceTest {
private val db = getTestDb().also { initTestDb(it) }
private val service = ProductsService(db)
@AfterAll
fun tearDown() {
transaction(db) {
SchemaUtils.drop(ProductsTable)
}
}
@Test
fun `get product list fun returns correct list of values`() {
val expected =
listOf(
Product(
id = 1,
uuid = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"),
name = "Diablo IV",
amount = 10L,
),
Product(
id = 2,
uuid = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"),
name = "Overwatch 2",
amount = 1L,
),
Product(
id = 3,
uuid = UUID.fromString("d2c02017-61f7-4609-9fa0-da6887aff9c6"),
name = "Half-Life 3",
amount = 10000L,
),
Product(
id = 4,
uuid = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"),
name = "CyberPunk 2077",
amount = 50L,
),
Product(
id = 5,
uuid = UUID.fromString("1603b0c2-952e-4400-89b4-49d2e3ee0e62"),
name = "God of War: Ragnarok",
amount = 5L,
),
)
service.getAllProducts() shouldBe expected
}
@Test
fun `get products summary fun returns correct list of values`() {
val expected =
ProductsSummary(
products =
listOf(
Product(
id = 1,
uuid = UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"),
name = "Diablo IV",
amount = 10L,
),
Product(
id = 2,
uuid = UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"),
name = "Overwatch 2",
amount = 1L,
),
Product(
id = 4,
uuid = UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"),
name = "CyberPunk 2077",
amount = 50L,
),
),
total = 61L,
)
service.getProductsSummary(
listOf(
UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"),
UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"),
UUID.fromString("a4d5e97a-e2c6-46c6-aec0-ddc2a6ca5bfc"),
),
) shouldBe expected
}
@Test
fun `get products summary fun returns empty product summary in case of empty list as argument`() {
service.getProductsSummary(emptyList()) shouldBe
ProductsSummary(products = emptyList(), total = 0L)
.also { it.isEmpty() shouldBe true }
}
@Test
fun `get products summary fun throw exception in case of not exists values provided`() {
assertThrows<ItemsNotFoundException> {
service.getProductsSummary(
listOf(
UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e4"),
UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb3"),
UUID.fromString("bfcfaa0a-e878-48b5-85c8-a4f20e52b3e5"),
UUID.fromString("bf70093e-a4d4-461b-86ff-6515feee9bb6"),
),
)
}.apply {
message shouldBe "Requested ids [bfcfaa0a-e878-48b5-85c8-a4f20e52b3e5, " +
"bf70093e-a4d4-461b-86ff-6515feee9bb6] not found"
}
}
}
|
amount-counter/src/main/kotlin/com/example/dto/ProductDto.kt | 2761653889 | package com.example.dto
import com.example.model.Product
import kotlinx.serialization.Serializable
@Serializable
data class ProductDto(
val id: String,
val name: String,
val amount: Long,
)
fun Product.toProductDto(): ProductDto {
return ProductDto(
id = uuid.toString(),
name = name,
amount = amount,
)
}
|
amount-counter/src/main/kotlin/com/example/dto/IdsRequestDto.kt | 2255352371 | package com.example.dto
import kotlinx.serialization.Serializable
@Serializable
data class IdsRequestDto(
val ids: List<String>,
)
|
amount-counter/src/main/kotlin/com/example/Application.kt | 3325309733 | package com.example
import com.example.plugins.configureDatabases
import com.example.plugins.configureHTTP
import com.example.plugins.configureLogging
import com.example.plugins.configureMonitoring
import com.example.plugins.configureRouting
import com.example.plugins.configureSerialization
import com.example.plugins.configureSwagger
import configureExceptionHandling
import io.ktor.server.application.Application
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
}
fun Application.module() {
val db = configureDatabases()
configurePlugins()
configureRouting(db)
}
fun Application.configurePlugins() {
configureExceptionHandling()
configureLogging()
configureMonitoring()
configureSerialization()
configureHTTP()
configureSwagger()
}
|
amount-counter/src/main/kotlin/com/example/plugins/HTTP.kt | 1970826979 | package com.example.plugins
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.cors.routing.CORS
fun Application.configureHTTP() {
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Post)
allowMethod(HttpMethod.Get)
allowHeader(HttpHeaders.ContentType)
allowHeader(HttpHeaders.AccessControlExposeHeaders)
allowHeader(HttpHeaders.AccessControlRequestHeaders)
allowHeader(HttpHeaders.ContentDisposition)
anyHost()
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Routing.kt | 1002514084 | package com.example.plugins
import com.example.routing.configureProductRouting
import com.example.service.ProductsService
import io.ktor.server.application.Application
import org.jetbrains.exposed.sql.Database
fun Application.configureRouting(
db: Database,
) {
configureProductRouting(ProductsService(db))
}
|
amount-counter/src/main/kotlin/com/example/plugins/ExceptionHandling.kt | 1778430588 | import com.example.exception.BadRequestException
import com.example.exception.ItemsNotFoundException
import com.example.exception.PdfWriterException
import io.ktor.http.HttpStatusCode.Companion.BadRequest
import io.ktor.http.HttpStatusCode.Companion.InternalServerError
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.response.respond
import mu.KotlinLogging
val log = KotlinLogging.logger {}
fun Application.configureExceptionHandling() {
install(StatusPages) {
exception<Throwable> { call, e ->
when (e) {
is BadRequestException -> {
log.info(e) { "Bad request" }
call.respond(BadRequest, e.message)
}
is ItemsNotFoundException -> {
log.info(e) { "Items not found" }
call.respond(BadRequest, "One or more requested elements are not found")
}
is PdfWriterException -> {
log.info(e) { "Pdf writer error" }
call.respond(InternalServerError)
}
else -> {
log.error(e) { "Uncaught exception was thrown by service" }
call.respond(InternalServerError)
}
}
}
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Serialization.kt | 671225728 | package com.example.plugins
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Swagger.kt | 3240219953 | package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.plugins.swagger.swaggerUI
import io.ktor.server.routing.routing
fun Application.configureSwagger() {
routing {
swaggerUI(path = "/docs/swagger", swaggerFile = "openapi/documentation.yaml")
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Logging.kt | 3207583169 | package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.callloging.CallLogging
import io.ktor.server.request.path
import org.slf4j.event.Level
fun Application.configureLogging() {
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Databases.kt | 105411478 | package com.example.plugins
import com.example.db.ProductsTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
fun configureDatabases(): Database {
return Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
user = "root",
driver = "org.h2.Driver",
password = "",
).also { initDb(it) }
}
@Suppress("MagicNumber")
fun initDb(db: Database) {
transaction(db) {
SchemaUtils.create(ProductsTable)
ProductsTable.insert {
it[uuid] = UUID.fromString("5d6aa284-0f05-49f5-b563-f83c3d2ffd90")
it[name] = "Diablo IV"
it[amount] = 10L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("77ac3a82-6a9c-427e-b281-a0a73b8a5847")
it[name] = "Overwatch 2"
it[amount] = 1L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("1e0b7134-cfd1-4a0b-89b2-9c2616478f36")
it[name] = "Half-Life 3"
it[amount] = 10000L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("d8806e47-5aa1-4dc1-8aba-f0c98d063422")
it[name] = "CyberPunk 2077"
it[amount] = 50L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("56795b27-73e5-4d59-b579-15bf14452302")
it[name] = "God of War: Ragnarok"
it[amount] = 5L
}
}
}
|
amount-counter/src/main/kotlin/com/example/plugins/Monitoring.kt | 3789788478 | package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.application.install
import io.ktor.server.metrics.micrometer.MicrometerMetrics
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Application.configureMonitoring() {
val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
install(MicrometerMetrics) {
registry = appMicrometerRegistry
}
routing {
get("/metrics-micrometer") {
call.respond(appMicrometerRegistry.scrape())
}
}
}
|
amount-counter/src/main/kotlin/com/example/model/Product.kt | 2580211215 | package com.example.model
import com.example.db.ProductsTable
import org.jetbrains.exposed.sql.ResultRow
import java.util.UUID
data class Product(
val id: Long,
val uuid: UUID,
val name: String,
val amount: Long,
)
fun ResultRow.toProduct(): Product {
return Product(
id = get(ProductsTable.id),
uuid = get(ProductsTable.uuid),
name = get(ProductsTable.name),
amount = get(ProductsTable.amount),
)
}
|
amount-counter/src/main/kotlin/com/example/model/ProductsSummary.kt | 101826230 | package com.example.model
data class ProductsSummary(val products: List<Product>, val total: Long) {
fun isEmpty(): Boolean {
return products.isEmpty()
}
}
|
amount-counter/src/main/kotlin/com/example/db/ProductsTable.kt | 1466681104 | package com.example.db
import org.jetbrains.exposed.sql.Table
private const val VARCHAR_LENGTH = 256
object ProductsTable : Table("Products") {
val id = long("id").uniqueIndex().autoIncrement()
val uuid = uuid("uuid").uniqueIndex().autoGenerate().index()
val name = varchar("name", VARCHAR_LENGTH)
val amount = long("amount")
override val primaryKey = PrimaryKey(id, name = "PK_Products_Id")
}
|
amount-counter/src/main/kotlin/com/example/routing/ProductRouting.kt | 2605297699 | package com.example.routing
import com.example.dto.toProductDto
import com.example.exception.PdfWriterException
import com.example.service.PdfPrinterService
import com.example.service.ProductsService
import com.example.validation.ProductRequestValidator
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.response.header
import io.ktor.server.response.respond
import io.ktor.server.response.respondOutputStream
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
fun Application.configureProductRouting(
productsService: ProductsService,
pdfPrinterService: PdfPrinterService = PdfPrinterService(),
validator: ProductRequestValidator = ProductRequestValidator(),
) {
routing {
route("/api") {
get("/getProducts") {
call.respond(productsService.getAllProducts().map { it.toProductDto() })
}
post("/getSummary") {
val uuids = validator.validateRequestBodyAndReturnUuids(call)
val productsSummary = productsService.getProductsSummary(uuids)
runCatching {
val outputStream = pdfPrinterService.printProductSummaryToByteArray(productsSummary)
call.response.header(HttpHeaders.ContentDisposition, "attachment; filename=SummaryTable.pdf")
call.respondOutputStream(ContentType.Application.OctetStream) {
outputStream.use { it.writeTo(this) }
}
}
.onFailure { ex -> throw PdfWriterException(ex) }
.getOrThrow()
}
}
}
}
|
amount-counter/src/main/kotlin/com/example/service/PdfPrinterService.kt | 4241799027 | package com.example.service
import com.example.model.ProductsSummary
import com.lowagie.text.Document
import com.lowagie.text.FontFactory
import com.lowagie.text.PageSize
import com.lowagie.text.Phrase
import com.lowagie.text.Rectangle
import com.lowagie.text.pdf.PdfPCell
import com.lowagie.text.pdf.PdfPTable
import com.lowagie.text.pdf.PdfWriter
import java.io.ByteArrayOutputStream
private const val COLUMN_RATIO = 33.33f
private const val PAGE_INDENTATION = 72
private const val FONT_SIZE = 8f
class PdfPrinterService {
fun printProductSummaryToByteArray(productsSummary: ProductsSummary): ByteArrayOutputStream {
val document = Document(PageSize.A4)
val outputStream = ByteArrayOutputStream()
PdfWriter.getInstance(document, outputStream)
document.open()
document.add(createPdfTable(document.pageSize.width, productsSummary))
document.close()
return outputStream
}
private fun createPdfTable(
pageWidth: Float,
productsSummary: ProductsSummary,
): PdfPTable {
val columnDefinitionSize = floatArrayOf(COLUMN_RATIO, COLUMN_RATIO, COLUMN_RATIO)
return PdfPTable(columnDefinitionSize).apply {
defaultCell.border = Rectangle.BOX
horizontalAlignment = 0
totalWidth = pageWidth - PAGE_INDENTATION
isLockedWidth = true
addCells(productsSummary, columnDefinitionSize.size)
}
}
private fun PdfPTable.addCells(
productsSummary: ProductsSummary,
size: Int,
) {
addCell(
PdfPCell(Phrase("Summary table")).apply {
colspan = size
},
)
productsSummary.products.map {
addTextCell(it.uuid)
addTextCell(it.name)
addTextCell(it.amount)
}
addTextCell("")
addTextCell("Total")
addTextCell(productsSummary.total)
}
private fun PdfPTable.addTextCell(value: Any) {
return addCell(Phrase(value.toString(), FontFactory.getFont(FontFactory.HELVETICA, FONT_SIZE)))
}
}
|
amount-counter/src/main/kotlin/com/example/service/ProductsService.kt | 930243108 | package com.example.service
import com.example.db.ProductsTable
import com.example.exception.ItemsNotFoundException
import com.example.model.Product
import com.example.model.ProductsSummary
import com.example.model.toProduct
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
class ProductsService(private val db: Database) {
fun getAllProducts(): List<Product> {
return transaction(db) { ProductsTable.selectAll().map { it.toProduct() }.sortedBy { it.id } }
}
fun getProductsSummary(uuids: List<UUID>): ProductsSummary {
val products =
transaction(db) {
ProductsTable.select { ProductsTable.uuid inList uuids }.map { it.toProduct() }.sortedBy { it.id }
}
if (products.size != uuids.size) {
throw ItemsNotFoundException(uuids.filter { it !in products.map { product -> product.uuid } })
}
return ProductsSummary(
products = products,
total = products.sumOf { it.amount },
)
}
}
|
amount-counter/src/main/kotlin/com/example/exception/BadRequestException.kt | 1590910692 | package com.example.exception
class BadRequestException(override val message: String, override val cause: Throwable? = null) :
RuntimeException(message, cause)
|
amount-counter/src/main/kotlin/com/example/exception/ItemsNotFoundException.kt | 518103969 | package com.example.exception
import java.util.UUID
class ItemsNotFoundException(uuids: List<UUID>) : RuntimeException("Requested ids $uuids not found")
|
amount-counter/src/main/kotlin/com/example/exception/PdfWriterException.kt | 3134096908 | package com.example.exception
class PdfWriterException(override val cause: Throwable? = null) :
RuntimeException("Pdf writer exception", cause)
|
amount-counter/src/main/kotlin/com/example/validation/ProductRequestValidator.kt | 1873223592 | package com.example.validation
import com.example.dto.IdsRequestDto
import com.example.exception.BadRequestException
import io.ktor.server.application.ApplicationCall
import io.ktor.server.request.receive
import java.util.UUID
class ProductRequestValidator {
suspend fun validateRequestBodyAndReturnUuids(call: ApplicationCall): List<UUID> {
return runCatching {
call.receive<IdsRequestDto>().ids.takeUnless { it.isEmpty() }?.map(UUID::fromString)
?: throw BadRequestException("'ids' list is empty")
}
.onFailure { ex ->
throw BadRequestException("Request body should contain ids list in form '{\"ids\":[\"id1\",\"id2\"]}'", ex)
}
.getOrThrow()
}
}
|
update-demo-app/app/src/androidTest/java/com/example/updatedemo/ExampleInstrumentedTest.kt | 3949068833 | package com.example.updatedemo
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.updatedemo", appContext.packageName)
}
} |
update-demo-app/app/src/test/java/com/example/updatedemo/ExampleUnitTest.kt | 146704787 | package com.example.updatedemo
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)
}
} |
update-demo-app/app/src/main/java/com/example/updatedemo/MainActivity.kt | 1039381883 | package com.example.updatedemo
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.updatedemo.util.featureDownload.AppUpgraderManager
import com.example.updatedemo.util.featureDownload.InstallPermissionChecker
class MainActivity : AppCompatActivity() {
companion object {
private const val APK_URL = "your apk url"
}
private lateinit var permissionChecker: InstallPermissionChecker
private lateinit var appUpgraderManager: AppUpgraderManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
permissionChecker = InstallPermissionChecker(this)
appUpgraderManager = AppUpgraderManager.getInstance(this)
findViewById<Button>(R.id.button).setOnClickListener {
checkAndStartDownloading()
}
}
private fun checkAndStartDownloading() {
permissionChecker.checkPermission(
onGranted = {
startDownloading()
showToast(getString(R.string.downloading))
},
onDenied = {
showToast(getString(R.string.permission_required_toast))
}
)
}
private fun startDownloading() {
appUpgraderManager.startApkUpgradingFlow(APK_URL)
}
private fun showToast(text: CharSequence) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
}
|
update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/AppUpgrader.kt | 2630204556 | package com.example.updatedemo.util.featureDownload
import android.content.Context
interface AppUpgrader {
fun startApkUpgradingFlow(url: String)
suspend fun downloadApk(url: String, context: Context)
fun installApk(context: Context, apkFilePath: String)
} |
update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/InstallPermissionChecker.kt | 3156682677 | package com.example.updatedemo.util.featureDownload
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
class InstallPermissionChecker(private val activity: AppCompatActivity) {
private var onPermissionGranted: (() -> Unit)? = null
private var onPermissionDenied: (() -> Unit)? = null
private val requestPermissionLauncher = activity.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (activity.packageManager.canRequestPackageInstalls()) {
onPermissionGranted?.invoke()
} else {
onPermissionDenied?.invoke()
}
}
}
fun checkPermission(onGranted: () -> Unit, onDenied: () -> Unit) {
this.onPermissionGranted = onGranted
this.onPermissionDenied = onDenied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!activity.packageManager.canRequestPackageInstalls()) {
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:${activity.packageName}")
}
requestPermissionLauncher.launch(intent)
} else {
onPermissionGranted?.invoke()
}
} else {
onPermissionGranted?.invoke()
}
}
}
|
update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/AppUpgraderManager.kt | 137487769 | package com.example.updatedemo.util.featureDownload
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class AppUpgraderManager private constructor(context: Context) : AppUpgrader {
private val appContext = context.applicationContext
private val upgradingFlowScope = CoroutineScope(Job() + Dispatchers.IO)
private var currentDownloadCall: Call? = null
companion object {
@Volatile private var AppUpgraderManagerInstance: AppUpgraderManager? = null
private const val CHILD_NAME = "downloaded_apk.apk"
private const val TYPE = "application/vnd.android.package-archive"
private const val PROVIDER_PATH = ".provider"
fun getInstance(context: Context): AppUpgraderManager =
AppUpgraderManagerInstance ?: synchronized(this) {
AppUpgraderManagerInstance ?: AppUpgraderManager(context).also { AppUpgraderManagerInstance = it }
}
}
override fun startApkUpgradingFlow(url: String) {
upgradingFlowScope.launch {
downloadApk(url, appContext)
}
}
override suspend fun downloadApk(url: String, context: Context) {
withContext(Dispatchers.IO) {
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val inputStream = response.body?.byteStream()
val apkFile = File(context.getExternalFilesDir(null), CHILD_NAME)
val outputStream = FileOutputStream(apkFile)
inputStream.use { input ->
outputStream.use { output ->
input?.copyTo(output)
}
}
installApk(context, apkFile.absolutePath)
}
})
if (!isActive) cancelUpgradingTasks()
}
}
override fun installApk(context: Context, apkFilePath: String) {
val apkUri: Uri =
FileProvider.getUriForFile(context, context.applicationContext.packageName + PROVIDER_PATH, File(apkFilePath))
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(apkUri, TYPE)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(intent)
}
private fun cancelUpgradingTasks() {
upgradingFlowScope.coroutineContext.cancelChildren()
currentDownloadCall?.cancel()
}
} |
dont-get-hangry/app/src/androidTest/java/com/hancock/dontgethangry/ExampleInstrumentedTest.kt | 22375681 | package com.hancock.dontgethangry
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.hancock.dontgethangry", appContext.packageName)
}
} |
dont-get-hangry/app/src/test/java/com/hancock/dontgethangry/ExampleUnitTest.kt | 744791336 | package com.hancock.dontgethangry
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)
}
} |
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Color.kt | 3721273759 | package com.hancock.dontgethangry.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) |
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Theme.kt | 3093119205 | package com.hancock.dontgethangry.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 DontGetHangryTheme(
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
)
} |
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Type.kt | 1478003041 | package com.hancock.dontgethangry.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
)
*/
) |
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/MainActivity.kt | 3835128139 | package com.hancock.dontgethangry
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.hancock.dontgethangry.composables.DGHTextField
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DontGetHangryTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DGHTextField(
hint = "Android",
validChecker = {s -> s.length > 2},
onValidChanged = {isValid -> println("JEH onValidChanged: $isValid")}
)
}
}
}
}
}
|
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/composables/DGHTextFields.kt | 238067073 | package com.hancock.dontgethangry.composables
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
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.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
@Composable
fun DGHTextField(
hint: String,
validChecker: ((String) -> Boolean)?,// = null,
onValidChanged: ((Boolean) -> Unit)?,// = null
) {
var textInput by remember { mutableStateOf(TextFieldValue()) }
fun checkValid(): Boolean {
val x = validChecker?.invoke(textInput.text) ?: true
println("JEH checkValid - $x ")
return x
}
var isValid by remember { mutableStateOf(false)}
OutlinedTextField(
value = textInput,
onValueChange = {
textInput = it
isValid = checkValid()
},
label = { Text(hint) },
modifier = Modifier
.padding(all = 16.dp)
.wrapContentHeight()
.fillMaxWidth(),
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None,
autoCorrect = false,
keyboardType = KeyboardType.Text
),
textStyle = TextStyle(
color = MaterialTheme.colorScheme.secondary,
fontSize = 16.sp,
fontFamily = FontFamily.SansSerif
),
singleLine = true,
trailingIcon = { DGHIcon(
icon = Icons.Filled.Clear,
modifier = Modifier.clickable {
textInput = TextFieldValue()
isValid = checkValid()
},
)}
)
}
@Preview(name = "Light Mode")
@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewEmptyTextField() {
DontGetHangryTheme {
Surface(color = MaterialTheme.colorScheme.background) {
DGHTextField(
hint = "hint",
validChecker = {s -> s.length > 2},
onValidChanged = {isValid -> println("JEH onValidChanged: $isValid")}
)
}
}
} |
dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/composables/DGHIcons.kt | 1099802409 | package com.hancock.dontgethangry.composables
import android.content.res.Configuration
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
@Composable
fun DGHIcon(
icon: ImageVector,
modifier: Modifier = Modifier,
contentDescription: String = "",
tint: Color = Color.Black,
) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
tint = tint,
modifier = modifier
)
}
@Preview(name = "Light Mode")
@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewDGHIcon() {
DontGetHangryTheme {
Surface(color = MaterialTheme.colorScheme.background) {
DGHIcon(icon = Icons.Filled.Clear, tint = Color.Magenta)
}
}
} |
DynamicRadioButton/android/app/src/main/java/com/dynamicradiobutton/MainActivity.kt | 2071254757 | package com.dynamicradiobutton
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "DynamicRadioButton"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
|
DynamicRadioButton/android/app/src/main/java/com/dynamicradiobutton/MainApplication.kt | 2899774710 | package com.dynamicradiobutton
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
|
lab10/app/src/androidTest/java/com/topic3/android/reddit/ExampleInstrumentedTest.kt | 2749661737 | package com.topic3.android.reddit
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.raywenderlich.android.jetreddit", appContext.packageName)
}
} |
lab10/app/src/test/java/com/topic3/android/reddit/ExampleUnitTest.kt | 305007576 | package com.topic3.android.reddit
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)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/viewmodel/MainViewModel.kt | 2019844107 | package com.topic3.android.reddit.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.topic3.android.reddit.data.repository.Repository
import com.topic3.android.reddit.domain.model.PostModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel(private val repository: Repository) : ViewModel() {
val allPosts by lazy { repository.getAllPosts() }
val myPosts by lazy { repository.getAllOwnedPosts() }
val subreddits by lazy { MutableLiveData<List<String>>() }
val selectedCommunity: MutableLiveData<String> by lazy { MutableLiveData<String>() }
fun searchCommunities(searchedText: String) {
viewModelScope.launch(Dispatchers.Default) {
subreddits.postValue(repository.getAllSubreddits(searchedText))
}
}
fun savePost(post: PostModel) {
viewModelScope.launch(Dispatchers.Default) {
repository.insert(post.copy(subreddit = selectedCommunity.value ?: ""))
}
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/viewmodel/MainViewModelFactory.kt | 3748045815 | package com.topic3.android.reddit.viewmodel
import android.os.Bundle
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.savedstate.SavedStateRegistryOwner
import com.topic3.android.reddit.data.repository.Repository
class MainViewModelFactory(
owner: SavedStateRegistryOwner,
private val repository: Repository,
private val defaultArgs: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T & Any {
return (MainViewModel(repository) as T)!!
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/RedditApplication.kt | 3970999801 | package com.topic3.android.reddit
import android.app.Application
import com.topic3.android.reddit.dependencyinjection.DependencyInjector
class RedditApplication : Application() {
lateinit var dependencyInjector: DependencyInjector
override fun onCreate() {
super.onCreate()
initDependencyInjector()
}
private fun initDependencyInjector() {
dependencyInjector = DependencyInjector(this)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/MainActivity.kt | 2186626954 | package com.topic3.android.reddit
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.topic3.android.reddit.viewmodel.MainViewModel
import com.topic3.android.reddit.viewmodel.MainViewModelFactory
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels(factoryProducer = {
MainViewModelFactory(
this,
(application as RedditApplication).dependencyInjector.repository
)
})
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RedditApp(viewModel)
}
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/models/SubredditModel.kt | 2310480849 | package com.topic3.android.reddit.models
import androidx.annotation.StringRes
import com.topic3.android.reddit.R
data class SubredditModel(
@StringRes val nameStringRes: Int,
@StringRes val membersStringRes: Int,
@StringRes val descriptionStringRes: Int
) {
companion object {
val DEFAULT_SUBREDDIT =
SubredditModel(
R.string.android,
R.string.members_400k,
R.string.welcome_to_android
)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/screens/ChooseCommunityScreen.kt | 1260531621 | package com.topic3.android.reddit.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.routing.BackButtonAction
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
private const val SEARCH_DELAY_MILLIS = 300L
private val defaultCommunities = listOf("raywenderlich", "androiddev", "puppies")
@Composable
fun ChooseCommunityScreen(viewModel: MainViewModel, modifier: Modifier = Modifier) {
//TODO Add your code here
val scope = rememberCoroutineScope()
val communities: List<String> by viewModel.subreddits.observeAsState(emptyList())
var searchedText by remember { mutableStateOf("") }
var currentJob by remember { mutableStateOf<Job?>(null) }
val activeColor = MaterialTheme.colors.onSurface
LaunchedEffect(Unit) {
viewModel.searchCommunities(searchedText)
}
Column {
ChooseCommunityTopBar()
TextField(
value = searchedText,
onValueChange = {
searchedText = it
currentJob?.cancel()
currentJob = scope.async {
delay(SEARCH_DELAY_MILLIS)
viewModel.searchCommunities(searchedText)
}
},
leadingIcon = {
Icon(Icons.Default.Search, contentDescription = stringResource(id = R.string.search))
},
label = { Text(stringResource(R.string.search)) },
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
SearchedCommunities(communities, viewModel, modifier)
}
BackButtonAction {
RedditRouter.goBack()
}
}
@Composable
fun SearchedCommunities(
communities: List<String>,
viewModel: MainViewModel?,
modifier: Modifier = Modifier
) {
//TODO Add your code here
communities.forEach { Community(
text = it,
modifier = modifier,
onCommunityClicked = {
viewModel?.selectedCommunity?.postValue(it)
RedditRouter.goBack()
}
)
}
}
@Composable
fun ChooseCommunityTopBar(modifier: Modifier = Modifier) {
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
fontSize = 16.sp,
text = stringResource(R.string.choose_community),
color = colors.primaryVariant
)
},
navigationIcon = {
IconButton(
onClick = { RedditRouter.goBack() }
) {
Icon(
imageVector = Icons.Default.Close,
tint = colors.primaryVariant,
contentDescription = stringResource(id = R.string.close)
)
}
},
backgroundColor = colors.primary,
elevation = 0.dp,
modifier = modifier
.height(48.dp)
.background(Color.Blue)
)
}
@Preview
@Composable
fun SearchedCommunitiesPreview(){
Column {
SearchedCommunities(
defaultCommunities,
null,
Modifier)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/screens/MyProfileScreen.kt | 164994388 | package com.topic3.android.reddit.screens
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Star
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.topic3.android.reddit.R
import com.topic3.android.reddit.appdrawer.ProfileInfo
import com.topic3.android.reddit.components.PostAction
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.routing.MyProfileRouter
import com.topic3.android.reddit.routing.MyProfileScreenType
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.NonDisposableHandle.parent
private val tabNames = listOf(R.string.posts, R.string.about)
@Composable
fun MyProfileScreen(viewModel: MainViewModel, modifier: Modifier = Modifier) {
ConstraintLayout(modifier = modifier.fillMaxSize()) {
val (topAppBar, tabs, bodyContent) = createRefs()
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
fontSize = 12.sp,
text = stringResource(R.string.default_username),
color = colors.primaryVariant
)
},
navigationIcon = {
IconButton(
onClick = { RedditRouter.goBack() }
) {
Icon(
imageVector = Icons.Default.ArrowBack,
tint = colors.primaryVariant,
contentDescription = stringResource(id = R.string.back)
)
}
},
backgroundColor = colors.primary,
elevation = 0.dp,
modifier = modifier
.constrainAs(topAppBar) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.height(48.dp)
.background(Color.Blue)
)
MyProfileTabs(
modifier = modifier.constrainAs(tabs) {
top.linkTo(topAppBar.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
)
Surface(
modifier = modifier
.constrainAs(bodyContent) {
top.linkTo(tabs.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.padding(bottom = 68.dp)
) {
Crossfade(targetState = MyProfileRouter.currentScreen) { screen ->
when (screen.value) {
MyProfileScreenType.Posts -> MyProfilePosts(modifier, viewModel)
MyProfileScreenType.About -> MyProfileAbout()
}
}
}
}
}
@Composable
fun MyProfileTabs(modifier: Modifier = Modifier) {
var selectedIndex by remember { mutableStateOf(0) }
TabRow(
selectedTabIndex = selectedIndex,
backgroundColor = MaterialTheme.colors.primary,
modifier = modifier
) {
tabNames.forEachIndexed { index, nameResource ->
Tab(
selected = index == selectedIndex,
onClick = {
selectedIndex = index
changeScreen(index)
}
) {
Text(
color = MaterialTheme.colors.primaryVariant,
fontSize = 12.sp,
text = stringResource(nameResource),
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
)
}
}
}
}
private fun changeScreen(index: Int) {
return when (index) {
0 -> MyProfileRouter.navigateTo(MyProfileScreenType.Posts)
else -> MyProfileRouter.navigateTo(MyProfileScreenType.About)
}
}
@Composable
fun MyProfilePosts(modifier: Modifier, viewModel: MainViewModel) {
val posts: List<PostModel> by viewModel.myPosts.observeAsState(listOf())
LazyColumn(
modifier = modifier.background(color = MaterialTheme.colors.secondary)
) {
items(posts) { MyProfilePost(modifier, it) }
}
}
@Composable
fun MyProfilePost(modifier: Modifier, post: PostModel) {
Card(shape = MaterialTheme.shapes.large) {
ConstraintLayout(
modifier = modifier.fillMaxSize()
) {
val (redditIcon, subredditName, actionsBar, title, description, settingIcon) = createRefs()
val postModifier = Modifier
val colors = MaterialTheme.colors
Image(
imageVector = Icons.Default.Star,
contentDescription = stringResource(id = R.string.my_profile),
modifier = postModifier
.size(20.dp)
.constrainAs(redditIcon) {
top.linkTo(parent.top)
start.linkTo(parent.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Image(
imageVector = ImageVector.vectorResource(id = R.drawable.ic_baseline_more_vert_24),
contentDescription = stringResource(id = R.string.more_actions),
modifier = postModifier
.size(20.dp)
.constrainAs(settingIcon) {
top.linkTo(parent.top)
end.linkTo(parent.end)
}
.padding(end = 8.dp, top = 8.dp)
)
Text(
text = "${post.username} • ${post.postedTime}",
fontSize = 8.sp,
modifier = postModifier
.constrainAs(subredditName) {
top.linkTo(redditIcon.top)
bottom.linkTo(redditIcon.bottom)
start.linkTo(redditIcon.end)
}
.padding(start = 2.dp, top = 8.dp)
)
Text(
text = post.title,
color = colors.primaryVariant,
fontSize = 12.sp,
modifier = postModifier
.constrainAs(title) {
top.linkTo(redditIcon.bottom)
start.linkTo(redditIcon.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Text(
text = post.text,
color = Color.DarkGray,
fontSize = 10.sp,
modifier = postModifier
.constrainAs(description) {
top.linkTo(title.bottom)
start.linkTo(redditIcon.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Row(
modifier = postModifier
.fillMaxWidth()
.constrainAs(actionsBar) {
top.linkTo(description.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.padding(
top = 8.dp,
bottom = 8.dp,
end = 16.dp,
start = 16.dp
),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
PostAction(
vectorResourceId = R.drawable.ic_baseline_arrow_upward_24,
text = post.likes,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_comment_24,
text = post.comments,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_share_24,
text = stringResource(R.string.share),
onClickAction = {}
)
}
}
}
Spacer(modifier = Modifier.height(6.dp))
}
@Composable
fun MyProfileAbout() {
Column {
ProfileInfo()
Spacer(modifier = Modifier.height(8.dp))
BackgroundText(stringResource(R.string.trophies))
val trophies = listOf(
R.string.verified_email,
R.string.gold_medal,
R.string.top_comment
)
LazyColumn {
items(trophies) { Trophy(text = stringResource(it)) }
}
}
}
@Composable
fun ColumnScope.BackgroundText(text: String) {
Text(
fontWeight = FontWeight.Medium,
text = text,
fontSize = 10.sp,
color = Color.DarkGray,
modifier = Modifier
.background(color = MaterialTheme.colors.secondary)
.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)
.fillMaxWidth()
.align(Alignment.Start)
)
}
@Composable
fun Trophy(text: String, modifier: Modifier = Modifier) {
Spacer(modifier = modifier.height(16.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Spacer(modifier = modifier.width(16.dp))
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.trophy),
contentDescription = stringResource(id = R.string.trophies),
contentScale = ContentScale.Crop,
modifier = modifier.size(24.dp)
)
Spacer(modifier = modifier.width(16.dp))
Text(
text = text, fontSize = 12.sp,
color = MaterialTheme.colors.primaryVariant,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium
)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/screens/AddScreen.kt | 3305704881 | package com.topic3.android.reddit.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.routing.Screen
import com.topic3.android.reddit.viewmodel.MainViewModel
@Composable
fun AddScreen(viewModel: MainViewModel) {
val selectedCommunity: String by viewModel.selectedCommunity.observeAsState("")
var post by remember { mutableStateOf(PostModel.EMPTY) }
Column(modifier = Modifier.fillMaxSize()) {
CommunityPicker(selectedCommunity)
TitleTextField(post.title) { newTitle -> post = post.copy(title = newTitle) }
BodyTextField(post.text) { newContent -> post = post.copy(text = newContent) }
AddPostButton(selectedCommunity.isNotEmpty() && post.title.isNotEmpty()) {
viewModel.savePost(post)
RedditRouter.navigateTo(com.topic3.android.reddit.routing.Screen.Home)
}
}
}
/**
* Input view for the post title
*/
@Composable
private fun TitleTextField(text: String, onTextChange: (String) -> Unit) {
val activeColor = MaterialTheme.colors.onSurface
TextField(
value = text,
onValueChange = onTextChange,
label = { Text(stringResource(R.string.title)) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
}
/**
* Input view for the post body
*/
@Composable
private fun BodyTextField(text: String, onTextChange: (String) -> Unit) {
val activeColor = MaterialTheme.colors.onSurface
TextField(
value = text,
onValueChange = onTextChange,
label = { Text(stringResource(R.string.body_text)) },
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
}
/**
* Input view for the post body
*/
@Composable
private fun AddPostButton(isEnabled: Boolean, onSaveClicked: () -> Unit) {
Button(
onClick = onSaveClicked,
enabled = isEnabled,
content = {
Text(
text = stringResource(R.string.save_post),
color = MaterialTheme.colors.onSurface
)
},
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp),
)
}
@Composable
private fun CommunityPicker(selectedCommunity: String) {
val selectedText =
if (selectedCommunity.isEmpty()) stringResource(R.string.choose_community) else selectedCommunity
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp)
.clickable {
RedditRouter.navigateTo(Screen.ChooseCommunity)
},
) {
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.subreddit_placeholder),
contentDescription = stringResource(id = R.string.subreddits),
modifier = Modifier
.size(24.dp)
.clip(CircleShape)
)
Text(
text = selectedText,
modifier = Modifier.padding(start = 8.dp)
)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/components/BackgroundText.kt | 4268857193 | package com.topic3.android.reddit.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun BackgroundText(text: String) {
Text(
fontWeight = FontWeight.Medium,
text = text,
fontSize = 10.sp,
color = Color.DarkGray,
modifier = Modifier
.background(color = MaterialTheme.colors.secondary)
.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)
.fillMaxWidth()
)
} |
lab10/app/src/main/java/com/topic3/android/reddit/components/Post.kt | 885420117 | package com.topic3.android.reddit.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.*
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.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.domain.model.PostModel.Companion.DEFAULT_POST
@Composable
fun TextPost(post: PostModel) {
Post(post) {
TextContent(post.text)
}
}
@Composable
fun ImagePost(post: PostModel) {
Post(post) {
ImageContent(post.image ?: R.drawable.compose_course)
}
}
@Composable
fun Post(post: PostModel, content: @Composable () -> Unit = {}) {
Card(shape = MaterialTheme.shapes.large) {
Column(
modifier = Modifier.padding(
top = 8.dp, bottom = 8.dp
)
) {
Header(post)
Spacer(modifier = Modifier.height(4.dp))
content.invoke()
Spacer(modifier = Modifier.height(8.dp))
PostActions(post)
}
}
}
@Composable
fun Header(post: PostModel) {
Row(modifier = Modifier.padding(start = 16.dp)) {
Image(
ImageBitmap.imageResource(id = R.drawable.subreddit_placeholder),
contentDescription = stringResource(id = R.string.subreddits),
Modifier
.size(40.dp)
.clip(CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.subreddit_header, post.subreddit),
fontWeight = FontWeight.Medium,
color = MaterialTheme.colors.primaryVariant
)
Text(
text = stringResource(R.string.post_header, post.username, post.postedTime),
color = Color.Gray
)
}
MoreActionsMenu()
}
Title(text = post.title)
}
@Composable
fun MoreActionsMenu() {
var expanded by remember { mutableStateOf(false) }
Box(modifier = Modifier.wrapContentSize(Alignment.TopStart)) {
IconButton(onClick = { expanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
tint = Color.DarkGray,
contentDescription = stringResource(id = R.string.more_actions)
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
CustomDropdownMenuItem(
vectorResourceId = R.drawable.ic_baseline_bookmark_24,
text = stringResource(id = R.string.save)
)
}
}
}
@Composable
fun CustomDropdownMenuItem(
@DrawableRes vectorResourceId: Int,
color: Color = Color.Black,
text: String,
onClickAction: () -> Unit = {}
) {
DropdownMenuItem(onClick = onClickAction) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = ImageVector.vectorResource(id = vectorResourceId),
tint = color,
contentDescription = stringResource(id = R.string.save)
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = text, fontWeight = FontWeight.Medium, color = color)
}
}
}
@Composable
fun Title(text: String) {
Text(
text = text,
maxLines = 3,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
color = MaterialTheme.colors.primaryVariant,
modifier = Modifier.padding(start = 16.dp, end = 16.dp)
)
}
@Composable
fun TextContent(text: String) {
Text(
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp
),
text = text,
color = Color.Gray,
fontSize = 12.sp,
maxLines = 3
)
}
@Composable
fun ImageContent(image: Int) {
val imageAsset = ImageBitmap.imageResource(id = image)
Image(
bitmap = imageAsset,
contentDescription = stringResource(id = R.string.post_header_description),
modifier = Modifier
.fillMaxWidth()
.aspectRatio(imageAsset.width.toFloat() / imageAsset.height),
contentScale = ContentScale.Crop
)
}
@Composable
fun PostActions(post: PostModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
VotingAction(text = post.likes, onUpVoteAction = {}, onDownVoteAction = {})
PostAction(
vectorResourceId = R.drawable.ic_baseline_comment_24,
text = post.comments,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_share_24,
text = stringResource(R.string.share),
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_emoji_events_24,
text = stringResource(R.string.award),
onClickAction = {}
)
}
}
@Composable
fun VotingAction(
text: String,
onUpVoteAction: () -> Unit,
onDownVoteAction: () -> Unit
) {
Row(verticalAlignment = Alignment.CenterVertically) {
ArrowButton(
onUpVoteAction,
R.drawable.ic_baseline_arrow_upward_24
)
Text(
text = text,
color = Color.Gray,
fontWeight = FontWeight.Medium, fontSize = 12.sp
)
ArrowButton(onDownVoteAction, R.drawable.ic_baseline_arrow_downward_24)
}
}
@Composable
fun ArrowButton(onClickAction: () -> Unit, arrowResourceId: Int) {
IconButton(onClick = onClickAction, modifier = Modifier.size(30.dp)) {
Icon(
imageVector = ImageVector.vectorResource(arrowResourceId),
contentDescription = stringResource(id = R.string.upvote),
modifier = Modifier.size(20.dp),
tint = Color.Gray
)
}
}
@Composable
fun PostAction(
@DrawableRes vectorResourceId: Int,
text: String,
onClickAction: () -> Unit
) {
Box(modifier = Modifier.clickable(onClick = onClickAction)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
ImageVector.vectorResource(id = vectorResourceId),
contentDescription = stringResource(id = R.string.post_action),
tint = Color.Gray,
modifier = Modifier.size(20.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = text, fontWeight = FontWeight.Medium, color = Color.Gray, fontSize = 12.sp)
}
}
}
@Preview(showBackground = true)
@Composable
fun ArrowButtonPreview() {
ArrowButton({}, R.drawable.ic_baseline_arrow_upward_24)
}
@Preview(showBackground = true)
@Composable
fun HeaderPreview() {
Column {
Header(DEFAULT_POST)
}
}
@Preview
@Composable
fun VotingActionPreview() {
VotingAction("555", {}, {})
}
@Preview
@Composable
fun PostPreview() {
Post(DEFAULT_POST)
}
@Preview
@Composable
fun TextPostPreview() {
Post(DEFAULT_POST) {
TextContent(DEFAULT_POST.text)
}
}
@Preview
@Composable
fun ImagePostPreview() {
Post(DEFAULT_POST) {
ImageContent(DEFAULT_POST.image ?: R.drawable.compose_course)
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/RedditApp.kt | 1611890679 | package com.topic3.android.reddit
import android.annotation.SuppressLint
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import com.topic3.android.reddit.appdrawer.AppDrawer
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.routing.Screen
import com.topic3.android.reddit.screens.*
import com.topic3.android.reddit.theme.RedditTheme
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Composable
fun RedditApp(viewModel: MainViewModel) {
RedditTheme {
AppContent(viewModel)
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
private fun AppContent(viewModel: MainViewModel) {
val scaffoldState: ScaffoldState = rememberScaffoldState()
val coroutineScope: CoroutineScope = rememberCoroutineScope()
Crossfade(targetState = RedditRouter.currentScreen) { screenState: MutableState<Screen> ->
Scaffold(
topBar = getTopBar(screenState.value, scaffoldState, coroutineScope),
drawerContent = {
AppDrawer(
closeDrawerAction = { coroutineScope.launch { scaffoldState.drawerState.close() } }
)
},
scaffoldState = scaffoldState,
bottomBar = {
BottomNavigationComponent(screenState = screenState)
},
content = {
MainScreenContainer(
modifier = Modifier.padding(bottom = 56.dp),
screenState = screenState,
viewModel = viewModel
)
}
)
}
}
fun getTopBar(
screenState: Screen,
scaffoldState: ScaffoldState,
coroutineScope: CoroutineScope
): @Composable (() -> Unit) {
if (screenState == Screen.MyProfile) {
return {}
} else {
return { TopAppBar(scaffoldState = scaffoldState, coroutineScope = coroutineScope) }
}
}
/**
* Представляет верхнюю панель приложений на экране
*/
@Composable
fun TopAppBar(scaffoldState: ScaffoldState, coroutineScope: CoroutineScope) {
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
text = stringResource(RedditRouter.currentScreen.value.titleResId),
color = colors.primaryVariant
)
},
backgroundColor = colors.surface,
navigationIcon = {
IconButton(onClick = {
coroutineScope.launch { scaffoldState.drawerState.open() }
}) {
Icon(
Icons.Filled.AccountCircle,
tint = Color.LightGray,
contentDescription = stringResource(id = R.string.account)
)
}
}
)
}
@Composable
private fun MainScreenContainer(
modifier: Modifier = Modifier,
screenState: MutableState<Screen>,
viewModel: MainViewModel
) {
Surface(
modifier = modifier,
color = MaterialTheme.colors.background
) {
when (screenState.value) {
Screen.Home -> HomeScreen(viewModel)
Screen.Subscriptions -> SubredditsScreen()
Screen.NewPost -> AddScreen(viewModel)
Screen.MyProfile -> MyProfileScreen(viewModel)
Screen.ChooseCommunity -> ChooseCommunityScreen(viewModel)
}
}
}
@Composable
private fun BottomNavigationComponent(
modifier: Modifier = Modifier,
screenState: MutableState<Screen>
) {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf(
NavigationItem(0, R.drawable.ic_baseline_home_24, R.string.home_icon, Screen.Home),
NavigationItem(
1,
R.drawable.ic_baseline_format_list_bulleted_24,
R.string.subscriptions_icon,
Screen.Subscriptions
),
NavigationItem(2, R.drawable.ic_baseline_add_24, R.string.post_icon, Screen.NewPost),
)
BottomNavigation(modifier = modifier) {
items.forEach {
BottomNavigationItem(
icon = {
Icon(
imageVector = ImageVector.vectorResource(id = it.vectorResourceId),
contentDescription = stringResource(id = it.contentDescriptionResourceId)
)
},
selected = selectedItem == it.index,
onClick = {
selectedItem = it.index
screenState.value = it.screen
}
)
}
}
}
private data class NavigationItem(
val index: Int,
val vectorResourceId: Int,
val contentDescriptionResourceId: Int,
val screen: Screen
) |
lab10/app/src/main/java/com/topic3/android/reddit/theme/Color.kt | 2345760543 | package com.topic3.android.reddit.theme
import androidx.compose.ui.graphics.Color
val RwPrimary = Color.White
val RwPrimaryDark = Color.Black
val RwAccent = Color(0xFF3F51B5)
val LightBlue = Color(0xFF2196F3)
val Red800 = Color(0xffd00036) |
lab10/app/src/main/java/com/topic3/android/reddit/theme/Theme.kt | 2416053452 | package com.topic3.android.reddit.theme
import android.annotation.SuppressLint
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.graphics.Color
@SuppressLint("ConflictingOnColor")
private val LightThemeColors = lightColors(
primary = RwPrimary,
primaryVariant = RwPrimaryDark,
onPrimary = Color.Gray,
secondary = Color.LightGray,
secondaryVariant = RwPrimaryDark,
onSecondary = Color.Black,
error = Red800
)
@SuppressLint("ConflictingOnColor")
private val DarkThemeColors = darkColors(
primary = RwPrimaryDark,
primaryVariant = RwPrimary,
onPrimary = Color.Gray,
secondary = Color.Black,
onSecondary = Color.White,
error = Red800
)
@Composable
fun RedditTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colors = if (RedditThemeSettings.isInDarkTheme.value) DarkThemeColors else LightThemeColors,
content = content
)
}
object RedditThemeSettings {
var isInDarkTheme: MutableState<Boolean> = mutableStateOf(false)
} |
lab10/app/src/main/java/com/topic3/android/reddit/routing/BackButtonHandler.kt | 2751911153 | package com.topic3.android.reddit.routing
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalLifecycleOwner
private val localBackPressedDispatcher = staticCompositionLocalOf<OnBackPressedDispatcher?> { null }
@Composable
fun BackButtonHandler(
enabled: Boolean = true,
onBackPressed: () -> Unit
){
val dispatcher = localBackPressedDispatcher.current ?: return
val backCallback = remember {
object : OnBackPressedCallback(enabled){
override fun handleOnBackPressed(){
onBackPressed.invoke()
}
}
}
DisposableEffect(dispatcher) {
dispatcher.addCallback(backCallback)
onDispose {
backCallback.remove()
}
}
}
@Composable
fun BackButtonAction(onBackPressed: () -> Unit){
CompositionLocalProvider (
localBackPressedDispatcher provides (
LocalLifecycleOwner.current as ComponentActivity
).onBackPressedDispatcher
){
BackButtonHandler {
onBackPressed.invoke()
}
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/routing/RedditRouter.kt | 3308827752 | package com.topic3.android.reddit.routing
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.topic3.android.reddit.R
/**
* Класс, определяющий экраны, которые есть в нашем приложении.
*
* Эти объекты должны соответствовать файлам, которые есть в пакете screens
*/
sealed class Screen(val titleResId: Int) {
object Home : Screen(R.string.home)
object Subscriptions : Screen(R.string.subreddits)
object NewPost : Screen(R.string.new_post)
object MyProfile : Screen(R.string.my_profile)
object ChooseCommunity : Screen(R.string.choose_community)
}
object RedditRouter {
var currentScreen: MutableState<Screen> = mutableStateOf(
Screen.Home
)
private var previousScreen: MutableState<Screen> = mutableStateOf(
Screen.Home
)
fun navigateTo(destination: Screen) {
previousScreen.value = currentScreen.value
currentScreen.value = destination
}
fun goBack() {
currentScreen.value = previousScreen.value
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/routing/MyProfileRouter.kt | 361433758 | package com.topic3.android.reddit.routing
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/**
* Класс, определяющий экраны, которые есть в нашем приложении.
*
* Эти объекты должны соответствовать файлам, которые есть в пакете screens
*/
sealed class MyProfileScreenType {
object Posts : MyProfileScreenType()
object About : MyProfileScreenType()
}
object MyProfileRouter {
var currentScreen: MutableState<MyProfileScreenType> = mutableStateOf(MyProfileScreenType.Posts)
fun navigateTo(destination: MyProfileScreenType) {
currentScreen.value = destination
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/database/dao/PostDao.kt | 1611971120 | package com.topic3.android.reddit.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.topic3.android.reddit.data.database.model.PostDbModel
/**
* Dao для управления таблицей сообщений в базе данных.
*/
@Dao
interface PostDao {
@Query("SELECT * FROM PostDbModel")
fun getAllPosts(): List<PostDbModel>
@Query("SELECT * FROM PostDbModel WHERE username = :username")
fun getAllOwnedPosts(username: String): List<PostDbModel>
@Query("SELECT DISTINCT subreddit FROM PostDbModel")
fun getAllSubreddits(): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(postDbModel: PostDbModel)
@Query("DELETE FROM PostDbModel")
fun deleteAll()
@Insert
fun insertAll(vararg PostDbModels: PostDbModel)
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/database/AppDatabase.kt | 3610982149 | package com.topic3.android.reddit.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.topic3.android.reddit.data.database.dao.PostDao
import com.topic3.android.reddit.data.database.model.PostDbModel
/**
* База данных приложения.
*
* Содержит таблицу для постов
*/
@Database(entities = [PostDbModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
companion object {
const val DATABASE_NAME = "jet-reddit-database"
}
abstract fun postDao(): PostDao
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/database/dbmapper/DbMapper.kt | 3705044081 | package com.topic3.android.reddit.data.database.dbmapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
interface DbMapper {
fun mapPost(dbPostDbModel: PostDbModel): PostModel
fun mapDbPost(postModel: PostModel): PostDbModel
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/database/dbmapper/DbMapperImpl.kt | 2909526430 | package com.topic3.android.reddit.data.database.dbmapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.domain.model.PostType
import java.util.concurrent.TimeUnit
class DbMapperImpl : DbMapper {
override fun mapPost(dbPostDbModel: PostDbModel): PostModel {
with(dbPostDbModel) {
return PostModel(
username,
subreddit,
title,
text,
likes.toString(),
comments.toString(),
PostType.fromType(type),
getPostedDate(datePosted),
image
)
}
}
override fun mapDbPost(postModel: PostModel): PostDbModel {
with(postModel) {
return PostDbModel(
null,
"raywenderlich",
subreddit,
title,
text,
0,
0,
type.type,
System.currentTimeMillis(),
false,
image
)
}
}
private fun getPostedDate(date: Long): String {
val hoursPassed =
TimeUnit.HOURS.convert(System.currentTimeMillis() - date, TimeUnit.MILLISECONDS)
if (hoursPassed > 24) {
val daysPassed = TimeUnit.DAYS.convert(hoursPassed, TimeUnit.HOURS)
if (daysPassed > 30) {
if (daysPassed > 365) {
return (daysPassed / 365).toString() + "y"
}
return (daysPassed / 30).toString() + "mo"
}
return daysPassed.toString() + "d"
}
return hoursPassed.inc().toString() + "h"
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/database/model/PostDbModel.kt | 1108878045 | package com.topic3.android.reddit.data.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.topic3.android.reddit.R
@Entity
data class PostDbModel(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id") val id: Long?,
@ColumnInfo(name = "username") val username: String,
@ColumnInfo(name = "subreddit") val subreddit: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "text") val text: String,
@ColumnInfo(name = "likes") val likes: Int,
@ColumnInfo(name = "comments") val comments: Int,
@ColumnInfo(name = "type") val type: Int,
@ColumnInfo(name = "date_posted") val datePosted: Long,
@ColumnInfo(name = "is_saved") val isSaved: Boolean,
@ColumnInfo(name = "image") val image: Int? = null
) {
companion object {
val DEFAULT_POSTS = listOf(
PostDbModel(
1,
"raywenderlich",
"androiddev",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
5614,
523,
0,
System.currentTimeMillis(),
false,
image = R.drawable.compose_course
),
PostDbModel(
2,
"pro_dev",
"digitalnomad",
"My ocean view in Thailand.",
"",
2314,
23,
1, System.currentTimeMillis(),
false,
image = R.drawable.thailand
),
PostDbModel(
3,
"raywenderlich",
"programming",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
5214,
423,
0,
System.currentTimeMillis(),
false
),
PostDbModel(
4,
"raywenderlich",
"puppies",
"My puppy running around the house looks so cute!",
"My puppy running around the house looks so cute!",
25315,
1362,
0,
System.currentTimeMillis(),
false
),
PostDbModel(
5, "ps_guy", "playstation", "My PS5 just arrived!",
"", 56231, 823, 0, System.currentTimeMillis(), false
)
)
}
}
|
lab10/app/src/main/java/com/topic3/android/reddit/data/repository/Repository.kt | 2729691922 | package com.topic3.android.reddit.data.repository
import androidx.lifecycle.LiveData
import com.topic3.android.reddit.domain.model.PostModel
interface Repository {
fun getAllPosts(): LiveData<List<PostModel>>
fun getAllOwnedPosts(): LiveData<List<PostModel>>
fun getAllSubreddits(searchedText: String): List<String>
fun insert(post: PostModel)
fun deleteAll()
} |
lab10/app/src/main/java/com/topic3/android/reddit/data/repository/RepositoryImpl.kt | 3304034557 | package com.topic3.android.reddit.data.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.topic3.android.reddit.data.database.dao.PostDao
import com.topic3.android.reddit.data.database.dbmapper.DbMapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class RepositoryImpl(private val postDao: PostDao, private val mapper: DbMapper) : Repository {
private var searchedText = ""
private val allPostsLiveData: MutableLiveData<List<PostModel>> by lazy {
MutableLiveData<List<PostModel>>()
}
private val ownedPostsLiveData: MutableLiveData<List<PostModel>> by lazy {
MutableLiveData<List<PostModel>>()
}
init {
initDatabase(this::updatePostLiveData)
}
/**
* Populates database with posts if it is empty.
*/
private fun initDatabase(postInitAction: () -> Unit) {
GlobalScope.launch {
// Prepopulate posts
val posts = PostDbModel.DEFAULT_POSTS.toTypedArray()
val dbPosts = postDao.getAllPosts()
if (dbPosts.isNullOrEmpty()) {
postDao.insertAll(*posts)
}
postInitAction.invoke()
}
}
override fun getAllPosts(): LiveData<List<PostModel>> = allPostsLiveData
override fun getAllOwnedPosts(): LiveData<List<PostModel>> = ownedPostsLiveData
override fun getAllSubreddits(searchedText: String): List<String> {
this.searchedText = searchedText
if (searchedText.isNotEmpty()) {
return postDao.getAllSubreddits().filter { it.contains(searchedText) }
}
return postDao.getAllSubreddits()
}
private fun getAllPostsFromDatabase(): List<PostModel> =
postDao.getAllPosts().map(mapper::mapPost)
private fun getAllOwnedPostsFromDatabase(): List<PostModel> =
postDao.getAllOwnedPosts("raywenderlich").map(mapper::mapPost)
override fun insert(post: PostModel) {
postDao.insert(mapper.mapDbPost(post))
updatePostLiveData()
}
override fun deleteAll() {
postDao.deleteAll()
updatePostLiveData()
}
private fun updatePostLiveData() {
allPostsLiveData.postValue(getAllPostsFromDatabase())
ownedPostsLiveData.postValue(getAllOwnedPostsFromDatabase())
}
} |
lab10/app/src/main/java/com/topic3/android/reddit/domain/model/PostModel.kt | 1666616389 | package com.topic3.android.reddit.domain.model
import com.topic3.android.reddit.R
data class PostModel(
val username: String,
val subreddit: String,
val title: String,
val text: String,
val likes: String,
val comments: String,
val type: PostType,
val postedTime: String,
val image: Int?
) {
companion object {
val DEFAULT_POST = PostModel(
"raywenderlich",
"androiddev",
"Watch this awesome Jetpack Compose course!",
"",
"5614",
"523",
PostType.IMAGE,
"4h",
R.drawable.compose_course
)
val EMPTY = PostModel(
"raywenderlich",
"raywenderlich.com",
"",
"",
"0",
"0",
PostType.TEXT,
"0h",
R.drawable.compose_course
)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.