path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/data/mapper/QuoteMapper.kt | 3364819075 | package com.example.quoteapp.data.mapper
import com.example.quoteapp.data.model.Quote
import com.example.quoteapp.data.source.network.model.QuoteResponse
fun QuoteResponse.toQuote() = Quote (
id = this.id.orEmpty(),
quote = this.quote.orEmpty(),
anime = this.anime.orEmpty(),
character = this.character.orEmpty()
)
fun Collection<QuoteResponse>.toQuotes() = this.map {
it.toQuote()
} |
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/data/model/Quote.kt | 3893214076 | package com.example.quoteapp.data.model
import com.google.gson.annotations.SerializedName
data class Quote(
val id : String,
val quote : String,
val anime : String,
val character : String
)
|
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/presentation/main/MainViewModel.kt | 1158426582 | package com.example.quoteapp.presentation.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.quoteapp.data.model.Quote
import com.example.quoteapp.data.repository.QuoteRepository
import com.example.quoteapp.utils.ResultWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel(private val quoteRepository: QuoteRepository) : ViewModel() {
private val _responseLiveData = MutableLiveData<ResultWrapper<List<Quote>>>()
val responseLiveData: LiveData<ResultWrapper<List<Quote>>>
get() = _responseLiveData
fun getRandomQuotes() {
viewModelScope.launch(Dispatchers.IO) {
quoteRepository.getRandomQuotes().collect {
_responseLiveData.postValue(it)
}
}
}
} |
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/presentation/main/MainActivity.kt | 1739618579 | package com.example.quoteapp.presentation.main
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModel
import com.example.quoteapp.R
import com.example.quoteapp.data.datasource.QuoteApiDataSource
import com.example.quoteapp.data.datasource.QuoteDataSource
import com.example.quoteapp.data.repository.QuoteRepository
import com.example.quoteapp.data.repository.QuoteRepositoryImpl
import com.example.quoteapp.data.source.network.services.QuoteApiServices
import com.example.quoteapp.databinding.ActivityMainBinding
import com.example.quoteapp.presentation.main.adapter.QuoteAdapter
import com.example.quoteapp.utils.GenericViewModelFactory
import com.example.quoteapp.utils.proceedWhen
class MainActivity : AppCompatActivity() {
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val adapter: QuoteAdapter by lazy {
QuoteAdapter()
}
private val viewModel: MainViewModel by viewModels {
val s = QuoteApiServices.invoke()
val ds: QuoteDataSource = QuoteApiDataSource(s)
val rp: QuoteRepository = QuoteRepositoryImpl(ds)
GenericViewModelFactory.create(MainViewModel(rp))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupRecyclerView()
getQuotes()
observeData()
}
private fun setupRecyclerView() {
binding.rvAnime.adapter = adapter
}
private fun getQuotes() {
viewModel.getRandomQuotes()
}
private fun observeData() {
viewModel.responseLiveData.observe(this) { result ->
result.proceedWhen(
doOnLoading = {
binding.layoutState.root.isVisible = true
binding.layoutState.pbLoading.isVisible = true
binding.layoutState.tvError.isVisible = false
binding.rvAnime.isVisible = false
},
doOnSuccess = {
binding.layoutState.root.isVisible = false
binding.layoutState.pbLoading.isVisible = false
binding.layoutState.tvError.isVisible = false
binding.rvAnime.isVisible = true
result.payload?.let { result ->
adapter.submitData(result)
}
},
doOnError = {
binding.layoutState.root.isVisible = true
binding.layoutState.pbLoading.isVisible = false
binding.layoutState.tvError.isVisible = true
binding.layoutState.tvError.text = result.exception?.message.orEmpty()
binding.rvAnime.isVisible = false
},
doOnEmpty = {
binding.layoutState.root.isVisible = true
binding.layoutState.pbLoading.isVisible = false
binding.layoutState.tvError.isVisible = true
binding.layoutState.tvError.text = getString(R.string.text_cart_is_empty)
binding.rvAnime.isVisible = false
}
)
}
}
} |
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/presentation/main/adapter/QuoteViewHolder.kt | 1276581338 | package com.example.quoteapp.presentation.main.adapter
import androidx.recyclerview.widget.RecyclerView
import com.example.quoteapp.R
import com.example.quoteapp.base.ViewHolderBinder
import com.example.quoteapp.data.model.Quote
import com.example.quoteapp.databinding.ItemQuoteBinding
class QuoteViewHolder(private val binding: ItemQuoteBinding) : RecyclerView.ViewHolder(binding.root),
ViewHolderBinder<Quote> {
override fun bind(item: Quote) {
binding.tvQuote.text = item.quote
binding.tvCharacter.text = item.character
binding.tvAnime.text = item.anime
}
}
|
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/presentation/main/adapter/QuotesAdapter.kt | 1953417196 | package com.example.quoteapp.presentation.main.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.quoteapp.base.ViewHolderBinder
import com.example.quoteapp.data.model.Quote
import com.example.quoteapp.databinding.ItemQuoteBinding
class QuoteAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val asyncDiffer = AsyncListDiffer(
this,
object : DiffUtil.ItemCallback<Quote>() {
override fun areItemsTheSame(oldItem: Quote, newItem: Quote): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Quote, newItem: Quote): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
}
)
fun submitData(data: List<Quote>) {
asyncDiffer.submitList(data)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuoteViewHolder {
return QuoteViewHolder(
ItemQuoteBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount(): Int = asyncDiffer.currentList.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as ViewHolderBinder<Quote>).bind(asyncDiffer.currentList[position])
}
} |
QuoteApp-Marcella/app/src/main/java/com/example/quoteapp/base/ViewHolderBinder.kt | 1981564113 | package com.example.quoteapp.base
interface ViewHolderBinder<T> {
fun bind(item: T)
} |
fullstackwebapp/src/test/kotlin/com/br/fullstackapp/poc/PocApplicationTests.kt | 1759996015 | package com.br.fullstackapp.poc
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class PocApplicationTests {
@Test
fun contextLoads() {
}
}
|
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/PocApplication.kt | 1989314093 | package com.br.fullstackapp.poc
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.context.annotation.ComponentScan
@ComponentScan("com.br.fullstackapp.poc")
@ConfigurationPropertiesScan
@SpringBootApplication
class PocApplication
fun main(args: Array<String>) {
runApplication<PocApplication>(*args)
}
|
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/input/web/converter/ConverterHelper.kt | 3118828571 | package com.br.fullstackapp.poc.adapter.input.web.converter
import com.br.fullstackapp.poc.adapter.input.web.model.RecursoRequest
import com.br.fullstackapp.poc.application.domain.RecursoDomain
fun RecursoRequest.toDomain() : RecursoDomain =
RecursoDomain(
nome = nome,
chave = chave
) |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/input/web/controller/RecursoController.kt | 2212025895 | package com.br.fullstackapp.poc.adapter.input.web.controller
import com.br.fullstackapp.poc.adapter.input.web.converter.toDomain
import com.br.fullstackapp.poc.adapter.input.web.model.RecursoRequest
import com.br.fullstackapp.poc.application.domain.RecursoDomain
import com.br.fullstackapp.poc.application.port.input.RecursoUseCase
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RequestMapping("recurso")
@RestController
class RecursoController(
val recursoUseCase: RecursoUseCase
) {
@PostMapping
fun criarRecurso(@RequestBody recursoRequest: RecursoRequest) : RecursoDomain{
return recursoUseCase.criarRecurso(recursoRequest.toDomain())
}
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/input/web/model/RecursoRequest.kt | 2401962235 | package com.br.fullstackapp.poc.adapter.input.web.model
data class RecursoRequest(
val nome: String?="",
val chave: String?=""
)
|
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/output/converter/ConverterHelper.kt | 1729872867 | package com.br.fullstackapp.poc.adapter.output.converter
import com.br.fullstackapp.poc.adapter.output.firebase.entity.RecursoEntity
import com.br.fullstackapp.poc.application.domain.RecursoDomain
fun RecursoEntity.toDomain() : RecursoDomain =
RecursoDomain(
nome = nome,
chave = chave
)
fun RecursoDomain.toEntity() : RecursoEntity =
RecursoEntity(
nome = nome,
chave = chave
) |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/output/firebase/repository/RecursoRepository.kt | 805224638 | package com.br.fullstackapp.poc.adapter.output.firebase.repository
import com.br.fullstackapp.poc.adapter.output.converter.toEntity
import com.br.fullstackapp.poc.application.domain.RecursoDomain
import com.br.fullstackapp.poc.application.port.output.RecursoRepositoryPort
import com.google.cloud.firestore.CollectionReference
import com.google.firebase.cloud.FirestoreClient
import org.springframework.stereotype.Repository
@Repository
class RecursoRepository : RecursoRepositoryPort {
private val collection : String = "recursos"
fun dbFirestore() = FirestoreClient.getFirestore()
fun getCollection() : CollectionReference {
return dbFirestore().collection(collection)
}
override fun criarRecurso(recursoDomain: RecursoDomain): RecursoDomain {
try {
getCollection().document().set(recursoDomain.toEntity())
}catch (e: Exception){
e.printStackTrace()
}
return recursoDomain
}
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/adapter/output/firebase/entity/RecursoEntity.kt | 862486499 | package com.br.fullstackapp.poc.adapter.output.firebase.entity
data class RecursoEntity(
val nome: String?="",
val chave: String?=""
)
|
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/application/config/FirebaseConfig.kt | 810405801 | package com.br.fullstackapp.poc.application.config
import com.google.auth.oauth2.GoogleCredentials
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.auth.FirebaseAuth
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.DependsOn
import org.springframework.context.annotation.Primary
import org.springframework.core.io.ClassPathResource
import java.io.IOException
import java.io.InputStream
import javax.annotation.PostConstruct
@Configuration
class FirebaseConfig {
val log : Logger = LoggerFactory.getLogger(FirebaseConfig::class.java)
@PostConstruct
fun firebaseInit(){
try {
val input : InputStream = ClassPathResource("firebase_config.json").inputStream
val options : FirebaseOptions = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(input))
.setDatabaseUrl("https://baladaeventos-5df67-default-rtdb.firebaseio.com")
.build()
if (FirebaseApp.getApps().isEmpty()){
FirebaseApp.initializeApp(options)
}
log.info("---- Firebase Initialize ----")
}catch (e: IOException){
e.printStackTrace()
}
}
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/application/service/RecursoService.kt | 2584455371 | package com.br.fullstackapp.poc.application.service
import com.br.fullstackapp.poc.application.domain.RecursoDomain
import com.br.fullstackapp.poc.application.port.input.RecursoUseCase
import com.br.fullstackapp.poc.application.port.output.RecursoRepositoryPort
import org.springframework.stereotype.Service
@Service
class RecursoService(
val recursoRepositoryPort: RecursoRepositoryPort
) : RecursoUseCase {
override fun criarRecurso(recursoDomain: RecursoDomain): RecursoDomain {
return recursoRepositoryPort.criarRecurso(recursoDomain)
}
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/application/port/input/RecursoUseCase.kt | 1209360579 | package com.br.fullstackapp.poc.application.port.input
import com.br.fullstackapp.poc.application.domain.RecursoDomain
interface RecursoUseCase {
fun criarRecurso(recursoDomain: RecursoDomain): RecursoDomain
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/application/port/output/RecursoRepository.kt | 773003754 | package com.br.fullstackapp.poc.application.port.output
import com.br.fullstackapp.poc.application.domain.RecursoDomain
interface RecursoRepositoryPort {
fun criarRecurso(recursoDomain: RecursoDomain) : RecursoDomain
} |
fullstackwebapp/src/main/kotlin/com/br/fullstackapp/poc/application/domain/RecursoDomain.kt | 562021865 | package com.br.fullstackapp.poc.application.domain
data class RecursoDomain(
val nome: String?="",
val chave: String?=""
)
|
ProiectCalculMobil/proiectcmo/app/src/androidTest/java/com/example/proiectcmo/ExampleInstrumentedTest.kt | 701320971 | package com.example.proiectcmo
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.proiectcmo", appContext.packageName)
}
} |
ProiectCalculMobil/proiectcmo/app/src/test/java/com/example/proiectcmo/ExampleUnitTest.kt | 1478933747 | package com.example.proiectcmo
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)
}
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/ui/theme/Color.kt | 2165836465 | package com.example.proiectcmo.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) |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/ui/theme/Theme.kt | 1689492710 | package com.example.proiectcmo.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 ProiectCMOTheme(
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
)
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/ui/theme/Type.kt | 3021975996 | package com.example.proiectcmo.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
)
*/
) |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/MainActivity.kt | 1072790770 | package com.example.proiectcmo
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Box (
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
AplicatiaMea()
}
}
}
}
@Preview(showBackground = true)
@Composable
fun AplicatiaMea () {
// val numeUtilizator: MutableState<String> = remember {mutableStateOf("")}
// val parolaUtilizator: MutableState<String> = remember {mutableStateOf("")}
val context = LocalContext.current
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Notepad", style = TextStyle (
fontWeight = FontWeight.Bold,
fontSize = TextUnit(12.0F, TextUnitType.Em)
),
modifier = Modifier.padding(bottom = 32.dp),
)
// CampIntroducere (
// descriere = "Nume utilizator",
// valoareData = numeUtilizator,
// modifier = Modifier.padding(PaddingValues(bottom = 8.dp))
// )
//
// CampIntroducere (
// descriere = "Parola utilizator",
// valoareData = parolaUtilizator,
// tipParola = true,
// modifier = Modifier.padding(PaddingValues(bottom = 16.dp))
// )
ButonText(descriere = "Intrare") {
var notite: List<Notita>? = null
val serviciuApi = ApiClient.apiService
val call = serviciuApi.getNotite()
val intent = Intent(context, SelectareNotita::class.java)
call.enqueue(object : Callback<List<Notita>?> {
override fun onResponse(call: Call<List<Notita>?>, response: Response<List<Notita>?>) {
if (response.isSuccessful) {
notite = response.body()
val arrayNotite: ArrayList<Notita> = arrayListOf()
notite?.forEach { notita: Notita -> arrayNotite.add(notita) }
println(RetrofitClient.retrofit.baseUrl())
intent.putExtra("notite", arrayNotite)
context.startActivity(intent)
} else {
println(response.errorBody())
println(response.raw().message())
println(response.raw().code())
}
}
override fun onFailure(call: Call<List<Notita>?>, t: Throwable) {
// Handle failure
}
})
}
}
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/RetrofitClient.kt | 919173440 | package com.example.proiectcmo
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
interface ApiService {
@GET("{id}")
fun getNotitaById(@Path("id") notitaId: Int): Call<Notita?>
@GET("toate")
fun getNotite(): Call<List<Notita>?>
@GET("toate")
fun getNotiteByAutor(@Path("autor") autor: String): Call<List<Notita>?>
@POST("publica")
fun postNotita(notita: Notita)
}
object RetrofitClient {
private const val BASE_URL = "http://10.0.2.2:8080/notita/"
val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
object ApiClient {
val apiService: ApiService by lazy {
RetrofitClient.retrofit.create(ApiService::class.java)
}
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/Widgeturi.kt | 80315923 | package com.example.proiectcmo
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CampIntroducere (
modifier: Modifier = Modifier,
descriere: String,
valoareData: MutableState<String>,
tipParola: Boolean = false,
) {
var customVis: VisualTransformation = VisualTransformation.None
if (tipParola) {
customVis = PasswordVisualTransformation('*')
}
TextField (
value = valoareData.value,
label = {Text(descriere)},
singleLine = true,
visualTransformation = customVis,
onValueChange = {
textIntrodus: String ->
valoareData.value = textIntrodus
},
modifier = modifier
)
}
@Composable
fun ButonText (descriere: String, functie: () -> Unit) {
Button (
onClick = functie,
content = {Text(descriere)}
)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun EditorMultilinie
(
modifier: Modifier = Modifier,
valoareData: MutableState<String>,
) {
TextField (
value = valoareData.value,
label = {Text("Continut text")},
singleLine = false,
maxLines = 15,
onValueChange = {
textIntrodus: String ->
valoareData.value = textIntrodus
},
modifier = modifier
)
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/SelectareNotita.kt | 1250715537 | package com.example.proiectcmo
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.example.proiectcmo.ui.theme.ProiectCMOTheme
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SelectareNotita : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Box (
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
ContinutSelectareNotita()
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ContinutSelectareNotita() {
var notite: List<Notita>? = null
val context = LocalContext.current
val activity = context.findActivity()
val intentActivitateAnterioara = activity?.intent
val intent = Intent(context, EditareNotite::class.java)
notite = intentActivitateAnterioara?.getParcelableArrayListExtra("notite")
println(notite?.size)
Column (
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Selectați o notița din lista dată de notițe")
LazyColumn {
items(notite!!) {
NotitaCard(notita = it, intent, context)
}
}
}
}
@Composable
fun NotitaCard (notita: Notita, intent: Intent, context: Context) {
ButonText(descriere = notita.titlu, functie = {
intent.putExtra("notita", notita)
context.startActivity(intent)
})
} |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/Notita.kt | 2543320122 | package com.example.proiectcmo
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class Notita (
@SerializedName("titlu") val titlu: String,
@SerializedName("continut") val continut: String,
@SerializedName("autor") val autor: String,
@SerializedName("id") val id: Int,
) : Parcelable |
ProiectCalculMobil/proiectcmo/app/src/main/java/com/example/proiectcmo/EditareNotite.kt | 644282033 | package com.example.proiectcmo
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
class EditareNotite : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Box (
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
ContinutEditareNotite()
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ContinutEditareNotite() {
val continutText: MutableState<String> = remember {mutableStateOf("")}
val context = LocalContext.current
val activity = context.findActivity()
val intent = activity?.intent
val notita: Notita = intent?.getParcelableExtra<Notita>("notita")!!
continutText.value = notita.continut
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Editare",
style = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = TextUnit(5.0F, TextUnitType.Em)
),
modifier = Modifier.padding(bottom = 8.dp),)
Text(
notita.titlu,
style = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = TextUnit(6.0F, TextUnitType.Em)
),
modifier = Modifier.padding(bottom = 16.dp),
)
EditorMultilinie (
valoareData = continutText,
modifier = Modifier.padding(bottom = 32.dp),
)
ButonText(descriere = "Salvați editarea") {
}
// LazyRow (
//
// )
}
}
fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
|
Screen-Recorder-App/android/app/src/main/kotlin/com/kmmc/media_record/ScreenRecordService.kt | 3523940596 | package com.kmmc.media_record
import android.app.*
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.media.MediaRecorder
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Environment
import android.os.IBinder
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.io.File
import java.io.IOException
import android.os.Build
class ScreenRecordService : Service() {
private var mediaProjection: MediaProjection? = null
private var mediaRecorder: MediaRecorder? = null
private lateinit var projectionManager: MediaProjectionManager
private var screenDensity: Int = 0
companion object {
const val ACTION_START = "ACTION_START"
const val ACTION_STOP = "ACTION_STOP"
const val NOTIFICATION_CHANNEL_ID = "screen_recording_channel"
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
when (intent.action) {
ACTION_START -> startRecording(intent)
ACTION_STOP -> stopRecording()
}
return START_NOT_STICKY
}
private fun startRecording(intent: Intent) {
projectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
mediaProjection = projectionManager.getMediaProjection(Activity.RESULT_OK, intent)
val metrics = DisplayMetrics()
val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getMetrics(metrics)
screenDensity = metrics.densityDpi
setupMediaRecorder()
mediaProjection?.createVirtualDisplay(
"ScreenRecordService",
720, 1280, screenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder?.surface, null, null
)
mediaRecorder?.start()
}
private fun setupMediaRecorder() {
val recordingDirectory = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"Videos"
)
if (!recordingDirectory.exists()) {
recordingDirectory.mkdirs()
}
val fileName = "recording_${System.currentTimeMillis()}.mp4"
val filePath = File(recordingDirectory, fileName).absolutePath
mediaRecorder = MediaRecorder().apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setVideoSource(MediaRecorder.VideoSource.SURFACE)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setOutputFile(filePath)
setVideoSize(720, 1282)
setVideoEncoder(MediaRecorder.VideoEncoder.H264)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setVideoEncodingBitRate(512 * 1000)
setVideoFrameRate(30)
try {
prepare()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun stopRecording() {
mediaRecorder?.apply {
stop()
reset()
release()
}
mediaRecorder = null
mediaProjection?.stop()
mediaProjection = null
stopForeground(true)
stopSelf()
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
startForeground(1, createNotification())
}
private fun createNotification(): Notification {
val notificationIntent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle("Screen Recording")
.setContentText("Recording your screen.")
.setSmallIcon(android.R.drawable.ic_dialog_info) // Replace with your icon resource
.setContentIntent(pendingIntent)
.build()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Screen Recording Service",
NotificationManager.IMPORTANCE_LOW
)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}}
|
Screen-Recorder-App/android/app/src/main/kotlin/com/kmmc/media_record/MainActivity.kt | 3611018630 | package com.kmmc.media_record
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import java.io.File // Import for File
import android.widget.Toast // Import for Toast
import android.os.Environment
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.media.projection.MediaProjectionManager
class MainActivity : FlutterActivity() {
private val CHANNEL = "com.kmmc.screenrecorder/screenrecord"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"startRecording" -> {
if (checkPermissions()) {
startRecording()
} else {
requestPermissions()
}
result.success(null)
}
"stopRecording" -> {
stopRecording()
result.success(null)
}
"openFileManager" -> {
openFileManager()
result.success(null)
}
else -> {
result.notImplemented()
}
}
}
}
private fun checkPermissions(): Boolean {
val audioPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
return audioPermission == PackageManager.PERMISSION_GRANTED
}
private fun requestPermissions() {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), PERMISSIONS_REQUEST_CODE)
}
private fun startRecording() {
val projectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val screenCaptureIntent = projectionManager.createScreenCaptureIntent()
startActivityForResult(screenCaptureIntent, SCREEN_RECORD_REQUEST_CODE)
}
private fun stopRecording() {
val serviceIntent = Intent(this, ScreenRecordService::class.java)
serviceIntent.action = ScreenRecordService.ACTION_STOP
startService(serviceIntent)
}
private fun openFileManager() {
val recordingDirectory = File(getExternalFilesDir(null), "support/recording")
val uri = Uri.parse(recordingDirectory.absolutePath)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "*/*")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
}
try {
startActivity(Intent.createChooser(intent, "Open folder"))
} catch (e: Exception) {
// Handle the situation where a file manager is not installed
Toast.makeText(this, "No file manager found", Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SCREEN_RECORD_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
val serviceIntent = Intent(this, ScreenRecordService::class.java)
serviceIntent.action = ScreenRecordService.ACTION_START
serviceIntent.putExtras(data)
startService(serviceIntent)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSIONS_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecording()
}
}
companion object {
private const val SCREEN_RECORD_REQUEST_CODE = 1000
private const val PERMISSIONS_REQUEST_CODE = 2000
}
}
|
NotesCompose/app/src/androidTest/java/com/example/testingproject/ExampleInstrumentedTest.kt | 1747975900 | package com.example.testingproject
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.testingproject", appContext.packageName)
}
} |
NotesCompose/app/src/test/java/com/example/testingproject/ExampleUnitTest.kt | 2677744028 | package com.example.testingproject
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)
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/add_note/AddNoteUi.kt | 3996369575 | package com.example.testingproject.ui.add_note
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.testingproject.R
import com.example.testingproject.ui.add_note.components.MyTextField
import com.example.testingproject.ui.base.LocalNavHostController
import com.example.testingproject.ui.components.HeadingText
import com.example.testingproject.ui.components.VerticalSpacer
import ir.kaaveh.sdpcompose.sdp
import ir.kaaveh.sdpcompose.ssp
import org.koin.androidx.compose.koinViewModel
@Preview(showSystemUi = true)
@Composable
fun AddNoteUi(viewModel: AddNotesViewModel = koinViewModel()) {
val context = LocalContext.current
val navController = LocalNavHostController.current
Scaffold(
modifier = Modifier
.fillMaxSize(),
bottomBar = {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.sdp, vertical = 5.sdp)
.background(
colorResource(id = R.color.mainColor),
RoundedCornerShape(20)
)
.padding(horizontal = 8.sdp, vertical = 10.sdp)
.clickable {
viewModel.saveNote {
if (it.isBlank()) {
Toast
.makeText(context, "Note Saved", Toast.LENGTH_SHORT)
.show()
navController.popBackStack()
} else {
Toast
.makeText(context, it, Toast.LENGTH_SHORT)
.show()
}
}
},
contentAlignment = Alignment.Center
) {
Text(
text = "Save",
fontSize = 14.ssp,
fontWeight = FontWeight.Medium,
color = colorResource(id = R.color.white)
)
}
}
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(it),
horizontalAlignment = Alignment.CenterHorizontally
) {
val state by viewModel.state.collectAsState()
VerticalSpacer(dp = 10.sdp)
HeadingText(text = "Add Note")
VerticalSpacer(dp = 20.sdp)
MyTextField(value = state.note.title,
modifier = Modifier
.padding(horizontal = 8.sdp),
hint = "title...", onValueChange = {
viewModel.setTitle(it)
})
VerticalSpacer(dp = 10.sdp)
MyTextField(
value = state.note.message,
hint = "body...",
modifier = Modifier
.height(100.sdp)
.padding(horizontal = 8.sdp),
onValueChange = {
viewModel.setMessage(it)
})
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/add_note/components/MyTextField.kt | 713841098 | package com.example.testingproject.ui.add_note.components
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.example.testingproject.R
import ir.kaaveh.sdpcompose.sdp
@Composable
fun MyTextField(value: String, hint: String,modifier: Modifier = Modifier, onValueChange: ((String) -> Unit)? = null) {
TextField(
value = value, onValueChange = {
onValueChange?.invoke(it)
},
modifier = modifier
.fillMaxWidth()
.border(
1.dp,
color = colorResource(id = R.color.almostBlack),
RoundedCornerShape(10.sdp)
)
.padding(horizontal = 8.sdp),
colors = TextFieldDefaults.colors(
unfocusedContainerColor = Color.Transparent,
focusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
placeholder = {
Text(text = hint)
}
)
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/add_note/components/AddNotesState.kt | 3321251090 | package com.example.testingproject.ui.add_note.components
import com.example.testingproject.ui.notes_list.components.NotesData
data class AddNotesState(
val note: NotesData =NotesData()
)
|
NotesCompose/app/src/main/java/com/example/testingproject/ui/add_note/AddNotesViewModel.kt | 3643007601 | package com.example.testingproject.ui.add_note
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testingproject.domain.usecases.AddNoteUseCase
import com.example.testingproject.domain.usecases.GetNoteById
import com.example.testingproject.ui.add_note.components.AddNotesState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class AddNotesViewModel(
private val addNote: AddNoteUseCase,
private val savedStateHandle: SavedStateHandle,
private val getNoteById: GetNoteById
) : ViewModel() {
private val _state = MutableStateFlow(AddNotesState())
val state = _state.asStateFlow()
init {
val id = (savedStateHandle.get<String>("id") ?: "-1").toInt()
if (id != -1) {
viewModelScope.launch {
getNoteById(id.toString())?.let { data ->
_state.update {
it.copy(
note = data
)
}
}
}
}
}
fun setTitle(text: String) {
_state.update {
it.copy(
note = it.note.copy(
title = text
)
)
}
}
fun setMessage(text: String) {
_state.update {
it.copy(
note = it.note.copy(
message = text
)
)
}
}
fun saveNote(callBack: (String) -> Unit) {
val notesData = state.value.note
if (notesData.title.isBlank() || notesData.message.isBlank()) {
callBack.invoke("Fields Empty")
return
}
viewModelScope.launch {
addNote(state.value.note)
callBack.invoke("")
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/components/HeadingText.kt | 3436711400 | package com.example.testingproject.ui.components
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import com.example.testingproject.R
import ir.kaaveh.sdpcompose.ssp
@Composable
fun HeadingText(text: String) {
Text(
text = text,
color = colorResource(id = R.color.black),
fontWeight = FontWeight.Medium,
fontSize = 13.ssp
)
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/components/Routes.kt | 3735660249 | package com.example.testingproject.ui.components
enum class Routes {
NotesListScreen,
AddNotesScreen,
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/components/Views.kt | 2029546372 | package com.example.testingproject.ui.components
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
@Composable
fun HorizontalSpacer(dp: Dp) {
Spacer(
modifier = Modifier
.width(dp)
)
}
@Composable
fun VerticalSpacer(dp: Dp) {
Spacer(
modifier = Modifier
.height(dp)
)
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/theme/Color.kt | 759383634 | package com.example.testingproject.ui.theme
import androidx.compose.ui.graphics.Color
val MainColor = Color(0xFFD0BCFF)
val BgColor = Color(0xFFCCC2DC)
val SecondaryMain = Color(0xFFEFB8C8)
val AlmostBlack = Color(0xFF5e5963)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) |
NotesCompose/app/src/main/java/com/example/testingproject/ui/theme/Theme.kt | 3168916995 | package com.example.testingproject.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 = MainColor,
secondary = BgColor,
tertiary = SecondaryMain,
)
private val LightColorScheme = lightColorScheme(
primary = MainColor,
secondary = BgColor,
tertiary = SecondaryMain,
)
@Composable
fun TestingProjectTheme(
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
)
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/theme/Type.kt | 1391392015 | package com.example.testingproject.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
)
*/
) |
NotesCompose/app/src/main/java/com/example/testingproject/ui/notes_list/NotesListViewModel.kt | 2279328433 | package com.example.testingproject.ui.notes_list
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testingproject.domain.usecases.GetNotesUseCase
import com.example.testingproject.ui.notes_list.components.NotesData
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class NotesListViewModel(
private val getNotesUseCase: GetNotesUseCase
) : ViewModel() {
private val _state = MutableStateFlow<List<NotesData>>(emptyList())
val state = _state.asStateFlow()
init {
viewModelScope.launch {
getNotesUseCase().collectLatest { list ->
_state.update {
list
}
}
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/notes_list/components/NoteItem.kt | 1418199878 | package com.example.testingproject.ui.notes_list.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.testingproject.R
import ir.kaaveh.sdpcompose.sdp
import ir.kaaveh.sdpcompose.ssp
@Preview(showSystemUi = true)
@Composable
fun NoteItem(
notesData: NotesData = NotesData(0, "Ishfaq", "Message here"),
onClick: (() -> Unit)? = null
) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable {
onClick?.invoke()
}
.padding(horizontal = 6.sdp, vertical = 4.sdp),
shape = RoundedCornerShape(10),
colors = CardDefaults.cardColors(
colorResource(id = R.color.cardColor)
),
elevation = CardDefaults.cardElevation(4.sdp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.sdp, vertical = 8.sdp),
verticalArrangement = Arrangement.spacedBy(3.sdp)
) {
Text(
text = notesData.title,
fontSize = 12.ssp,
color = colorResource(id = R.color.black)
)
Text(
text = notesData.message,
fontSize = 10.ssp,
color = colorResource(id = R.color.almostBlack)
)
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/notes_list/components/NotesData.kt | 962195016 | package com.example.testingproject.ui.notes_list.components
import com.example.testingproject.data.model.NotesTable
data class NotesData(
val id: Int = 0,
val title: String = "",
val message: String = ""
)
fun NotesData.toNotesTable(): NotesTable {
return NotesTable(
title,
message,
System.currentTimeMillis(),
id,
)
}
|
NotesCompose/app/src/main/java/com/example/testingproject/ui/notes_list/components/FabButton.kt | 3452714091 | package com.example.testingproject.ui.notes_list.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import com.example.testingproject.R
import ir.kaaveh.sdpcompose.sdp
@Composable
fun FabButton(onClick: () -> Unit) {
Box(
modifier = Modifier
.size(50.sdp)
.background(
color = colorResource(id = R.color.cardColor), RoundedCornerShape(30)
)
.clickable {
onClick.invoke()
},
contentAlignment = Alignment.Center
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(20.sdp)
)
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/notes_list/NotesListScreen.kt | 2253408553 | package com.example.testingproject.ui.notes_list
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import com.example.testingproject.R
import com.example.testingproject.ui.base.LocalNavHostController
import com.example.testingproject.ui.components.HeadingText
import com.example.testingproject.ui.components.Routes
import com.example.testingproject.ui.components.VerticalSpacer
import com.example.testingproject.ui.notes_list.components.FabButton
import com.example.testingproject.ui.notes_list.components.NoteItem
import ir.kaaveh.sdpcompose.sdp
import org.koin.androidx.compose.koinViewModel
@Preview(showSystemUi = true)
@Composable
fun NotesListScreen(viewModel: NotesListViewModel = koinViewModel()) {
val navController = LocalNavHostController.current
val state by viewModel.state.collectAsState()
Scaffold(modifier = Modifier.fillMaxSize(),
floatingActionButton = {
FabButton {
navController.navigate(Routes.AddNotesScreen.name)
}
}
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(it)
.background(color = colorResource(id = R.color.bgColor)),
horizontalAlignment = Alignment.CenterHorizontally
) {
VerticalSpacer(dp = 10.sdp)
HeadingText(text = "Notes")
VerticalSpacer(dp = 10.sdp)
LazyColumn {
items(state) { note ->
NoteItem(note, onClick = {
navController.navigate(
Routes.AddNotesScreen.name + "/${note.id}"
)
})
}
}
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/base/MyNavHost.kt | 1052085738 | package com.example.testingproject.ui.base
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.testingproject.ui.add_note.AddNoteUi
import com.example.testingproject.ui.components.Routes
import com.example.testingproject.ui.notes_list.NotesListScreen
@Composable
fun MyNavHost() {
val controller = LocalNavHostController.current
NavHost(navController = controller, startDestination = Routes.NotesListScreen.name) {
composable(Routes.NotesListScreen.name) {
NotesListScreen()
}
composable(Routes.AddNotesScreen.name+"/{id}") {
AddNoteUi()
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/ui/base/MainActivity.kt | 1386308327 | package com.example.testingproject.ui.base
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
val LocalNavHostController = compositionLocalOf<NavHostController> {
error("")
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
CompositionLocalProvider(LocalNavHostController provides navController) {
MyNavHost()
}
}
}
}
|
NotesCompose/app/src/main/java/com/example/testingproject/ui/base/BaseApp.kt | 3096008954 | package com.example.testingproject.ui.base
import android.app.Application
import com.example.testingproject.di.sharedModules
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class BaseApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(applicationContext)
modules(sharedModules)
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/di/Koin.kt | 4276514258 | package com.example.testingproject.di
import androidx.room.Room
import com.example.testingproject.data.data_source.AppDatabase
import com.example.testingproject.data.data_source.NotesTableDao
import com.example.testingproject.data.repository.NotesRepositoryImpl
import com.example.testingproject.domain.repository.NotesRepository
import com.example.testingproject.domain.usecases.AddNoteUseCase
import com.example.testingproject.domain.usecases.GetNoteById
import com.example.testingproject.domain.usecases.GetNotesUseCase
import com.example.testingproject.ui.add_note.AddNotesViewModel
import com.example.testingproject.ui.notes_list.NotesListViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val sharedModules = module {
single<AppDatabase> {
Room.databaseBuilder(get(), AppDatabase::class.java, "AppDb")
.build()
}
factory<NotesTableDao> {
get<AppDatabase>().getMyDao()
}
viewModel {
AddNotesViewModel(get(), get(), get())
}
factory {
AddNoteUseCase(get())
}
factory<NotesRepository> {
NotesRepositoryImpl(get())
}
viewModel {
NotesListViewModel(get())
}
factory {
GetNotesUseCase(get())
}
factory {
GetNoteById(get())
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/data/repository/NotesRepositoryImpl.kt | 383752228 | package com.example.testingproject.data.repository
import com.example.testingproject.data.data_source.NotesTableDao
import com.example.testingproject.data.model.NotesTable
import com.example.testingproject.domain.repository.NotesRepository
import kotlinx.coroutines.flow.Flow
class NotesRepositoryImpl(
private val notesTableDao: NotesTableDao
) : NotesRepository {
override suspend fun insertOrUpdate(notesTable: NotesTable) {
notesTableDao.insertNote(notesTable)
}
override suspend fun deleteNote(id: String) {
notesTableDao.deleteNote(id)
}
override fun getAllNotes(): Flow<List<NotesTable>> = notesTableDao.getAllNotes()
override suspend fun getNoteById(id: String): NotesTable? {
return notesTableDao.getNoteById(id)
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/data/data_source/AppDatabase.kt | 2001390309 | package com.example.testingproject.data.data_source
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.testingproject.data.model.NotesTable
@Database(entities = [NotesTable::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun getMyDao(): NotesTableDao
} |
NotesCompose/app/src/main/java/com/example/testingproject/data/data_source/NotesTableDao.kt | 2763915495 | package com.example.testingproject.data.data_source
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
import com.example.testingproject.data.model.NotesTable
import kotlinx.coroutines.flow.Flow
@Dao
interface NotesTableDao {
@Upsert
suspend fun insertNote(notesTable: NotesTable)
@Query("DELETE FROM Notes WHERE id=:id")
suspend fun deleteNote(id: String)
@Query("SELECT * FROM Notes")
fun getAllNotes(): Flow<List<NotesTable>>
@Query("SELECT * FROM Notes WHERE id=:id")
suspend fun getNoteById(id: String): NotesTable?
} |
NotesCompose/app/src/main/java/com/example/testingproject/data/model/NotesTable.kt | 4166693879 | package com.example.testingproject.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.testingproject.ui.notes_list.components.NotesData
@Entity("Notes")
data class NotesTable(
val title: String,
val message: String,
val timeInMillis: Long,
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
)
fun NotesTable.toNotesData() = NotesData(
id, title, message
)
|
NotesCompose/app/src/main/java/com/example/testingproject/domain/repository/NotesRepository.kt | 150842578 | package com.example.testingproject.domain.repository
import com.example.testingproject.data.model.NotesTable
import kotlinx.coroutines.flow.Flow
interface NotesRepository {
suspend fun insertOrUpdate(notesTable: NotesTable)
suspend fun deleteNote(id: String)
fun getAllNotes(): Flow<List<NotesTable>>
suspend fun getNoteById(id: String): NotesTable?
} |
NotesCompose/app/src/main/java/com/example/testingproject/domain/usecases/GetNoteById.kt | 2396905934 | package com.example.testingproject.domain.usecases
import com.example.testingproject.data.model.toNotesData
import com.example.testingproject.domain.repository.NotesRepository
import com.example.testingproject.ui.notes_list.components.NotesData
class GetNoteById(
private val repository: NotesRepository
) {
suspend operator fun invoke(id: String): NotesData? {
return repository.getNoteById(id)?.toNotesData()
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/domain/usecases/GetNotesUseCase.kt | 3794659363 | package com.example.testingproject.domain.usecases
import com.example.testingproject.data.model.toNotesData
import com.example.testingproject.domain.repository.NotesRepository
import com.example.testingproject.ui.notes_list.components.NotesData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class GetNotesUseCase(
private val repository: NotesRepository
) {
operator fun invoke(): Flow<List<NotesData>> {
return repository.getAllNotes().map { list ->
list.map {
it.toNotesData()
}
}
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/domain/usecases/AddNoteUseCase.kt | 4069361084 | package com.example.testingproject.domain.usecases
import com.example.testingproject.domain.repository.NotesRepository
import com.example.testingproject.ui.notes_list.components.NotesData
import com.example.testingproject.ui.notes_list.components.toNotesTable
class AddNoteUseCase(
private val repository: NotesRepository
) {
suspend operator fun invoke(notesData: NotesData) {
repository.insertOrUpdate(notesData.toNotesTable())
}
} |
NotesCompose/app/src/main/java/com/example/testingproject/domain/usecases/DeleteNoteUseCase.kt | 2677961681 | package com.example.testingproject.domain.usecases
import com.example.testingproject.domain.repository.NotesRepository
class DeleteNoteUseCase(
private val repository: NotesRepository
) {
suspend fun invoke(id: String) {
repository.deleteNote(id)
}
} |
android-jc-auth0-sample/app/src/androidTest/java/com/example/auth0example1/ExampleInstrumentedTest.kt | 2436004411 | package com.example.auth0example1
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.auth0example1", appContext.packageName)
}
} |
android-jc-auth0-sample/app/src/test/java/com/example/auth0example1/ExampleUnitTest.kt | 892888569 | package com.example.auth0example1
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/ViewModel/MainViewModel.kt | 1994514954 | package com.example.auth0example1.ViewModel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import android.content.Context
import com.auth0.android.Auth0
import com.auth0.android.provider.WebAuthProvider
import com.auth0.android.callback.Callback
import com.auth0.android.authentication.AuthenticationException
import com.auth0.android.result.Credentials
import android.util.Log
import com.example.auth0example1.Model.User
import com.example.auth0example1.R
class MainViewModel : ViewModel() {
var appJustLaunched by mutableStateOf(true)
var userIsAuthenticated by mutableStateOf(false)
private val TAG = "MainViewModel"
private lateinit var account: Auth0
private lateinit var context: Context
var user by mutableStateOf(User())
fun setContext(activityContext: Context) {
context = activityContext
account = Auth0(
context.getString(R.string.com_auth0_client_id),
context.getString(R.string.com_auth0_domain)
)
}
// fun login() {
// userIsAuthenticated = true
// appJustLaunched = false
// }
fun login() {
WebAuthProvider
.login(account)
.withScheme(context.getString(R.string.com_auth0_scheme))
.start(context, object : Callback<Credentials, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
// The user either pressed the “Cancel” button
// on the Universal Login screen or something
// unusual happened.
Log.e(TAG, "Error occurred in login(): $error")
}
override fun onSuccess(result: Credentials) {
// The user successfully logged in.
val idToken = result.idToken
// TODO: 🚨 REMOVE BEFORE GOING TO PRODUCTION!
Log.d(TAG, "ID token: $idToken")
user = User(idToken)
userIsAuthenticated = true
appJustLaunched = false
}
})
}
// fun logout() {
// userIsAuthenticated = false
// }
fun logout() {
WebAuthProvider
.logout(account)
.withScheme(context.getString(R.string.com_auth0_scheme))
.start(context, object : Callback<Void?, AuthenticationException> {
override fun onFailure(error: AuthenticationException) {
// For some reason, logout failed.
Log.e(TAG, "Error occurred in logout(): $error")
}
override fun onSuccess(result: Void?) {
// The user successfully logged out.
user = User()
userIsAuthenticated = false
}
})
}
} |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/ui/theme/Color.kt | 3020705882 | package com.example.auth0example1.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) |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/ui/theme/Theme.kt | 3420392892 | package com.example.auth0example1.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 Auth0Example1Theme(
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
)
} |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/ui/theme/Type.kt | 3593668654 | package com.example.auth0example1.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
)
*/
) |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/UserInfoRow.kt | 2280035855 | package com.example.auth0example1
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.dp
import androidx.compose.ui.unit.sp
@Composable
fun UserInfoRow(
label: String,
value: String,
) {
Row {
Text(
text = label,
style = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
)
)
Spacer(
modifier = Modifier.width(10.dp),
)
Text(
text = value,
style = TextStyle(
fontFamily = FontFamily.Default,
fontSize = 20.sp,
)
)
}
}
|
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/MainActivity.kt | 791207939 | package com.example.auth0example1
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.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.auth0example1.ui.theme.Auth0Example1Theme
import androidx.activity.viewModels
import com.example.auth0example1.ViewModel.MainViewModel
class MainActivity : ComponentActivity() {
private val mainViewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainViewModel.setContext(this)
setContent {
Auth0Example1Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainView(mainViewModel)
}
}
}
}
}
|
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/LogButton.kt | 2778247855 | package com.example.auth0example1
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.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun LogButton(
text: String,
onClick: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Button(
onClick = { onClick() },
modifier = Modifier
.width(200.dp)
.height(50.dp),
) {
Text(
text = text,
fontSize = 20.sp,
)
}
}
} |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/Model/User.kt | 2453552518 | package com.example.auth0example1.Model
import android.util.Log
import com.auth0.android.jwt.JWT
data class User(val idToken: String? = null) {
private val TAG = "User"
var id = ""
var name = ""
var email = ""
var emailVerified = ""
var picture = ""
var updatedAt = ""
init {
if (idToken != null) {
try {
// Attempt to decode the ID token.
val jwt = JWT(idToken ?: "")
// The ID token is a valid JWT,
// so extract information about the user from it.
id = jwt.subject ?: ""
name = jwt.getClaim("name").asString() ?: ""
email = jwt.getClaim("email").asString() ?: ""
emailVerified = jwt.getClaim("email_verified").asString() ?: ""
picture = jwt.getClaim("picture").asString() ?: ""
updatedAt = jwt.getClaim("updated_at").asString() ?: ""
} catch (error: com.auth0.android.jwt.DecodeException) {
// The ID token is NOT a valid JWT, so log the error
// and leave the user properties as empty strings.
Log.e(TAG, "Error occurred trying to decode JWT: ${error.toString()} ")
}
} else {
// The User object was instantiated with a null value,
// which means the user is being logged out.
// The user properties will be set to empty strings.
Log.d(TAG, "User is logged out - instantiating empty User object.")
}
}
} |
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/MainView.kt | 4123864572 | package com.example.auth0example1
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.dp
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.example.auth0example1.ViewModel.MainViewModel
@Composable
fun MainView(
viewModel: MainViewModel
) {
Column(
modifier = Modifier.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
val title = if (viewModel.userIsAuthenticated) {
"User Logged in"
} else {
if (viewModel.appJustLaunched) {
"Welcome, please login"
} else {
"User Logged out"
}
}
Text(
text = title,
style = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 30.sp,
)
)
Spacer(
modifier = Modifier.width(10.dp),
)
if (viewModel.userIsAuthenticated){
UserInfoRow(
label = "user_info_row_name_label",
//value = "Name goes here",
value = viewModel.user.name,
)
UserInfoRow(
label = "user_info_row_email_label",
//value = "Email goes here",
value = viewModel.user.email,
)
UserPicture(
//url = "https://images.ctfassets.net/23aumh6u8s0i/5hHkO5DxWMPxDjc2QZLXYf/403128092dedc8eb3395314b1d3545ad/icon-user.png",
url = viewModel.user.picture,
description = "Description goes here",
)
}
val buttonText: String
val onClickAction: () -> Unit
if (viewModel.userIsAuthenticated) {
buttonText = "Log out"
onClickAction = {
viewModel.logout()
}
} else {
buttonText = "Log in"
onClickAction = {
viewModel.login()
}
}
LogButton(
text = buttonText,
onClick = onClickAction,
)
}
}
|
android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/UserPicture.kt | 2870866267 | package com.example.auth0example1
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
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.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberAsyncImagePainter
@Composable
fun UserPicture(
url: String,
description: String,
) {
Column(
modifier = Modifier
.padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Image(
painter = rememberAsyncImagePainter(url),
contentDescription = description,
modifier = Modifier
.fillMaxSize(0.5f),
)
}
} |
SporterApp/app/src/androidTest/java/com/graduate/work/sporterapp/ExampleInstrumentedTest.kt | 2040210395 | package com.graduate.work.sporterapp
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.graduate.work.sporterapp", appContext.packageName)
}
} |
SporterApp/app/src/test/java/com/graduate/work/sporterapp/ExampleUnitTest.kt | 2797727041 | package com.graduate.work.sporterapp
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)
}
} |
MiAgenda-Room2.0/app/src/androidTest/java/com/example/agenda/ExampleInstrumentedTest.kt | 4253196848 | package com.example.agenda
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.agenda", appContext.packageName)
}
} |
MiAgenda-Room2.0/app/src/test/java/com/example/agenda/ExampleUnitTest.kt | 4241411300 | package com.example.agenda
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)
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/MyViewModelFactory.kt | 869848476 | package com.example.agenda
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class MyViewModelFactory (
private val customerRepository: CustomerRepository,
private val supplierRepository: SupplierRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MyViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return MyViewModel(customerRepository, supplierRepository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/ListCustomersActivity.kt | 1500176544 | package com.example.agenda
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
class ListCustomersActivity: AppCompatActivity(){
private lateinit var recyclerView: RecyclerView
lateinit var myViewModel: MyViewModel
lateinit var customerAdapter: CustomersAdapter
private lateinit var atras: Button
private lateinit var textViewNombre: TextView
private lateinit var nombreCliente: EditText
private lateinit var ok: Button
private lateinit var buscarCliPorNombre: Button
private lateinit var volverListaCli: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_customers)
textViewNombre = findViewById(R.id.textView_nombreCli)
nombreCliente = findViewById(R.id.editTextNombreCli)
ok = findViewById(R.id.btnOkCli)
volverListaCli = findViewById(R.id.btnVolverListaCli)
textViewNombre.visibility = View.GONE
nombreCliente.visibility = View.GONE
ok.visibility = View.GONE
volverListaCli.visibility = View.GONE
val customerRepository =
CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository =
SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
val onItemClickListener: (String) -> Unit = { code ->
// Manejar el clic en un elemento para abrir una nueva pantalla con detalles
val intent = Intent(this, CustomersDetail::class.java)
intent.putExtra("code", code)
startActivity(intent)
}
customerAdapter = CustomersAdapter(onItemClickListener)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = customerAdapter
atras = findViewById(R.id.btnAtrasRegistroClientes)
atras.setOnClickListener() {
val toFifth = Intent(this, FifthActivity::class.java)
startActivity(toFifth)
}
buscarCliPorNombre = findViewById(R.id.findCustomerByName)
buscarCliPorNombre.setOnClickListener() {
recyclerView.visibility = View.GONE
atras.visibility = View.GONE
buscarCliPorNombre.visibility = View.GONE
textViewNombre.visibility = View.VISIBLE
nombreCliente.visibility = View.VISIBLE
ok.visibility = View.VISIBLE
volverListaCli.visibility = View.VISIBLE
}
ok.setOnClickListener() {
val nombre = nombreCliente.text.toString()
if(TextUtils.isEmpty(nombre)){
mostrarToastEnLaMitadDeLaPantalla("Por favor, introduzca un nombre.")
}else{
myViewModel.loadCustomerByName(nombre)
myViewModel.customer.observeOnce(this, Observer { customers ->
customerAdapter.setCustomers(customers)
})
textViewNombre.visibility = View.GONE
nombreCliente.visibility = View.GONE
ok.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
myViewModel.viewModelScope.launch{
if(myViewModel.obtenerNumeroClientesPorNombre(nombre)==0){
mostrarToastEnLaMitadDeLaPantalla("No existe ningún cliente con ese nombre en la base de datos.")
}
}
}
}
volverListaCli.setOnClickListener() {
myViewModel.loadCustomers()
myViewModel.customers.observeOnce(this, Observer { customers ->
customerAdapter.setCustomers(customers)
})
textViewNombre.visibility = View.GONE
nombreCliente.visibility = View.GONE
ok.visibility = View.GONE
volverListaCli.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
atras.visibility = View.VISIBLE
buscarCliPorNombre.visibility = View.VISIBLE
}
// Obtener datos de la base de datos y actualizar el RecyclerView
myViewModel.loadCustomers()
myViewModel.customers.observeOnce(this, Observer { customers ->
customerAdapter.setCustomers(customers)
})
myViewModel.viewModelScope.launch {
if (myViewModel.obtenerNumeroClientes()==0) {
mostrarToastEnLaMitadDeLaPantalla("No existe ningún cliente en la base de datos")
}
}
}
private fun mostrarToastEnLaMitadDeLaPantalla(mensaje: String) {
val inflater: LayoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val layout = inflater.inflate(R.layout.custom_toast_layout, findViewById(R.id.custom_toast_root))
// Crea un objeto Toast personalizado con la vista personalizada
val toast = Toast(applicationContext)
toast.setGravity(Gravity.CENTER, 0, 0)
toast.duration = Toast.LENGTH_SHORT
toast.view = layout
layout.findViewById<TextView>(R.id.custom_toast_text).text = mensaje
// Muestra el Toast personalizado
toast.show()
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/ThirdActivity.kt | 3662639184 | package com.example.agenda
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class ThirdActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_third)
val proveedores = findViewById<Button>(R.id.btnProveedores)
val clientes = findViewById<Button>(R.id.btnClientes)
val atras = findViewById<Button>(R.id.btnAtrasThird)
proveedores.setOnClickListener(){
val intentFourth = Intent(this, FourthActivity::class.java)
startActivity(intentFourth)
}
clientes.setOnClickListener(){
val intentFifth = Intent(this, FifthActivity::class.java)
startActivity(intentFifth)
}
atras.setOnClickListener{
val toMain = Intent(this, MainActivity::class.java)
startActivity(toMain)
}
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/SupplierRepository.kt | 2317037374 | package com.example.agenda
import androidx.lifecycle.LiveData
class SupplierRepository (private val peticionesDao: PeticionesDao) {
suspend fun insertSupplier(s: Supplier) {
peticionesDao.insertSupplier(s)
}
suspend fun getAllSuppliers(): List<Supplier> {
return peticionesDao.getAllSuppliers()
}
suspend fun getSupplierDetails(supplierId: String): Supplier {
return peticionesDao.getSupplierById(supplierId)
}
suspend fun getSupplierByName(supplierName: String): List<Supplier>{
return peticionesDao.getSupplierByName(supplierName)
}
suspend fun deleteSupplierById(supplierId: String){
peticionesDao.deleteSupplierById(supplierId)
}
suspend fun updateSupplierById(codigo: String, nuevoNombre: String, nuevaDireccion: String, nuevoTelefono: String) {
peticionesDao.updateSupplierById(codigo, nuevoNombre, nuevaDireccion, nuevoTelefono)
}
fun isCodigoSupplierExists(codigo: String): LiveData<Boolean> {
return peticionesDao.isCodigoSupplierExists(codigo)
}
suspend fun obtenerNumeroProveedores(): Int {
return peticionesDao.getNumberOfSuppliers()
}
suspend fun obtenerNumeroProveedoresPorNombre(nombre: String): Int {
return peticionesDao.getNumberOfSuppliersByName(nombre)
}
}
|
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/MainActivity.kt | 3119737324 |
package com.example.agenda
import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.room.Room
class
MainActivity : AppCompatActivity() {
companion object {
lateinit var database: AgendaDatabase
}
// definir el requestCode
val RESULTADO_UNO=1
val RESULTADO_DOS=2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
database = Room.databaseBuilder(
applicationContext,
AgendaDatabase::class.java, "agenda-database"
).build()
val registro = findViewById<Button>(R.id.btnRegistro)
val salir = findViewById<Button>(R.id.btnSalir)
/*val gosecond = findViewById<Button>(R.id.askMeBtn)
gosecond.setOnClickListener{
// Crea un Intent para iniciar la segunda actividad
// Añade datos adicionales al Intent
intent.putExtra("proveedor", "Castelao")
intent.putExtra("cliente", "Google")
// Inicia la segunda actividad
startActivityForResult(intent, RESULTADO_UNO)
startActivityForResult(intent, RESULTADO_DOS)
}*/
registro.setOnClickListener{
val intentThird = Intent(this, ThirdActivity::class.java)
startActivity(intentThird)
}
salir.setOnClickListener{
finishAffinity()
}
}
/*@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val saludo = findViewById<TextView>(R.id.originalTextView)
val goSecond = findViewById<TextView>(R.id.textViewGo)
if(resultCode != Activity.RESULT_OK) return
when(requestCode) {
RESULTADO_UNO -> {
if (data != null) {
saludo.text = data.getStringExtra("pregunta")
}; }
// Other result codes
else -> {}
}
when(requestCode) {
RESULTADO_DOS -> {
if (data != null) {
goSecond.text = data.getStringExtra("hecho")
}; }
// Other result codes
else -> {}
}
}*/
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/PeticionesDao.kt | 2680613161 | package com.example.agenda
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface PeticionesDao {
@Insert
suspend fun insertCustomer(c: Customer)
@Query("SELECT * FROM Customer")
suspend fun getAllCustomers(): List<Customer>
@Query("SELECT * FROM Customer WHERE codigoCli = :customerId")
suspend fun getCustomerById(customerId: String): Customer
@Query("SELECT * FROM Customer WHERE nombreCli = :customerName")
suspend fun getCustomerByName(customerName: String): List<Customer>
@Query("DELETE FROM Customer WHERE codigoCli = :customerId")
suspend fun deleteCustomerById(customerId: String)
@Query("UPDATE Customer SET nombreCli = :customerName, direccionCli = :customerAddress, telefonoCli = :customerPhone WHERE codigoCli = :customerId")
suspend fun updateCustomerById(customerId: String, customerName: String, customerAddress: String, customerPhone: String)
@Insert
suspend fun insertSupplier(s: Supplier)
@Query("SELECT * FROM Supplier")
suspend fun getAllSuppliers(): List<Supplier>
@Query("SELECT * FROM Supplier WHERE codigoProv = :supplierId")
suspend fun getSupplierById(supplierId: String): Supplier
@Query("SELECT * FROM Supplier WHERE nombreProv = :supplierName")
suspend fun getSupplierByName(supplierName: String): List<Supplier>
@Query("DELETE FROM Supplier WHERE codigoProv = :supplierId")
suspend fun deleteSupplierById(supplierId: String)
@Query("UPDATE Supplier SET nombreProv = :supplierName, direccionProv = :supplierAddress, telefonoProv = :supplierPhone WHERE codigoProv = :supplierId")
suspend fun updateSupplierById(supplierId: String, supplierName: String, supplierAddress: String, supplierPhone: String)
//Comprobamos si el código que recibe como parámetro existe en la entidad Customer
@Query("SELECT EXISTS(SELECT 1 FROM Customer WHERE codigoCli = :customerId LIMIT 1)")
fun isCodigoCustomerExists(customerId: String): LiveData<Boolean>
//Comprobamos si el código que recibe como parámetro existe en la entidad Supplier
@Query("SELECT EXISTS(SELECT 1 FROM Supplier WHERE codigoProv = :supplierId LIMIT 1)")
fun isCodigoSupplierExists(supplierId: String): LiveData<Boolean>
@Query("SELECT COUNT(*) FROM Customer")
suspend fun getNumberOfCustomers(): Int
@Query("SELECT COUNT(*) FROM Supplier")
suspend fun getNumberOfSuppliers(): Int
@Query("SELECT COUNT(*) FROM Customer WHERE nombreCli = :customerName")
suspend fun getNumberOfCustomersByName(customerName: String): Int
@Query("SELECT COUNT(*) FROM Supplier WHERE nombreProv = :supplierName")
suspend fun getNumberOfSuppliersByName(supplierName: String): Int
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/MyViewModel.kt | 3542837613 | package com.example.agenda
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MyViewModel(private val customerRepository: CustomerRepository, private val supplierRepository:SupplierRepository) : ViewModel() {
private val _customers = MutableLiveData<List<Customer>>()
val customers: LiveData<List<Customer>> get() = _customers
private val _customer = MutableLiveData<List<Customer>>()
val customer: LiveData<List<Customer>> get() = _customer
private val _customerDetails = MutableLiveData<Customer>()
val customerDetails: LiveData<Customer> get() = _customerDetails
private val _supplierDetails = MutableLiveData<Supplier>()
val supplierDetails: LiveData<Supplier> get() = _supplierDetails
private val _suppliers = MutableLiveData<List<Supplier>>()
val suppliers: LiveData<List<Supplier>> get() = _suppliers
private val _supplier = MutableLiveData<List<Supplier>>()
val supplier: LiveData<List<Supplier>> get() = _supplier
fun insertCustomer(c: Customer) {
viewModelScope.launch(Dispatchers.IO) {
customerRepository.insertCustomer(c)
}
}
fun loadCustomerByName(nombre: String){
viewModelScope.launch(Dispatchers.IO) {
val customer = customerRepository.getCustomerByName(nombre)
_customer.postValue(customer)
}
}
fun loadCustomers() {
viewModelScope.launch(Dispatchers.IO){
val customers = customerRepository.getAllCustomers()
_customers.postValue(customers)
}
}
fun loadCustomerDetails(codigo: String) {
viewModelScope.launch(Dispatchers.IO) {
val customer = customerRepository.getCustomerDetails(codigo)
_customerDetails.postValue(customer)
}
}
fun deleteCustomer(codigo: String) {
viewModelScope.launch(Dispatchers.IO) {
customerRepository.deleteCustomerById(codigo)
}
}
fun updateCustomer(codigo: String, nuevoNombre: String, nuevaDireccion: String, nuevoTelefono: String) {
viewModelScope.launch(Dispatchers.IO) {
customerRepository.updateCustomerById(codigo, nuevoNombre, nuevaDireccion, nuevoTelefono)
}
}
fun insertSupplier(s: Supplier) {
viewModelScope.launch(Dispatchers.IO) {
supplierRepository.insertSupplier(s)
}
}
fun loadSuppliers() {
viewModelScope.launch(Dispatchers.IO) {
val suppliers = supplierRepository.getAllSuppliers()
_suppliers.postValue(suppliers)
}
}
fun loadSupplierByName(nombre: String){
viewModelScope.launch(Dispatchers.IO) {
val supplier = supplierRepository.getSupplierByName(nombre)
_supplier.postValue(supplier)
}
}
fun loadSupplierDetails(codigo: String) {
viewModelScope.launch(Dispatchers.IO) {
val supplier = supplierRepository.getSupplierDetails(codigo)
_supplierDetails.postValue(supplier)
}
}
fun deleteSupplier(codigo: String) {
viewModelScope.launch(Dispatchers.IO) {
supplierRepository.deleteSupplierById(codigo)
}
}
fun updateSupplier(codigo: String, nuevoNombre: String, nuevaDireccion: String, nuevoTelefono: String) {
viewModelScope.launch(Dispatchers.IO) {
supplierRepository.updateSupplierById(codigo, nuevoNombre, nuevaDireccion, nuevoTelefono)
}
}
fun existeCodigoCliente(codigo: String): LiveData<Boolean> {
return customerRepository.isCodigoCustomerExists(codigo)
}
fun existeCodigoProveedor(codigo: String): LiveData<Boolean> {
return supplierRepository.isCodigoSupplierExists(codigo)
}
suspend fun obtenerNumeroClientes(): Int {
return customerRepository.obtenerNumeroClientes()
}
suspend fun obtenerNumeroProveedores(): Int {
return supplierRepository.obtenerNumeroProveedores()
}
suspend fun obtenerNumeroClientesPorNombre(nombre: String): Int {
return customerRepository.obtenerNumeroClientesPorNombre(nombre)
}
suspend fun obtenerNumeroProveedoresPorNombre(nombre: String): Int {
return supplierRepository.obtenerNumeroProveedoresPorNombre(nombre)
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/SuppliersAdapter.kt | 2617438383 | package com.example.agenda
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
class SuppliersAdapter (private val onItemClickListener: (String) -> Unit) :
ListAdapter<Supplier, SuppliersAdapter.SupplierViewHolder>(SupplierDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SupplierViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.list_item_suppliers, parent, false)
return SupplierViewHolder(itemView)
}
fun setSuppliers(suppliers: List<Supplier>) {
submitList(suppliers.toMutableList())
}
override fun onBindViewHolder(holder: SupplierViewHolder, position: Int) {
val supplier = getItem(position)
holder.bind(supplier, onItemClickListener)
/*holder.itemView.setOnClickListener {
onItemClickListener.accederDatosProveedor(item)
}*/
}
/*override fun getItemCount(): Int {
return data.size
}*/
class SupplierViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val codeTextView: TextView = itemView.findViewById(R.id.tvCode)
fun bind(supplier: Supplier, onItemClickListener: (String) -> Unit) {
codeTextView.text = supplier.codigoProv.toString()
// Configurar el clic en un elemento
itemView.setOnClickListener {
onItemClickListener(supplier.codigoProv.toString())
}
}
}
class SupplierDiffCallback : DiffUtil.ItemCallback<Supplier>() {
override fun areItemsTheSame(oldItem: Supplier, newItem: Supplier): Boolean {
return oldItem.codigoProv == newItem.codigoProv
}
override fun areContentsTheSame(oldItem: Supplier, newItem: Supplier): Boolean {
return oldItem == newItem
}
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/FifthActivity.kt | 1399832976 | package com.example.agenda
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
class FifthActivity : AppCompatActivity() {
// Creamos variables para editText y Buttons
lateinit var codigoCliente:EditText
lateinit var nombreCliente:EditText
lateinit var telefonoCliente: EditText
lateinit var direccionCliente: EditText
lateinit var insertarDatos: Button
lateinit var atras: Button
lateinit var listaClientes: Button
lateinit var myViewModel: MyViewModel
lateinit var customerAdapter: CustomersAdapter
//lateinit var peticionesDao: PeticionesDao
//lateinit var firebaseDatabase: FirebaseDatabase
//Creamos variable para referenciar nuestra base de datos
//lateinit var databaseReference: DatabaseReference
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fifth)
val customerRepository = CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository = SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
//customerAdapter = CustomersAdapter()
//Inicializamos variables para identificar los editText y Buttons del layout
codigoCliente = findViewById<EditText>(R.id.edtCodigoCliente)
nombreCliente = findViewById<EditText>(R.id.edtNombreCliente)
telefonoCliente = findViewById<EditText>(R.id.edtTelefonoCliente)
direccionCliente = findViewById<EditText>(R.id.edtDireccionCliente)
insertarDatos = findViewById<Button>(R.id.btnEnviarCliente)
atras = findViewById<Button>(R.id.btnAtrasFifth)
listaClientes = findViewById<Button>(R.id.btnListaClientes)
//firebaseDatabase = FirebaseDatabase.getInstance()
// Obtenemos la referencia a nuestra base de datos en Firebase
//databaseReference = firebaseDatabase!!.getReference("MyDatabase")
//Añadimos evento al botón insertarDatos
insertarDatos.setOnClickListener {
// Capturamos cadenas introducidas por usuario y las almacenamos en variables
var codigoCliente: String = codigoCliente.text.toString()
var nombreCliente: String = nombreCliente.text.toString()
var telefonoCliente: String = telefonoCliente.text.toString()
var direccionCliente: String = direccionCliente.text.toString()
myViewModel.existeCodigoCliente(codigoCliente).observeOnce(this, Observer { codigoExists ->
if (codigoExists) {
// Si el código ya existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(this@FifthActivity, "El código introducido ya existe en la base de datos.", Toast.LENGTH_SHORT).show()
}
else if (TextUtils.isEmpty(codigoCliente) || TextUtils.isEmpty(nombreCliente) || TextUtils.isEmpty(telefonoCliente) || TextUtils.isEmpty(direccionCliente)) {
// Si alguno de los campos está sin rellenar, lanzamos aviso al usuario para que los rellene todos.
Toast.makeText(this@FifthActivity, "Por favor, rellena todos los campos.", Toast.LENGTH_SHORT).show()
}
else {
//En caso contrario, llamamos al método que añadirá los datos introducidos a Firebase, y posteriormente dejamos en blanco otra vez todos los campos
insertarDatos(codigoCliente, nombreCliente, direccionCliente, telefonoCliente)
limpiarTodosLosCampos()
}
})
}
//Añadimos evento al boton masOpciones
listaClientes.setOnClickListener(){
val toCustomersList = Intent(this, ListCustomersActivity::class.java)
startActivity(toCustomersList)
}
//Añadimos evento al botón atras
atras.setOnClickListener{
val toThird = Intent(this, ThirdActivity::class.java)
startActivity(toThird)
}
}
private fun insertarDatos(codigo: String, nombre: String, direccion: String, telefono: String) {
val customer = Customer(codigoCli = codigo, nombreCli = nombre, direccionCli = direccion, telefonoCli = telefono)
myViewModel.insertCustomer(customer)
Toast.makeText(this@FifthActivity, "Datos guardados.", Toast.LENGTH_SHORT).show()
}
//Método que vuelve a dejar en blanco todos los campos del layout
fun limpiarTodosLosCampos(){
codigoCliente.setText("")
nombreCliente.setText("")
direccionCliente.setText("")
telefonoCliente.setText("")
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/FourthActivity.kt | 1693883033 | package com.example.agenda
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
class FourthActivity : AppCompatActivity() {
lateinit var myViewModel: MyViewModel
// Creamos variables para editText y Buttons
lateinit var nombreProveedor: EditText
lateinit var telefonoProveedor: EditText
lateinit var direccionProveedor: EditText
lateinit var codigoProveedor: EditText
lateinit var insertarDatos: Button
lateinit var atras: Button
lateinit var listaProveedores: Button
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fourth)
//Inicializamos variables para identificar los editText y Buttons del layout
codigoProveedor = findViewById<EditText>(R.id.edtCodigoProveedor)
nombreProveedor = findViewById<EditText>(R.id.edtNombreProveedor)
telefonoProveedor = findViewById<EditText>(R.id.edtTelefonoProveedor)
direccionProveedor = findViewById<EditText>(R.id.edtDireccionProveedor)
insertarDatos = findViewById<Button>(R.id.btnEnviarProveedor)
atras = findViewById<Button>(R.id.btnAtrasFourth)
listaProveedores = findViewById<Button>(R.id.btnListaProveedores)
val customerRepository = CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository = SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
//Añadimos evento al botón insertarDatos
insertarDatos.setOnClickListener {
// Capturamos cadenas introducidas por usuario y las almacenamos en variables
var codigoProveedor: String = codigoProveedor.text.toString()
var nombreProveedor: String = nombreProveedor.text.toString()
var telefonoProveedor: String = telefonoProveedor.text.toString()
var direccionProveedor: String = direccionProveedor.text.toString()
myViewModel.existeCodigoProveedor(codigoProveedor).observeOnce(this, Observer { codigoExists ->
if (codigoExists) {
// Si el código ya existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(this@FourthActivity, "El código introducido ya existe en la base de datos.", Toast.LENGTH_SHORT).show()
}
else if (TextUtils.isEmpty(codigoProveedor) || TextUtils.isEmpty(nombreProveedor) || TextUtils.isEmpty(telefonoProveedor) || TextUtils.isEmpty(direccionProveedor)) {
// Si alguno de los campos está sin rellenar, lanzamos aviso al usuario para que los rellene todos.
Toast.makeText(this@FourthActivity, "Por favor, rellena todos los campos.", Toast.LENGTH_SHORT).show()
}
else {
//En caso contrario, llamamos al método que añadirá los datos introducidos a Firebase, y posteriormente dejamos en blanco otra vez todos los campos
insertarDatos(codigoProveedor, nombreProveedor, direccionProveedor, telefonoProveedor)
limpiarTodosLosCampos()
}
})
}
//Añadimos evento al botón opcionesProveedor
listaProveedores.setOnClickListener{
val toListSuppliers = Intent(this, ListSuppliersActivity::class.java)
startActivity(toListSuppliers)
}
//Añadimos evento al botón atrás
atras.setOnClickListener{
val toThird = Intent(this, ThirdActivity::class.java)
startActivity(toThird)
}
}
private fun insertarDatos(codigo: String, nombre: String, direccion: String, telefono: String) {
val supplier = Supplier(codigoProv = codigo, nombreProv = nombre, direccionProv = direccion, telefonoProv = telefono)
myViewModel.insertSupplier(supplier)
Toast.makeText(this@FourthActivity, "Datos guardados.", Toast.LENGTH_SHORT).show()
}
//Método que vuelve a dejar en blanco todos los campos del layout
fun limpiarTodosLosCampos(){
codigoProveedor.setText("")
nombreProveedor.setText("")
direccionProveedor.setText("")
telefonoProveedor.setText("")
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
}
|
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/CustomersDetail.kt | 3692688796 | package com.example.agenda
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.Observer as Observer
class CustomersDetail : AppCompatActivity() {
lateinit var myViewModel: MyViewModel
lateinit var codigoCliente: EditText
lateinit var nombreCliente: EditText
lateinit var telefonoCliente: EditText
lateinit var direccionCliente: EditText
lateinit var eliminarCliente: Button
lateinit var modificarCliente: Button
lateinit var limpiar: Button
lateinit var atras: Button
lateinit var nombreAntiguo: String
lateinit var direccionAntigua: String
lateinit var telefonoAntiguo: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_customers_detail)
val customerRepository = CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository = SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
codigoCliente = findViewById(R.id.editText_codigo_cli)
nombreCliente = findViewById(R.id.editText_nombre_cli)
direccionCliente = findViewById(R.id.editText_direccion_cli)
telefonoCliente = findViewById(R.id.editText_telefono_cli)
eliminarCliente = findViewById(R.id.btn_Eliminar_cli)
modificarCliente = findViewById(R.id.btn_Modificar_cli)
atras = findViewById(R.id.btn_Atras_Lista_Cli)
eliminarCliente.setOnClickListener(){
eliminarCliente(this)
}
modificarCliente.setOnClickListener(){
modificarCliente(this)
}
atras.setOnClickListener(){
val intentListCustomers = Intent(this, ListCustomersActivity::class.java)
startActivity(intentListCustomers)
}
listarDatosCliente(this)
}
private fun listarDatosCliente(context: Context) {
val code = intent.getStringExtra("code").toString()
myViewModel.loadCustomerDetails(code)
myViewModel.customerDetails.observeOnce(this, Observer { customer ->
// Aquí actualizas tu interfaz de usuario con los detalles del cliente
// Puedes acceder a los campos de customer, por ejemplo, customer.nombre, customer.direccion, etc.
val nombre = customer.nombreCli
val direccion = customer.direccionCli
val telefono = customer.telefonoCli
codigoCliente.setText(code)
nombreCliente.setText(nombre)
direccionCliente.setText(direccion)
telefonoCliente.setText(telefono)
codigoCliente.isEnabled = false
nombreAntiguo = nombreCliente.text.toString()
direccionAntigua = direccionCliente.text.toString()
telefonoAntiguo = telefonoCliente.text.toString()
})
}
private fun eliminarCliente(context: Context) {
val alertDialog = AlertDialog.Builder(context)
val codigo = codigoCliente.text.toString()
myViewModel.existeCodigoCliente(codigo).observeOnce(this, Observer { codigoExists ->
if (!codigoExists) {
// Si el código no existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(this@CustomersDetail, "El código introducido no existe en la base de datos.", Toast.LENGTH_SHORT).show()
}
else {
alertDialog.apply {
setTitle("Advertencia")
setMessage("¿Está seguro que desea eliminar el cliente " + codigo + "?")
setPositiveButton("Aceptar") { _: DialogInterface?, _: Int ->
myViewModel.deleteCustomer(codigo)
limpiarTodosLosCampos()
volverAListaClientes()
Toast.makeText(
this@CustomersDetail,
"El cliente ha sido eliminado de la base de datos.",
Toast.LENGTH_SHORT
).show()
}
setNegativeButton("Cancelar") { _, _ ->
volverAListaClientes()
Toast.makeText(context, "Operación cancelada", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
})
}
private fun modificarCliente(context: Context) {
//databaseReference = firebaseDatabase!!.getReference("MyDatabase")
val alertDialog = AlertDialog.Builder(context)
val codigo = codigoCliente.text.toString()
val nombre = nombreCliente.text.toString()
val direccion = direccionCliente.text.toString()
val telefono = telefonoCliente.text.toString()
myViewModel.existeCodigoCliente(codigo).observeOnce(this, Observer { codigoExists ->
if (!codigoExists) {
// Si el código no existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(
this@CustomersDetail,
"El código introducido no existe en la base de datos.",
Toast.LENGTH_SHORT
).show()
} else if (TextUtils.isEmpty(nombre) || TextUtils.isEmpty(telefono) || TextUtils.isEmpty(direccion)) {
// Si alguno de los campos está sin rellenar, lanzamos aviso al usuario para que los rellene todos.
Toast.makeText(this@CustomersDetail, "Por favor, rellena todos los campos.", Toast.LENGTH_SHORT).show()
} else if(nombre==nombreAntiguo && direccion==direccionAntigua && telefono==telefonoAntiguo){
Toast.makeText(this@CustomersDetail, "No se ha modificado ningún campo.", Toast.LENGTH_SHORT).show()
} else {
alertDialog.apply {
setTitle("Advertencia")
setMessage("¿Está seguro que desea modificar el cliente " + codigo + "?")
setPositiveButton("Aceptar") { _: DialogInterface?, _: Int ->
myViewModel.updateCustomer(codigo, nombre, direccion, telefono)
Toast.makeText(this@CustomersDetail, "Registro actualizado correctamente.", Toast.LENGTH_SHORT).show()
limpiarTodosLosCampos()
volverAListaClientes()
}
setNegativeButton("Cancelar") { _, _ ->
volverAListaClientes()
Toast.makeText(context, "Operación cancelada", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
})
}
private fun limpiarTodosLosCampos(){
codigoCliente.setText("")
nombreCliente.setText("");
direccionCliente.setText("");
telefonoCliente.setText("");
}
private fun volverAListaClientes(){
val intentListCustomers = Intent(this, ListCustomersActivity::class.java)
startActivity(intentListCustomers)
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
}
|
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/Customer.kt | 1872738526 | package com.example.agenda
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Customer (
@PrimaryKey val codigoCli: String,
val nombreCli: String,
val direccionCli: String,
val telefonoCli: String
) |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/Supplier.kt | 2684412326 | package com.example.agenda
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Supplier (
@PrimaryKey val codigoProv: String,
val nombreProv: String,
val direccionProv: String,
val telefonoProv: String
)
|
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/SuppliersDetail.kt | 3458124970 | package com.example.agenda
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
class SuppliersDetail : AppCompatActivity() {
lateinit var myViewModel: MyViewModel
lateinit var codigoProveedor: EditText
lateinit var nombreProveedor: EditText
lateinit var telefonoProveedor: EditText
lateinit var direccionProveedor: EditText
lateinit var eliminarProveedor: Button
lateinit var modificarProveedor: Button
lateinit var limpiar: Button
lateinit var atras: Button
lateinit var nombreAntiguo: String
lateinit var direccionAntigua: String
lateinit var telefonoAntiguo: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_suppliers_detail)
val customerRepository = CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository = SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
codigoProveedor = findViewById(R.id.editText_codigo_prov)
nombreProveedor = findViewById(R.id.editText_nombre_prov)
direccionProveedor = findViewById(R.id.editText_direccion_prov)
telefonoProveedor = findViewById(R.id.editText_telefono_prov)
eliminarProveedor = findViewById(R.id.btn_Eliminar_Prov)
modificarProveedor = findViewById(R.id.btn_Modificar_Prov)
atras = findViewById(R.id.btn_Atras_Lista_Prov)
eliminarProveedor.setOnClickListener(){
eliminarProveedor(this)
}
modificarProveedor.setOnClickListener(){
modificarProveedor(this)
}
atras.setOnClickListener(){
val intentListSuppliers = Intent(this, ListSuppliersActivity::class.java)
startActivity(intentListSuppliers)
}
listarDatosProveedor(this)
}
private fun listarDatosProveedor(context: Context) {
val code = intent.getStringExtra("code").toString()
myViewModel.loadSupplierDetails(code)
myViewModel.supplierDetails.observeOnce(this, Observer { supplier ->
// Aquí actualizas tu interfaz de usuario con los detalles del cliente
// Puedes acceder a los campos de customer, por ejemplo, customer.nombre, customer.direccion, etc.
val nombre = supplier.nombreProv
val direccion = supplier.direccionProv
val telefono = supplier.telefonoProv
codigoProveedor.setText(code)
nombreProveedor.setText(nombre)
direccionProveedor.setText(direccion)
telefonoProveedor.setText(telefono)
codigoProveedor.isEnabled = false
nombreAntiguo = nombreProveedor.text.toString()
direccionAntigua = direccionProveedor.text.toString()
telefonoAntiguo = telefonoProveedor.text.toString()
})
}
private fun eliminarProveedor(context: Context) {
val alertDialog = AlertDialog.Builder(context)
val codigo = codigoProveedor.text.toString()
myViewModel.existeCodigoProveedor(codigo).observeOnce(this, Observer { codigoExists ->
if (!codigoExists) {
// Si el código no existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(this@SuppliersDetail, "El código introducido no existe en la base de datos.", Toast.LENGTH_SHORT).show()
}
else {
alertDialog.apply {
setTitle("Advertencia")
setMessage("¿Está seguro que desea eliminar el proveedor "+codigo+"?")
setPositiveButton("Aceptar") { _: DialogInterface?, _: Int ->
myViewModel.deleteSupplier(codigo)
limpiarTodosLosCampos()
volverAListaProveedores()
Toast.makeText(this@SuppliersDetail, "El proveedor ha sido eliminado de la base de datos.", Toast.LENGTH_SHORT).show()
}
setNegativeButton("Cancelar") { _, _ ->
volverAListaProveedores()
Toast.makeText(context, "Operación cancelada", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
})
}
private fun modificarProveedor(context: Context) {
val alertDialog = AlertDialog.Builder(context)
val codigo = codigoProveedor.text.toString()
val direccion = direccionProveedor.text.toString()
val nombre = nombreProveedor.text.toString()
val telefono = telefonoProveedor.text.toString()
myViewModel.existeCodigoProveedor(codigo).observeOnce(this, Observer { codigoExists ->
if (!codigoExists) {
// Si el código no existe en la base de datos, lanzar mensaje de aviso al usuario
Toast.makeText(this@SuppliersDetail, "El código introducido no existe en la base de datos.", Toast.LENGTH_SHORT).show()
}
else if (TextUtils.isEmpty(nombre) || TextUtils.isEmpty(telefono) || TextUtils.isEmpty(direccion)) {
// Si alguno de los campos está sin rellenar, lanzamos aviso al usuario para que los rellene todos.
Toast.makeText(this@SuppliersDetail, "Por favor, rellena todos los campos.", Toast.LENGTH_SHORT).show()
}
else if(nombre==nombreAntiguo && direccion==direccionAntigua && telefono==telefonoAntiguo){
Toast.makeText(this@SuppliersDetail, "No se ha modificado ningún campo.", Toast.LENGTH_SHORT).show()
}
else{
alertDialog.apply {
setTitle("Advertencia")
setMessage("¿Está seguro que desea modificar el proveedor "+codigo+"?")
setPositiveButton("Aceptar") { _: DialogInterface?, _: Int ->
myViewModel.updateSupplier(codigo, nombre, direccion, telefono)
Toast.makeText(this@SuppliersDetail, "Registro actualizado correctamente.", Toast.LENGTH_SHORT).show()
limpiarTodosLosCampos()
volverAListaProveedores()
}
setNegativeButton("Cancelar") { _, _ ->
volverAListaProveedores()
Toast.makeText(context, "Operación cancelada", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
})
}
private fun limpiarTodosLosCampos(){
codigoProveedor.setText("")
nombreProveedor.setText("");
direccionProveedor.setText("");
telefonoProveedor.setText("");
}
private fun volverAListaProveedores(){
val intentListSuppliers = Intent(this, ListSuppliersActivity::class.java)
startActivity(intentListSuppliers)
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/SecondActivity.kt | 3422529127 | package com.example.agenda
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
// Recoge el Intent que ha iniciado la actividad
val intent = getIntent()
val proveedor = findViewById<TextView>(R.id.nombreProveedor)
val cliente = findViewById<TextView>(R.id.nombreCliente)
val b: Bundle? = intent.getExtras()
if (b != null) {
val prov = b.get("proveedor") as String
val cl = b.get("cliente") as String
proveedor.setText(prov)
cliente.setText(cl)
}
intent.putExtra("pregunta", "How are you?");
Log.d("MENSAJES", "actualizado intent")
intent.putExtra("hecho", "Done!");
Log.d("MENSAJES", "actualizado intent")
setResult(Activity.RESULT_OK, intent);
Log.d("MENSAJES", "actualizado resultado")
val btnGoFirst = findViewById<Button>(R.id.btnGoFirst)
btnGoFirst.setOnClickListener{
finish()
}
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/ListSuppliersActivity.kt | 3215101599 | package com.example.agenda
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
class ListSuppliersActivity : AppCompatActivity(){
private lateinit var recyclerView: RecyclerView
lateinit var myViewModel: MyViewModel
lateinit var supplierAdapter: SuppliersAdapter
private lateinit var atras: Button
private lateinit var textViewNombre: TextView
private lateinit var nombreProveedor: EditText
private lateinit var ok: Button
private lateinit var buscarProvPorNombre: Button
private lateinit var volverListaProv: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_suppliers)
textViewNombre = findViewById(R.id.textView_nombreProv)
nombreProveedor = findViewById(R.id.editTextNombreProv)
ok = findViewById(R.id.btnOkProv)
volverListaProv = findViewById(R.id.btnVolverListaProv)
textViewNombre.visibility = View.GONE
nombreProveedor.visibility = View.GONE
ok.visibility = View.GONE
volverListaProv.visibility = View.GONE
val customerRepository = CustomerRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val supplierRepository = SupplierRepository(AgendaDatabase.getInstance(applicationContext).peticionesDao())
val factory = MyViewModelFactory(customerRepository, supplierRepository)
myViewModel = ViewModelProvider(this, factory).get(MyViewModel::class.java)
val onItemClickListener: (String) -> Unit = { code ->
// Manejar el clic en un elemento para abrir una nueva pantalla con detalles
val intent = Intent(this, SuppliersDetail::class.java)
intent.putExtra("code", code)
startActivity(intent)
}
supplierAdapter = SuppliersAdapter(onItemClickListener)
recyclerView = findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = supplierAdapter
atras = findViewById(R.id.btnAtrasRegistroProveedores)
atras.setOnClickListener(){
val toFourth = Intent(this, FourthActivity::class.java)
startActivity(toFourth)
}
buscarProvPorNombre = findViewById(R.id.findSupplierByName)
buscarProvPorNombre.setOnClickListener(){
recyclerView.visibility = View.GONE
atras.visibility = View.GONE
buscarProvPorNombre.visibility = View.GONE
textViewNombre.visibility = View.VISIBLE
nombreProveedor.visibility = View.VISIBLE
ok.visibility = View.VISIBLE
volverListaProv.visibility = View.VISIBLE
}
ok.setOnClickListener(){
val nombre = nombreProveedor.text.toString()
if(TextUtils.isEmpty(nombre)){
mostrarToastEnLaMitadDeLaPantalla("Por favor, introduzca un nombre.")
}else{
myViewModel.loadSupplierByName(nombre)
myViewModel.supplier.observeOnce(this, Observer { suppliers ->
supplierAdapter.setSuppliers(suppliers)
})
textViewNombre.visibility = View.GONE
nombreProveedor.visibility = View.GONE
ok.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
myViewModel.viewModelScope.launch{
if(myViewModel.obtenerNumeroProveedoresPorNombre(nombre)==0){
mostrarToastEnLaMitadDeLaPantalla("No existe ningún proveedor con ese nombre en la base de datos.")
}
}
}
}
volverListaProv.setOnClickListener(){
myViewModel.loadSuppliers()
myViewModel.suppliers.observeOnce(this, Observer { suppliers ->
supplierAdapter.setSuppliers(suppliers)
})
textViewNombre.visibility = View.GONE
nombreProveedor.visibility = View.GONE
ok.visibility = View.GONE
volverListaProv.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
atras.visibility = View.VISIBLE
buscarProvPorNombre.visibility = View.VISIBLE
}
myViewModel.loadSuppliers()
myViewModel.suppliers.observeOnce(this, Observer { suppliers ->
supplierAdapter.setSuppliers(suppliers)
})
myViewModel.viewModelScope.launch {
if (myViewModel.obtenerNumeroProveedores()==0) {
mostrarToastEnLaMitadDeLaPantalla("No existe ningún proveedor en la base de datos")
}
}
}
private fun mostrarToastEnLaMitadDeLaPantalla(mensaje: String) {
val inflater: LayoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val layout = inflater.inflate(R.layout.custom_toast_layout, findViewById(R.id.custom_toast_root))
// Crea un objeto Toast personalizado con la vista personalizada
val toast = Toast(applicationContext)
toast.setGravity(Gravity.CENTER, 0, 0)
toast.duration = Toast.LENGTH_SHORT
toast.view = layout
layout.findViewById<TextView>(R.id.custom_toast_text).text = mensaje
// Muestra el Toast personalizado
toast.show()
}
fun <T> LiveData<T>.observeOnce(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner, object : Observer<T> {
override fun onChanged(t: T) {
observer.onChanged(t)
removeObserver(this)
}
})
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/AgendaDatabase.kt | 509616633 | package com.example.agenda
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Customer::class, Supplier::class], version = 1)
abstract class AgendaDatabase : RoomDatabase() {
abstract fun peticionesDao(): PeticionesDao
companion object {
private var instance: AgendaDatabase? = null
fun getInstance(context: Context): AgendaDatabase {
if (instance == null) {
synchronized(AgendaDatabase::class) {
instance = Room.databaseBuilder(
context.applicationContext,
AgendaDatabase::class.java,
"app_database"
).build()
}
}
return instance!!
}
}
} |
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/CustomerRepository.kt | 3880953482 | package com.example.agenda
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
class CustomerRepository (private val peticionesDao: PeticionesDao) {
suspend fun insertCustomer(c: Customer) {
peticionesDao.insertCustomer(c)
}
suspend fun getAllCustomers(): List<Customer> {
return peticionesDao.getAllCustomers()
}
suspend fun getCustomerDetails(customerId: String): Customer {
return peticionesDao.getCustomerById(customerId)
}
suspend fun getCustomerByName(customerName: String): List<Customer>{
return peticionesDao.getCustomerByName(customerName)
}
suspend fun deleteCustomerById(customerId: String){
peticionesDao.deleteCustomerById(customerId)
}
suspend fun updateCustomerById(codigo: String, nuevoNombre: String, nuevaDireccion: String, nuevoTelefono: String) {
peticionesDao.updateCustomerById(codigo, nuevoNombre, nuevaDireccion, nuevoTelefono)
}
fun isCodigoCustomerExists(codigo: String): LiveData<Boolean> {
return peticionesDao.isCodigoCustomerExists(codigo)
}
suspend fun obtenerNumeroClientes(): Int {
return peticionesDao.getNumberOfCustomers()
}
suspend fun obtenerNumeroClientesPorNombre(nombre: String): Int {
return peticionesDao.getNumberOfCustomersByName(nombre)
}
}
|
MiAgenda-Room2.0/app/src/main/java/com/example/agenda/CustomersAdapter.kt | 500358154 | package com.example.agenda
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
class CustomersAdapter(private val onItemClickListener: (String) -> Unit) :
ListAdapter<Customer, CustomersAdapter.CustomerViewHolder>(CustomerDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomerViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.list_item_customers, parent, false)
return CustomerViewHolder(itemView)
}
fun setCustomers(customers: List<Customer>) {
submitList(customers.toMutableList())
}
override fun onBindViewHolder(holder: CustomerViewHolder, position: Int) {
val customer = getItem(position)
holder.bind(customer, onItemClickListener)
}
/*override fun getItemCount(): Int {
return data.size
}*/
class CustomerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val codeTextView: TextView = itemView.findViewById(R.id.tvCode)
fun bind(customer: Customer, onItemClickListener: (String) -> Unit) {
codeTextView.text = customer.codigoCli.toString()
// Configurar el clic en un elemento
itemView.setOnClickListener {
onItemClickListener(customer.codigoCli.toString())
}
}
}
class CustomerDiffCallback : DiffUtil.ItemCallback<Customer>() {
override fun areItemsTheSame(oldItem: Customer, newItem: Customer): Boolean {
return oldItem.codigoCli == newItem.codigoCli
}
override fun areContentsTheSame(oldItem: Customer, newItem: Customer): Boolean {
return oldItem == newItem
}
}
} |
AndroidSt_Calculator/app/src/androidTest/java/com/example/ivanov_calc/ExampleInstrumentedTest.kt | 11733635 | package com.example.ivanov_calc
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.ivanov_calc", appContext.packageName)
}
} |
AndroidSt_Calculator/app/src/test/java/com/example/ivanov_calc/ExampleUnitTest.kt | 3807935432 | package com.example.ivanov_calc
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)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.