content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
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/theme/Type.kt | 1391392015 |
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/NotesListViewModel.kt | 2279328433 |
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/NoteItem.kt | 1418199878 |
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/NotesData.kt | 962195016 |
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/components/FabButton.kt | 3452714091 |
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/notes_list/NotesListScreen.kt | 2253408553 |
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/MyNavHost.kt | 1052085738 |
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/MainActivity.kt | 1386308327 |
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/ui/base/BaseApp.kt | 3096008954 |
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/di/Koin.kt | 4276514258 |
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/repository/NotesRepositoryImpl.kt | 383752228 |
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/AppDatabase.kt | 2001390309 |
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/data_source/NotesTableDao.kt | 2763915495 |
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/data/model/NotesTable.kt | 4166693879 |
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/repository/NotesRepository.kt | 150842578 |
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/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
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/GetNotesUseCase.kt | 3794659363 |
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/AddNoteUseCase.kt | 4069361084 |
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)
}
} | NotesCompose/app/src/main/java/com/example/testingproject/domain/usecases/DeleteNoteUseCase.kt | 2677961681 |
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/androidTest/java/com/example/auth0example1/ExampleInstrumentedTest.kt | 2436004411 |
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/test/java/com/example/auth0example1/ExampleUnitTest.kt | 892888569 |
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/ViewModel/MainViewModel.kt | 1994514954 |
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/Color.kt | 3020705882 |
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/Theme.kt | 3420392892 |
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/ui/theme/Type.kt | 3593668654 |
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/UserInfoRow.kt | 2280035855 |
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/MainActivity.kt | 791207939 |
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/LogButton.kt | 2778247855 |
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/Model/User.kt | 2453552518 |
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/MainView.kt | 4123864572 |
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),
)
}
} | android-jc-auth0-sample/app/src/main/java/com/example/auth0example1/UserPicture.kt | 2870866267 |
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/androidTest/java/com/graduate/work/sporterapp/ExampleInstrumentedTest.kt | 2040210395 |
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)
}
} | SporterApp/app/src/test/java/com/graduate/work/sporterapp/ExampleUnitTest.kt | 2797727041 |
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/androidTest/java/com/example/agenda/ExampleInstrumentedTest.kt | 4253196848 |
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/test/java/com/example/agenda/ExampleUnitTest.kt | 4241411300 |
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/MyViewModelFactory.kt | 869848476 |
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/ListCustomersActivity.kt | 1500176544 |
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/ThirdActivity.kt | 3662639184 |
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/SupplierRepository.kt | 2317037374 |
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/MainActivity.kt | 3119737324 |
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/PeticionesDao.kt | 2680613161 |
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/MyViewModel.kt | 3542837613 |
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/SuppliersAdapter.kt | 2617438383 |
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/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 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/FourthActivity.kt | 1693883033 |
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/CustomersDetail.kt | 3692688796 |
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/Customer.kt | 1872738526 |
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/Supplier.kt | 2684412326 |
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/SuppliersDetail.kt | 3458124970 |
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/SecondActivity.kt | 3422529127 |
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/ListSuppliersActivity.kt | 3215101599 |
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/AgendaDatabase.kt | 509616633 |
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/CustomerRepository.kt | 3880953482 |
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
}
}
} | MiAgenda-Room2.0/app/src/main/java/com/example/agenda/CustomersAdapter.kt | 500358154 |
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/androidTest/java/com/example/ivanov_calc/ExampleInstrumentedTest.kt | 11733635 |
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)
}
} | AndroidSt_Calculator/app/src/test/java/com/example/ivanov_calc/ExampleUnitTest.kt | 3807935432 |
package com.example.ivanov_calc
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | AndroidSt_Calculator/app/src/main/java/com/example/ivanov_calc/MainActivity.kt | 681265143 |
/***** Interface resolve conflict *****/
interface A{
fun callMe(){
println("From interface A")
}
}
interface B {
fun callMe(){
println("From interface B")
}
}
class C:A,B{
override fun callMe() {
super<A>.callMe()
super<B>.callMe()
}
}
fun main() {
val obj = C()
obj.callMe()
} | MyKotlinNotes/src/Ch15.kt | 574656394 |
/****** Inheritance with Primary and Secondary Constructor with overriding *******/
open class Father2(_car: String, _money: Int) {
// Properties
open var car: String = _car
var money: Int = _money
// Member Function
open fun disp() {
println("Father Class Disp")
}
}
class Son2 : Father2 {
// Properties
var bike: String
override var car:String = "BMW" // Overriding Properties of father
var fcar:String = super.car
// Secondary Constructor
constructor(_car: String, _money: Int, _bike: String) : super(_car, _money) {
this.bike = _bike
}
// Member Function
fun show() {
println("Son bike: $bike")
println("Son car: $car")
println("Father car: $fcar")
println("Father Money: $money")
}
override fun disp (){
println("Son Class Disp")
}
}
fun main() {
println("*********")
// Using the secondary constructor
val s1 = Son2("Alt 100", 1000, "K10")
s1.show()
s1.disp()
println("*********")
val f1 = Father2("ZLX Super",5000)
f1.disp()
}
| MyKotlinNotes/src/Ch11.kt | 905894744 |
import java.util.Scanner
/*
Main Function
An entry point of a kotlin application is the main function
*/
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
//fun main() {
// println("Hello, Kotlin !")
//}
fun main(array: Array<String>) {
// var - Variables that can be reassigned
// Dynamic Type
// var roll = 10 //Integer
// var mobilenumber = 9000L //Long
// var price = 83.12f //float
// var totalcost = 6324.3215 //double
// var gender = 'F' //char
// var name = "Vivek" //string
// var isActive = true //boolean
println("Hello, Kotlin !")
// println(roll)
// println(mobilenumber)
// roll = 125
// mobilenumber = 9876543210
// println("*** value reassigned ***")
// println(roll)
// println(mobilenumber)
// variable()
// value()
// add()
// arithemeticOperations()
// comparisonOperations()
//// userInput()
// stringOperations()
// conditionalOperations()
// loops()
// val multi = multi(b=10,a=20) // function with named arguments
// println(multi)
//
// h0F(12,15, :: add) // calling higher order function
//
// val addl = { a:Int, b:Int -> a + b} // Lambda expression
// println(addl(20,30))
//
// val addl2:(Int,Int)-> Int = {a,b -> a+b} // Lambda expression
// println(addl2(12,28))
//
// h0F(10,20) { a: Int, b: Int -> a + b } // Higher order function with Lambda Expressions
//
// val sum = fun( a:Int, b:Int):Int{ return a+b}
// println(sum(22,32))
// nullSafety()
// arrays()
// lists()
// sets()
// maps()
}
/**** Function - Kotlin functions are declared using the fun keyword ****/
// Functions are with and without parameters
fun variable(){
// Spesific data Type
var roll:Int = 10 //Integer
var mobilenumber:Long = 9990000000L //Long
var price:Float = 83.12f //float
var totalcost:Double = 6324.3215 //double
var gender:Char = 'F' //char
var name:String = "Vivek" //string
var isActive:Boolean = true //boolean
println(roll)
println(mobilenumber)
roll = 125
println("*** Integer Value only can be assigned to roll number ***")
println(roll)
}
fun value(){
// val can't be reassigned
val roll = 123
val mobile = 9638527410
val price:Float = 83.12f
println("Printing the val assigned data types...")
println(roll)
println(mobile)
println(price)
}
fun add(){
println("** Printing the values **")
println(" Hello Vivek ")
val a = 12
val b = 20
println(" Hello "+a)
println(" Hello $a")
println(" Addition of $a + $b")
println(" Addition is ${a+b}")
}
fun arithemeticOperations(){
println(" ** Arithemetic Operations **")
val a = 5
val b = 2
val addition = a + b
println("Addition "+ addition)
print("Difference is ")
println(a-b)
println("Multiplication is ${a*b}")
println(b..a)
print("Range is ")
for (i in b..a)
print(i)
println()
}
fun comparisonOperations(){
var a = 5
val b = 3
val c = 5
println("*** Printing the Comparison operations ***")
println(a > b)
println(a != b)
println( (a>b) && (a<c) )
// Increment and decrement operatora
println(++a)
println(a--)
// assigment operator
a+=5
println(a)
}
fun userInput(){
print("Enter your name: ")
val name: String? = readLine()
print("Enter your roll: ")
val roll = readLine()!!.toInt()
println("Name: $name")
println("Roll: $roll")
println(name!!::class.simpleName)
println(roll::class.simpleName)
val scanner = Scanner(System.`in`)
print("Enter your branch: ")
val branch = scanner.next()
println("Branch: $branch")
println(name::class.simpleName)
print("Enter the fees: ")
val fee = scanner.nextFloat()
println("Fee is $fee")
}
fun stringOperations(){
/*
Strings ara immutable. Once you initialize a string, you can't change the value or assign a new value to it. All operations that transform strings return their results in an new String object, leaving the original string unchanged.
*/
val str = "Hello"
val str2 = " Kotlin"
print(str)
print(str[1])
println("\nThis is "+ str + str2 + 50)
//String Literals
println("Hello\t World")
//Raw String
val message = """ Dear Sir/Madam,
I would like to request you kindly recheck my exam
copy and reevaluate the marks.
""".trimMargin()
print(message)
//String Template
val str3 = "Kotlin"
val cart = 50
val quantity = 3
println("\nThis is ${str3.uppercase()}, your cart value is $cart. \nand total price is: $cart * $quantity = ${cart*quantity}")
}
fun conditionalOperations(){
val a = 10
val b = 15
var max = 0
if (a < b){
println("This is IF Expressions")
}
// if(a>b) max = a
// else max = b
max = if(a>b) a else b
println("Max expressions is $max")
if (a>b) println("\nThis is If statement: , $a")
else println("This is else statement: , $b")
// Other Method for If-else statement
max = if(a>b){
a
} else{
b
}
println(max)
//**** When Expression ****
print("Enter the number: ")
val x = readlnOrNull()?.toInt()
when(x){
1 -> print("One")
2 -> print("Two")
3 -> print("Three")
4,5 -> print("Four or Five")
in 6..8 -> {
print("Six ")
print("or Seven ")
print("or Eight")
}
else -> print("Not Valid")
}
when("Monday"){
"Sunday" -> println("Holiday")
"Monday" -> println("Workday")
}
}
fun loops(){
/**** for loop ****/
// Syntax :- for ( item in collection ) print ( item)
for( item in 1..5) println(item)
for( item in 5 downTo 1){
print("Step: ")
println(item)
}
/**** while loop ****/
var x = 0
while (x<5){
x++
println(x)
}
// while(true){
// println("Always True")
// }
/**** do while ****/
do{
x++
println(x)
} while (x < 5)
// do{
// println("Always True")
// } while (true)
/**** Break and Continue ****/
while (x<10){
x++
if (x == 5) continue
if (x == 8) break
println(x)
}
}
fun multi(a:Int,b:Int=5): String{ // Funtion with return type, arguments and default value of arguments
return("Multiplication of $a and $b is: ${a*b}")
}
fun add (a:Int, b:Int= 10): Int{
return a+b
}
// higher order function
fun h0F(a:Int, b:Int, callback:(Int, Int)-> Int){
println(callback(a,b))
}
fun nullSafety(){
/****** Null Safety ******/
var name1:String = "Sonal"
// name1 = null // Not Allowed
var name2:String? = "Rahul Kumar"
name2 = null // Allowed
println(name1.length) // will not work on null variable
println(if(name2 !=null)name2.length else -1) // Option 1
println(name2?.length) // Option 2 : Safe Call
// println(name2!!.length) // Option 3: The !! Operator : Throws exception if null
}
fun arrays(){
/***** Array ******/
val names = arrayOf("Sonam","Rahul","Gaurav", 399,'M')
names.forEach {name -> println(name) }
val num = arrayOf<Int>(20,399,21) // array of integers
num[1]= 25 // updating the value of index
num.set(0,22) // set method for setting in the indexes
for (i in num.indices){
println("In Index $i = ${num[i]}")
}
println(num.size)
println(names.get(0)) //get method
/***** Array Constructor*****/
val roll1 = Array(5,{ i -> i*2})
for (rl in roll1){
println(rl)
}
/****** Built-in Methods ******/
val roll2 = intArrayOf(101,102,103)
for (rl in roll2){
println(rl)
}
val gender2 = charArrayOf('M','F')
/******** User Input Array ********/
print("Enter Number of Student: ")
val num3 = readln().toInt()
println("The Student Name: ")
val students = Array(num3) { readln() }
for (student in students){
println(student)
}
}
fun lists(){
/********* List *********/
// List is an ordered collection with access to elements by indices - integer numbers that reflect position. Elements can occur more than once in a list.
val data = listOf("Sonam", "Sumit", 100, 'M',"Sonam")
println(data) // All values in a list are printed but this will not in case of Array
println("${data.get(0)} and Size: "+data.size)
// data[0] = "Sona" //cannot add or modify to this List i.e. Immutable
data.indices.forEach{dt -> print("$dt = ${data[dt]}\t")} // printing using for loop and indices
val data2 = listOf<String>("Sonal","Sonam","Soan","Sona", 20.toString())
val s = data2.size
for (i in 0..s-1){
println("$i = ${data2[i]}")
}
/**** Mutable List ****/
val data3 = mutableListOf(40,"Sonal","Sonam","Soan","Sona")
data3[0]="Sonu" // updating the list
data3.add(data3.size,"Solution") // adding in the list
data3.removeAt(1) // removing the data
data3.forEach{dt -> println(dt) }
/**** User Input List ****/
print("Enter Number of Student: ")
val nd4 = readln().toInt()
println("The Student Name: ")
val data4 = List<String>(nd4) { readln() }
for (student in data4){
println(student)
}
}
fun sets(){
/******* Set *******/
// Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the order of set elements has no significance. also there is no index in sets
val data5 = mutableSetOf("Sonam","Rahul", "Sonam", "Sumit","Rahul",20,50) // SetOf can also be used for immutable set
println("Data is: "+data5 +" and size is: "+ data5.size) // It will print after removing all the duplicates
data5.add("Saurav")
data5.remove("Sonam")
println(data5)
}
fun maps(){
/***** Map or Dictionary *****/
// Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee's ID and their positions.
val data6 = mapOf(1 to "Sonal", "key2" to "Sumit", "key3" to "Rahul", 4 to 100)
print("Size: "+data6.size+", Values: "+data6)
println(data6.get(5))
data6.forEach{dt -> print("Key: "+dt.key+", "); print("Value: "+dt.value+ " \n") }
val data7 = mutableMapOf<Int,String>(1 to "Abhi", 2 to "Raj", 3 to "Kallu", 4 to "Shyam")
data7[2] = "Raju" // update
data7.put(1, "Abhiraj") // update
data7.put(5,"Kavalya") //add
data7.remove(3) //remove
data7.keys.remove(4) // can be removed on the basis of either keys or values
println(data7)
}
| MyKotlinNotes/src/Ch1.kt | 3212940844 |
/******* Inheritance with Primary Constructor *******/
open class Father1(_car:String, _money:Int){
// Properties
var car:String = _car
var money:Int = _money
// Member Function
fun disp(){
println("Father Car: $car")
println("Father Money: $money")
}
}
class Son1(_car: String, _money: Int, _bike:String):Father1(_car,_money){
// Properties
var bike:String = _bike
// Member Function
fun show(){
println("Son bike: $bike")
}
}
fun main() {
println("*********")
val s1 = Son1("Alt 100",1000,"K10")
s1.show()
// s1.car = "ZSV"
// s1.money = 8000
s1.disp()
println("*********")
} | MyKotlinNotes/src/Ch10.kt | 376030567 |
// Secondary Constructor
class People{
// Properties
var gender:String = "Female"
var name: String
var hAge: Int
constructor(name:String, age: Int){
println("Secondary Constructor Called")
this.name = name
hAge = age
}
// Member Function
fun disp(){
println("Name = $name")
println("Age = $hAge")
println("Gender = $gender")
}
}
fun main(){
val p1 = People("Sonam",28)
p1.disp()
} | MyKotlinNotes/src/Ch5.kt | 2856020050 |
/***** Interface *****/
interface Father5 {
//Properties
var car:String //by default Abstract Property: cannot be initialized in interface class
//Member Function
fun disp(){
println("Father Car: $car")
}
fun hello() //Abstract Method
}
class Son5: Father5{
//Properties
var bike:String = "K10"
// Member Function
fun show(){
println("Son's Member Function")
}
// Implementing Father's Abstract Property
override var car: String = "Alt 100"
// Implementing Father's Abstract Method
override fun hello() {
println("Father's Abstract Method Hello")
}
}
fun main() {
val s1= Son5()
s1.show()
s1.disp()
s1.hello()
// val f1 = Father5() // Object of Interface cann't be created
} | MyKotlinNotes/src/Ch14.kt | 1523953790 |
/****** Class and Object ******/
// Creating Class
class Mobile{
// Properties
var model : String = "LG 100K"
var price : Float = 1233.50F
// Member Function
fun disp(){
println("Model = $model")
println("Price = $price")
}
}
fun main(){
val lg = Mobile() // Creating Object
lg.model = "LG K38" // Assessing Properties using Object
lg.price = 3999.60f // Accessing Properties using Object
lg.disp() // Calling Function Member using Object
val realme = Mobile() // Creating another Object
realme.model = "Real 10t"
realme.price = 11000f
realme.disp()
} | MyKotlinNotes/src/Ch2.kt | 261186507 |
/******* Abstract Class and Abstract Method ******/
//5:56:30
//Abstract classes are by default open
abstract class Father4{
// Properties
var car: String = "Alt 100"
// Member Function
fun disp(){
println("Father car: $car")
}
//Abstract Method
abstract fun hello()
}
class Son4:Father4(){
// Member Function
fun show(){
println("Father car: $car")
}
override fun hello() { //Override is used to rewrite the inherited function
println("Father's Abstract Method Hello! ")
}
}
fun main() {
val s1= Son4()
s1.show()
s1.disp()
s1.hello()
} | MyKotlinNotes/src/Ch13.kt | 325562403 |
/******* Constructor ******/
// Primary & Secondary Constructor
class Registration(email:String, password:String){
// Properties
var hName:String = ""
var hAge:Int? = null
var hEmail:String = email
var hPassword:String
var gender:String = "Female"
// Secondary Constructor
constructor(name:String, age:Int, email: String, password: String):this(email,password){
hName = name
hAge = age
}
// Initializer Block
init {
hPassword = password
}
// Member Function
fun disp(){
println("Name = $hName")
println("Age = $hAge")
println("Email = $hEmail")
println("Password = $hPassword")
println("Gender = $gender")
}
}
fun main() {
val user1 = Registration("Aashu",21,"[email protected]","123456")
user1.disp()
} | MyKotlinNotes/src/Ch6.kt | 2511556182 |
fun main() {
val result = try {
val a = 10/0
a
}catch (e:Exception){
e.message
} finally {
println("Finally Always Executes")
}
println(result)
} | MyKotlinNotes/src/Ch17.kt | 330533819 |
/******* Constructor ******/
// Primary & Secondary Constructor
class Registration2(_email:String, _password:String){
// Properties
var name:String = ""
var age:Int? = null
var email:String = _email
var password:String
var gender:String = "Female"
// Secondary Constructor
constructor(name:String, age:Int, _email: String, _password: String):this(_email,_password){
this.name = name
this.age = age
}
// Initializer Block
init {
this.password = _password
}
// Member Function
fun disp(){
println("Name = $name")
println("Age = $age")
println("Email = $email")
println("Password = $password")
println("Gender = $gender")
}
}
fun main() {
val user1 = Registration2("Aashu",21,"[email protected]","123456")
user1.disp()
} | MyKotlinNotes/src/Ch7.kt | 93765279 |
/***** Data Class *****/
// Where you need to create a class solely to hold data
data class Employee(val name:String, val age:Int)
fun main() {
val emp = Employee("Sonam", 26)
println("Name: ${emp.name}")
println(emp.toString())
// Destructuring
val(name, age) = emp
println("Name: $name")
println("Age: $age")
} | MyKotlinNotes/src/Ch16.kt | 2430976629 |
/****** Constructor ******/
// Primary Constructor
class Person constructor(val name:String, val age:Int) {
// Properties
var gender: String = "Female"
// Member Function
fun disp() {
println("Name = $name")
println("Age = $age")
println("Gender = $gender")
}
}
class Human (name: String, age: Int){
// Properties
var hName: String
var hAge: Int = age
var gender: String = "Female"
// Initializer Block
init {
hName = name
}
// Member Function
fun disp(){
println("Name = $hName")
println("Age = $hAge")
println("Gender = $gender")
}
}
fun main (){
val p1 = Person("Sonam", 27)
p1.disp()
val p2 = Person("Rahul", 20)
p2.gender = "Male"
println(p2.name)
println(p2.age)
println(p2.gender)
val h1 = Human("Sonal", 26 )
h1.disp()
val h2 = Human("Rani", 20 )
h2.disp()
} | MyKotlinNotes/src/Ch3.kt | 427471244 |
/******* Visibility Modifiers *******/
/*
* private means visible inside this class only (including all its members).
* protected is the same as private but is also visible in subclasses.
* internal means that any client inside this module who seed the declaring class sees its internal members.
* public means that any client who sees the declaring class sees its public members.
* */
open class Father3{
// Properties
private var a:Int = 10 // private can be access inside this class only
protected var b:Int = 20 // protected can be used inside inherited classes only
internal var c: Int = 30 // internal can be accessed inside this module only
var d: Int = 40 // public can be accessed from anywhere
// Member Function
fun disp(){
println("A: $a")
println("B: $b")
println("C: $c")
println("D: $d")
}
fun hello(){
println("Hello Father !")
}
}
class Son3:Father3(){
// Properties
var bike:String = "K 10"
// Member Function
fun show(){
// println("A: $a") // cannot be access as it is private
println("B: $b") // protected can be used inside inherited classes only
println("C: $c")
println("D: $d")
hello()
}
}
fun main() {
val s1 = Son3()
s1.show()
// s1.a = 100 // cannot be access as it is private
// s1.b = 101 // protected can be used inside inherited classes only
s1.c = 102 // internal can be accessed inside this module only
s1.d = 103
s1.disp()
s1.hello()
val f1 = Father3()
// f1.a = 110 // can't be accessed as it is private
// f1.b = 111 // can't be accesses as it is protected
f1.c = 123
}
//class Father3 private constructor(a:Int){....} //constructor keyword must be used if using visibility modifier in primary constructor
| MyKotlinNotes/src/Ch12.kt | 2605057291 |
/****** Getter and Setter ******/
class User(_id:Int, _name:String, _age:Int){
val id:Int = _id
get() = field
var name:String = _name
get() = field
set(value) {
field = value
}
var age:Int = _age
get() = field
set(value){
field = value
}
}
fun main() {
val u1 = User(1,"Sonam", 27)
println("Id: "+u1.id+" Name: "+u1.name+" Age: "+u1.age) // get Property
u1.name = "Roshni"
u1.age = 23
println(u1.name)
println(u1.age)
} | MyKotlinNotes/src/Ch8.kt | 3939561779 |
package com.company.utils
import com.company.services.openingyt as op
fun openingyt(){
println("Opened function from util package")
}
fun main() {
openingyt()
op()
} | MyKotlinNotes/src/com/company/utils/ut.kt | 262039424 |
package com.company.services
fun openingyt(){
println("Opened function from services package")
} | MyKotlinNotes/src/com/company/services/openyt.kt | 1336070095 |
/******* Inheritance *******/
open class Father{
// Properties
var car:String = "Alt 100"
var money:Int = 10000
// Member Function
fun disp(){
println("Father Car: $car")
println("Father Money: $money")
}
}
class Son:Father(){
// Properties
var bike:String = "K 20"
// Member Function
fun show(){
println("Son bike: $bike")
}
}
class Daughter : Father(){
// Properties
var bike:String = "KT9"
fun show(){
println("Daughter bike: $bike")
}
}
fun main() {
println("*********")
val f1 = Father()
f1.disp()
println("*********")
val s1 = Son()
s1.show()
s1.car = "ZSV"
s1.money = 8000
s1.disp()
println("*********")
val d1 = Daughter()
d1.show()
d1.disp()
// 5:20:30
} | MyKotlinNotes/src/Ch9.kt | 4003778196 |
/***** Calling Java from Kotlin (MyJava) *****/
/***** Calling Kotlin from Java (MyJava) *****/
fun main() {
val obj = MyJava()
obj.setValue(10)
println(obj.getValue())
}
fun addition(a:Int,b:Int):Int{
return (a+b)
} | MyKotlinNotes/src/Ch18.kt | 237277789 |
package com.serhiitymoshenko.organizer
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.serhiitymoshenko.organizer", appContext.packageName)
}
} | Organizer/app/src/androidTest/java/com/serhiitymoshenko/organizer/ExampleInstrumentedTest.kt | 2933404260 |
package com.serhiitymoshenko.organizer
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)
}
} | Organizer/app/src/test/java/com/serhiitymoshenko/organizer/ExampleUnitTest.kt | 1666843731 |
package com.serhiitymoshenko.organizer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Organizer/app/src/main/java/com/serhiitymoshenko/organizer/MainActivity.kt | 3814523391 |
package com.askjeffreyliu.floydsteinbergdithering
import android.graphics.*
import com.cloudpos.mvc.common.Logger
class Utils {
fun floydSteinbergDithering(originalColorBitmap: Bitmap): Bitmap {
val bmpGrayScaled = toGrayscale(originalColorBitmap)
floydSteinbergNative(bmpGrayScaled)
return bmpGrayScaled
}
fun binaryBlackAndWhite(originalColorBitmap: Bitmap): Bitmap {
val bmpGrayScaled = toGrayscale(originalColorBitmap)
binaryBlackAndWhiteNative(bmpGrayScaled)
return bmpGrayScaled
}
fun toGrayscale(bmpOriginal: Bitmap): Bitmap {
val bmpGrayscale = Bitmap.createBitmap(bmpOriginal.width, bmpOriginal.height, Bitmap.Config.ARGB_8888)
val c = Canvas(bmpGrayscale)
val paint = Paint()
val cm = ColorMatrix()
cm.setSaturation(0.0f)
val f = ColorMatrixColorFilter(cm)
paint.colorFilter = f
c.drawBitmap(bmpOriginal, 0.0f, 0.0f, paint)
return bmpGrayscale
}
companion object {
private external fun floydSteinbergNative(var1: Bitmap)
private external fun binaryBlackAndWhiteNative(var1: Bitmap)
}
init {
Logger.debug("loadLibrary+++")
System.loadLibrary("fsdither")
Logger.debug("loadLibrary---")
}
} | APIDemoForAarBykotlin/app/src/main/java/com/askjeffreyliu/floydsteinbergdithering/Utils.kt | 3836361771 |
package com.cloudpos.androidmvcmodel
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.*
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import com.android.common.utils.PackageUtils
import com.cloudpos.androidmvcmodel.adapter.ListViewAdapter
import com.cloudpos.androidmvcmodel.common.Constants
import com.cloudpos.androidmvcmodel.entity.MainItem
import com.cloudpos.androidmvcmodel.helper.LanguageHelper
import com.cloudpos.androidmvcmodel.helper.LogHelper
import com.cloudpos.apidemoforunionpaycloudpossdk.R
import com.cloudpos.mvc.base.ActionCallback
import com.cloudpos.mvc.base.ActionManager
import com.cloudpos.mvc.common.Logger
import com.cloudpos.mvc.impl.ActionCallbackImpl
import java.util.*
class MainActivity : Activity(), OnItemClickListener {
var txtLog: TextView? = null
// var txtIntroduction: TextView? = null
var lvwTestItems: ListView? = null
var context: Context? = null
var adapter: ListViewAdapter? = null
private var isMain = true
private var clickedPosition = 0
private var scrollPosition = 0
private var clickedMainItem: MainItem? = null
private var handler: Handler? = null
private var actionCallback: ActionCallback? = null
private var testParameters: MutableMap<String?, Any?>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initParameter()
initView()
initUI()
}
private fun initParameter() {
Logger.debug("initParameter +")
context = this@MainActivity
adapter = ListViewAdapter(context as MainActivity)
handler = Handler(handlerCallback)
actionCallback = ActionCallbackImpl(context, handler!!)
testParameters = HashMap()
Logger.debug("initParameter -")
}
private fun initView() {
Logger.debug("initView +")
txtLog = findViewById<View>(R.id.txt_log) as TextView
// txtIntroduction = findViewById<View>(R.id.txt_introduction) as TextView
lvwTestItems = findViewById<View>(R.id.lvw_test_items) as ListView
Logger.debug("initView -")
}
private fun initUI() {
Logger.debug("initUI +")
txtLog!!.movementMethod = ScrollingMovementMethod.getInstance()
lvwTestItems!!.adapter = adapter
lvwTestItems!!.onItemClickListener = this
lvwTestItems!!.setOnScrollListener(onTestItemsScrollListener)
Logger.debug("initUI -")
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val cleanLogMenu = menu.addSubMenu(MENU_GROUP_ID, MENU_CLEAN_LOG, Menu.NONE,
R.string.clean_log)
cleanLogMenu.setIcon(android.R.drawable.ic_menu_revert)
val uninstallMenu = menu.addSubMenu(MENU_GROUP_ID, MENU_UNINSTALL, Menu.NONE,
R.string.uninstall_app)
uninstallMenu.setIcon(android.R.drawable.ic_menu_delete)
return super.onCreateOptionsMenu(menu)
}
override fun onMenuItemSelected(featureId: Int, item: MenuItem): Boolean {
when (item.itemId) {
MENU_CLEAN_LOG -> txtLog!!.text = ""
MENU_UNINSTALL -> PackageUtils.uninstall(context, context!!.packageName)
else -> {
}
}
return super.onMenuItemSelected(featureId, item)
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
clickedPosition = position
if (isMain) {
performMainItemClick()
} else {
performSubItemClick()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackKeyClick()
return true
}
return super.onKeyDown(keyCode, event)
}
private fun onBackKeyClick() {
if (isMain) {
System.exit(0)
} else {
isMain = true
displayIntroduction()
adapter!!.refreshView(ListViewAdapter.Companion.INDEX_NONE)
setListViewSelection()
actionCallback!!.sendResponse(context!!.getString(R.string.test_end))
}
}
private fun setListViewSelection() {
lvwTestItems!!.adapter = adapter
lvwTestItems!!.setSelection(scrollPosition)
}
private fun performMainItemClick() {
isMain = false
clickedMainItem = MainApplication.Companion.testItems!!.get(clickedPosition)
actionCallback!!.sendResponse(context!!.getString(R.string.welcome_to)
+ "\t" + clickedMainItem!!.getDisplayName(LanguageHelper.getLanguageType(context)))
displayIntroduction()
if (clickedMainItem!!.isActivity()) {
// if the test item is a activity, jump by package-name property.
val cn = ComponentName(context,
clickedMainItem!!.packageName)
val intent = Intent()
intent.component = cn
intent.putExtra(Constants.MAIN_ITEM,
clickedMainItem!!.command)
startActivityForResult(intent, clickedPosition)
} else {
// otherwise jump to SubItem page and automatically execute autoTest
// item if exsies
adapter!!.refreshView(clickedPosition)
lvwTestItems!!.setSelection(0)
lvwTestItems!!.adapter = adapter
// setLayoutIntroductionIfExists();
}
}
private fun performSubItemClick() {
testParameters!!.clear()
testParameters!![Constants.MAIN_ITEM] = clickedMainItem!!.command
val subItemCommand = clickedMainItem!!.getSubItem(clickedPosition).command
testParameters!![Constants.SUB_ITEM] = subItemCommand
Log.e(TAG, "itemPressed : " + clickedMainItem!!.command + "/" + subItemCommand)
ActionManager.Companion.doSubmit(clickedMainItem!!.command + "/" + subItemCommand,
context, testParameters, actionCallback)
}
/**
* 显示Introduction信息<br></br>
* 如果isMain == true,则隐藏,否则显示
*/
private fun displayIntroduction() {
// if (txtIntroduction != null) {
// if (isMain) {
// txtIntroduction!!.visibility = View.GONE
// } else {
// txtIntroduction!!.visibility = View.VISIBLE
// txtIntroduction!!.text = """
// ${context!!.getString(R.string.welcome_to)}
// ${clickedMainItem!!.getDisplayName(LanguageHelper.getLanguageType(context))}
// """.trimIndent()
// }
// }
}
private val onTestItemsScrollListener: AbsListView.OnScrollListener = object : AbsListView.OnScrollListener {
override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {
// position which records the position of the visible top line
if (isMain) {
scrollPosition = lvwTestItems!!.firstVisiblePosition
}
}
override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int,
totalItemCount: Int) {
}
}
private val handlerCallback = Handler.Callback { msg ->
when (msg.what) {
Constants.HANDLER_LOG -> LogHelper.infoAppendMsg(msg.obj as String, txtLog)
Constants.HANDLER_LOG_SUCCESS -> LogHelper.infoAppendMsgForSuccess(msg.obj as String, txtLog)
Constants.HANDLER_LOG_FAILED -> LogHelper.infoAppendMsgForFailed(msg.obj as String, txtLog)
else -> {
}
}
true
}
companion object {
private const val TAG = "DEBUG"
private const val MENU_CLEAN_LOG = Menu.FIRST
private const val MENU_UNINSTALL = Menu.FIRST + 1
private const val MENU_GROUP_ID = 0
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/MainActivity.kt | 894793661 |
package com.cloudpos.androidmvcmodel.entity
class SubItem : TestItem() {
var isNeedTest = false
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/SubItem.kt | 1009020284 |
package com.cloudpos.androidmvcmodel.entity
import com.cloudpos.androidmvcmodel.helper.LanguageHelper
open class TestItem {
var command: String? = null
private var displayNameCN: String? = null
private var displayNameEN: String? = null
fun getDisplayName(languageType: Int): String? {
return if (languageType == LanguageHelper.LANGUAGE_TYPE_CN) {
displayNameCN
} else {
displayNameEN
}
}
fun setDisplayNameCN(displayNameCN: String?) {
this.displayNameCN = displayNameCN
}
fun setDisplayNameEN(displayNameEN: String?) {
this.displayNameEN = displayNameEN
}
override fun toString(): String {
return String.format("command = %s, displayCN = %s, displyEN = %s", command, displayNameCN,
displayNameEN)
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/TestItem.kt | 2692581469 |
package com.cloudpos.androidmvcmodel.entity
import java.util.*
class MainItem : TestItem() {
private var isActivity = false
private val subItems: MutableList<SubItem> = ArrayList()
var packageName: String? = null
private var isUnique = false
fun isActivity(): Boolean {
return isActivity
}
fun setActivity(isActivity: Boolean) {
this.isActivity = isActivity
}
fun getSubItem(position: Int): SubItem {
return subItems[position]
}
fun getSubItems(): List<SubItem> {
return subItems
}
val testSubItems: List<SubItem>
get() {
val testSubItems: MutableList<SubItem> = ArrayList()
for (subItem in subItems) {
if (subItem.isNeedTest) {
testSubItems.add(subItem)
}
}
return testSubItems
}
fun addSubItem(subItem: SubItem) {
subItems.add(subItem)
}
fun isUnique(): Boolean {
return isUnique
}
fun setUnique(isUnique: Boolean) {
this.isUnique = isUnique
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/entity/MainItem.kt | 1343875790 |
package com.cloudpos.androidmvcmodel.adapter
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.cloudpos.androidmvcmodel.MainApplication
import com.cloudpos.androidmvcmodel.entity.MainItem
import com.cloudpos.androidmvcmodel.helper.LanguageHelper
import com.cloudpos.apidemoforunionpaycloudpossdk.R
import java.util.logging.Logger
class ListViewAdapter(private val context: Context) : BaseAdapter() {
private val inflater: LayoutInflater
// private DBHelper dbHelper;
private var mainItemIndex = INDEX_NONE
override fun getCount(): Int {
var count = 0
count = if (mainItemIndex <= INDEX_NONE) {
MainApplication.Companion.testItems!!.size
} else {
MainApplication.Companion.testItems!!.get(mainItemIndex)!!.getSubItems().size
}
return count
}
override fun getItem(position: Int): Any {
val item: Any?
item = if (mainItemIndex <= INDEX_NONE) {
MainApplication.Companion.testItems.get(position)
} else {
MainApplication.Companion.testItems.get(mainItemIndex).getSubItem(position)
}
return item
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View?{
var convertView = convertView
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_test, null)
}
// TextView txtSignature = (TextView)
// convertView.findViewById(R.id.txt_signature);
val txtButton = convertView!!.findViewById<View>(R.id.txt_button) as TextView
// setDisplayedSignature(position, txtSignature);
setDisplayedButton(position, txtButton)
return convertView
}
/**
* refresh listview when switching from MainItem page and SubItem page
*/
fun refreshView(index: Int) {
mainItemIndex = index
Log.e(TAG, "mainItemIndex = $mainItemIndex")
notifyDataSetChanged()
}
/**
* refresh specified item when changed
*/
fun refreshChangedItemView(position: Int, convertView: View, parent: ViewGroup) {
getView(position, convertView, parent)
}
// private void setDisplayedSignature(int position, TextView txtSignature) {
// String testResult = getTestResult(position);
// Log.e(TAG, "setDisplayedSignature testResult = " + testResult);
// if (testResult.equals(SqlConstants.RESULT_SUCCESS)) {
// txtSignature.setText("√");
// txtSignature.setTextColor(Color.rgb(0, 0, 0));
// } else if (testResult.equals(SqlConstants.RESULT_FAILED)) {
// txtSignature.setText("X");
// txtSignature.setTextColor(Color.rgb(255, 0, 0));
// } else if (testResult.equals(SqlConstants.RESULT_EXCEPTION)) {
// txtSignature.setText("O");
// txtSignature.setTextColor(Color.rgb(255, 255, 255));
// } else {
// txtSignature.setText("");
// txtSignature.setTextColor(Color.rgb(0, 0, 0));
// }
// }
private fun setDisplayedButton(position: Int, txtButton: TextView) {
val mainItem = getMainItem(position)
// txtButton.setText(mainItem.getDisplayName(LanguageHelper.getLanguageType(context)));
if (mainItemIndex <= INDEX_NONE) {
txtButton.text = mainItem!!.getDisplayName(LanguageHelper.getLanguageType(context))
} else {
txtButton.text = mainItem!!.getSubItem(position).getDisplayName(
LanguageHelper.getLanguageType(context))
// txtButton.setTag(mainItem.getSubItem(position).getDisplayName(LanguageHelper.getLanguageType(context)));
}
}
/**
* get test result from sqlite database<br></br>
*/
// private String getTestResult(int position) {
// MainItem mainItem = getMainItem(position);
// // String testResult = dbHelper.queryTestResultByMainItem(mainItem);
// return testResult;
// }
private fun getMainItem(position: Int): MainItem? {
var mainItem: MainItem? = null
mainItem = if (mainItemIndex <= INDEX_NONE) {
MainApplication.Companion.testItems!!.get(position)
} else {
MainApplication.Companion.testItems!!.get(mainItemIndex)
}
return mainItem
}
companion object {
private const val TAG = "ListViewAdapter"
const val INDEX_NONE = -1
}
init {
inflater = LayoutInflater.from(context)
// dbHelper = DBHelper.getInstance();
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/adapter/ListViewAdapter.kt | 1336731872 |
package com.cloudpos.androidmvcmodel.common
object Constants {
const val AUTO_TEST = "autoTest"
const val CLOSE = "close"
const val MAIN_ITEM = "MainItem"
const val SUB_ITEM = "SubItem"
const val TEST_RESULT = "TestResult"
const val MAIN_ITEM_DISPLAY_NAME = "MainItem displayName"
const val CLICK_POSITION = "ClickPosition"
const val HANDLER_LOG = 1
const val HANDLER_LOG_SUCCESS = 2
const val HANDLER_LOG_FAILED = 3
const val HANDLER_ALERT_SOUND = 4
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/common/Constants.kt | 2906566477 |
package com.cloudpos.androidmvcmodel.callback
import android.content.Context
import android.os.Handler
import android.os.Message
import android.widget.TextView
import com.cloudpos.androidmvcmodel.helper.LogHelper
class HandlerCallback
/**
* 将信息输出到显示屏上
*/(private val context: Context, private val txtResult: TextView) : Handler.Callback {
override fun handleMessage(msg: Message): Boolean {
when (msg.what) {
LOG -> LogHelper.infoAppendMsg(msg.obj as String, txtResult)
LOG_SUCCESS -> LogHelper.infoAppendMsgForSuccess(msg.obj as String, txtResult)
LOG_FAILED -> LogHelper.infoAppendMsgForFailed(msg.obj as String, txtResult)
ALERT_SOUND -> showDialog(msg.obj.toString())
else -> LogHelper.infoAppendMsg(msg.obj as String, txtResult)
}
return true
}
private fun showDialog(testItem: String) {
val showMsgAndItems = testItem.split("/").toTypedArray()
// new AlertDialog.Builder(context)
// .setTitle(showMsgAndItems[0])
// .setPositiveButton(context.getString(R.string.sound_btn_success),
// new DialogInterface.OnClickListener() {
//
// @Override
// public void onClick(DialogInterface dialog, int which) {
// setSuccessfullResult(showMsgAndItems[1], showMsgAndItems[2]);
// }
// })
// .setNegativeButton(context.getString(R.string.sound_btn_failed),
// new DialogInterface.OnClickListener() {
//
// @Override
// public void onClick(DialogInterface dialog, int which) {
// setFailedResult(showMsgAndItems[1], showMsgAndItems[2]);
// }
// }).show();
}
private fun setSuccessfullResult(mainItem: String, subItem: String) {
// DBHelper.getInstance().saveTestResult(mainItem, subItem, SqlConstants.RESULT_SUCCESS);
}
private fun setFailedResult(mainItem: String, subItem: String) {
// DBHelper.getInstance().saveTestResult(mainItem, subItem, SqlConstants.RESULT_FAILED);
}
companion object {
const val LOG = 1
const val LOG_SUCCESS = 2
const val LOG_FAILED = 3
const val ALERT_SOUND = 4
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/callback/HandlerCallback.kt | 1969464748 |
package com.cloudpos.androidmvcmodel
import android.app.Application
import android.content.Context
import android.util.Log
import com.cloudpos.androidmvcmodel.entity.MainItem
import com.cloudpos.androidmvcmodel.helper.LanguageHelper
import com.cloudpos.androidmvcmodel.helper.TerminalHelper
import com.cloudpos.androidmvcmodel.helper.XmlPullParserHelper
import com.cloudpos.mvc.base.ActionManager
import com.cloudpos.mvc.impl.ActionContainerImpl
import java.util.*
class MainApplication : Application() {
private var context: Context? = null
override fun onCreate() {
super.onCreate()
initParameter()
ActionManager.Companion.initActionContainer(ActionContainerImpl(context))
}
private fun initParameter() {
context = this
testItems = XmlPullParserHelper.getTestItems(context as MainApplication, TerminalHelper.terminalType)
for (mainItem in testItems) {
Log.e("DEBUG", "" + mainItem.getDisplayName(LanguageHelper.getLanguageType(context)))
}
}
companion object {
var testItems: MutableList<MainItem> = ArrayList()
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/MainApplication.kt | 1139541490 |
package com.cloudpos.androidmvcmodel.helper
import android.util.Log
object SystemPropertyHelper {
operator fun get(propertyName: String): String {
var property: Any? = null
try {
val systemProperties = Class.forName("android.os.SystemProperties")
Log.i("systemProperties", systemProperties.toString())
property = systemProperties.getMethod("get", *arrayOf<Class<*>>(
String::class.java, String::class.java
)).invoke(systemProperties, *arrayOf<Any>(
propertyName, "unknown"
))
Log.i("bootloaderVersion", property.javaClass.toString())
} catch (e: Exception) {
property = ""
e.printStackTrace()
}
return property.toString()
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/SystemPropertyHelper.kt | 1227181031 |
/**
*
*/
package com.cloudpos.androidmvcmodel.helper
import android.graphics.*
import android.text.Spannable
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.widget.TextView
/**
* @author john 打印信息的格式控制类。 红色:出现的问题。 绿色:正常的信息。 黄色:可能出现的问题。 1 : color is black 2
* : color is yellow 3 : color is blue 4 : color is red other number :
* color is black;
*/
object LogHelper {
/**
* TestView changed color and info message. Called after the TestView is
* created and whenever the TextView changes. Set your TextView's message
* here.
*
* @param TextView text
* @param String infoMsg : color is red < color name="red">#FF0000< /color><
* !--红色 -->
*/
@Deprecated("")
fun infoException(text: TextView, infoMsg: String) {
text.setText(infoMsg, TextView.BufferType.SPANNABLE)
val start = text.text.length
val end = start + infoMsg.length
val style = text.text as Spannable
style.setSpan(ForegroundColorSpan(Color.RED), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
/**
* @param TextView text
* @param String infoMsg : color is black
*/
@Deprecated("")
fun info(text: TextView, infoMsg: String?) {
// int start = text.getText().length();
// int end = start +infoMsg.length();
text.text = infoMsg
}
/**
* @param TextView text
* @param String infoMsg : color is yellow
*/
@Deprecated("")
fun infoWarning(text: TextView, infoMsg: String) {
text.text = infoMsg
val style = text.text as Spannable
val start = text.text.length
val end = start + infoMsg.length
style.setSpan(ForegroundColorSpan(Color.YELLOW), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
/**
* @param TextView text
* @param String infoMsg
* @param order :set background color. 1 : color is black. 2 : color is
* yellow. 3 : color is blue .4 : color is red .other number :
* color is black;
*/
fun infoMsgAndColor(text: TextView, infoMsg: String, order: Int) {
text.text = infoMsg
val style = text.text as Spannable
val start = 0
val end = start + infoMsg.length
val color: ForegroundColorSpan
color = when (order) {
1 -> ForegroundColorSpan(Color.BLACK)
2 -> ForegroundColorSpan(Color.YELLOW)
3 -> ForegroundColorSpan(Color.BLUE)
4 -> ForegroundColorSpan(Color.RED)
else -> ForegroundColorSpan(Color.BLACK)
}
style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun infoAppendMsgAndColor(text: TextView, infoMsg: String, order: Int) {
var start = 0
if (text.text.length == 0) {
} else {
start = text.text.length
}
text.append(infoMsg)
val style = text.text as Spannable
val end = start + infoMsg.length
val color: ForegroundColorSpan
color = when (order) {
1 -> ForegroundColorSpan(Color.BLACK)
2 -> ForegroundColorSpan(Color.YELLOW)
3 -> ForegroundColorSpan(Color.BLUE)
4 -> ForegroundColorSpan(Color.RED)
5 -> ForegroundColorSpan(Color.RED)
else -> ForegroundColorSpan(Color.YELLOW)
}
style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
/**
* 蓝色字体打印成功信息
*
* @param msg
* @param text
*/
fun infoAppendMsgForSuccess(msg: String, text: TextView?) {
// TextView text = PreMainActivity.txtResult;
var start = 0
if (text!!.text.length == 0) {
} else {
start = text.text.length
}
if (start > 1000) {
text.text = ""
start = 0
}
text.append(msg)
val style = text.text as Spannable
val end = start + msg.length
val color: ForegroundColorSpan
color = ForegroundColorSpan(Color.BLUE)
style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
moveScroller(text)
// text.setScrollY(text.getScrollY()+text.getLineHeight());
}
/**
* 红色字体打印失败信息
*
* @param msg
* @param text
*/
fun infoAppendMsgForFailed(msg: String, text: TextView?) {
// TextView text = PreMainActivity.txtResult;
var start = 0
if (text!!.text.length == 0) {
} else {
start = text.text.length
}
if (start > 1000) {
text.text = ""
start = 0
}
text.append(msg)
val style = text.text as Spannable
val end = start + msg.length
val color: ForegroundColorSpan
color = ForegroundColorSpan(Color.RED)
style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
moveScroller(text)
// Scroller scr = text.
// text.setScrollY(text.getScrollY()+text.getLineHeight());
}
/**
* 给textresult上用黑色写上命令。
*/
fun infoAppendMsg(msg: String, text: TextView?) {
// TextView text = PreMainActivity.txtResult;
var start = 0
if (text!!.text.length == 0) {
} else {
start = text.text.length
}
if (start > 1000) {
text.text = ""
start = 0
}
text.append(msg)
val style = text.text as Spannable
val end = start + msg.length
val color: ForegroundColorSpan
color = ForegroundColorSpan(Color.BLACK)
style.setSpan(color, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
moveScroller(text)
//
}
private fun moveScroller(text: TextView?) {
// find the amount we need to scroll. This works by
// asking the TextView's internal layout for the position
// of the final line and then subtracting the TextView's height
val scrollAmount = (text!!.layout.getLineTop(text.lineCount)
- text.height)
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0) {
text.scrollTo(0, scrollAmount + 30)
} else {
text.scrollTo(0, 0)
}
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/LogHelper.kt | 3524246946 |
package com.cloudpos.androidmvcmodel.helper
import android.content.Context
object LanguageHelper {
const val LANGUAGE_TYPE_OTHER = 0
const val LANGUAGE_TYPE_CN = 1
private const val LANGUAGE_TYPE_NONE = -1
private var languageType = LANGUAGE_TYPE_NONE
fun getLanguageType(context: Context?): Int {
if (languageType == LANGUAGE_TYPE_NONE) {
languageType = LANGUAGE_TYPE_OTHER
val locale = context!!.resources.configuration.locale
val language = locale.language
if (language.endsWith("zh")) {
languageType = LANGUAGE_TYPE_CN
}
}
return languageType
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/LanguageHelper.kt | 2467269118 |
package com.cloudpos.androidmvcmodel.helper
import android.util.Log
object TerminalHelper {
const val TERMINAL_TYPE_WIZARPOS_1 = 0
const val TERMINAL_TYPE_WIZARHAND_Q1 = 1
const val TERMINAL_TYPE_WIZARHAND_M0 = 2
const val TERMINAL_TYPE_WIZARPAD_1 = 3
const val TERMINAL_TYPE_NONE = -1// 找到对应的设备类型WIZARPOS,WIZARPAD,...
// 判断是否为手持
/**
* 获取设备类型<br></br>
* [.TERMINAL_TYPE_WIZARPOS_1]<br></br>
* [.TERMINAL_TYPE_WIZARHAND_Q1]<br></br>
* [.TERMINAL_TYPE_WIZARHAND_M0]<br></br>
* [.TERMINAL_TYPE_WIZARPAD_1]<br></br>
*/
var terminalType = TERMINAL_TYPE_NONE
get() {
if (field == TERMINAL_TYPE_NONE) {
field = TERMINAL_TYPE_WIZARPOS_1
productModel = getProductModel()
Log.d("model", productModel)
// 找到对应的设备类型WIZARPOS,WIZARPAD,...
// 判断是否为手持
if (productModel == "WIZARHAND_Q1" || productModel == "MSM8610" || productModel == "WIZARHAND_Q0") {
field = TERMINAL_TYPE_WIZARHAND_Q1
} else if (productModel == "FARS72_W_KK" || productModel == "WIZARHAND_M0") {
field = TERMINAL_TYPE_WIZARHAND_M0
} else if (productModel == "WIZARPOS1" || productModel == "WIZARPOS_1") {
field = TERMINAL_TYPE_WIZARPOS_1
} else if (productModel == "WIZARPAD1" || productModel == "WIZARPAD_1") {
field = TERMINAL_TYPE_WIZARPAD_1
}
}
return field
}
private set
private var productModel: String? = null
/**
* 获取设备的model<br></br>
* 通过读取 ro.product.model 属性 获得
*/
fun getProductModel(): String? {
if (productModel == null) {
productModel = SystemPropertyHelper.get("ro.product.model").trim { it <= ' ' }
productModel = productModel!!.replace(" ", "_")
productModel = productModel!!.toUpperCase()
}
return productModel
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/TerminalHelper.kt | 456664042 |
package com.cloudpos.androidmvcmodel.helper
import android.content.Context
import android.util.Log
import com.cloudpos.androidmvcmodel.common.Constants
import com.cloudpos.androidmvcmodel.entity.MainItem
import com.cloudpos.androidmvcmodel.entity.SubItem
import com.cloudpos.apidemoforunionpaycloudpossdk.R
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.util.*
object XmlPullParserHelper {
@Throws(XmlPullParserException::class)
fun getXmlPullParser(context: Context, terminalType: Int): XmlPullParser {
var xmlPullParser = XmlPullParserFactory.newInstance().newPullParser()
xmlPullParser = when (terminalType) {
TerminalHelper.TERMINAL_TYPE_WIZARHAND_Q1 -> context.resources.getXml(R.xml.wizarhand_q1)
TerminalHelper.TERMINAL_TYPE_WIZARPAD_1 -> context.resources.getXml(R.xml.wizarpad_1)
TerminalHelper.TERMINAL_TYPE_WIZARHAND_M0 -> context.resources.getXml(R.xml.wizarhand_m0)
else -> context.resources.getXml(R.xml.wizarpos_1)
}
return xmlPullParser
}
fun parseToMainItem(xmlPullParser: XmlPullParser): MainItem {
val mainItem = MainItem()
val nameCN = xmlPullParser.getAttributeValue(null, "name_CN")
val nameEN = xmlPullParser.getAttributeValue(null, "name_EN")
val command = xmlPullParser.getAttributeValue(null, "command")
val isActivity = xmlPullParser.getAttributeValue(null, "isActivity")
mainItem.setDisplayNameCN(nameCN)
mainItem.setDisplayNameEN(nameEN)
mainItem.command = command
if (isActivity != null && isActivity == "true") {
mainItem.setActivity(true)
} else {
mainItem.setActivity(false)
}
return mainItem
}
fun parseToSubItem(xmlPullParser: XmlPullParser): SubItem {
val subItem = SubItem()
val nameCN = xmlPullParser.getAttributeValue(null, "name_CN")
val nameEN = xmlPullParser.getAttributeValue(null, "name_EN")
val command = xmlPullParser.getAttributeValue(null, "command")
val needTest = xmlPullParser.getAttributeValue(null, "needTest")
subItem.setDisplayNameCN(nameCN)
subItem.setDisplayNameEN(nameEN)
subItem.command = command
if (needTest != null && needTest == "true") {
subItem.isNeedTest = true
} else {
subItem.isNeedTest = false
}
return subItem
}
fun getTestItems(context: Context, terminalType: Int): MutableList<MainItem> {
Log.d("DEBUG", "getTestItems")
val testItems: MutableList<MainItem> = ArrayList()
try {
val xmlPullParser = getXmlPullParser(context,
terminalType)
var mEventType = xmlPullParser.eventType
var mainItem = MainItem()
var tagName: String? = null
while (mEventType != XmlPullParser.END_DOCUMENT) {
if (mEventType == XmlPullParser.START_TAG) {
tagName = xmlPullParser.name
if (tagName == Constants.MAIN_ITEM) {
mainItem = parseToMainItem(xmlPullParser)
// Log.d("DEBUG", "" + mainItem.getDisplayName(1));
} else if (tagName == Constants.SUB_ITEM) {
val subItem = parseToSubItem(xmlPullParser)
mainItem!!.addSubItem(subItem)
}
} else if (mEventType == XmlPullParser.END_TAG) {
tagName = xmlPullParser.name
if (tagName == Constants.MAIN_ITEM) {
testItems.add(mainItem)
}
}
mEventType = xmlPullParser.next()
}
} catch (e: Exception) {
e.printStackTrace()
}
return testItems
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/androidmvcmodel/helper/XmlPullParserHelper.kt | 3270034868 |
package com.cloudpos.mvc.impl
import android.content.Context
import android.os.Handler
import com.cloudpos.androidmvcmodel.common.Constants
import com.cloudpos.mvc.base.ActionCallback
class ActionCallbackImpl(override var context: Context?, private val handler: Handler) : ActionCallback() {
override fun sendResponse(code: Int) {
handler.obtainMessage(code).sendToTarget()
}
override fun sendResponse(code: Int, msg: String?) {
handler.obtainMessage(code, """ $msg
""").sendToTarget()
}
override fun sendResponse(msg: String?) {
sendResponse(Constants.HANDLER_LOG, msg)
} // public void sendLog(String log) {
// handler.obtainMessage(Constants.HANDLER_LOG, "\t\t" + log + "\n").sendToTarget();
// }
//
// public void sendSuccessLog(String successLog) {
// handler.obtainMessage(Constants.HANDLER_LOG_SUCCESS, "\t\t" + successLog + "\n")
// .sendToTarget();
// }
//
// public void sendFailedLog(String failedLog) {
// handler.obtainMessage(Constants.HANDLER_LOG_FAILED, "\t\t" + failedLog + "\n")
// .sendToTarget();
// }
}
| APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/impl/ActionCallbackImpl.kt | 2887882404 |
package com.cloudpos.mvc.impl
import android.content.Context
import android.util.Log
import com.cloudpos.androidmvcmodel.MainApplication
import com.cloudpos.androidmvcmodel.entity.MainItem
import com.cloudpos.apidemoforunionpaycloudpossdk.R
import com.cloudpos.mvc.base.AbstractAction
import com.cloudpos.mvc.base.ActionContainer
class ActionContainerImpl(private val context: Context?) : ActionContainer() {
override fun initActions() {
for (mainItem in MainApplication.Companion.testItems) {
try {
val classPath = getClassPath(mainItem)
val clazz = Class.forName(classPath)
if (mainItem != null) {
addAction(mainItem.command, clazz as Class<out AbstractAction>, true)
}
} catch (e: Exception) {
e.printStackTrace()
Log.e(TAG, "Can't find this action")
}
}
}
private fun getClassPath(mainItem: MainItem): String? {
var classPath: String? = null
classPath = if (mainItem.isUnique()) {
mainItem.packageName
} else {
(context!!.resources.getString(R.string.action_package_name)
+ mainItem.command)
}
return classPath
}
companion object {
private const val TAG = "ActionContainerImpl"
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/impl/ActionContainerImpl.kt | 2101387920 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.cloudpos.mvc.common
class MVCException : RuntimeException {
constructor() {}
constructor(msg: String?) : super(msg) {}
constructor(cause: Throwable?) : super(cause) {}
constructor(msg: String?, cause: Throwable?) : super(msg, cause) {}
companion object {
private const val serialVersionUID = -5923896637917336703L
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/common/MVCException.kt | 4283945064 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.cloudpos.mvc.common
import android.util.Log
object Logger {
var level = 3
fun debug(msg: String?) {
if (level <= 3) {
Log.d(createTag(), msg)
}
}
fun debug(msg: String?, tr: Throwable?) {
if (level <= 3) {
Log.d(createTag(), msg, tr)
}
}
fun info(msg: String?) {
if (level <= 4) {
Log.i(createTag(), msg)
}
}
fun info(msg: String?, tr: Throwable?) {
if (level <= 4) {
Log.i(createTag(), msg, tr)
}
}
fun warn(msg: String?) {
if (level <= 5) {
Log.w(createTag(), msg)
}
}
fun warn(msg: String?, tr: Throwable?) {
if (level <= 5) {
Log.w(createTag(), msg, tr)
}
}
fun error(msg: String?) {
if (level <= 6) {
Log.e(createTag(), msg)
}
}
fun error(msg: String?, tr: Throwable?) {
if (level <= 6) {
Log.e(createTag(), msg, tr)
}
}
private fun createTag(): String? {
val sts = Thread.currentThread().stackTrace
return if (sts == null) {
null
} else {
val var3 = sts.size
for (var2 in 0 until var3) {
val st = sts[var2]
if (!st.isNativeMethod && st.className != Thread::class.java.name && st.className != Logger::class.java.name) {
return st.lineNumber.toString() + ":" + st.fileName
}
}
""
}
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/common/Logger.kt | 3932621486 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.cloudpos.mvc.base
import android.content.Context
import com.cloudpos.mvc.common.Logger
import com.cloudpos.mvc.common.MVCException
import java.util.*
class ActionManager {
private val actionScheduler: ActionScheduler = ActionScheduler.Companion.instance
protected var mActionContainer: HashMap<Any?, Any?> = HashMap<Any?, Any?>()
private var isStart = false
private fun start() {
actionScheduler.start()
}
private fun newActionContext(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): ActionContext? {
val acontext = ActionContext()
acontext.setActionUrl(actionUrl)
acontext.setParam(param)
acontext.setCallback(callback)
if (acontext != null) {
acontext.setContext(context)
}
setAction(actionUrl, acontext)
actionScheduler.setActionContext(acontext)
return acontext
}
private fun setAction(actionUrl: String, context: ActionContext?) {
val actionId: String = ActionContext.Companion.parseActionId(actionUrl)
val obj = mActionContainer[actionId]
if (obj == null) {
throw MVCException("Not found actionId in ActionContainer. The actionId is [$actionId].")
} else {
if (Class::class.java.isInstance(obj)) {
try {
context!!.setAction((Class::class.java.cast(obj) as Class<*>).newInstance() as AbstractAction)
} catch (var6: Exception) {
Logger.error("build instance error:", var6)
}
} else {
context!!.setAction(obj as AbstractAction?)
}
}
}
companion object {
private val actionManager = ActionManager()
private val instance: ActionManager
private get() {
if (!actionManager.isStart) {
actionManager.start()
actionManager.isStart = true
}
return actionManager
}
fun initActionContainer(actions: ActionContainer) {
actions.initActions()
instance.mActionContainer.putAll(actions.getActions())
}
fun doSubmit(actionUrl: String, param: Map<String?, Any?>?, callback: ActionCallback?) {
doSubmit(actionUrl, null as Context?, param, callback)
}
fun doSubmit(clazz: Class<out AbstractAction?>, methodName: String, param: Map<String?, Any?>?, callback: ActionCallback?) {
doSubmit(clazz.name + "/" + methodName, param, callback)
}
fun doSubmit(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?) {
instance.newActionContext(actionUrl, context, param, callback)
}
fun doSubmit(clazz: Class<out AbstractAction?>, methodName: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?) {
doSubmit(clazz.name + "/" + methodName, context, param, callback)
}
fun <T> doSubmitForResult(actionUrl: String, param: Map<String?, Any?>?, callback: ActionCallback?): T? {
return doSubmitForResult(actionUrl, null as Context?, param, callback)
}
fun <T> doSubmitForResult(clazz: Class<out AbstractAction?>, methodName: String, param: Map<String?, Any?>?, callback: ActionCallback?): T? {
return doSubmitForResult(clazz.name + "/" + methodName, param, callback)
}
fun <T> doSubmitForResult(actionUrl: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): T? {
val acontext = instance.newActionContext(actionUrl, context, param, callback)
return acontext!!.result as T
}
fun <T> doSubmitForResult(clazz: Class<out AbstractAction?>, methodName: String, context: Context?, param: Map<String?, Any?>?, callback: ActionCallback?): T? {
return doSubmitForResult(clazz.name + "/" + methodName, context, param, callback)
}
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionManager.kt | 3921670354 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.cloudpos.mvc.base
import android.content.Context
import android.os.Handler
abstract class ActionCallback {
open var context: Context? = null
open fun ActionCallback() {}
open fun ActionCallback(context: Context?) {
this.context = context
}
open fun callbackInHandler(methodName: String?, vararg args: Any?) {
val handler = Handler()
handler.post(object : Runnable {
override fun run() {
try {
BeanHelper(this).invoke(methodName, *args)
} catch (var2: Exception) {
var2.printStackTrace()
}
}
})
}
open fun sendResponse(code: Int) {}
open fun sendResponse(msg: String?) {}
open fun sendResponse(code: Int, msg: String?) {}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionCallback.kt | 1378663942 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.cloudpos.mvc.base
import com.cloudpos.mvc.common.Logger
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
class ActionScheduler : Thread() {
private val mActionQueue: LinkedBlockingQueue<ActionContext?> = LinkedBlockingQueue<ActionContext?>(20)
private val service = Executors.newFixedThreadPool(30)
override fun run() {
var mContext: ActionContext? = null
while (true) {
while (true) {
try {
mContext = mActionQueue.take()
service.submit(mContext)
} catch (var3: Exception) {
Logger.error("调度器发生错误", var3)
}
}
}
}
fun setActionContext(context: ActionContext?) {
if (context != null) {
try {
mActionQueue.put(context)
} catch (var3: InterruptedException) {
var3.printStackTrace()
}
}
}
companion object {
val instance = ActionScheduler()
}
} | APIDemoForAarBykotlin/app/src/main/java/com/cloudpos/mvc/base/ActionScheduler.kt | 670071464 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.