content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package app.sanao1006.tsundoku.feature.create
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Done
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import app.sanao1006.tsundoku.data.desiginsystem.TsundokuTheme
import app.sanao1006.tsundoku.data.model.InputForCreateTsundoku
import io.sanao1006.tsundoku.R
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TsundokuCreateScreen(
input: InputForCreateTsundoku,
onBackButtonClick: () -> Unit,
onCreateButtonClick: () -> Unit,
onTitleValueChange: (String) -> Unit,
onDescriptionValueChange: (String) -> Unit,
onTotalPageValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
) {
val keyboardController = LocalSoftwareKeyboardController.current
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.title_create_tsundoku)) },
navigationIcon = {
IconButton(onClick = onBackButtonClick) {
Icon(Icons.Default.ArrowBack, "")
}
},
backgroundColor = Color(0xfff2fbff)
)
}
) { innerPadding ->
Box(modifier = modifier.padding(innerPadding)) {
Column {
OutlinedTextField(
value = input.title,
onValueChange = onTitleValueChange,
label = { Text(stringResource(R.string.pref_create_tsundoku_title)) },
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
colors = TextFieldDefaults.outlinedTextFieldColors(
backgroundColor = Color(0xffFFFFFF),
unfocusedLabelColor = Color.Black
)
)
OutlinedTextField(
value = input.description,
onValueChange = onDescriptionValueChange,
label = { Text(stringResource(R.string.pref_create_tsundoku_description)) },
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
colors = TextFieldDefaults.outlinedTextFieldColors(
backgroundColor = Color(0xffFFFFFF),
unfocusedLabelColor = Color.Black
)
)
OutlinedTextField(
value = input.totalPage,
onValueChange = onTotalPageValueChange,
label = { Text(stringResource(R.string.pref_create_tsundoku_page_count)) },
colors = TextFieldDefaults.outlinedTextFieldColors(
backgroundColor = Color(0xffFFFFFF),
unfocusedLabelColor = Color.Black
),
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
}
),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
)
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
enabled = !input.title.isNullOrBlank() && !input.totalPage.isNullOrBlank() && input.totalPage.toIntOrNull() != null,
onClick = onCreateButtonClick
) {
Icon(Icons.Default.Done, "")
Spacer(modifier = Modifier.width(4.dp))
Text(stringResource(R.string.create_tsundoku))
}
}
}
}
}
@Preview(showBackground = true, name = "テキストあり")
@Composable
fun PreviewTsundokuCreateScreen() {
TsundokuTheme {
TsundokuCreateScreen(
input = InputForCreateTsundoku(
title = "タイトル",
description = "",
totalPage = "200",
),
onBackButtonClick = {},
onCreateButtonClick = {},
onTitleValueChange = {},
onDescriptionValueChange = {},
onTotalPageValueChange = {}
)
}
}
@Preview(showBackground = true, name = "テキストなし")
@Composable
fun PreviewTsundokuCreateScreenWithoutText() {
TsundokuTheme {
TsundokuCreateScreen(
input = InputForCreateTsundoku(
title = "",
description = "",
totalPage = "",
),
onBackButtonClick = {},
onCreateButtonClick = {},
onTitleValueChange = {},
onDescriptionValueChange = {},
onTotalPageValueChange = {}
)
}
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/feature/create/TsundokuCreateScreen.kt
|
1261205280
|
package app.sanao1006.tsundoku.data.di
import javax.inject.Qualifier
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class IODispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class MainDispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class DefaultDispatcher
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class UnconfinedDispatcher
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/di/HiltCoroutineDispatcherAnnotation.kt
|
128108629
|
package app.sanao1006.tsundoku.data.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
@InstallIn(SingletonComponent::class)
@Module
object CoroutineDispatcherModule {
@DefaultDispatcher
@Provides
fun provideDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
@IODispatcher
@Provides
fun provideIODispatcher(): CoroutineDispatcher = Dispatchers.IO
@MainDispatcher
@Provides
fun provideMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
@UnconfinedDispatcher
@Provides
fun provideUnconfinedDispatcher(): CoroutineDispatcher = Dispatchers.Unconfined
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/di/CoroutineDispatcherModule.kt
|
4058930500
|
package app.sanao1006.tsundoku.data.di
import app.sanao1006.tsundoku.data.db.BookDao
import app.sanao1006.tsundoku.data.db.BookEntity
import app.sanao1006.tsundoku.data.model.Book
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TsundokuRepository @Inject constructor(
private val bookDao: BookDao,
@IODispatcher private val ioDispatcher: CoroutineDispatcher
) {
fun getBooks(): Flow<List<Book>> = bookDao.getBooks().mapNotNull { it.mapNotNull { bookEntity -> bookEntity?.toBook() } }
fun getBook(bookId: Int): Flow<Book> = bookDao.getBook(bookId).mapNotNull { it?.toBook() }
suspend fun insertBook(book: BookEntity) = withContext(ioDispatcher) {
bookDao.insertBook(book = book)
}
suspend fun updateBookInfo(book: BookEntity) = withContext(ioDispatcher) {
bookDao.updateBookInfo(book = book)
}
suspend fun deleteBook(bookId: Int) = withContext(ioDispatcher) {
bookDao.deleteBook(bookId = bookId)
}
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/di/TsundokuRepository.kt
|
4022917999
|
package app.sanao1006.tsundoku.data.di
import android.content.Context
import androidx.room.Room
import app.sanao1006.tsundoku.data.db.BookDao
import app.sanao1006.tsundoku.data.db.TsundokuDb
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
fun provideRoomDao(db: TsundokuDb): BookDao = db.bookDao()
@Provides
@Singleton
fun provideTsundokuDatabase(
@ApplicationContext context: Context
): TsundokuDb = Room.databaseBuilder(
context = context,
klass = TsundokuDb::class.java,
name = "tsundoku-database"
).fallbackToDestructiveMigration().build()
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/di/DatabaseModule.kt
|
133241856
|
package app.sanao1006.tsundoku.data.desiginsystem
import androidx.compose.ui.graphics.Color
object Colors {
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val BackgroundLight = Color(0xFFE5F7FF)
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/desiginsystem/Colors.kt
|
282945941
|
package app.sanao1006.tsundoku.data.desiginsystem
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/desiginsystem/Shapes.kt
|
1996783769
|
package app.sanao1006.tsundoku.data.desiginsystem
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Colors.Purple200,
primaryVariant = Colors.Purple700,
secondary = Colors.Teal200
)
private val LightColorPalette = lightColors(
primary = Colors.Purple500,
primaryVariant = Colors.Purple700,
secondary = Colors.Teal200,
background = Colors.BackgroundLight
)
@Composable
fun TsundokuTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/desiginsystem/Theme.kt
|
2248384579
|
package app.sanao1006.tsundoku.data.desiginsystem
import androidx.compose.material.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(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
h1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
)
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/desiginsystem/Type.kt
|
2507785247
|
package app.sanao1006.tsundoku.data.model
data class Book(
val id: Int,
val title: String,
val description: String,
val totalPage: Int,
var nowPage: Int = 0,
val createAt: String,
var updatedAt: String,
)
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/model/Book.kt
|
3950026208
|
package app.sanao1006.tsundoku.data.model
data class InputForCreateTsundoku(
val title: String,
val description: String,
val totalPage: String,
)
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/model/InputForCreateTsundoku.kt
|
3287378948
|
package app.sanao1006.tsundoku.data.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import app.sanao1006.tsundoku.data.model.Book
@Entity(tableName = "books")
data class BookEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "title")
val title: String? = "",
@ColumnInfo(name = "description")
val description: String? = "",
@ColumnInfo(name = "total_page")
val totalPage: Int,
@ColumnInfo(name = "now_page")
var nowPage: Int = 0,
@ColumnInfo(name = "created_at")
val createdAt: String,
@ColumnInfo(name = "updated_at")
val updatedAt: String,
) {
fun toBook(): Book {
return Book(
id = this.id,
description = this.description ?: "",
title = this.title ?: "",
totalPage = this.totalPage,
nowPage = this.nowPage,
createAt = this.createdAt,
updatedAt = this.updatedAt
)
}
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/db/BookEntity.kt
|
4094594149
|
package app.sanao1006.tsundoku.data.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface BookDao {
@Query("select * from books")
fun getBooks(): Flow<List<BookEntity?>>
@Query("select * from books where id = :bookId")
fun getBook(bookId: Int): Flow<BookEntity?>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertBook(book: BookEntity)
@Update(entity = BookEntity::class)
suspend fun updateBookInfo(book: BookEntity)
@Query("DELETE FROM books WHERE id = :bookId")
fun deleteBook(bookId: Int)
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/db/BookDao.kt
|
3221300649
|
package app.sanao1006.tsundoku.data.db
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [BookEntity::class],
version = 1
)
abstract class TsundokuDb : RoomDatabase() {
abstract fun bookDao(): BookDao
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/data/db/TsundokuDb.kt
|
3054022334
|
package app.sanao1006.tsundoku.domain
import app.sanao1006.tsundoku.data.db.BookEntity
import app.sanao1006.tsundoku.data.di.TsundokuRepository
import javax.inject.Inject
class InsertTsundokuUseCase @Inject constructor(
private val tsundokuRepository: TsundokuRepository
) {
suspend operator fun invoke(
title: String,
description: String,
totalPage: Int,
createAt: String,
updatedAt: String
) {
tsundokuRepository.insertBook(
BookEntity(
id = 0,
title = title,
description = description,
totalPage = totalPage,
createdAt = createAt,
updatedAt = updatedAt
)
)
}
}
|
Tsundoku/app/src/main/java/app/sanao1006/tsundoku/domain/InsertTsundokuUseCase.kt
|
3333112429
|
package com.example.footballapidemo
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.footballapidemo", appContext.packageName)
}
}
|
FootballApiDemo/app/src/androidTest/java/com/example/footballapidemo/ExampleInstrumentedTest.kt
|
68853922
|
package com.example.footballapidemo
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)
}
}
|
FootballApiDemo/app/src/test/java/com/example/footballapidemo/ExampleUnitTest.kt
|
3871218478
|
package com.example.footballapidemo.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)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/ui/theme/Color.kt
|
2169076090
|
package com.example.footballapidemo.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 FootballApiDemoTheme(
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
)
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/ui/theme/Theme.kt
|
1444506446
|
package com.example.footballapidemo.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
)
*/
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/ui/theme/Type.kt
|
2982504213
|
package com.example.footballapidemo
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresExtension
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
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.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
const val TAG = "MyTag"
class MainActivity : ComponentActivity() {
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel = ApiViewModel()
setContent {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ApiTest(viewModel)
}
}
}
}
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
@Composable
fun ApiTest(viewModel: ApiViewModel) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Yellow)
){
Text(viewModel.text.value)
}
val api = RetrofitInstance.api
LaunchedEffect(Unit){
viewModel.testApi(
apiFunc = {api.getTeamById(64)},
::teamCallback,
viewModel
)
// viewModel.testApi(
// {api.getLeagueTeams("PL")},
// ::teamsCallback
// )
}
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/MainActivity.kt
|
2688525642
|
package com.example.footballapidemo
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitInstance{
private const val BASE_URL = "https://api.football-data.org/v4/"
//BASE_URL必须以/结尾
private const val API_KEY = "c07c3b803ea6471fa7208842a6946e0c"
private val client = OkHttpClient.Builder().apply {
addInterceptor(Interceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("X-Auth-Token", API_KEY)
.build()
chain.proceed(request)
})
}.build()
//构建OkHTTPClient对象,用于在每次使用api实例时添加api key
val api: FootballDataInterface by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(FootballDataInterface::class.java)
}
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/RetrofitInstance.kt
|
38026661
|
package com.example.basic_ui_demo.news
data class Result(
val allnum: Int, //返回的news总数
val curpage: Int, //正在访问的页面
val newsList: List<News> //实际的新闻列表
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/news/Result.kt
|
1251064434
|
package com.example.basic_ui_demo.news
data class News(
val ctime: String, //新闻时间
val description: String, //新闻描述
val id: String, //新闻的id
val picUrl: String, //外显的图片的url
val source: String, //新闻来源
val title: String, //标题
val url: String //原文网址
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/news/News.kt
|
2662364587
|
package com.example.basic_ui_demo.news
data class NewsJson(
val code: Int,
val msg: String,
val result: Result?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/news/NewsJson.kt
|
596946318
|
package com.example.news_screen_demo.news
import com.example.basic_ui_demo.news.NewsJson
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface NewsInterface {
@GET
suspend fun getNews(
@Query("rand") rand: Int = 0,
@Query("num") num: Int = 20
): Response<NewsJson>
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/news/NewsInterface.kt
|
1319354108
|
package com.example.news_screen_demo.news
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object NewsRetrofitInstance{
private const val BASE_URL = "https://apis.tianapi.com/tiyu/index/"
//BASE_URL必须以/结尾
private const val API_KEY = "e27d3e1149c669a570070b4ac801de1a"
private val client = OkHttpClient.Builder().apply {
addInterceptor(Interceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("key", API_KEY)
.build()
chain.proceed(request)
})
}.build()
//构建OkHTTPClient对象,用于在每次使用api实例时添加api key
val api: NewsInterface by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(NewsInterface::class.java)
}
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/news/NewsRetrofitInstance.kt
|
2722232230
|
package com.example.footballapidemo
import android.util.Log
import com.example.basic_ui_demo.news.NewsJson
import com.example.footballapidemo.data.Matches
import com.example.footballapidemo.data.Person
import com.example.footballapidemo.data.Team
import com.example.footballapidemo.data.Teams
fun matchesCallback(matchesJson:Matches, viewModel: ApiViewModel){
viewModel.changeText("")
for(match in matchesJson.matches){
Log.d(TAG,"home = ${match.homeTeam.name} away = ${match.awayTeam.name} date = ${match.utcDate}")
viewModel.addText(match.homeTeam.name+" id = "+match.homeTeam.id+"\n")
viewModel.addText(match.awayTeam.name+" id = "+match.awayTeam.id+"\n")
viewModel.addText("winner: "+match.score.winner.toString()+"\n")
viewModel.addText("date:"+match.utcDate.toString()+"\n")
}
}
fun teamsCallback(teamsJson:Teams, viewModel: ApiViewModel){
viewModel.changeText("")
for(team in teamsJson.teams){
Log.d(TAG,"team = ${team.name} team id = ${team.id}")
viewModel.addText("team = ${team.name} team id = ${team.id} \n\n")
}
}
fun teamCallback(team: Team, viewModel: ApiViewModel){
viewModel.changeText("")
viewModel.addText("name = ${team.name}\n id = ${team.id}\n\n")
viewModel.addText("coach: ${team.coach?.name} id: ${team.coach?.id}\n")
viewModel.addText("squad:\n")
for(person in team.squad)
viewModel.addText("name: ${person.name} id: ${person.id}\n")
}
fun personCallback(person: Person, viewModel: ApiViewModel){
viewModel.changeText("")
viewModel.addText("name: ${person.name} \n")
}
fun newsJsonCallback(newsJson: NewsJson, viewModel: ApiViewModel){
var newsList = newsJson.result?.newsList
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/TestCallback.kt
|
2324539568
|
package com.example.footballapidemo
import com.example.footballapidemo.data.Matches
import com.example.footballapidemo.data.Person
import com.example.footballapidemo.data.Team
import com.example.footballapidemo.data.Teams
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface FootballDataInterface {
@GET("teams/")
suspend fun getTeams():Response<Teams>
//OK
@GET("teams/{teamId}/")
suspend fun getTeamById(
@Path("teamId") teamId: Int
):Response<Team>
//OK
@GET("matches")
suspend fun getMatches():Response<Matches>
//OK
// 获取特定联赛的比赛数据,api定义联赛是competition,这里用个人习惯的league
@GET("competitions/{league}/matches")
suspend fun getLeagueMatches(
@Path("league") league:String
):Response<Matches>
//OK
@GET("competitions/{league}/teams")
suspend fun getLeagueTeams(
@Path("league") league:String
):Response<Teams>
//OK
@GET("teams/{teamId}/matches")
suspend fun getTeamMatchesByTeamId(
@Path("teamId") teamId: Int,
@Query("status") status: String = "",
@Query("date") date: String = "",
@Query("dateFrom") dateFrom: String = "",
@Query("dateTo") dateTo: String = "",
@Query("season") season:Int = 2023
): Response<Matches>
@GET("persons/{personId}")
suspend fun getPersonById(
@Path("personId") personId: Int
): Response<Person>
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/FootballDataInterface.kt
|
1808023288
|
package com.example.footballapidemo.data
data class Odds(
val awayWin: Any,
val draw: Any,
val homeWin: Any
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Odds.kt
|
1042147042
|
package com.example.footballapidemo.data
data class Season(
val currentMatchday: Int,
val endDate: String,
val id: Int,
val stages: List<String>,
val startDate: String,
val winner: Any
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Season.kt
|
1242911348
|
package com.example.footballapidemo.data
data class ResultSet(
val competitions: String,
val count: Int,
val draws: Int,
val first: String,
val last: String,
val losses: Int,
val played: Int,
val wins: Int
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/ResultSet.kt
|
355144501
|
package com.example.footballapidemo.data
data class Area(
val code: String,
val flag: String,
val id: Int,
val name: String
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Area.kt
|
1510535226
|
package com.example.footballapidemo.data
data class HalfTime(
val away: Int?,
val home: Int?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/HalfTime.kt
|
3860423310
|
package com.example.footballapidemo.data
data class RunningCompetition(
val code: String,
val emblem: String,
val id: Int,
val name: String,
val type: String
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/RunningCompetition.kt
|
102976581
|
package com.example.footballapidemo.data
data class Scorer(
val player: Person,
val team: Team,
val goals: Int,
val assist: Int,
val penalties: Int
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Scorer.kt
|
3055821032
|
package com.example.footballapidemo.data
data class Match(
val area: Area?,
val attendance: Any?,
val awayTeam: Team,
val bookings: List<Any>?,
val competition: Competition?,
val goals: List<Any>?,
val group: String?,
val homeTeam: Team,
val id: Int,
val injuryTime: Any?,
val lastUpdated: String?,
val matchday: Int,
val minute: Any?,
val odds: Odds?,
val penalties: List<Any>?,
val referees: List<Any>?,
val score: Score,
val season: Season?,
val stage: String?,
val status: String?,
val substitutions: List<Any>?,
val utcDate: String?,
val venue: String?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Match.kt
|
3472220493
|
package com.example.footballapidemo.data
import java.util.Date
data class Filters(
val id : Int?,
val matchday : Int?,
val season: Int?,
val competitions: String?,
val limit: Int?,
val permission: String?,
val offset : Int?,
val status : Status?,
val venue : Venue?,
val date : String?,
val dateFrom : String?,
val dateTo : String?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Filters.kt
|
3238721618
|
package com.example.footballapidemo.data
data class Score(
val duration: String,
val fullTime: Int,
val halfTime: HalfTime,
val winner: Any
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Score.kt
|
4109326689
|
package com.example.footballapidemo.data
enum class Status(val value: String = "") {
FINAL("FINAL"),
THIRD_PLACE("THIRD_PLACE"),
SEMI_FINALS("SEMI_FINALS"),
QUARTER_FINALS("QUARTER_FINALS"),
LAST_16("LAST_16"),
LAST_32("LAST_32"),
LAST_64("LAST_64"),
ROUND_4("ROUND_4"),
ROUND_3("ROUND_3"),
ROUND_2("ROUND_2"),
ROUND_1("ROUND_1"),
GROUP_STAGE("GROUP_STAGE"),
PRELIMINARY_ROUND("PRELIMINARY_ROUND"),
QUALIFICATION("QUALIFICATION"),
QUALIFICATION_ROUND_1("QUALIFICATION_ROUND_1"),
QUALIFICATION_ROUND_2("QUALIFICATION_ROUND_2"),
QUALIFICATION_ROUND_3("QUALIFICATION_ROUND_3"),
PLAYOFF_ROUND_1("PLAYOFF_ROUND_1"),
PLAYOFF_ROUND_2("PLAYOFF_ROUND_2"),
PLAYOFFS("PLAYOFFS"),
REGULAR_SEASON("REGULAR_SEASON"),
CLAUSURA("CLAUSURA"),
APERTURA("APERTURA"),
CHAMPIONSHIP("CHAMPIONSHIP"),
RELEGATION("RELEGATION"),
RELEGATION_ROUND("RELEGATION_ROUND")
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Status.kt
|
4103951300
|
package com.example.footballapidemo.data
data class TopScorers(
val competition: Competition,
val count: Int,
val filters: Filters,
val season: Season,
val scorers: List<Scorer>
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/TopScorers.kt
|
265061949
|
package com.example.footballapidemo.data
data class Anys<T>(
val filters: Filters,
val anys: List<T>,
val resultSet: ResultSet
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Anys.kt
|
3583361451
|
package com.example.footballapidemo.data
data class CurrentSeason(
val currentMatchday: Int,
val endDate: String,
val id: Int,
val startDate: String,
val winner: Any
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/CurrentSeason.kt
|
3775130446
|
package com.example.footballapidemo.data
// 球员合同时间
data class Contract(
val start: String,
val until: String
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Contract.kt
|
2412915708
|
package com.example.footballapidemo.data
data class Coach(
val contract: Contract?,
val dateOfBirth: String?,
val firstName: String?,
val id: Int,
val lastName: String?,
val name: String,
val nationality: String
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Coach.kt
|
3286667001
|
package com.example.footballapidemo.data
data class Person(
val team: Team?,
val dateOfBirth: String,
val firstName: String,
val id: Int,
val lastName: String,
val marketValue: Int,
val lastUpdated: String,
val name: String,
val nationality: String,
val position: String,
val shirtNumber: Int,
val runningCompetitions: List<RunningCompetition>?,
val contract: Contract?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Person.kt
|
1808041248
|
package com.example.footballapidemo.data
enum class Venue(val value:String = "") {
HOME("HOME"),
AWAY("AWAY")
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Venue.kt
|
1206054999
|
package com.example.footballapidemo.data
data class Matches(
val filters: Filters,
val matches: List<Match>,
val resultSet: ResultSet,
val competition: Competition
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Matches.kt
|
2046829409
|
package com.example.footballapidemo.data
data class Team(
val id: Int,
val address: String?,
val area: Area?,
val clubColors: String?,
val contract: Contract?,
val crest: String?,
val founded: Int?,
val name: String?,
val runningCompetitions: List<Competition>?,
val shortName: String?,
val tla: String?,
val venue: String?,
val website: String?,
val bench: List<Person>,
val coach: Coach?,
val formation: Any?,
val leagueRank: Any?,
val lineup: List<Person>?,
val lastUpdated: String?,
val marketValue: Int?,
val squad: List<Person>,
val staff: List<Any>,
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Team.kt
|
3086745938
|
package com.example.footballapidemo.data
// 联赛
data class Competition(
val area: Area?,
val code: String,
val currentSeason: CurrentSeason?,
val emblem: String,
val id: Int,
val lastUpdated: String?,
val name: String,
val numberOfAvailableSeasons: Int?,
val plan: String?,
val type: String
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Competition.kt
|
1624256529
|
package com.example.footballapidemo.data
data class Teams(
val filters: Filters,
val teams: List<Team>,
val resultSet: ResultSet
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/Teams.kt
|
2315968745
|
package com.example.footballapidemo.data
data class FullTime(
val away: Int?,
val home: Int?
)
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/data/FullTime.kt
|
1432865718
|
package com.example.footballapidemo
import android.net.http.HttpException
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresExtension
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Response
import java.io.IOException
class ApiViewModel:ViewModel() {
//注意这里导入的State是runtime包里的
private var _text = mutableStateOf("abcdefg")
var text: State<String> = _text
fun changeText(textToChnage:String){
_text.value = textToChnage
}
fun addText(textToAdd:String?){
_text.value += textToAdd
}
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
fun <T,R: ViewModel> testApi(
apiFunc: suspend () -> Response<T>, //要调用的Api请求,T是response的类型
bodyCallback: (T, R) -> Unit, //函数从response中获取body后在此回调函数中处理,输出到viewModel
objectiveViewModel: R //传入回调函数进行输出或更改的viewModel
) {
viewModelScope.launch {
var attempts = 0
val maxAttempts = 4
var response: Response<T>? = null
//由于网络连接不稳,设置多次请求数据
while(response == null && attempts<maxAttempts){
attempts++
Log.d(TAG,"attempts: $attempts")
try{
response = withContext(Dispatchers.IO){
apiFunc.invoke()
}
}catch (e: IOException){
Log.e("MyTag","IOException,you may not have Internet connection")
}catch (e: HttpException){
Log.e("MyTag","HTTPException, you may not have access")
}
delay(200)
}
if (response?.body() != null) {
val body:T = response.body()!!
bodyCallback(body, objectiveViewModel)
return@launch
}
else{
Log.e(TAG,"no response or no body")
changeText("no response or no body")
}
}
}
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
fun getTeamById(teamId:Int){
viewModelScope.launch{
val result = async(Dispatchers.IO) {
try {
RetrofitInstance.api.getTeamById(teamId)
}catch (e: IOException){
Log.e("MyTag","IOException,you may not have Internet connection")
return@async null
}catch (e: HttpException){
Log.e("MyTag","HTTPException, you may not have access")
return@async null
}
}
val response = result.await()
if (response != null){
val team = response.body()!!
Log.d(TAG,team.name.toString())
Log.d(TAG,team.id.toString())
changeText("name = ${team.name} id = ${team.id.toString()}")
}
else{
Log.e(TAG,"no return")
changeText("error")
}
}
}
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
fun getMatches(){
viewModelScope.launch{
val result = async(Dispatchers.IO){
try {
RetrofitInstance.api.getMatches()
}catch (e: IOException){
Log.e("MyTag","IOException,you may not have Internet connection")
return@async null
}catch (e: HttpException){
Log.e("MyTag","HTTPException, you may not have access")
return@async null
}
}
val response = result.await()
if(response?.body() != null){
// Log.d(TAG,response.body().toString())
val matches = response.body()!!.matches
changeText(matches.size.toString())
Log.d(TAG,matches.size.toString())
for(match in matches){
val awayTeam = match.awayTeam.name
val homeTeam = match.homeTeam.name
changeText("away = $awayTeam home = $homeTeam")
Log.d(TAG,"away = $awayTeam home = $homeTeam")
}
}
else{
Log.e(TAG,"get matches error")
changeText("error")
}
}
}
}
|
FootballApiDemo/app/src/main/java/com/example/footballapidemo/ApiViewModel.kt
|
2731833497
|
package com.example.fitflowapp
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.fitflowapp", appContext.packageName)
}
}
|
Proyectorecuperacion/app/src/androidTest/java/com/example/fitflowapp/ExampleInstrumentedTest.kt
|
2933041968
|
package com.example.fitflowapp
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)
}
}
|
Proyectorecuperacion/app/src/test/java/com/example/fitflowapp/ExampleUnitTest.kt
|
3059996361
|
package com.example.fitflowapp.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)
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/ui/theme/Color.kt
|
667305096
|
package com.example.fitflowapp.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 FitFlowAppTheme(
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
)
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/ui/theme/Theme.kt
|
2165807525
|
package com.example.fitflowapp.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
)
*/
)
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/ui/theme/Type.kt
|
1170386884
|
package com.example.fitflowapp.viewmodels
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.fitflowapp.models.Usuarios
import com.example.fitflowapp.room.UsuariosDatabaseDao
import com.example.fitflowapp.states.UsuariosState
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class UsuariosViewModel (
private val dao: UsuariosDatabaseDao
): ViewModel(){
var state by mutableStateOf(UsuariosState())
private set
init {
viewModelScope.launch {
dao.obtenerUsuarios().collectLatest {
state = state.copy(
listaUsuarios = it
)
}
}
}
fun agregarUsuario(usuario: Usuarios) = viewModelScope.launch {
dao.agregarUsuario(usuario = usuario)
}
fun actualizarUsuario(usuario: Usuarios) = viewModelScope.launch {
dao.actualizarUsuario(usuario = usuario)
}
fun borrarUsuario(usuario: Usuarios) = viewModelScope.launch {
dao.borrarUsuario(usuario = usuario)
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/viewmodels/UsuariosViewModel.kt
|
2418015017
|
package com.example.fitflowapp
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 androidx.room.Room
import com.example.fitflowapp.navigation.NavManager
import com.example.fitflowapp.room.UsuariosDatabase
import com.example.fitflowapp.ui.theme.FitFlowAppTheme
import com.example.fitflowapp.viewmodels.UsuariosViewModel
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FitFlowAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val database = Room.databaseBuilder(this, UsuariosDatabase::class.java, "db_usuarios").build()
val dao = database.usuariosDao()
val viewModel = UsuariosViewModel(dao)
NavManager(viewModel = viewModel)
}
}
}
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/MainActivity.kt
|
2826967306
|
package com.example.fitflowapp.room
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.fitflowapp.models.Usuarios
@Database(
entities = [Usuarios::class],
version = 1,
exportSchema = false
)
abstract class UsuariosDatabase: RoomDatabase() {
abstract fun usuariosDao(): UsuariosDatabaseDao
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/room/UsuariosDatabase.kt
|
115294920
|
package com.example.fitflowapp.room
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.fitflowapp.models.Usuarios
import kotlinx.coroutines.flow.Flow
@Dao
interface UsuariosDatabaseDao {
@Query("SELECT * FROM usuarios")
fun obtenerUsuarios(): Flow<List<Usuarios>>
@Query("SELECT * FROM usuarios WHERE id = :id")
fun obtenerUsuario(id: Int): Flow<Usuarios>
@Insert
suspend fun agregarUsuario(usuario: Usuarios)
@Update
suspend fun actualizarUsuario(usuario: Usuarios)
@Delete
suspend fun borrarUsuario(usuario: Usuarios)
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/room/UsuariosDatabaseDao.kt
|
676487474
|
package com.example.fitflowapp.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.fitflowapp.viewmodels.UsuariosViewModel
import com.example.fitflowapp.views.AgregarView
import com.example.fitflowapp.views.EditarView
import com.example.fitflowapp.views.InicioView
@Composable
fun NavManager(viewModel: UsuariosViewModel){
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "inicio"){
composable("inicio"){
InicioView(navController, viewModel)
}
composable("agregar"){
AgregarView(navController, viewModel)
}
composable("editar/{id}/{usuario}/{email}", arguments = listOf(
navArgument("id"){ type = NavType.IntType},
navArgument("usuario"){ type = NavType.StringType},
navArgument("email"){ type = NavType.StringType},
)){
EditarView(
navController,
viewModel,
it.arguments!!.getInt("id"),
it.arguments?.getString("usuario"),
it.arguments?.getString("email")
)
}
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/navigation/NavManager.kt
|
278411487
|
package com.example.fitflowapp.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "usuarios")
data class Usuarios(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo("nombre")
val usuario: String,
@ColumnInfo("descripción")
val email: String
)
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/models/Usuarios.kt
|
839612102
|
package com.example.fitflowapp.states
import com.example.fitflowapp.models.Usuarios
data class UsuariosState(
val listaUsuarios: List<Usuarios> = emptyList()
)
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/states/UsuariosState.kt
|
383145555
|
package com.example.fitflowapp.views
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.fitflowapp.models.Usuarios
import com.example.fitflowapp.viewmodels.UsuariosViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditarView(navController: NavController, viewModel: UsuariosViewModel, id: Int, usuario: String?, email: String?) {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(text = "Editar Rutinas", color = Color.White, fontWeight = FontWeight.Bold)
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primary
),
navigationIcon = {
IconButton(
onClick = { navController.popBackStack() }
) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Regresar", tint = Color.White)
}
}
)
}
) {
ContentEditarView(it, navController, viewModel, id, usuario, email)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContentEditarView(it: PaddingValues, navController: NavController, viewModel: UsuariosViewModel, id: Int, usuario: String?, email: String?) {
var usuario by remember { mutableStateOf(usuario) }
var email by remember { mutableStateOf(email) }
Column(
modifier = Modifier
.padding(it)
.padding(top = 30.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
value = usuario ?: "",
onValueChange = { usuario = it },
label = { Text(text = "nombre") },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 30.dp)
.padding(bottom = 15.dp)
)
OutlinedTextField(
value = email ?: "",
onValueChange = { email = it },
label = { Text(text = "descripción") },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 30.dp)
.padding(bottom = 15.dp)
)
Button(
onClick = {
val usuario = Usuarios(id = id, usuario = usuario!!, email = email!!)
viewModel.actualizarUsuario(usuario)
navController.popBackStack()
}
) {
Text(text = "Editar")
}
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/views/EditarView.kt
|
38670463
|
package com.example.fitflowapp.views
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.navigation.NavController
import com.example.fitflowapp.viewmodels.UsuariosViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InicioView(navController: NavController, viewModel: UsuariosViewModel) {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(text = "FitFlow Rutinas", color = Color.White, fontWeight = FontWeight.Bold)
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primary
)
)
},
floatingActionButton = {
FloatingActionButton(
onClick = { navController.navigate("agregar") },
containerColor = MaterialTheme.colorScheme.primary,
contentColor = Color.White
) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Agregar")
}
}
) {
ContentInicioView(it, navController, viewModel)
}
}
@Composable
fun ContentInicioView(it: PaddingValues, navController: NavController, viewModel: UsuariosViewModel) {
val state = viewModel.state
Column(
modifier = Modifier.padding(it)
) {
LazyColumn {
items(state.listaUsuarios) {
Box(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth()
) {
Column(
modifier = Modifier
.padding(12.dp)
) {
Text(text = it.usuario)
Text(text = it.email)
Row(
modifier = Modifier
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(
onClick = { navController.navigate("editar/${it.id}/${it.usuario}/${it.email}") }
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Editar"
)
}
IconButton(
onClick = { viewModel.borrarUsuario(it) }
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Borrar"
)
}
}
}
}
}
}
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/views/InicioView.kt
|
2601298087
|
package com.example.fitflowapp.views
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.example.fitflowapp.models.Usuarios
import com.example.fitflowapp.viewmodels.UsuariosViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AgregarView(navController: NavController, viewModel: UsuariosViewModel) {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(text = "Agregar Rutinas", color = Color.White, fontWeight = FontWeight.Bold)
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primary
),
navigationIcon = {
IconButton(
onClick = { navController.popBackStack() }
) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Regresar", tint = Color.White)
}
}
)
}
) {
ContentAgregarView(it, navController, viewModel)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContentAgregarView(it: PaddingValues, navController: NavController, viewModel: UsuariosViewModel) {
var usuario by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
Column(
modifier = Modifier
.padding(it)
.padding(top = 30.dp)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
value = usuario,
onValueChange = { usuario = it },
label = { Text(text = "nombre") },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 30.dp)
.padding(bottom = 15.dp)
)
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text(text = "descripción") },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 30.dp)
.padding(bottom = 15.dp)
)
Button(
onClick = {
val usuario = Usuarios(usuario = usuario, email = email)
viewModel.agregarUsuario(usuario)
//para volver al inicio
navController.popBackStack()
}
) {
Text(text = "Agregar")
}
}
}
|
Proyectorecuperacion/app/src/main/java/com/example/fitflowapp/views/AgregarView.kt
|
3822454372
|
package com.abto.checkpoint
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.abto.checkpoint", appContext.packageName)
}
}
|
CheckpointAndroid/app/src/androidTest/java/com/abto/checkpoint/ExampleInstrumentedTest.kt
|
1295630584
|
package com.abto.checkpoint
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)
}
}
|
CheckpointAndroid/app/src/test/java/com/abto/checkpoint/ExampleUnitTest.kt
|
3918871071
|
package com.abto.checkpoint.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is home Fragment"
}
val text: LiveData<String> = _text
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/home/HomeViewModel.kt
|
636911577
|
package com.abto.checkpoint.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.abto.checkpoint.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/home/HomeFragment.kt
|
680875855
|
package com.abto.checkpoint.ui.dashboard
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.abto.checkpoint.databinding.FragmentDashboardBinding
class DashboardFragment : Fragment() {
private var _binding: FragmentDashboardBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val dashboardViewModel =
ViewModelProvider(this).get(DashboardViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/dashboard/DashboardFragment.kt
|
649208128
|
package com.abto.checkpoint.ui.dashboard
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class DashboardViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is dashboard Fragment"
}
val text: LiveData<String> = _text
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/dashboard/DashboardViewModel.kt
|
1063108488
|
package com.abto.checkpoint.ui.notifications
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class NotificationsViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is notifications Fragment"
}
val text: LiveData<String> = _text
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/notifications/NotificationsViewModel.kt
|
3408201015
|
package com.abto.checkpoint.ui.notifications
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.abto.checkpoint.databinding.FragmentNotificationsBinding
class NotificationsFragment : Fragment() {
private var _binding: FragmentNotificationsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val notificationsViewModel =
ViewModelProvider(this).get(NotificationsViewModel::class.java)
_binding = FragmentNotificationsBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textNotifications
notificationsViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/ui/notifications/NotificationsFragment.kt
|
918359729
|
package com.abto.checkpoint
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.abto.checkpoint.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
}
|
CheckpointAndroid/app/src/main/java/com/abto/checkpoint/MainActivity.kt
|
634527755
|
package np.com.bimalkafle.quizonline
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("np.com.bimalkafle.quizonline", appContext.packageName)
}
}
|
Android_QuizAppWithFirebase/app/src/androidTest/java/np/com/bimalkafle/quizonline/ExampleInstrumentedTest.kt
|
3250638994
|
package np.com.bimalkafle.quizonline
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_QuizAppWithFirebase/app/src/test/java/np/com/bimalkafle/quizonline/ExampleUnitTest.kt
|
6185776
|
package np.com.bimalkafle.quizonline
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.ktx.Firebase
import np.com.bimalkafle.quizonline.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var quizModelList : MutableList<QuizModel>
lateinit var adapter: QuizListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
quizModelList = mutableListOf()
getDataFromFirebase()
}
private fun setupRecyclerView(){
binding.progressBar.visibility = View.GONE
adapter = QuizListAdapter(quizModelList)
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
}
private fun getDataFromFirebase(){
binding.progressBar.visibility = View.VISIBLE
FirebaseDatabase.getInstance().reference
.get()
.addOnSuccessListener { dataSnapshot->
if(dataSnapshot.exists()){
for (snapshot in dataSnapshot.children){
val quizModel = snapshot.getValue(QuizModel::class.java)
if (quizModel != null) {
quizModelList.add(quizModel)
}
}
}
setupRecyclerView()
}
}
}
|
Android_QuizAppWithFirebase/app/src/main/java/np/com/bimalkafle/quizonline/MainActivity.kt
|
467671230
|
package np.com.bimalkafle.quizonline
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import np.com.bimalkafle.quizonline.databinding.QuizItemRecyclerRowBinding
class QuizListAdapter(private val quizModelList : List<QuizModel>) :
RecyclerView.Adapter<QuizListAdapter.MyViewHolder>() {
class MyViewHolder(private val binding: QuizItemRecyclerRowBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(model : QuizModel){
binding.apply {
quizTitleText.text = model.title
quizSubtitleText.text = model.subtitle
quizTimeText.text = model.time + " min"
root.setOnClickListener {
val intent = Intent(root.context,QuizActivity::class.java)
QuizActivity.questionModelList = model.questionList
QuizActivity.time = model.time
root.context.startActivity(intent)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val binding = QuizItemRecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return quizModelList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(quizModelList[position])
}
}
|
Android_QuizAppWithFirebase/app/src/main/java/np/com/bimalkafle/quizonline/QuizListAdapter.kt
|
2997120683
|
package np.com.bimalkafle.quizonline
data class QuizModel(
val id : String,
val title : String,
val subtitle : String,
val time : String,
val questionList : List<QuestionModel>
){
constructor() : this("","","","", emptyList())
}
data class QuestionModel(
val question : String,
val options : List<String>,
val correct : String,
){
constructor() : this ("", emptyList(),"")
}
|
Android_QuizAppWithFirebase/app/src/main/java/np/com/bimalkafle/quizonline/QuizModel.kt
|
1050351106
|
package np.com.bimalkafle.quizonline
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import np.com.bimalkafle.quizonline.databinding.ActivityQuizBinding
import np.com.bimalkafle.quizonline.databinding.ScoreDialogBinding
import kotlin.math.min
class QuizActivity : AppCompatActivity(),View.OnClickListener {
companion object {
var questionModelList : List<QuestionModel> = listOf()
var time : String = ""
}
lateinit var binding: ActivityQuizBinding
var currentQuestionIndex = 0;
var selectedAnswer = ""
var score = 0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityQuizBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
btn0.setOnClickListener(this@QuizActivity)
btn1.setOnClickListener(this@QuizActivity)
btn2.setOnClickListener(this@QuizActivity)
btn3.setOnClickListener(this@QuizActivity)
nextBtn.setOnClickListener(this@QuizActivity)
}
loadQuestions()
startTimer()
}
private fun startTimer(){
val totalTimeInMillis = time.toInt() * 60 * 1000L
object : CountDownTimer(totalTimeInMillis,1000L){
override fun onTick(millisUntilFinished: Long) {
val seconds = millisUntilFinished /1000
val minutes = seconds/60
val remainingSeconds = seconds % 60
binding.timerIndicatorTextview.text = String.format("%02d:%02d", minutes,remainingSeconds)
}
override fun onFinish() {
//Finish the quiz
}
}.start()
}
private fun loadQuestions(){
selectedAnswer = ""
if(currentQuestionIndex == questionModelList.size){
finishQuiz()
return
}
binding.apply {
questionIndicatorTextview.text = "Question ${currentQuestionIndex+1}/ ${questionModelList.size} "
questionProgressIndicator.progress =
( currentQuestionIndex.toFloat() / questionModelList.size.toFloat() * 100 ).toInt()
questionTextview.text = questionModelList[currentQuestionIndex].question
btn0.text = questionModelList[currentQuestionIndex].options[0]
btn1.text = questionModelList[currentQuestionIndex].options[1]
btn2.text = questionModelList[currentQuestionIndex].options[2]
btn3.text = questionModelList[currentQuestionIndex].options[3]
}
}
override fun onClick(view: View?) {
binding.apply {
btn0.setBackgroundColor(getColor(R.color.gray))
btn1.setBackgroundColor(getColor(R.color.gray))
btn2.setBackgroundColor(getColor(R.color.gray))
btn3.setBackgroundColor(getColor(R.color.gray))
}
val clickedBtn = view as Button
if(clickedBtn.id==R.id.next_btn){
//next button is clicked
if(selectedAnswer.isEmpty()){
Toast.makeText(applicationContext,"Please select answer to continue",Toast.LENGTH_SHORT).show()
return;
}
if(selectedAnswer == questionModelList[currentQuestionIndex].correct){
score++
Log.i("Score of quiz",score.toString())
}
currentQuestionIndex++
loadQuestions()
}else{
//options button is clicked
selectedAnswer = clickedBtn.text.toString()
clickedBtn.setBackgroundColor(getColor(R.color.orange))
}
}
private fun finishQuiz(){
val totalQuestions = questionModelList.size
val percentage = ((score.toFloat() / totalQuestions.toFloat() ) *100 ).toInt()
val dialogBinding = ScoreDialogBinding.inflate(layoutInflater)
dialogBinding.apply {
scoreProgressIndicator.progress = percentage
scoreProgressText.text = "$percentage %"
if(percentage>60){
scoreTitle.text = "Congrats! You have passed"
scoreTitle.setTextColor(Color.BLUE)
}else{
scoreTitle.text = "Oops! You have failed"
scoreTitle.setTextColor(Color.RED)
}
scoreSubtitle.text = "$score out of $totalQuestions are correct"
finishBtn.setOnClickListener {
finish()
}
}
AlertDialog.Builder(this)
.setView(dialogBinding.root)
.setCancelable(false)
.show()
}
}
|
Android_QuizAppWithFirebase/app/src/main/java/np/com/bimalkafle/quizonline/QuizActivity.kt
|
1408704082
|
package com.example.phonebook2
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.phonebook2", appContext.packageName)
}
}
|
Mobile-W10/app/src/androidTest/java/com/example/phonebook2/ExampleInstrumentedTest.kt
|
3222604114
|
package com.example.phonebook2
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)
}
}
|
Mobile-W10/app/src/test/java/com/example/phonebook2/ExampleUnitTest.kt
|
30918942
|
package com.example.phonebook2
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
class ListFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val contacts = listOf(
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
ItemModel(R.drawable.img1, "Huy Tran"),
)
val listView: ListView = view.findViewById(R.id.list_view)
val adapter = ItemAdapter(requireContext(), contacts)
listView.adapter = adapter
listView.setOnItemClickListener { parent, view, position, id ->
val selectedContact = contacts[position]
val nameAcc = selectedContact.nameAcc
// val params: Bundle = Bundle()
// val navController = view.findNavController()
// navController.navigate(R.id.action_listFragment_to_infDetailFragment, params)
//
// params.putString("SELECTED_ITEM", name)
val detailFragment = InfDetailFragment.newInstance(nameAcc)
requireActivity().supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, detailFragment)
.addToBackStack(null)
.commit()
}
}
// override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// inflater.inflate(R.menu.option_menu, menu)
// super.onCreateOptionsMenu(menu, inflater)
// }
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.add_option -> {
Log.d("ListFragment", "Add option selected")
val addItemFragment = AddFragment()
requireActivity().supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, addItemFragment)
.addToBackStack(null)
.commit()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/ListFragment.kt
|
192320785
|
package com.example.phonebook2
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.option_menu, menu)
return true
}
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/MainActivity.kt
|
3068051258
|
package com.example.phonebook2
data class ItemModel( val profileImg : Int, val nameAcc: String) {
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/ItemModel.kt
|
2456939684
|
package com.example.phonebook2
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class AddFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add, container, false)
}
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/AddFragment.kt
|
2435060963
|
package com.example.phonebook2
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class InfDetailFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_inf_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
companion object {
fun newInstance(name: String): InfDetailFragment {
val fragment = InfDetailFragment()
return fragment
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.add_option -> {
val addItemFragment = AddFragment()
requireActivity().supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, addItemFragment)
.addToBackStack(null)
.commit()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/InfDetailFragment.kt
|
4215819467
|
package com.example.phonebook2
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ItemAdapter(context: Context, contacts: List<ItemModel>) :
ArrayAdapter<ItemModel>(context, R.layout.list_item, contacts) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val itemView = convertView ?: LayoutInflater.from(context)
.inflate(R.layout.list_item, parent, false)
val imageViewContact: ImageView = itemView.findViewById(R.id.contact_img)
val textViewContactName: TextView = itemView.findViewById(R.id.contact_name)
val contact = getItem(position)
imageViewContact.setImageResource(contact?.profileImg ?: R.drawable.img)
textViewContactName.text = contact?.nameAcc
return itemView
}
}
|
Mobile-W10/app/src/main/java/com/example/phonebook2/ItemAdapter.kt
|
2441563409
|
package io.github.yuazer.zaxworld.database
import io.github.yuazer.zaxworld.ZaxWorld
import taboolib.module.database.use
import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.SQLException
class DataSQL {
private val host = ZaxWorld.databaseConfig.getString("database.host")
private val port = ZaxWorld.databaseConfig.getString("database.port")
private val user = ZaxWorld.databaseConfig.getString("database.user")
private val password = ZaxWorld.databaseConfig.getString("database.password")
private val name = ZaxWorld.databaseConfig.getString("database.database")
private val url = "jdbc:mysql://${host}:${port}/${name}?useSSL=false"
private val serverUrl = "jdbc:mysql://localhost:3306/?useSSL=false&allowPublicKeyRetrieval=true"
fun createDatabaseIfNotExists(serverUrl: String, username: String, password: String, databaseName: String) {
var connection: Connection? = null
try {
// 连接到MySQL服务器
connection = DriverManager.getConnection(serverUrl, username, password)
val statement = connection.createStatement()
// 执行SQL语句,检查数据库是否存在,如果不存在则创建
val sql = "CREATE DATABASE IF NOT EXISTS $databaseName"
statement.executeUpdate(sql)
println("数据库 $databaseName 已经成功创建或已存在。")
} catch (e: SQLException) {
e.printStackTrace()
} finally {
// 确保数据库连接被正确关闭
try {
connection?.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
}
fun createTableIfNotExists(databaseUrl: String, username: String, password: String, tableName: String) {
var connection: Connection? = null
try {
// 连接到指定的数据库
connection = DriverManager.getConnection(databaseUrl, username, password)
val statement = connection.createStatement()
// 检查表是否存在,如果不存在则创建
val sql = """
CREATE TABLE IF NOT EXISTS $tableName (
id INT AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(255) NOT NULL,
worldName VARCHAR(255) NOT NULL,
time INT NOT NULL
)
""".trimIndent()
statement.executeUpdate(sql)
println("表 $tableName 已经成功创建或已存在。")
} catch (e: SQLException) {
e.printStackTrace()
} finally {
// 确保数据库连接被正确关闭
try {
connection?.close()
} catch (e: SQLException) {
e.printStackTrace()
}
}
}
init {
createDatabaseIfNotExists(serverUrl,user?:"root",password?:"root",name?:"zaxworld")
createTableIfNotExists(url,user?:"root",password?:"root","player_data")
}
private fun getConnection(): Connection? {
return try {
DriverManager.getConnection(url, user, password)
} catch (e: SQLException) {
e.printStackTrace()
null
}
}
fun addUser(user: String, worldName: String, time: Int) {
getConnection()?.use { conn ->
val stmt = conn.prepareStatement("INSERT INTO player_data (user, worldName, time) VALUES (?, ?, ?)")
stmt.setString(1, user)
stmt.setString(2, worldName)
stmt.setInt(3, time)
stmt.executeUpdate()
}
}
fun deleteUser(user: String) {
getConnection()?.use { conn ->
val stmt = conn.prepareStatement("DELETE FROM player_data WHERE user = ?")
stmt.setString(1, user)
stmt.executeUpdate()
}
}
fun upsertUserWorld(user: String, worldName: String, time: Int) {
getConnection()?.use { conn ->
// 首先尝试更新存在的记录
val updateStmt = conn.prepareStatement("UPDATE player_data SET time = ? WHERE user = ? AND worldName = ?")
updateStmt.setInt(1, time)
updateStmt.setString(2, user)
updateStmt.setString(3, worldName)
val updatedRows = updateStmt.executeUpdate()
// 如果没有记录被更新(意味着不存在相同的user和worldName组合),则插入新记录
if (updatedRows == 0) {
val insertStmt = conn.prepareStatement("INSERT INTO player_data (user, worldName, time) VALUES (?, ?, ?)")
insertStmt.setString(1, user)
insertStmt.setString(2, worldName)
insertStmt.setInt(3, time)
insertStmt.executeUpdate()
}
}
}
fun upsertPlayerData(user: String, worldName: String, time: Int) {
getConnection()?.use {
connection: Connection ->
try {
// 尝试更新记录
val updateSql = "UPDATE player_data SET time = ? WHERE user = ? AND worldName = ?"
val updateStmt: PreparedStatement = connection.prepareStatement(updateSql).apply {
setInt(1, time)
setString(2, user)
setString(3, worldName)
}
val updatedRows = updateStmt.executeUpdate()
// 如果没有记录被更新,则插入新记录
if (updatedRows == 0) {
val insertSql = "INSERT INTO player_data (user, worldName, time) VALUES (?, ?, ?)"
val insertStmt: PreparedStatement = connection.prepareStatement(insertSql).apply {
setString(1, user)
setString(2, worldName)
setInt(3, time)
}
insertStmt.executeUpdate()
}
println("数据更新成功")
} catch (e: SQLException) {
e.printStackTrace()
} finally {
connection.close()
}
}
}
fun queryUserWorldsAndTimes(user: String): List<Map<String, Int>> {
val results = mutableListOf<Map<String, Int>>()
getConnection()?.use { conn ->
val stmt = conn.prepareStatement("SELECT worldName, time FROM player_data WHERE user = ?")
stmt.setString(1, user)
val resultSet = stmt.executeQuery()
while (resultSet.next()) {
val worldName = resultSet.getString("worldName")
val time = resultSet.getInt("time")
results.add(mapOf(worldName to time))
}
}
return results // 返回一个包含Map的List
}
fun listAllUsers(): Set<String> {
val users = mutableSetOf<String>()
getConnection()?.use { conn ->
val stmt = conn.prepareStatement("SELECT DISTINCT user FROM player_data")
val resultSet = stmt.executeQuery()
while (resultSet.next()) {
users.add(resultSet.getString("user"))
}
}
return users // 直接返回users,而不是在use块中返回
}
fun getUserWorldsAndTimes(user: String): MutableMap<String, Int> {
val worldTimes = mutableMapOf<String, Int>()
getConnection()?.use { conn ->
val stmt = conn.prepareStatement("SELECT worldName, time FROM player_data WHERE user = ?")
stmt.setString(1, user)
val resultSet = stmt.executeQuery()
while (resultSet.next()) {
val worldName = resultSet.getString("worldName")
val time = resultSet.getInt("time")
worldTimes[worldName] = time
}
}
return worldTimes
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/database/DataSQL.kt
|
2785213217
|
package io.github.yuazer.zaxworld.database
import io.github.yuazer.zaxworld.ZaxWorld
import taboolib.common.platform.function.submitAsync
object DataLoader{
private val dataSQL = DataSQL()
fun loadData2Cache_Async(){
submitAsync(now = true, delay = 0) {
dataSQL.listAllUsers().forEach {username->
val userAllData:List<Map<String, Int>> = dataSQL.queryUserWorldsAndTimes(username)
for (data:Map<String,Int> in userAllData){
data.keys.forEach(action = {world->
val totalName:String = ZaxWorld.getPlayerCacheMap().getPWKey(username,world)
val defaultTime = ZaxWorld.config.getInt("World.${world}.time")
ZaxWorld.getPlayerCacheMap().getMap()[totalName] = data[world] ?:defaultTime
})
}
}
}
}
fun saveDataFromCache_Async(){
submitAsync(now = true) {
val dataMap: MutableMap<String, Int> = ZaxWorld.getPlayerCacheMap().getMap()
dataMap.keys.forEach {
val playerName = it.split("<>")[0]
val worldName = it.split("<>")[1]
val defaultTime = ZaxWorld.config.getInt("World.${worldName}.time")
dataSQL.upsertPlayerData(playerName,worldName,dataMap[it]?:defaultTime)
}
}
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/database/DataLoader.kt
|
2059480365
|
package io.github.yuazer.zaxworld
import io.github.yuazer.zaxworld.database.DataLoader
import io.github.yuazer.zaxworld.manager.BukkitRunnableManager
import io.github.yuazer.zaxworld.mymap.PlayerWorldMap
import taboolib.common.platform.Plugin
import taboolib.common.platform.function.info
import taboolib.module.configuration.Config
import taboolib.module.configuration.ConfigFile
import taboolib.platform.BukkitPlugin
object ZaxWorld : Plugin() {
private lateinit var playerWorldCache:PlayerWorldMap
lateinit var runnableManager: BukkitRunnableManager
fun getPlayerCacheMap():PlayerWorldMap {
return playerWorldCache
}
@Config("config.yml")
lateinit var config: ConfigFile
@Config("database.yml")
lateinit var databaseConfig: ConfigFile
override fun onEnable() {
//初始化缓存,并从数据库中读取数据加载进缓存
playerWorldCache = PlayerWorldMap
//初始化Runnable管理器
runnableManager = BukkitRunnableManager(BukkitPlugin.getInstance())
//初始化数据库
DataLoader.loadData2Cache_Async()
info("Successfully running ZaxWorld!")
info("Author: YuaZer[QQ:1109132]")
}
override fun onDisable() {
//取消所有调度器
runnableManager.stopAll()
//TODO 缓存数据保存到文件
DataLoader.saveDataFromCache_Async()
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/ZaxWorld.kt
|
3542989319
|
package io.github.yuazer.zaxworld.listener
import io.github.yuazer.zaxworld.ZaxWorld
import taboolib.common.platform.event.SubscribeEvent
import taboolib.module.lang.event.PlayerSelectLocaleEvent
import taboolib.module.lang.event.SystemSelectLocaleEvent
object LangEvent {
@SubscribeEvent
fun lang(event: PlayerSelectLocaleEvent) {
event.locale = ZaxWorld.config.getString("Lang", "zh_CN")!!
}
@SubscribeEvent
fun lang(event: SystemSelectLocaleEvent) {
event.locale = ZaxWorld.config.getString("Lang", "zh_CN")!!
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/listener/LangEvent.kt
|
2874517541
|
package io.github.yuazer.zaxworld.listener
import io.github.yuazer.zaxworld.ZaxWorld
import io.github.yuazer.zaxworld.runnable.WorldRunnable
import org.bukkit.event.player.PlayerChangedWorldEvent
import taboolib.common.platform.event.SubscribeEvent
object WorldEvent {
@SubscribeEvent
fun onChangeWorld(e:PlayerChangedWorldEvent) {
val player = e.player
val playerName = player.name
val worldName = player.world.name
val worldList = ZaxWorld.config.getConfigurationSection("World")?.getKeys(false) ?: emptySet()
if (!worldList.contains(worldName)){
ZaxWorld.getPlayerCacheMap().getPlayerAllWorld(playerName).forEach {
ZaxWorld.runnableManager.stop(playerName, it)
}
return
}else{
val worldRunnable = WorldRunnable(playerName,worldName)
ZaxWorld.runnableManager.add(playerName , worldName,worldRunnable)
ZaxWorld.runnableManager.asyncStart(playerName,worldName)
}
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/listener/WorldEvent.kt
|
2848907405
|
package io.github.yuazer.zaxworld.listener
import io.github.yuazer.zaxworld.ZaxWorld
import io.github.yuazer.zaxworld.runnable.WorldRunnable
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import taboolib.common.platform.event.SubscribeEvent
object PlayerEvent {
@SubscribeEvent
fun onJoin(e: PlayerJoinEvent){
val player = e.player
val playerName = player.name
val worldName = player.world.name
val worldList = ZaxWorld.config.getConfigurationSection("World")?.getKeys(false) ?: emptySet()
if (!worldList.contains(worldName)){
ZaxWorld.getPlayerCacheMap().getPlayerAllWorld(playerName).forEach {
ZaxWorld.runnableManager.stop(playerName, it)
}
return
}else{
val worldRunnable = WorldRunnable(playerName,worldName)
ZaxWorld.runnableManager.add(playerName , worldName,worldRunnable)
ZaxWorld.runnableManager.asyncStart(playerName,worldName)
}
}
@SubscribeEvent
fun onQuit(e:PlayerQuitEvent){
val player=e.player
val worldName = player.world.name
ZaxWorld.runnableManager.stop(player.name, worldName)
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/listener/PlayerEvent.kt
|
905127402
|
package io.github.yuazer.zaxworld.utils
import org.bukkit.entity.Player
import taboolib.common.platform.function.adaptCommandSender
import taboolib.module.kether.KetherShell
import taboolib.module.kether.ScriptOptions
object PlayerUtils {
fun runKether(script: List<String>, player: Player) {
taboolib.module.kether.runKether(script,detailError = true) {
KetherShell.eval(
script, options = ScriptOptions(
sender = adaptCommandSender(player)
)
)
}
}
fun replaceInList(strings: List<String>, oldChar: String, newChar: String): List<String> {
return strings.map { it.replace(oldChar, newChar) }
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/utils/PlayerUtils.kt
|
3841422477
|
package io.github.yuazer.zaxworld.runnable
import io.github.yuazer.zaxworld.ZaxWorld
import io.github.yuazer.zaxworld.utils.PlayerUtils
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitRunnable
class WorldRunnable(var playerName:String,var worldName:String): BukkitRunnable() {
private val worldList = ZaxWorld.config.getConfigurationSection("World")?.getKeys(false) ?: emptySet()
val player = Bukkit.getPlayer(playerName)
override fun run() {
if (worldList.contains(worldName)){
var time = ZaxWorld.getPlayerCacheMap().getPlayerWorldTime(playerName, worldName)
if (time<=0){
val ketherList = PlayerUtils.replaceInList(ZaxWorld.config.getStringList("World.${worldName}.endScript"),"%player_name%",playerName)
PlayerUtils.runKether(ketherList,Bukkit.getPlayer(playerName)?:return)
ZaxWorld.runnableManager.stop(playerName, worldName)
return
}
time--
ZaxWorld.getPlayerCacheMap().set(playerName,worldName,time)
}else{
ZaxWorld.runnableManager.stop(playerName, worldName)
}
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/runnable/WorldRunnable.kt
|
1002581510
|
package io.github.yuazer.zaxworld.manager
import io.github.yuazer.zaxworld.ZaxWorld
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.scheduler.BukkitRunnable
class BukkitRunnableManager(private val plugin: JavaPlugin) {
private val tasks: MutableMap<String, BukkitRunnable> = mutableMapOf()
fun add(key: String, runnable: BukkitRunnable) {
// 添加任务到管理器,不立即启动
tasks[key]?.cancel() // 如果有相同的任务正在运行,则先停止它
tasks[key] = runnable
}
fun add(playerName: String, worldName: String, runnable: BukkitRunnable) {
val key = ZaxWorld.getPlayerCacheMap().getPWKey(playerName, worldName)
tasks[key]?.cancel() // 如果有相同的任务正在运行,则先停止它
tasks[key] = runnable
}
fun syncStart(playerName: String, worldName: String, delay: Long = 0L, period: Long = 20L) {
val key = ZaxWorld.getPlayerCacheMap().getPWKey(playerName, worldName)
tasks[key]?.runTaskTimer(plugin, delay, period)
}
fun asyncStart(playerName: String, worldName: String, delay: Long = 0L, period: Long = 20L) {
val key = ZaxWorld.getPlayerCacheMap().getPWKey(playerName, worldName)
tasks[key]?.runTaskTimerAsynchronously(plugin, delay, period)
}
fun stop(key: String) {
tasks[key]?.cancel()
tasks.remove(key)
}
fun stop(playerName: String, worldName: String) {
val key = ZaxWorld.getPlayerCacheMap().getPWKey(playerName, worldName)
tasks[key]?.cancel()
tasks.remove(key)
}
fun stopAll() {
tasks.keys.toList().forEach(this::stop) // 防止ConcurrentModificationException
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/manager/BukkitRunnableManager.kt
|
971625106
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.