content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package jp.co.yumemi.android.code_check
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* 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-full-coding/app/src/test/kotlin/jp/co/yumemi/android/code_check/ExampleUnitTest.kt | 1145374110 |
package jp.co.yumemi.android.code_check.viewModel
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import jp.co.yumemi.android.code_check.common.NetworkResponse
import jp.co.yumemi.android.code_check.common.State.GithubRepositoryState
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.viewModel.utlil.SearchGithubUtil
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class GithubDetailViewModel
@Inject
constructor(
private val searchGithubUtil: SearchGithubUtil,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val _state = mutableStateOf(GithubRepositoryState<Item>())
val state: State<GithubRepositoryState<Item>> = _state
init {
val owner = checkNotNull(savedStateHandle.get<String>("owner"))
val repo = checkNotNull(savedStateHandle.get<String>("repo"))
Log.d("owner", owner)
Log.d("repo", repo)
getGithubDetail(repo = repo, owner = owner)
}
private fun getGithubDetail(
repo: String,
owner: String,
) {
searchGithubUtil.getRepositoryDetail(repo = repo, owner = owner).onEach { result ->
when (result) {
is NetworkResponse.Loading -> {
_state.value = GithubRepositoryState(isLoading = true)
}
is NetworkResponse.Failure -> {
_state.value = GithubRepositoryState(error = result.error)
}
is NetworkResponse.Success -> {
Log.d("Response", _state.value.data.toString())
_state.value = GithubRepositoryState(data = result.data)
}
}
}
.launchIn(viewModelScope)
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/viewModel/GithubDetailViewModel.kt | 2390554913 |
package jp.co.yumemi.android.code_check.viewModel.utlil
import jp.co.yumemi.android.code_check.common.NetworkResponse
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.model.SearchGithubRepositoryModel
import jp.co.yumemi.android.code_check.repository.GithubRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class SearchGithubUtil
@Inject
constructor(
private val githubRepository: GithubRepository,
) {
// query -> searchGithubRepositoryで検索 -> responseの取得
fun searchGithubRepository(query: String): Flow<NetworkResponse<SearchGithubRepositoryModel>> =
flow {
try {
emit(NetworkResponse.Loading())
val result = githubRepository.searchGithubRepository(query)
emit(NetworkResponse.Success(data = result))
} catch (e: Exception) {
emit(NetworkResponse.Failure(error = e.toString()))
}
}
fun getRepositoryDetail(
repo: String,
owner: String,
): Flow<NetworkResponse<Item>> =
flow {
try {
emit(NetworkResponse.Loading())
val result = githubRepository.getGithubDetail(owner = owner, repo = repo)
emit(NetworkResponse.Success(data = result))
} catch (e: Exception) {
emit(NetworkResponse.Failure(error = e.toString()))
}
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/viewModel/utlil/SearchGithubUtil.kt | 2892786042 |
package jp.co.yumemi.android.code_check.viewModel
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import jp.co.yumemi.android.code_check.common.NetworkResponse
import jp.co.yumemi.android.code_check.common.State.GithubRepositoryState
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.viewModel.utlil.SearchGithubUtil
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class SearchGithubViewModel
@Inject
constructor(
private val searchGithubUtil: SearchGithubUtil,
) : ViewModel() {
private val _state = mutableStateOf(GithubRepositoryState<List<Item>>())
val state: State<GithubRepositoryState<List<Item>>> = _state
var query by mutableStateOf("")
fun searchGithubRepository() {
searchGithubUtil.searchGithubRepository(query).onEach { result ->
when (result) {
is NetworkResponse.Success -> {
_state.value =
GithubRepositoryState(
data = result.data.items,
isLoading = false,
)
}
is NetworkResponse.Failure -> {
_state.value = GithubRepositoryState(error = result.error)
}
is NetworkResponse.Loading -> {
_state.value = GithubRepositoryState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/viewModel/SearchGithubViewModel.kt | 4140274347 |
package jp.co.yumemi.android.code_check.ui.theme
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.ui.platform.LocalContext
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 YumemiCodeCheckTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
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
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/ui/theme/YumemiCodeCheckTheme.kt | 2045046519 |
package jp.co.yumemi.android.code_check.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/ui/theme/Color.kt | 2620769278 |
package jp.co.yumemi.android.code_check.ui.theme
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
val Typography = androidx.compose.material3.Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
bodyMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
bodySmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/ui/theme/Type.kt | 2502084232 |
package jp.co.yumemi.android.code_check.repository
import android.util.Log
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.model.SearchGithubRepositoryModel
import javax.inject.Inject
class GithubRepository
@Inject
constructor(
private val githubService: GithubService,
) {
suspend fun searchGithubRepository(query: String): SearchGithubRepositoryModel {
return githubService.searchGithubRepository(query)
}
suspend fun getGithubDetail(
owner: String,
repo: String,
): Item {
Log.d("GithubRepository", githubService.getGithubDetail(owner, repo).toString())
return githubService.getGithubDetail(owner, repo)
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/repository/GithubRepository.kt | 2795658801 |
package jp.co.yumemi.android.code_check.repository
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.model.SearchGithubRepositoryModel
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface GithubService {
@GET("search/repositories")
suspend fun searchGithubRepository(
@Query("q") query: String,
): SearchGithubRepositoryModel
@GET("repos/{owner}/{repo}")
suspend fun getGithubDetail(
@Path("owner") owner: String,
@Path("repo") repo: String,
): Item
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/repository/GithubService.kt | 2841235916 |
package jp.co.yumemi.android.code_check
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import dagger.hilt.android.AndroidEntryPoint
import jp.co.yumemi.android.code_check.ui.theme.YumemiCodeCheckTheme
import jp.co.yumemi.android.code_check.view.GithubDetailView
import jp.co.yumemi.android.code_check.view.SearchGithubView
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
YumemiCodeCheckTheme {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = ViewRoute.SearchGithubView.route,
) {
composable(route = ViewRoute.SearchGithubView.route) {
SearchGithubView(
goToDetailView = {
navController.navigate(
ViewRoute.GithubDetailView.route.replace(
"{repo}",
it.name,
).replace("{owner}", it.owner.name),
)
},
)
}
composable(
route = ViewRoute.GithubDetailView.route,
arguments =
listOf(
navArgument("repo") {
type = NavType.StringType
},
navArgument("owner") {
type = NavType.StringType
},
),
) { backStackEntry ->
GithubDetailView(
goToSearchView = { navController.navigate(ViewRoute.SearchGithubView.route) },
)
}
}
}
}
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/MainActivity.kt | 2243583023 |
package jp.co.yumemi.android.code_check.di
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityRetainedComponent
import jp.co.yumemi.android.code_check.repository.GithubService
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
@Module
@InstallIn(ActivityRetainedComponent::class)
object GithubModule {
@Provides
fun provideRetrofit(): Retrofit {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
return Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
}
@Provides
fun provideGithubService(retrofit: Retrofit): GithubService {
return retrofit.create(GithubService::class.java)
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/di/GithubModule.kt | 2332174723 |
package jp.co.yumemi.android.code_check
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class Application : Application()
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/Application.kt | 1363761704 |
package jp.co.yumemi.android.code_check.common
sealed class NetworkResponse<T>(
val error: String? = null,
) {
class Success<T>(val data: T) : NetworkResponse<T>()
class Failure<T>(error: String) : NetworkResponse<T>(error = error)
class Loading<T> : NetworkResponse<T>()
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/common/NetworkResponse.kt | 3210990826 |
package jp.co.yumemi.android.code_check.common.State
data class GithubRepositoryState<T>(
val isLoading: Boolean = false,
val data: T? = null,
val error: String? = null,
)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/common/State/GithubRepositoryState.kt | 4212289269 |
package jp.co.yumemi.android.code_check.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
// /val name: String,
// val ownerIconUrl: OwnerList,
@JsonClass(generateAdapter = true)
data class Item(
@Json(name = "name")
val name: String,
@Json(name = "forks_count")
val forksCount: Int?,
@Json(name = "open_issues_count")
val openIssuesCount: Int,
val language: String?,
@Json(name = "stargazers_count")
val stargazersCount: Int?,
@Json(name = "watchers_count")
val watchersCount: Int?,
val owner: Owner,
)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/model/Item.kt | 1907931199 |
package jp.co.yumemi.android.code_check.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class SearchGithubRepositoryModel(
@Json(name = "incomplete_results")
val incompleteResults: Boolean?,
val items: List<Item>,
@Json(name = "total_count")
val totalCount: Int?
)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/model/SearchGithubRepositoryModel.kt | 2417184479 |
package jp.co.yumemi.android.code_check.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Owner(
@Json(name = "avatar_url") val avatarUrl: String,
@Json(name = "login") val name: String,
)
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/model/Owner.kt | 267835985 |
package jp.co.yumemi.android.code_check.view
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import jp.co.yumemi.android.code_check.ui.theme.Typography
import jp.co.yumemi.android.code_check.viewModel.GithubDetailViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GithubDetailView(
goToSearchView: () -> Unit,
viewModel: GithubDetailViewModel = hiltViewModel(),
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally,
) {
val state = viewModel.state.value
val ctx = LocalContext.current
when {
state.isLoading -> {
CircularProgressIndicator()
}
!state.error.isNullOrBlank() -> {
Toast.makeText(ctx, "レポジトリを検索できませんでした", Toast.LENGTH_LONG).show()
Log.d("Error", state.error)
}
state.data != null -> {
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(text = state.data.owner.name)
},
navigationIcon = {
IconButton(onClick = { goToSearchView() }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "戻る",
)
}
},
)
},
) { inner ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier =
Modifier
.fillMaxWidth()
.padding(inner),
) {
AsyncImage(
model = state.data.owner.avatarUrl,
contentDescription = state.data.name,
modifier =
Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
)
Column(
verticalArrangement =
Arrangement.spacedBy(
20.dp,
Alignment.CenterVertically,
),
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize(),
) {
Text(
text = "${state.data.owner.name}/${state.data.name}",
style = Typography.bodyLarge,
)
Spacer(modifier = Modifier)
val language = state.data.language ?: "No Language"
Text(
text = "programming language: $language",
style = Typography.bodyLarge,
)
Spacer(modifier = Modifier)
Text(
text = "Star Count: ${state.data.stargazersCount}",
style = Typography.bodyLarge,
)
Spacer(modifier = Modifier)
Text(
text = "watcherCount ${state.data.watchersCount}",
style = Typography.bodyLarge,
)
Spacer(modifier = Modifier)
Text(
text = "forkCount: ${state.data.forksCount}",
style = Typography.bodyLarge,
)
}
}
}
}
}
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/view/GithubDetailView.kt | 2661274458 |
package jp.co.yumemi.android.code_check.view.component
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import jp.co.yumemi.android.code_check.model.Item
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SearchGithubThubnail(
item: Item,
goToDetailView: (Item) -> Unit,
) {
Box(
modifier =
Modifier
.fillMaxWidth()
.heightIn(min = 50.dp, max = 100.dp)
.clickable {
goToDetailView(item)
}
.semantics { testTagsAsResourceId = true }
.testTag("item"),
) {
Row {
AsyncImage(
model = item.owner.avatarUrl,
contentDescription = "Image",
)
Column(
modifier =
Modifier.background(MaterialTheme.colorScheme.background)
.fillMaxSize().weight(1f),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom,
) {
Text(text = "Language: ${item.name}")
Text(text = "Watch Count: ${item.watchersCount}")
Text(text = "Star Count: ${item.stargazersCount}")
}
}
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/view/component/SearchGithubThumbnail.kt | 51291689 |
package jp.co.yumemi.android.code_check.view
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.hilt.navigation.compose.hiltViewModel
import jp.co.yumemi.android.code_check.model.Item
import jp.co.yumemi.android.code_check.view.component.SearchGithubThubnail
import jp.co.yumemi.android.code_check.viewModel.SearchGithubViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchGithubView(
viewModel: SearchGithubViewModel = hiltViewModel(),
goToDetailView: (Item) -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "Android Engineer CodeCheck") },
colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.primary),
)
},
) { inner ->
Column(modifier = Modifier.padding(inner)) {
OutlinedTextField(
value = viewModel.query,
onValueChange = { viewModel.query = it },
maxLines = 1,
placeholder = {
Text(text = "Github Search...")
},
modifier = Modifier.fillMaxWidth(),
keyboardActions = KeyboardActions(onDone = { viewModel.searchGithubRepository() }),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
)
val state = viewModel.state.value
val ctx = LocalContext.current
when {
state.isLoading -> {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(),
) {
CircularProgressIndicator()
}
}
!state.error.isNullOrBlank() -> {
Toast.makeText(ctx, "検索できませんでした", Toast.LENGTH_LONG).show()
Log.d("Error Log", state.error)
}
state.data != null -> {
LazyColumn {
items(state.data) { item ->
SearchGithubThubnail(
item = item,
goToDetailView = { goToDetailView(item) },
)
}
}
}
}
}
}
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/view/SearchGithubView.kt | 2261504992 |
package jp.co.yumemi.android.code_check
sealed class ViewRoute(val route: String) {
object SearchGithubView : ViewRoute("searchGithubView")
object GithubDetailView : ViewRoute("githubDetailView/{owner}/{repo}")
}
| Android-full-coding/app/src/main/kotlin/jp/co/yumemi/android/code_check/ViewRoute.kt | 426600959 |
package com.paulo.githubnavigator
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.paulo.githubnavigator", appContext.packageName)
}
} | GitHubNavigator/app/src/androidTest/java/com/paulo/githubnavigator/ExampleInstrumentedTest.kt | 1272056796 |
package com.paulo.githubnavigator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
suspend fun advanceTimeBy(delayMillis: Long) {
withContext(Dispatchers.Main) {
delay(delayMillis)
}
} | GitHubNavigator/app/src/androidTest/java/com/paulo/githubnavigator/utils.kt | 3882128336 |
package com.paulo.githubnavigator
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performTextInput
import androidx.navigation.NavHostController
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.repository.UserRepository
import com.paulo.githubnavigator.screen.Users
import com.paulo.githubnavigator.ui.theme.GitHubNavigatorTheme
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.koin.core.context.loadKoinModules
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class UserTest: KoinTest {
@get:Rule
val composeTestRule = createComposeRule()
private lateinit var mockModule: Module
private lateinit var userRepository: UserRepository
private val fakeUsers = listOf(
User(login = "Nome do Usuário 1"),
User(login = "Nome do Usuário 2"),
User(login = "Nome do Usuário 3")
)
@Before
fun setup() {
userRepository = mock()
mockModule = module {
single { userRepository }
}
loadKoinModules(mockModule)
}
@Test
fun `list_users`() = runTest {
`when`(userRepository.getUsers()).thenReturn(flow {
emit(Output.Success(fakeUsers))
})
val mockNavController = mock<NavHostController>()
composeTestRule.setContent {
GitHubNavigatorTheme {
Users(navController = mockNavController)
}
}
advanceTimeBy(500)
composeTestRule.onNodeWithText("Nome do Usuário 1").assertIsDisplayed()
composeTestRule.onNodeWithText("Nome do Usuário 2").assertIsDisplayed()
composeTestRule.onNodeWithText("Nome do Usuário 3").assertIsDisplayed()
}
@Test
fun `search_users`() = runTest {
`when`(userRepository.getUsers()).thenReturn(flow {
emit(Output.Success(fakeUsers))
})
val search = "Paulo"
val fakeSearchUsers = listOf(
User(login = "Paulo 1"),
User(login = "Paulo 2"),
User(login = "Paulo 3")
)
`when`(userRepository.searchUsers(search)).thenReturn(flow {
emit(Output.Success(fakeSearchUsers))
})
val mockNavController = mock<NavHostController>()
composeTestRule.setContent {
GitHubNavigatorTheme {
Users(navController = mockNavController)
}
}
advanceTimeBy(500)
composeTestRule.onNodeWithText("Busque por usuários").performTextInput(search)
advanceTimeBy(500)
composeTestRule.onNodeWithText(search).assertIsDisplayed()
fakeSearchUsers[0].login?.let { composeTestRule.onNodeWithText(it).assertIsDisplayed() }
}
}
| GitHubNavigator/app/src/androidTest/java/com/paulo/githubnavigator/UserTest.kt | 3831568162 |
package com.paulo.githubnavigator
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.navigation.compose.ComposeNavigator
import androidx.navigation.testing.TestNavHostController
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.repository.UserRepository
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.koin.core.context.loadKoinModules
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class UserDetailsTest : KoinTest {
@get:Rule
val composeTestRule = createComposeRule()
private lateinit var mockModule: Module
private lateinit var userRepository: UserRepository
lateinit var navController: TestNavHostController
private val fakeUsers = listOf(
User(login = "Nome do Usuário 1"),
User(login = "Nome do Usuário 2"),
User(login = "Nome do Usuário 3")
)
@Before
fun setup() {
userRepository = mock()
mockModule = module {
single { userRepository }
}
loadKoinModules(mockModule)
composeTestRule.setContent {
navController = TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(ComposeNavigator())
AppNavHost(navController = navController)
}
}
@Test
fun `get_user_details`() = runTest {
`when`(userRepository.getUsers()).thenReturn(flow {
emit(Output.Success(fakeUsers))
})
val username = fakeUsers[0].login ?: ""
`when`(userRepository.getInfoUser(username)).thenReturn(flow {
emit(Output.Success(fakeUsers[0]))
})
`when`(userRepository.getInfoRepositorysByUser(username)).thenReturn(flow {
emit(Output.Success(listOf()))
})
advanceTimeBy(500)
composeTestRule.onNodeWithTag("rowUserDetails_${username}").performClick()
val route = navController.currentBackStackEntry?.destination?.route
assertEquals(route, "${Screen.USERS_DETAILS.name}/${fakeUsers[0].login}")
}
} | GitHubNavigator/app/src/androidTest/java/com/paulo/githubnavigator/UserDetailsTest.kt | 1009234355 |
package com.paulo.githubnavigator
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)
}
} | GitHubNavigator/app/src/test/java/com/paulo/githubnavigator/ExampleUnitTest.kt | 3681937104 |
package com.paulo.githubnavigator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.paulo.githubnavigator.screen.UserDetails
import com.paulo.githubnavigator.screen.Users
@Composable
fun AppNavHost(
modifier: Modifier = Modifier,
navController: NavHostController,
startDestination: String = NavigationItem.Users.route,
) {
NavHost(
modifier = modifier,
navController = navController,
startDestination = startDestination
) {
composable(NavigationItem.Users.route) {
Users(navController)
}
composable("${NavigationItem.UserDetails.route}/{username}") {
val username = it.arguments?.getString("username")
UserDetails(navController,username ?: "Não foi possivel recuperar o usuário")
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/AppNavHost.kt | 2139155322 |
package com.paulo.githubnavigator.viewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.paulo.githubnavigator.model.Repository
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.repository.UserRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class UserDetailsViewModel(private val userRepository: UserRepository): ViewModel() {
private val _user = MutableStateFlow<Output<User>>(Output.Loading())
val user = _user.asStateFlow()
private val _repositories = MutableStateFlow<Output<List<Repository>>>(Output.Loading())
val repositories = _repositories.asStateFlow()
fun getUserInfo(username: String){
viewModelScope.launch {
userRepository.getInfoUser(username).collect{
_user.value = it
}
}
}
fun getRepositoriesByUserName(username: String){
viewModelScope.launch {
userRepository.getInfoRepositorysByUser(username).collect{
_repositories.value = it
}
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/viewModel/UserDetailsViewModel.kt | 3885143553 |
package com.paulo.githubnavigator.viewModel
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.repository.UserRepository
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class UsersViewModel(private val userRepository: UserRepository) : ViewModel(),
DefaultLifecycleObserver {
private val _users = MutableStateFlow<Output<List<User>>>(Output.Loading())
val users = _users.asStateFlow()
private val _searchUserText = MutableStateFlow("")
val searchUserText = _searchUserText.asStateFlow()
@OptIn(FlowPreview::class)
fun initialize() {
viewModelScope.launch {
searchUserText.debounce(500).collectLatest { input ->
searchUser(input)
}
}
}
fun updateSearch(search: String) {
_searchUserText.update { search }
}
private fun getUsers() {
viewModelScope.launch {
userRepository.getUsers().collect {
_users.value = it
}
}
}
private fun searchUser(username: String) {
if (username.isNotEmpty()) {
viewModelScope.launch {
userRepository.searchUsers(username).collect {
_users.value = it
}
}
} else {
getUsers()
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/viewModel/UsersViewModel.kt | 1980584275 |
package com.paulo.githubnavigator.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) | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/ui/theme/Color.kt | 2291814922 |
package com.paulo.githubnavigator.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 GitHubNavigatorTheme(
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
)
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/ui/theme/Theme.kt | 3228766637 |
package com.paulo.githubnavigator.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
)
*/
) | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/ui/theme/Type.kt | 4073940517 |
package com.paulo.githubnavigator.repository
import com.paulo.githubnavigator.model.Repository
import com.paulo.githubnavigator.model.SearchUser
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
interface UserRepository {
suspend fun getUsers(): Flow<Output<List<User>>>
suspend fun getInfoUser(
username: String
): Flow<Output<User>>
suspend fun getInfoRepositorysByUser(username: String): Flow<Output<List<Repository>>>
suspend fun searchUsers(username: String): Flow<Output<List<User>>>
}
class UserRepositoryImpl(private val httpClient: HttpClient) : UserRepository {
override suspend fun getUsers() = flow {
emit(Output.Loading())
try {
val response = httpClient.get("users")
emit(Output.Success(response.body<List<User>>()))
} catch (e: Exception) {
emit(Output.Error(e))
}
}
override suspend fun getInfoUser(username: String) = flow {
emit(Output.Loading())
try {
emit(Output.Success(httpClient.get("users/${username}").body<User>()))
} catch (e: Exception) {
emit(Output.Error(e))
}
}
override suspend fun getInfoRepositorysByUser(username: String) = flow {
emit(Output.Loading())
try {
emit(Output.Success(httpClient.get("users/${username}/repos").body<List<Repository>>()))
} catch (e: Exception) {
emit(Output.Error(e))
}
}
override suspend fun searchUsers(username: String) = flow {
emit(Output.Loading())
try {
emit(Output.Success(httpClient.get("search/users") {
url {
parameters.append("q", username)
parameters.append("type", "user")
}
}.body<SearchUser>().items))
} catch (e: Exception) {
emit(Output.Error(e))
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/repository/UserRepository.kt | 1063059023 |
package com.paulo.githubnavigator
enum class Screen {
USERS,
USERS_DETAILS,
}
sealed class NavigationItem(val route: String) {
object Users : NavigationItem(Screen.USERS.name)
object UserDetails : NavigationItem(Screen.USERS_DETAILS.name)
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/AppNavigation.kt | 1105329159 |
package com.paulo.githubnavigator
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.navigation.compose.rememberNavController
import com.paulo.githubnavigator.ui.theme.GitHubNavigatorTheme
import com.paulo.githubnavigator.viewModel.UsersViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GitHubNavigatorTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
AppNavHost(navController = navController)
}
}
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/MainActivity.kt | 2009390469 |
package com.paulo.githubnavigator.di
import com.paulo.githubnavigator.network.createHttpClient
import com.paulo.githubnavigator.repository.UserRepository
import com.paulo.githubnavigator.repository.UserRepositoryImpl
import com.paulo.githubnavigator.viewModel.UserDetailsViewModel
import com.paulo.githubnavigator.viewModel.UsersViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val appModule = module {
single { createHttpClient("https://api.github.com") }
single<UserRepository> { UserRepositoryImpl(get()) }
viewModel { UsersViewModel(get()) }
viewModel { UserDetailsViewModel(get()) }
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/di/app.kt | 425689330 |
package com.paulo.githubnavigator.network
sealed class Output<out Response> {
data class Success<out T>(val data: T?) : Output<T>()
data class Loading<out T>(val data: T? = null) : Output<T>()
data class Error<out T>(val error: Throwable) : Output<T>()
object NetworkError : Output<Nothing>()
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/network/Output.kt | 121744696 |
package com.paulo.githubnavigator.network
import android.util.Log
import com.paulo.githubnavigator.BuildConfig
import io.ktor.client.HttpClient
import io.ktor.client.engine.android.Android
import io.ktor.client.plugins.DefaultRequest
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.plugins.observer.ResponseObserver
import io.ktor.client.request.header
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.json.Json
private const val TIME_OUT = 60_000
fun createHttpClient(baseUrl: String) = HttpClient(Android) {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
}
)
engine {
connectTimeout = TIME_OUT
socketTimeout = TIME_OUT
}
}
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Log.v("Logger Ktor =>", message)
}
}
level =
if (BuildConfig.DEBUG)
LogLevel.ALL
else
LogLevel.NONE
}
install(ResponseObserver) {
onResponse { response ->
Log.d("HTTP status:", "${response.status.value}")
}
}
install(DefaultRequest) {
header(HttpHeaders.ContentType, ContentType.Application.Json)
}
defaultRequest {
url(baseUrl)
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/network/KtorClient.kt | 3179691528 |
package com.paulo.githubnavigator.screen
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.paulo.githubnavigator.R
import com.paulo.githubnavigator.model.Repository
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.viewModel.UserDetailsViewModel
import org.koin.androidx.compose.koinViewModel
@Composable
fun UserDetails(navController: NavHostController, username: String) {
val viewModel = koinViewModel<UserDetailsViewModel>()
Column( modifier = Modifier
.padding(16.dp)) {
Icon(
Icons.Filled.ArrowBack,
contentDescription = "",
modifier = Modifier.clickable {
navController.popBackStack()
}
)
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
) {
Spacer(modifier = Modifier.height(16.dp))
UserInfo(viewModel)
Spacer(modifier = Modifier.height(16.dp))
Divider()
Spacer(modifier = Modifier.height(16.dp))
Repositories(viewModel)
}
LaunchedEffect(true) {
viewModel.getUserInfo(username)
viewModel.getRepositoriesByUserName(username)
}
}
}
@Composable
fun UserInfo(viewModel: UserDetailsViewModel) {
val userState = viewModel.user.collectAsState()
Column(Modifier.fillMaxWidth()) {
when (val output = userState.value) {
is Output.Success -> {
val user = output.data
AsyncImage(
model = user?.avatarUrl
?: "https://seeklogo.com/images/G/github-logo-2E3852456C-seeklogo.com.png",
contentDescription = "Avatar do usuário",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(150.dp)
.clip(CircleShape)
.align(alignment = Alignment.CenterHorizontally)
)
Text(
text = user?.name ?: "",
fontSize = 26.sp,
fontWeight = FontWeight.Bold
)
Text(text = user?.login ?: "")
Spacer(modifier = Modifier.height(10.dp))
Text(
text = user?.bio ?: "",
fontStyle = FontStyle.Italic
)
Spacer(modifier = Modifier.height(10.dp))
Row {
Icon(
Icons.Filled.Person,
contentDescription = "Pessoas"
)
Text(
text = user?.followers.toString(),
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(5.dp))
Text(text = "Seguidores")
Spacer(modifier = Modifier.width(10.dp))
Text(
text = user?.following.toString(),
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(5.dp))
Text(text = "Seguindo")
}
Spacer(modifier = Modifier.height(10.dp))
Row {
Icon(
painterResource(id = R.drawable.apartment),
contentDescription = "Empresa"
)
Text(text = user?.company ?: "")
}
Spacer(modifier = Modifier.height(10.dp))
Row {
Icon(
Icons.Filled.LocationOn,
contentDescription = "Localização"
)
Text(text = user?.location ?: "")
}
}
is Output.Error -> {
Text(
text = "Não foi possivel buscar as informação do usuário. Para mais detalhes: ${output.error.message}",
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
else -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
}
@Composable
fun Repositories(viewModel: UserDetailsViewModel) {
val repositories = viewModel.repositories.collectAsState()
Column(modifier = Modifier.fillMaxWidth()) {
when (val output = repositories.value) {
is Output.Success -> {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
output.data?.forEach {
RepositoryItem(it)
}
}
}
is Output.Error -> {
Text(
text = "Não foi possivel buscar os repositorios. Para mais detalhes: ${output.error.message}",
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
else -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
}
@Composable
fun RepositoryItem(repository: Repository) {
Column {
Text(
text = repository.name,
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Text(
text = repository.description ?: "",
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Spacer(modifier = Modifier.height(10.dp))
Row {
Icon(
painterResource(id = R.drawable.book),
contentDescription = ""
)
Spacer(modifier = Modifier.width(10.dp))
Text(repository.stargazersCount.toString())
}
Row {
Icon(painterResource(id = R.drawable.eye), contentDescription = "")
Spacer(modifier = Modifier.width(10.dp))
Text(repository.watchersCount.toString())
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/screen/UserDetails.kt | 2246123647 |
package com.paulo.githubnavigator.screen
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.paulo.githubnavigator.NavigationItem
import com.paulo.githubnavigator.model.User
import com.paulo.githubnavigator.network.Output
import com.paulo.githubnavigator.viewModel.UsersViewModel
import org.koin.androidx.compose.koinViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Users(
navController: NavHostController
) {
val usersViewModel: UsersViewModel = koinViewModel()
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize()
) {
val search = usersViewModel.searchUserText.collectAsState()
OutlinedTextField(
value = search.value,
onValueChange = {
usersViewModel.updateSearch(it)
},
label = { Text("Busque por usuários") },
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Search
),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "Usuários",
fontSize = 26.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(20.dp))
ListUsers(usersViewModel, navController)
var functionExecuted by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(functionExecuted) {
if (!functionExecuted) {
functionExecuted = true
usersViewModel.initialize()
}
}
}
}
@Composable
fun ListUsers(usersViewModel: UsersViewModel, navController: NavHostController) {
val users = usersViewModel.users.collectAsState()
Column ( modifier = Modifier
.fillMaxSize()){
when (val output = users.value) {
is Output.Success -> {
val data = output.data ?: listOf()
LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
items(
items = data,
itemContent = {
UserItem(user = it, navController)
})
}
}
is Output.Error -> {
Text(
text = "Não foi possivel buscar os usuários. Mais detalhes: ${output.error.message}",
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
else -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
}
@Composable
fun UserItem(user: User, navController: NavHostController, modifier: Modifier = Modifier) {
Row(
modifier = Modifier
.testTag("rowUserDetails_${user.login}")
.fillMaxWidth()
.clickable {
navController.navigate("${NavigationItem.UserDetails.route}/${user.login}")
},
verticalAlignment = Alignment.CenterVertically
) {
AsyncImage(
model = user.avatarUrl
?: "https://seeklogo.com/images/G/github-logo-2E3852456C-seeklogo.com.png",
contentDescription = "Avatar do usuário",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(100.dp)
.clip(CircleShape)
)
Spacer(modifier = Modifier.width(16.dp))
Text(text = user.login ?: "UserDetauils do usuário", modifier)
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/screen/Users.kt | 3293213610 |
package com.paulo.githubnavigator.model
import kotlinx.serialization.Serializable
@Serializable
data class SearchUser (
val items: List<User>
) | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/model/SearchUser.kt | 3755262460 |
package com.paulo.githubnavigator.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Repository(
val id: Long,
val name: String,
@SerialName("full_name")
val fullName: String,
val owner: Owner?,
val description: String?,
val size: Long,
@SerialName("stargazers_count")
val stargazersCount: Int,
@SerialName("watchers_count")
val watchersCount: Int,
)
| GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/model/Repository.kt | 368370972 |
package com.paulo.githubnavigator.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class User(
val login: String?,
val id: Int? = -1,
@SerialName("node_id")
val nodeId: String? = "",
@SerialName("avatar_url")
val avatarUrl: String? = "",
val gravatarId: String? = "",
val url: String? = "",
val htmlUrl: String? = "",
val followersUrl: String? = "",
val followingUrl: String? = "",
val gistsUrl: String? = "",
val starredUrl: String?= "",
val subscriptionsUrl: String?= "",
val organizationsUrl: String?= "",
val reposUrl: String?= "",
val eventsUrl: String?="",
val receivedEventsUrl: String?="",
val type: String?="",
val siteAdmin: Boolean?=false,
val name: String?= "",
val followers: Int?=0,
val following: Int?=0,
val location: String?="",
val company: String?="",
val bio: String?=""
) | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/model/User.kt | 3143697528 |
package com.paulo.githubnavigator.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Owner(
val login: String,
val id: Long,
@SerialName("node_id")
val nodeId: String,
@SerialName("avatar_url")
val avatarUrl: String,
@SerialName("gravatar_id")
val gravatarId: String,
val url: String?,
@SerialName("html_url")
val htmlUrl: String,
@SerialName("followers_url")
val followersUrl: String,
@SerialName("following_url")
val followingUrl: String,
@SerialName("gists_url")
val gistsUrl: String,
@SerialName("starred_url")
val starredUrl: String,
@SerialName("subscriptions_url")
val subscriptionsUrl: String,
@SerialName("organizations_url")
val organizationsUrl: String,
@SerialName("repos_url")
val reposUrl: String,
@SerialName("events_url")
val eventsUrl: String,
@SerialName("received_events_url")
val receivedEventsUrl: String,
val type: String,
@SerialName("site_admin")
val siteAdmin: Boolean
) | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/model/Owner.kt | 3825518002 |
package com.paulo.githubnavigator
import android.app.Application
import com.paulo.githubnavigator.di.appModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin
class MainApplication: Application() {
override fun onCreate() {
super.onCreate()
startKoin{
androidLogger()
androidContext(this@MainApplication)
modules(appModule)
}
}
} | GitHubNavigator/app/src/main/java/com/paulo/githubnavigator/MainApplication.kt | 1735493812 |
object Versions {
const val kotlin = "1.8.10"
const val coreKtx = "1.9.0"
const val lifecycleRuntime = "2.6.1"
const val activityCompose = "1.7.0"
const val composeBom = "2023.03.00"
const val composeNavigation = "2.7.1"
const val coil = "2.5.0"
const val coroutines = "1.6.4"
const val junit = "4.13.2"
const val androidXJunit = "1.1.5"
const val espresso = "3.5.1"
const val retrofit = "2.9.0"
const val ktor = "2.2.4"
const val okhttpLogging = "4.9.3"
const val koin = "3.5.3"
const val mockito = "5.1.1"
const val mockitoKotlin = "2.1.0"
const val coreKtxTest = "1.2.0"
} | GitHubNavigator/buildSrc/src/main/kotlin/Versions.kt | 2921662898 |
package com.kkakaku
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.regex.Pattern
class MainActivity : AppCompatActivity() {
private var iWebEngine = 0
private var bHistory = false
private var bOption = false
private var bBarcode = false
private var toast0: Toast = Toast.makeText(this, "", Toast.LENGTH_SHORT)
private var history: ArrayList<String> = ArrayList()
// ユーザー領域
private var pref: SharedPreferences = getSharedPreferences("pref", MODE_PRIVATE)
private var prefedit: SharedPreferences.Editor? = pref.edit()
private val thread: Thread? = null
private val iSearchType = 0
private val strProductName: String? = null
private var bNetworkFailed = false
private var bNetworking = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bNetworkFailed = true
bNetworking = false
history = ArrayList()
// プログレスダイアログの設定
// waitDialog = ProgressDialog(this)
// プログレスダイアログのメッセージを設定します
// waitDialog!!.setMessage(R.string.serching)
// 円スタイル(くるくる回るタイプ)に設定します
// waitDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
// ユーザー領域を読み出す
var iOptionSort = 0
var iOptionMNP = 0
var iOptionMXP = 0
var iOptionCondition = 0
var iOptionShipfree = 0
var iOptionEndTime = 0
var iOptionProductID = 0
iWebEngine = pref.getInt("WebEngine", 0)
bHistory = pref.getBoolean("History", true)
if (bHistory) {
for (i in 0 until iHistoryNum) {
val strHistory = pref.getString("History" + String.format("%02d", i), "")
if (strHistory != null && strHistory != "") {
history.add(strHistory)
}
}
}
bOption = pref.getBoolean("Option", true)
if (bOption) {
iOptionSort = pref.getInt("OptionSort", 0)
iOptionMNP = pref.getInt("OptionMNP", 0)
iOptionMXP = pref.getInt("OptionMXP", 0)
iOptionCondition = pref.getInt("OptionCondition", 0)
iOptionShipfree = pref.getInt("OptionShipfree", 0)
iOptionEndTime = pref.getInt("OptionEndTime", 0)
iOptionProductID = pref.getInt("OptionProductID", 0)
}
val btnClear = findViewById<View>(R.id.id_btnClear) as Button
val btnHistory = findViewById<View>(R.id.id_btnHistory) as Button
val btnGetBarcode = findViewById<View>(R.id.id_GetBarcode) as Button
val btnSearch = findViewById<View>(R.id.id_btnSearch) as Button
val btnWebSearch = findViewById<View>(R.id.id_btnWebSearch) as Button
val btnShareText = findViewById<View>(R.id.id_btnShareText) as Button
val edtText = findViewById<View>(R.id.id_Text) as EditText
val edtMNP = findViewById<View>(R.id.id_edtMNP) as EditText
val edtMXP = findViewById<View>(R.id.id_edtMXP) as EditText
val radio0 = findViewById<View>(R.id.radio0) as RadioButton
val radio1 = findViewById<View>(R.id.radio1) as RadioButton
val radio2 = findViewById<View>(R.id.radio2) as RadioButton
val radio3 = findViewById<View>(R.id.radio3) as RadioButton
val radio4 = findViewById<View>(R.id.radio4) as RadioButton
// val radio5 = (RadioButton)findViewById(R.id.radio5);
// val radio6 = (RadioButton)findViewById(R.id.radio6);
// val radio7 = (RadioButton)findViewById(R.id.radio7);
val radio8 = findViewById<View>(R.id.radio8) as RadioButton
val radio9 = findViewById<View>(R.id.radio9) as RadioButton
val radio10 = findViewById<View>(R.id.radio10) as RadioButton
val radio11 = findViewById<View>(R.id.radio11) as RadioButton
when (iOptionSort) {
1 -> radio1.isChecked = true
2 -> radio2.isChecked = true
else -> radio0.isChecked = true
}
edtMNP.setText(iOptionMNP.toString())
edtMXP.setText(iOptionMXP.toString())
if (iOptionCondition == 1) {
radio4.isChecked = true
} else {
radio3.isChecked = true
}
if (iOptionShipfree == 1) {
radio11.isChecked = true
} else {
radio10.isChecked = true
}
// when (iOptionEndTime) {
// 1 -> radio6.isChecked = true
// 2 -> radio7.isChecked = true
// else -> radio5.isChecked = true
// }
if (iOptionProductID == 1) {
radio9.isChecked = true
} else {
radio8.isChecked = true
}
val HistoryDialog = AlertDialog.Builder(this)
prefcommit()
edtText.setText("")
clear()
btnClear.setOnClickListener {
edtText.setText("")
clear()
}
edtText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(arg0: Editable) {
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
checkinput()
}
})
edtText.setOnKeyListener { v, keyCode, event ->
event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
}
edtMNP.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(arg0: Editable) {
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
checkinput()
}
})
edtMXP.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(arg0: Editable) {
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
checkinput()
}
})
btnGetBarcode.setOnClickListener {
btnGetBarcode.isEnabled = false
val intentScan = Intent("com.google.zxing.client.android.SCAN")
intentScan.putExtra("SCAN_MODE", "PRODUCT_MODE")
try {
startActivityForResult(intentScan, 1)
} catch (e: ActivityNotFoundException) {
toast0.setText("バーコードの読み出しに失敗しました。")
toast0.show()
}
btnGetBarcode.isEnabled = true
}
btnHistory.setOnClickListener {
HistoryDialog.setTitle("検索履歴")
// 履歴を逆順に並べ替え
val backhistory = ArrayList<String?>()
for (i in history.indices.reversed()) {
backhistory.add(history[i])
}
val cs = backhistory.toTypedArray<CharSequence?>()
HistoryDialog.setSingleChoiceItems(cs, -1) { dialog, which ->
val bhwork = ArrayList<String?>()
for (i in history.indices.reversed()) {
bhwork.add(history[i])
}
val cswork = bhwork.toTypedArray<CharSequence?>()
edtText.setText(cswork[which])
bBarcode = false
}
HistoryDialog.show()
}
btnWebSearch.setOnClickListener {
// 入力チェック
checkinput()
// ボタン有効時
if (btnWebSearch.isEnabled) {
// ボタンを無効化
btnWebSearch.isEnabled = false
val strURI: String
strURI = when (iWebEngine) {
1 -> "https://google.com/search?q=" + edtText.text.toString() + "&ei=UTF-8&safe=off"
2 -> "https://search.yahoo.com/search?q=" + edtText.text.toString() + "&ei=UTF-8&safe=off"
3 -> "https://www.bing.com/search?q=" + edtText.text.toString()
4 -> "https://duckduckgo.com/?q=" + edtText.text.toString()
5 -> "https://yandex.com/search/?q=" + edtText.text.toString()
else -> "http://search.yahoo.co.jp/search?p=" + edtText.text.toString() + "&ei=UTF-8&save=0"
}
// URLを指定してブラウザを開く
val uri = Uri.parse(strURI)
val i = Intent(Intent.ACTION_VIEW, uri)
startActivity(i)
// ボタンを有効化
btnWebSearch.isEnabled = true
}
}
btnShareText.setOnClickListener {
// 入力チェック
checkinput()
// ボタン有効時
if (btnShareText.isEnabled) {
// ボタンを無効化
btnShareText.isEnabled = false
// 検索ワードを共有
val i = Intent(Intent.ACTION_SEND)
i.type = "text/plain"
i.putExtra(Intent.EXTRA_TEXT, edtText.text.toString() + " (by " + R.string.app_base_url + "kkc.php #kkakaku)")
startActivity(i)
// ボタンを有効化
btnShareText.isEnabled = true
}
}
btnSearch.setOnClickListener {
// 入力チェック
checkinput()
// ボタン有効時
if (btnSearch.isEnabled) {
// ボタンを無効化
btnSearch.isEnabled = false
if (bHistory) {
// 履歴の重複を消去
for (i in history.indices) {
if (history[i] == edtText.text.toString() + "") {
history.removeAt(i)
break
}
}
// 履歴に追加
history.add("" + edtText.text.toString())
if (history.size > iHistoryNum) {
history.removeAt(0)
}
}
// 設定をユーザー領域に保存
prefcommit()
var strURI = R.string.app_base_url.toString() + "kkc.php?q="
strURI += edtText.text.toString()
// 表示順序
strURI += if (radio1.isChecked) {
"&so=1"
} else if (radio2.isChecked) {
"&so=2"
} else {
"&so=0"
}
// 最低値段
strURI += "&mnp=" + edtMNP.text.toString()
// 最高値段
strURI += "&mxp=" + edtMXP.text.toString()
// 商品状態
strURI += if (radio4.isChecked) {
"&co=1"
} else {
"&co=0"
}
// 送料無料指定
strURI += if (radio11.isChecked) {
"&sf=1"
} else {
"&sf=0"
}
// 出品終了表示
// strURI += if (radio6!!.isChecked) {
// "&et=1"
// } else if (radio7!!.isChecked) {
// "&et=2"
// } else {
// "&et=0"
// }
strURI += "&et=0"
// 商品ID表示
strURI += if (radio9.isChecked) {
"&pi=1"
} else {
"&pi=0"
}
strURI += "&sh=0&pn=1"
// URLを指定してブラウザで開く
val uri = Uri.parse(strURI)
val i = Intent(Intent.ACTION_VIEW, uri)
startActivity(i)
// 入力チェック
checkinput()
// ボタンを有効化
btnSearch.isEnabled = true
}
}
}
fun clear() {
val btnClear = findViewById<View>(R.id.id_btnClear) as Button
val btnHistory = findViewById<View>(R.id.id_btnHistory) as Button
// val btnGetBarcode = findViewById<View>(R.id.id_GetBarcode) as Button
val btnSearch = findViewById<View>(R.id.id_btnSearch) as Button
val btnWebSearch = findViewById<View>(R.id.id_btnWebSearch) as Button
val btnShareText = findViewById<View>(R.id.id_btnShareText) as Button
// クリアボタンを無効化
btnClear.isEnabled = false
bBarcode = false
// strBarcode = ""
// btnGetEAN.isEnabled = false
// btnGetISBN.isEnabled = false
// btnBackToNum.isEnabled = false
btnWebSearch.isEnabled = false
btnShareText.isEnabled = false
btnSearch.isEnabled = false
// 履歴の設定で有効/無効を切り替える
btnHistory.isEnabled = false
if (bHistory) {
if (history.size > 0) {
btnHistory.isEnabled = true
}
}
// クリアボタンを有効化
btnClear.isEnabled = true
}
fun checkinput() {
val edtText = findViewById<View>(R.id.id_Text) as EditText
val edtMNP = findViewById<View>(R.id.id_edtMNP) as EditText
val edtMXP = findViewById<View>(R.id.id_edtMXP) as EditText
val btnHistory = findViewById<View>(R.id.id_btnHistory) as Button
// val btnGetBarcode = findViewById<View>(R.id.id_GetBarcode) as Button
val btnSearch = findViewById<View>(R.id.id_btnSearch) as Button
val btnWebSearch = findViewById<View>(R.id.id_btnWebSearch) as Button
val btnShareText = findViewById<View>(R.id.id_btnShareText) as Button
if (edtText.text.toString() == "") {
// クリア
clear()
} else {
// 数字8桁ならEAN変換を有効にする
// var objPattern = Pattern.compile("^[0-9]{8,}$")
// var objMatcher = objPattern.matcher(edtText.text.toString())
// btnGetEAN.isEnabled = objMatcher.find()
// 数字13桁ならISBN変換を有効にする
// objPattern = Pattern.compile("^[0-9]{13,}$")
// objMatcher = objPattern.matcher(edtText.text.toString())
// btnGetISBN.isEnabled = objMatcher.find()
// 価格調査を無効にする
btnSearch.isEnabled = false
// Web検索を無効にする
btnWebSearch.isEnabled = false
// 共有を無効にする
btnShareText.isEnabled = false
// 最低値段が入力されている場合
val objPattern = Pattern.compile("^[0-9]+$")
var objMatcher = objPattern.matcher(edtMNP.text.toString())
if (objMatcher.find()) {
// 最高値段が入力されている場合
objMatcher = objPattern.matcher(edtMXP.text.toString())
if (objMatcher.find()) {
// 価格調査を有効にする
btnSearch.isEnabled = true
// Web検索を有効にする
btnWebSearch.isEnabled = true
// 共有を有効にする
btnShareText.isEnabled = true
}
}
// 履歴の設定で有効/無効を切り替える
btnHistory.isEnabled = false
if (bHistory) {
if (history.size > 0) {
btnHistory.isEnabled = true
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.activity_main, menu)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
val edtText = findViewById<View>(R.id.id_Text) as EditText
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
edtText.setText(data.getStringExtra("SCAN_RESULT"))
}
}
}
// 設定をユーザー領域に保存
private fun prefcommit() {
val edtText = findViewById<View>(R.id.id_Text) as EditText
val edtMNP = findViewById<View>(R.id.id_edtMNP) as EditText
val edtMXP = findViewById<View>(R.id.id_edtMXP) as EditText
val radio0 = findViewById<View>(R.id.radio0) as RadioButton
val radio1 = findViewById<View>(R.id.radio1) as RadioButton
val radio2 = findViewById<View>(R.id.radio2) as RadioButton
val radio3 = findViewById<View>(R.id.radio3) as RadioButton
val radio4 = findViewById<View>(R.id.radio4) as RadioButton
// val radio5 = (RadioButton)findViewById(R.id.radio5);
// val radio6 = (RadioButton)findViewById(R.id.radio6);
// val radio7 = (RadioButton)findViewById(R.id.radio7);
val radio8 = findViewById<View>(R.id.radio8) as RadioButton
val radio9 = findViewById<View>(R.id.radio9) as RadioButton
val radio10 = findViewById<View>(R.id.radio10) as RadioButton
val radio11 = findViewById<View>(R.id.radio11) as RadioButton
prefedit!!.putInt("WebEngine", iWebEngine)
prefedit!!.putBoolean("History", bHistory)
if (bHistory) {
for (i in 0 until iHistoryNum) {
if (i < history.size) {
prefedit!!.putString("History" + String.format("%02d", i), history[i])
} else {
prefedit!!.putString("History" + String.format("%02d", i), "")
}
}
} else {
for (i in 0 until iHistoryNum) {
prefedit!!.putString("History" + String.format("%02d", i), "")
}
}
prefedit!!.putBoolean("Option", bOption)
if (bOption) {
if (radio1.isChecked) {
prefedit!!.putInt("OptionSort", 1)
} else if (radio2.isChecked) {
prefedit!!.putInt("OptionSort", 2)
} else {
prefedit!!.putInt("OptionSort", 0)
}
if (edtMNP.text.toString() == "") {
edtMNP.setText("0")
}
prefedit!!.putInt("OptionMNP", edtMNP!!.text.toString().toInt())
if (edtMXP.text.toString() == "") {
edtMXP.setText("0")
}
prefedit!!.putInt("OptionMXP", edtMXP!!.text.toString().toInt())
if (radio4.isChecked) {
prefedit!!.putInt("OptionCondition", 1)
} else {
prefedit!!.putInt("OptionCondition", 0)
}
if (radio11.isChecked) {
prefedit!!.putInt("OptionShipfree", 1)
} else {
prefedit!!.putInt("OptionShipfree", 0)
}
// if (radio6.isChecked) {
// prefedit.putInt("OptionEndTime", 1)
// } else if (radio7.isChecked) {
// prefedit.putInt("OptionEndTime", 2)
// } else {
// prefedit.putInt("OptionEndTime", 0)
// }
prefedit!!.putInt("OptionEndTime", 0)
if (radio9.isChecked) {
prefedit!!.putInt("OptionProductID", 1)
} else {
prefedit!!.putInt("OptionProductID", 0)
}
} else {
prefedit!!.putInt("OptionSort", 0)
prefedit!!.putInt("OptionMNP", 0)
prefedit!!.putInt("OptionMXP", 0)
prefedit!!.putInt("OptionCondition", 0)
prefedit!!.putInt("OptionEndTime", 0)
prefedit!!.putInt("OptionProductID", 0)
}
prefedit!!.commit()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// TODO 自動生成されたメソッド・スタブ
val alertDialogBuilder = AlertDialog.Builder(this)
return when (item.itemId) {
R.id.id_menu_Usage -> {
alertDialogBuilder.setTitle(R.string.usage)
alertDialogBuilder.setMessage(R.string.usage_detail)
alertDialogBuilder.setPositiveButton(R.string.ok) { dialog, which ->
// TODO 自動生成されたメソッド・スタブ
}
alertDialogBuilder.show()
true
}
R.id.id_menu_HistorySettings -> {
val iSetHistory: Int
iSetHistory = if (bHistory) {
0
} else {
1
}
val items_History = arrayOf<CharSequence>(resources.getString(R.string.memory), resources.getString(R.string.nomemory))
alertDialogBuilder.setTitle(R.string.setting_history)
alertDialogBuilder.setSingleChoiceItems(items_History, iSetHistory) { dialog, which ->
// TODO 自動生成されたメソッド・スタブ
}
alertDialogBuilder.setPositiveButton(R.string.ok) { dialog, which -> // TODO 自動生成されたメソッド・スタブ
bHistory = if (which == 0) {
true
} else {
history.clear()
false
}
// 設定をユーザー領域に保存
prefcommit()
// 入力チェック
checkinput()
}
alertDialogBuilder.show()
true
}
R.id.id_menu_SearchOptionSettings -> {
val iSetSearchOption: Int
iSetSearchOption = if (bOption) {
0
} else {
1
}
val items_SearchOption = arrayOf<CharSequence>(resources.getString(R.string.memory), resources.getString(R.string.nomemory))
alertDialogBuilder.setTitle(R.string.seting_web_search)
alertDialogBuilder.setSingleChoiceItems(items_SearchOption, iSetSearchOption) { dialog, which -> // TODO 自動生成されたメソッド・スタブ
bOption = if (which == 0) {
true
} else {
false
}
// 設定をユーザー領域に保存
prefcommit()
}
alertDialogBuilder.show()
true
}
R.id.id_menu_HistoryClear -> {
alertDialogBuilder.setTitle(R.string.clear_history)
alertDialogBuilder.setMessage(R.string.delete_history)
alertDialogBuilder.setPositiveButton(R.string.yes) { dialog, which -> // TODO 自動生成されたメソッド・スタブ
history.clear()
// 設定をユーザー領域に保存
prefcommit()
// 入力チェック
checkinput()
}
alertDialogBuilder.setNegativeButton(R.string.no) { dialog, which ->
// TODO 自動生成されたメソッド・スタブ
}
alertDialogBuilder.show()
true
}
R.id.id_menu_WebEngine -> {
val items_Web = arrayOf<CharSequence>("Yahoo! JAPAN", "Google.com", "Yahoo!", "DuckDuckGo", "Bing", "Yandex")
alertDialogBuilder.setTitle(R.string.seting_web_search)
alertDialogBuilder.setSingleChoiceItems(items_Web, iWebEngine) { dialog, which -> // TODO 自動生成されたメソッド・スタブ
iWebEngine = which
// 設定をユーザー領域に保存
prefcommit()
}
alertDialogBuilder.show()
true
}
R.id.id_menu_About -> {
val packageManager = this.packageManager
var strVersion = ""
try {
val packageInfo = packageManager.getPackageInfo(this.packageName, PackageManager.GET_ACTIVITIES)
strVersion = packageInfo.versionName
} catch (e: PackageManager.NameNotFoundException) {
}
alertDialogBuilder.setTitle(R.string.about)
alertDialogBuilder.setMessage("""${R.string.app_name} Ver$strVersion
${R.string.app_base_url}kkc.php
Programed by AZO (for A.K)""")
alertDialogBuilder.setPositiveButton(R.string.ok) { dialog, which ->
// TODO 自動生成されたメソッド・スタブ
}
alertDialogBuilder.show()
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private const val iHistoryNum = 10
private var waitDialog: ProgressDialog? = null
private const val iNetworkTimeout = 30000
private const val msgidSearched = 0
private const val msgidTimeout = 1
}
} | kkakaku_android/app/src/main/java/com/kkakaku/MainActivity.kt | 644610376 |
package com.otumian.springbootapiwithvalidation
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class SpringBootApiWithValidationApplicationTests {
@Test
fun contextLoads() {
}
}
| spring-boot-api-with-validation/src/test/kotlin/com/otumian/springbootapiwithvalidation/SpringBootApiWithValidationApplicationTests.kt | 179141620 |
package com.otumian.springbootapiwithvalidation.dto
import com.otumian.springbootapiwithvalidation.bean.validation.HasAdequateWords
import com.otumian.springbootapiwithvalidation.extension.toSlug
import jakarta.validation.constraints.NotBlank
import java.time.LocalDateTime
data class ArticleDto(
var id: Long?,
// @field:NotNull(message = "title must not be null")
// @field:NotBlank(message = "title must not be blank")
// @field:NotEmpty(message = "title must not be empty")
// @field:HasAdequateWords(min = 3, max = 10, message = "title must be between 3 to 10 words")
@field:HasAdequateWords(message = "title must be at most 10 words")
// @field:Size(min = 3, max = 10, message = "title should have between 3 to a max of 10 words")
var title: String?,
// @field:NotNull(message = "content must not be null")
// @field:NotBlank(message = "content must not be blank")
// @field:NotEmpty(message = "content must not be empty")
@field:HasAdequateWords(min = 10, max = 25, message = "content must be between 10 to 25 words")
// @field:HasMaximumWord(message = "content must be at most 10 words")
// @field:Size(min = 10, max = 20, message = "content should have between 10 to a max of 20 words")
var content: String?,
val createdAt: LocalDateTime = LocalDateTime.now(), val slug: String? = title?.toSlug()
)
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/dto/ArticleDto.kt | 3681335826 |
package com.otumian.springbootapiwithvalidation.handler
class CustomException(override val message: String) : Exception(message)
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/handler/CustomException.kt | 2238460948 |
package com.otumian.springbootapiwithvalidation.handler
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
@RestControllerAdvice
class ErrorHandling {
// handles any other error
@ExceptionHandler(Exception::class)
fun handleExceptions(exception: Exception): ResponseEntity<ApiError> {
println("handleExceptions")
println(exception)
return ResponseEntity(
ApiError(
message = exception.message ?: "exception: Something went wrong",
status = HttpStatus.INTERNAL_SERVER_ERROR
), HttpStatus.INTERNAL_SERVER_ERROR
)
}
// handles errors thrown by the validation middleware
@ExceptionHandler(BindException::class)
fun handleBeanValidationExceptions(exception: BindException): ResponseEntity<ApiError> {
val message = exception.fieldErrors.associate { it.field to it.defaultMessage }
val firstError = message.entries.firstOrNull()
return ResponseEntity(ApiError(firstError?.value?:"Something went wrong with the validation"), HttpStatus.BAD_REQUEST)
}
// handles validation error (custom)
@ExceptionHandler(CustomException::class)
fun handleValidationExceptions(exception: CustomException): ResponseEntity<ApiError> {
val message = exception.message
return ResponseEntity(ApiError(message), HttpStatus.BAD_REQUEST)
}
// handles json parsing error
@ExceptionHandler(HttpMessageNotReadableException::class)
fun handleHttpMessageNotReadableException(exception: HttpMessageNotReadableException): ResponseEntity<ApiError> {
val message = "Invalid request body: ${exception.cause?.cause}"
return ResponseEntity(ApiError(message), HttpStatus.BAD_REQUEST)
}
// handle sql error: DataIntegrityViolationException
@ExceptionHandler(DataIntegrityViolationException::class)
fun handleDataIntegrityViolationException(exception: DataIntegrityViolationException): ResponseEntity<ApiError> {
val message = "Some went wrong"
return ResponseEntity(ApiError(message), HttpStatus.BAD_REQUEST)
}
// handle sql error: DataIntegrityViolationException
@ExceptionHandler(MethodArgumentTypeMismatchException::class)
fun handleMethodArgumentTypeMismatchException(exception: MethodArgumentTypeMismatchException): ResponseEntity<ApiError> {
val message = "Pass the appropriate value"
return ResponseEntity(ApiError(message), HttpStatus.BAD_REQUEST)
}
} | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/handler/ErrorHandling.kt | 285378516 |
package com.otumian.springbootapiwithvalidation.handler
import org.springframework.http.HttpStatus
data class ApiError(val message: String, val status: HttpStatus = HttpStatus.BAD_REQUEST)
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/handler/ApiError.kt | 1423314472 |
package com.otumian.springbootapiwithvalidation.repository
import com.otumian.springbootapiwithvalidation.entity.Article
import org.springframework.data.repository.CrudRepository
interface ArticleRepository : CrudRepository<Article, Long> | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/repository/ArticleRepository.kt | 2031769650 |
package com.otumian.springbootapiwithvalidation.extension
import java.util.*
fun String.toSlug(): String = lowercase(Locale.getDefault())
.replace("\n", " ")
.replace("[^a-z\\d\\s]".toRegex(), " ")
.split(" ")
.joinToString("-")
.replace("-+".toRegex(), "-")
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/extension/StringExtensions.kt | 2942241362 |
package com.otumian.springbootapiwithvalidation.entity
import com.otumian.springbootapiwithvalidation.extension.toSlug
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import java.time.LocalDateTime
@Entity
class Article(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long?,
var title: String,
var content: String,
var createdAt: LocalDateTime = LocalDateTime.now(),
var slug: String = title.toSlug()
) | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/entity/Article.kt | 540723181 |
package com.otumian.springbootapiwithvalidation.bean.validation
import jakarta.validation.ConstraintValidator
import jakarta.validation.ConstraintValidatorContext
class HasAdequateWordsValidator(private var min: Int = 0, private var max: Int = 120) :
ConstraintValidator<HasAdequateWords, String> {
// Override the initialize method to set the min and max values from the annotation
override fun initialize(hasMinimumWords: HasAdequateWords) {
this.min = hasMinimumWords.min
this.max = hasMinimumWords.max
}
override fun isValid(stringVal: String?, context: ConstraintValidatorContext): Boolean {
// Check if the string is null or empty
if (stringVal.isNullOrEmpty()) {
return false
}
// Count the words in the string
val size = stringVal.split(" ").count()
// Check if the size is within the specified range
return size in min..max
}
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/bean/validation/HasAdequateWordsValidator.kt | 3157310340 |
package com.otumian.springbootapiwithvalidation.bean.validation
import jakarta.validation.Constraint
import jakarta.validation.Payload
import kotlin.reflect.KClass
@MustBeDocumented
@Constraint(validatedBy = [HasAdequateWordsValidator::class])
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class HasAdequateWords(
val message: String = "Must have minimum and maximum number of words",
val groups: Array<KClass<*>> = [], // we won't be using this
val payload: Array<KClass<out Payload>> = [], // we won't be using this
val min: Int = 0,
val max: Int = 120
)
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/bean/validation/HasAdequateWordsAnnotation.kt | 3247101378 |
package com.otumian.springbootapiwithvalidation.mapper
interface ArticleMapper<Dto, Entity> {
fun fromEntityToDto(entity: Entity): Dto
fun fromDtoToEntity(dto: Dto): Entity
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/mapper/ArticleMapper.kt | 2348955454 |
package com.otumian.springbootapiwithvalidation.mapper
import com.otumian.springbootapiwithvalidation.dto.ArticleDto
import com.otumian.springbootapiwithvalidation.entity.Article
import org.springframework.stereotype.Service
@Service
class ArticleMapperImpl : ArticleMapper<ArticleDto, Article> {
override fun fromEntityToDto(entity: Article): ArticleDto {
return ArticleDto(
entity.id,
entity.title,
entity.content
)
}
override fun fromDtoToEntity(dto: ArticleDto): Article {
return Article(
dto.id,
dto.title!!,
dto.content!!
)
}
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/mapper/ArticleMapperImpl.kt | 2209132132 |
package com.otumian.springbootapiwithvalidation.controller
import com.otumian.springbootapiwithvalidation.dto.ArticleDto
import com.otumian.springbootapiwithvalidation.service.ArticleService
import jakarta.validation.Valid
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Positive
import org.springframework.format.annotation.NumberFormat
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/api/v1/articles")
class ArticleController(val service: ArticleService) {
@GetMapping
fun articles() = service.getArticles()
@GetMapping("/{id}")
fun article(@PathVariable id: Long) = service.getArticleById(id)
@PostMapping
fun newArticle(@Valid @RequestBody article: ArticleDto) = service.createArticle(article)
@PutMapping("/{id}")
fun updateArticle(
@Valid
@RequestBody article: ArticleDto,
@Valid
@PathVariable
@NotNull(message = "Id required")
@NumberFormat(style = NumberFormat.Style.NUMBER)
@Positive(message = "Id must be a positive number")
id: Long
): ArticleDto? {
var a: ArticleDto? = null
try {
a=service.updateArticle(id, article)
} catch (exception: Exception) {
println(exception)
}
return a
}
@DeleteMapping("/{id}")
fun deleteArticle(
@Valid
@PathVariable
@NotNull(message = "Id required")
@Positive(message = "Id must be a positive number")
id: Long
) = service.deleteArticleById(id)
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/controller/ArticleController.kt | 961836758 |
package com.otumian.springbootapiwithvalidation
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class SpringBootApiWithValidationApplication
fun main(args: Array<String>) {
runApplication<SpringBootApiWithValidationApplication>(*args)
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/SpringBootApiWithValidationApplication.kt | 1088534145 |
package com.otumian.springbootapiwithvalidation.service
import com.otumian.springbootapiwithvalidation.dto.ArticleDto
interface ArticleService {
fun createArticle(article: ArticleDto): ArticleDto
fun getArticles(): List<ArticleDto>
fun getArticleById(id: Long): ArticleDto
fun updateArticle(id: Long, article: ArticleDto): ArticleDto
fun deleteArticleById(id: Long)
} | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/service/ArticleService.kt | 853547363 |
package com.otumian.springbootapiwithvalidation.service
import com.otumian.springbootapiwithvalidation.dto.ArticleDto
import com.otumian.springbootapiwithvalidation.entity.Article
import com.otumian.springbootapiwithvalidation.handler.CustomException
import com.otumian.springbootapiwithvalidation.mapper.ArticleMapper
import com.otumian.springbootapiwithvalidation.repository.ArticleRepository
import com.otumian.springbootapiwithvalidation.validation.IArticleValidator
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
@Service
class ArticleServiceImpl(
private val repository: ArticleRepository,
private val mapper: ArticleMapper<ArticleDto, Article>,
private val validation: IArticleValidator // comment this out
): ArticleService {
override fun createArticle(article: ArticleDto): ArticleDto {
article.id = null
// we are programmatically doing validation on the incoming article
// this will throw a ValidationException
// validation.article.validate(article)
// commented out because we are now using the bean validation
val entity = mapper.fromDtoToEntity(article)
repository.save(entity)
return mapper.fromEntityToDto(entity)
}
override fun getArticles(): List<ArticleDto> {
return repository.findAll().map { mapper.fromEntityToDto(it) }
}
override fun getArticleById(id: Long): ArticleDto {
// validation.id.validate(id)
val entity = repository.findByIdOrNull(id) ?: throw CustomException("Article with id, $id, not found")
return mapper.fromEntityToDto(entity)
}
override fun updateArticle(id: Long, article: ArticleDto): ArticleDto {
// validation.id.validate(id)
// validation.article.validate(article)
val entity = repository.findByIdOrNull(id) ?: throw CustomException("Article with id, $id, not found")
entity.title = article.title!!
entity.content = article.content!!
repository.save(entity)
return mapper.fromEntityToDto(entity)
}
override fun deleteArticleById(id: Long) {
// validation.id.validate(id)
val entity = repository.findByIdOrNull(id) ?: throw CustomException("Article with id, $id, not found")
repository.delete(entity)
}
} | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/service/ArticleServiceImpl.kt | 1321766233 |
package com.otumian.springbootapiwithvalidation.validation
import com.otumian.springbootapiwithvalidation.handler.CustomException
import org.springframework.stereotype.Service
interface IStringValidationMechanism {
fun isNotNull(value: Any?, message: String)
fun isString(value: Any?, message: String)
fun isAtLeast(value: Any?, minimum: Int, message: String)
fun isAtMost(value: Any?, maximum: Int, message: String)
}
@Service
class StringValidationMechanism : IStringValidationMechanism {
override fun isNotNull(value: Any?, message: String) {
if (value == null) {
throw CustomException(message)
}
}
override fun isString(value: Any?, message: String) {
if (value !is String) {
throw CustomException(message)
}
}
override fun isAtLeast(value: Any?, minimum: Int, message: String) {
val newValue = value as String
if (newValue.split(" ").count() < minimum) {
throw CustomException(message)
}
}
override fun isAtMost(value: Any?, maximum: Int, message: String) {
val newValue = value as String
if (newValue.split(" ").count() > maximum) {
throw CustomException(message)
}
}
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/validation/StringValidationMechanism.kt | 198711488 |
package com.otumian.springbootapiwithvalidation.validation
import org.springframework.stereotype.Service
interface IIdValidation {
fun validate(id: Long)
}
@Service
class IdValidation (val mechanism: INumberValidationMechanism): IIdValidation {
override fun validate(id: Long) {
mechanism.idIsNumber(id, "id must be a number")
mechanism.idIsLessThanOne(id, "id can not zero")
}
} | spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/validation/IdValidation.kt | 2618983558 |
package com.otumian.springbootapiwithvalidation.validation
import org.springframework.stereotype.Service
interface IArticleValidator {
val article: ICreateArticleValidation
val id: IIdValidation
}
@Service
class ArticleValidator(
val articleValidation: ICreateArticleValidation,
val idValidation: IIdValidation,
) : IArticleValidator {
override val article: ICreateArticleValidation
get() = articleValidation
override val id: IIdValidation
get() = idValidation
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/validation/ArticleValidator.kt | 2250194694 |
package com.otumian.springbootapiwithvalidation.validation
import com.otumian.springbootapiwithvalidation.handler.CustomException
import org.springframework.stereotype.Service
interface INumberValidationMechanism {
fun idIsNumber(id: Any?, message: String)
fun idIsLessThanOne(id: Any?, message: String)
}
@Service
class NumberValidationMechanism : INumberValidationMechanism {
override fun idIsNumber(id: Any?, message: String) {
if (id !is Long) {
throw CustomException(message)
}
}
override fun idIsLessThanOne(id: Any?, message: String) {
if ((id as Long) < 1.toLong()) {
throw CustomException(message)
}
}
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/validation/NumberValidationMechanis.kt | 915937932 |
package com.otumian.springbootapiwithvalidation.validation
import com.otumian.springbootapiwithvalidation.dto.ArticleDto
import org.springframework.stereotype.Service
interface ICreateArticleValidation {
fun validate(article: ArticleDto)
}
@Service
class CreateArticleValidation(val mechanism: IStringValidationMechanism) : ICreateArticleValidation {
override fun validate(article: ArticleDto) {
this.titleValidation(article.title!!)
this.contentValidation(article.content!!)
}
private fun titleValidation(title: String, minimum: Int = 3, maximum: Int = 10) {
this.mechanism.isNotNull(title, "title is required")
this.mechanism.isString(title, "title must be a string")
this.mechanism.isAtLeast(
value = title, minimum = minimum, message = "title must be at least $minimum words"
)
this.mechanism.isAtMost(
value = title, maximum = maximum, message = "title must be at most $maximum words"
)
}
private fun contentValidation(content: String, minimum: Int = 10, maximum: Int = 20) {
this.mechanism.isNotNull(content, "content is required")
this.mechanism.isString(content, "content must be a string")
this.mechanism.isAtLeast(
value = content, minimum = minimum, message = "content must be at least $minimum words"
)
this.mechanism.isAtMost(
value = content, maximum = maximum, message = "content must be at most $maximum words"
)
}
}
| spring-boot-api-with-validation/src/main/kotlin/com/otumian/springbootapiwithvalidation/validation/CreateArticleValidation.kt | 3272196469 |
package com.ese12.gilgitapp
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.ese12.gilgitapp", appContext.packageName)
}
} | Ghizer_App/app/src/androidTest/java/com/ese12/gilgitapp/ExampleInstrumentedTest.kt | 1821274302 |
package com.ese12.gilgitapp
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)
}
} | Ghizer_App/app/src/test/java/com/ese12/gilgitapp/ExampleUnitTest.kt | 1313289488 |
package com.ese12.gilgitapp
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.ese12.gilgitapp.Activities.SignUpActivity
import com.ese12.gilgitapp.Fragments.AccountFragment
import com.ese12.gilgitapp.Fragments.HomeFragment
import com.ese12.gilgitapp.Fragments.MessagesFragment
import com.ese12.gilgitapp.Fragments.NotificationFragment
import com.ese12.gilgitapp.selectcategory.*
import com.google.android.material.bottomappbar.BottomAppBar
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.auth.FirebaseAuth
class MainActivity : AppCompatActivity() {
private lateinit var bottomAppBar: BottomAppBar
private lateinit var bottomNavigationView: BottomNavigationView
private lateinit var fragmentContainer: FrameLayout
private lateinit var fab: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
window.statusBarColor = ContextCompat.getColor(this, R.color.black)
bottomAppBar = findViewById(R.id.bottomAppBar)
bottomNavigationView = findViewById(R.id.bottomNavigationView)
fragmentContainer = findViewById(R.id.fragmentContainer)
fab = findViewById(R.id.fab)
bottomNavigationView.background = null
bottomNavigationView.menu.getItem(2).isEnabled = false
fab.setOnClickListener {
showDialog()
}
bottomNavigationView.setOnNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.nav_home -> {
replaceFragment(HomeFragment())
true
}
R.id.nav_account -> {
replaceFragment(AccountFragment())
true
}
R.id.nav_messages -> {
replaceFragment(MessagesFragment())
true
}
R.id.nav_notifi -> {
replaceFragment(NotificationFragment())
true
}
// Handle other menu items here
else -> false
}
}
replaceFragment(HomeFragment())
}
private fun replaceFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, fragment)
.commit()
}
private fun showDialog() {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.bottomsheetlayout)
val buyer_request = dialog.findViewById<LinearLayout>(R.id.buyer_request)
val cars_suvs = dialog.findViewById<LinearLayout>(R.id.cars_suvs)
val bikes = dialog.findViewById<LinearLayout>(R.id.bikes)
val mobile_accessories = dialog.findViewById<LinearLayout>(R.id.mobile_accessories)
val laptops_accessories = dialog.findViewById<LinearLayout>(R.id.laptops_accessories)
val house = dialog.findViewById<LinearLayout>(R.id.house)
val pets = dialog.findViewById<LinearLayout>(R.id.pets)
val office = dialog.findViewById<LinearLayout>(R.id.office)
val shop = dialog.findViewById<LinearLayout>(R.id.shop)
val plot = dialog.findViewById<LinearLayout>(R.id.plot)
val appliances = dialog.findViewById<LinearLayout>(R.id.appliances)
val furniture = dialog.findViewById<LinearLayout>(R.id.furniture)
val fashion_beauty = dialog.findViewById<LinearLayout>(R.id.fashion_beauty)
val books = dialog.findViewById<LinearLayout>(R.id.books)
val dry_friut = dialog.findViewById<LinearLayout>(R.id.dry_friut)
val other = dialog.findViewById<LinearLayout>(R.id.other)
buyer_request.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, BuyerRequest::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
cars_suvs.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, CarsSuvs::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
bikes.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Bikes::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
mobile_accessories.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, MobileAccessories::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
laptops_accessories.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, LaptopsAccessories::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
house.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, House::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
pets.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Pets::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
office.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Office::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
shop.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Shop::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
plot.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Plot::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
appliances.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Appliances::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
furniture.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Furniture::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
fashion_beauty.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, FashionBeauty::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
books.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Books::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
dry_friut.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Dry_Friut::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
other.setOnClickListener {
if (FirebaseAuth.getInstance().currentUser != null) {
startActivity(Intent(this, Other::class.java))
}else{
startActivity(Intent(this, SignUpActivity::class.java))
}
}
dialog.show()
dialog.window!!.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.window!!.attributes.windowAnimations = R.style.DialogAnimation
dialog.window!!.setGravity(Gravity.BOTTOM)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/MainActivity.kt | 1755628126 |
package com.ese12.gilgitapp.Fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ese12.gilgitapp.R
class AccountFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_account, container, false)
return view
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Fragments/AccountFragment.kt | 2097206089 |
package com.ese12.gilgitapp.Fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ese12.gilgitapp.R
class NotificationFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_notification, container, false)
return view
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Fragments/NotificationFragment.kt | 1038839482 |
package com.ese12.gilgitapp.Fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ese12.gilgitapp.R
class MessagesFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_messages, container, false)
return view
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Fragments/MessagesFragment.kt | 2899070285 |
package com.ese12.gilgitapp.Fragments
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.denzcoskun.imageslider.ImageSlider
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.models.SlideModel
import com.ese12.gilgitapp.*
import com.ese12.gilgitapp.Adapters.*
import com.ese12.gilgitapp.Models.*
import com.ese12.gilgitapp.domain.models.BuyerRequestModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class HomeFragment : Fragment() {
lateinit var recyclerView: RecyclerView
lateinit var carsRecyclerView: RecyclerView
lateinit var bikesRecyclerView: RecyclerView
lateinit var imageSlider: ImageSlider
lateinit var list: ArrayList<BuyerRequestModel>
lateinit var carsRecyclerViewList: ArrayList<CarsSuvsModel>
lateinit var bikesRecyclerViewList: ArrayList<BikeModel>
lateinit var mobilesRecyclerView: RecyclerView
lateinit var mobilesList: ArrayList<MobileModels>
lateinit var laptopsRecyclerView: RecyclerView
lateinit var laptopList: ArrayList<LaptopsModel>
lateinit var houseRecyclerView: RecyclerView
lateinit var houseList: ArrayList<HouseModel>
lateinit var petsRecyclerView: RecyclerView
lateinit var petsList: ArrayList<PetsModel>
lateinit var officeRecyclerView: RecyclerView
lateinit var officeList: ArrayList<OfficeModel>
lateinit var shopRecyclerView: RecyclerView
lateinit var shopList: ArrayList<ShopModel>
lateinit var textView: TextView
lateinit var textView2: TextView
lateinit var textView3: TextView
lateinit var textView4: TextView
lateinit var textView5: TextView
lateinit var textView6: TextView
lateinit var textView7: TextView
lateinit var textView8: TextView
lateinit var textView9: TextView
@SuppressLint("MissingInflatedId")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
recyclerView = view.findViewById(R.id.buyerRecyclerView)
carsRecyclerView = view.findViewById(R.id.carsRecyclerView)
bikesRecyclerView = view.findViewById(R.id.bikesRecyclerView)
mobilesRecyclerView = view.findViewById(R.id.mobileRecyclerView)
laptopsRecyclerView = view.findViewById(R.id.laptopRecyeclerView)
houseRecyclerView = view.findViewById(R.id.houseRecyclerView)
petsRecyclerView = view.findViewById(R.id.petsRecyclerView)
officeRecyclerView = view.findViewById(R.id.officeRecyclerView)
shopRecyclerView = view.findViewById(R.id.shopRecyclerView)
textView = view.findViewById(R.id.textView)
textView2 = view.findViewById(R.id.textView2)
textView3 = view.findViewById(R.id.textView3)
textView4 = view.findViewById(R.id.textView4)
textView5 = view.findViewById(R.id.textView5)
textView6 = view.findViewById(R.id.textView6)
textView7 = view.findViewById(R.id.textView7)
textView8 = view.findViewById(R.id.textView8)
textView9 = view.findViewById(R.id.textView9)
imageSlider = view.findViewById(R.id.imageSlider)
val imageListForSlider = ArrayList<SlideModel>().apply {
add(SlideModel("https://firebasestorage.googleapis.com/v0/b/online-bussines-6e1c9.appspot.com/o/user1%2Fimages%2F1703828687622.jpg?alt=media&token=5c58ed5b-2c57-4914-9162-6e421fa510ab", ""))
add(SlideModel("https://firebasestorage.googleapis.com/v0/b/online-bussines-6e1c9.appspot.com/o/user1%2Fimages%2F1703828719387.jpg?alt=media&token=7cc8ca87-8e81-4ee1-9b6f-74a372361755", ""))
add(SlideModel("https://firebasestorage.googleapis.com/v0/b/online-bussines-6e1c9.appspot.com/o/user1%2Fimages%2F1703828732087.jpg?alt=media&token=68d580bb-61d9-4218-a1a3-9dd1e6ecd2f9", ""))
add(SlideModel("https://media-cldnry.s-nbcnews.com/image/upload/newscms/2021_07/3451045/210218-product-of-the-year-2x1-cs.jpg", ""))
}
// val imageListForSlider = arrayListOf(
// SlideModel("https://i.insider.com/63a0ad5c0675db0018b3765b?width=700"),
// SlideModel("https://media-cldnry.s-nbcnews.com/image/upload/newscms/2021_07/3451045/210218-product-of-the-year-2x1-cs.jpg"),
// SlideModel("https://images.moneycontrol.com/static-mcnews/2019/07/Amul-770x435.jpg?impolicy=website&width=770&height=431")
// )
imageSlider.setImageList(imageListForSlider, ScaleTypes.FIT)
carsRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
bikesRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
mobilesRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
laptopsRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
houseRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
petsRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
officeRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
shopRecyclerView.layoutManager = GridLayoutManager(requireContext(), 2)
list = ArrayList()
carsRecyclerViewList = ArrayList()
bikesRecyclerViewList = ArrayList()
mobilesList = ArrayList()
laptopList = ArrayList()
houseList = ArrayList()
petsList = ArrayList()
officeList = ArrayList()
shopList = ArrayList()
if (FirebaseAuth.getInstance().currentUser == null) {
} else {
var uid = FirebaseAuth.getInstance().currentUser!!.uid
FirebaseDatabase.getInstance().getReference("Buyer Requests").child(uid)
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
list.clear()
for (snap in snapshot.children) {
val model = snap.getValue(BuyerRequestModel::class.java)
list.add(model!!)
textView.visibility = View.VISIBLE
list.reverse()
}
if (isAdded) {
recyclerView.adapter = BuyerRequestsAdapter(context!!, list)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Cars")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
carsRecyclerViewList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(CarsSuvsModel::class.java)
carsRecyclerViewList.add(model!!)
textView2.visibility = View.VISIBLE
carsRecyclerViewList.reverse()
}
if (isAdded) {
carsRecyclerView.adapter =
CarsSuvsAdapter(context!!, carsRecyclerViewList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Bikes")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
bikesRecyclerViewList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(BikeModel::class.java)
bikesRecyclerViewList.add(model!!)
textView3.visibility = View.VISIBLE
bikesRecyclerViewList.reverse()
}
if (isAdded) {
bikesRecyclerView.adapter =
BikesAdapter(context!!, bikesRecyclerViewList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Mobiles")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
mobilesList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(MobileModels::class.java)
mobilesList.add(model!!)
textView4.visibility = View.VISIBLE
mobilesList.reverse()
}
if (isAdded) {
mobilesRecyclerView.adapter = MobilesAdapter(context!!, mobilesList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Laptops")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
laptopList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(LaptopsModel::class.java)
laptopList.add(model!!)
textView5.visibility = View.VISIBLE
laptopList.reverse()
}
if (isAdded) {
laptopsRecyclerView.adapter = LaptopsAdapter(context!!, laptopList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
FirebaseDatabase.getInstance().getReference("House")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
houseList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(HouseModel::class.java)
houseList.add(model!!)
textView6.visibility = View.VISIBLE
houseList.reverse()
}
if (isAdded) {
houseRecyclerView.adapter = HouseAdapter(context!!, houseList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Pets")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
petsList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(PetsModel::class.java)
petsList.add(model!!)
textView7.visibility = View.VISIBLE
petsList.reverse()
}
if (isAdded) {
petsRecyclerView.adapter = PetsAdapter(context!!, petsList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Office")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
officeList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(OfficeModel::class.java)
officeList.add(model!!)
textView8.visibility = View.VISIBLE
officeList.reverse()
}
if (isAdded) {
officeRecyclerView.adapter = OfficeAdapter(context!!, officeList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
FirebaseDatabase.getInstance().getReference("Shop")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
shopList.clear()
for (snap in snapshot.children) {
val model = snap.getValue(ShopModel::class.java)
shopList.add(model!!)
textView9.visibility = View.VISIBLE
shopList.reverse()
}
if (isAdded) {
shopRecyclerView.adapter = ShopAdapter(context!!, shopList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
return view
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Fragments/HomeFragment.kt | 3929108152 |
package com.ese12.gilgitapp.Models
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ese12.gilgitapp.domain.models.ProductModel
import com.ese12.gilgitapp.repo.MainRepository
import com.ese12.gilgitapp.repo.MainRepositoryImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainViewModel : ViewModel() {
var mainRepository: MainRepository = MainRepositoryImpl()
private val _allProducts = MutableStateFlow<List<ProductModel>>(emptyList())
val allProducts: StateFlow<List<ProductModel>> = _allProducts
init {
// Load all products into _allProducts
viewModelScope.launch {
val products = mainRepository.collectAllProductsList()
products.collect {
_allProducts.value = it
}
}
}
suspend fun searchProduct(query: String): List<ProductModel> {
return withContext(Dispatchers.Default) {
_allProducts.value.filter { it.title.contains(query, true) }
}
}
}
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/MainViewModel.kt | 2237472097 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class BikeModel(var key:String="",var bikeImage:String="",var title:String="",var description:String="",var manufacture:String="",var location:String="",var price:String="",var newCondition:Boolean=false,var usedCondition:Boolean = false, var sevenDays:Boolean=false,var fifteenDays:Boolean = false,var thirtyDays:Boolean=false,var noWarranty:Boolean=false,var negotiableYes:Boolean=false,var negotiableNo:Boolean=false,var marchaYes:Boolean=false,var marchaNo:Boolean=false,var modelYear:String="",var engine:String="",var bikeColor:String="",var registrationCity:String="",var milage:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/BikeModel.kt | 3757316807 |
package com.ese12.gilgitapp.Models
data class OfferModel(var buyerUid:String="",var key:String="",var title:String="",var price:String="",var image:String="",var description:String="",var stockAmount:String="") | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/OfferModel.kt | 505020224 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class CarsSuvsModel(var carImage:String="",var title:String="",var description:String="",var manufacturer:String="",
var location:String="",var price:String="",var new:Boolean = false,var used:Boolean = false,var sevenDaysWarranty:Boolean=false,var fifteenDaysWarranty:Boolean=false,
var thirtyDaysWarranty:Boolean=false,var noWarranty:Boolean=false,var negotiableYes:Boolean = false,var negotiableNo:Boolean = false,var availableForMarchaYes:Boolean=false,
var availableForMarchaNo:Boolean=false,var engine:String="",var registrationCity:String="",var petrol:Boolean=false,var diesel:Boolean=false,var hybrid:Boolean=false,
var cng:Boolean=false,var millage:String="",var airBags:Boolean=false,var airConditioning:Boolean=false,var power:Boolean=false,var mirror:Boolean = false,var abs:Boolean=false,var usb:Boolean=false,var stockAmount:String=""):Parcelable | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/CarsSuvsModel.kt | 172725037 |
package com.ese12.gilgitapp.Models
data class BooksModel(var key:String="", var imageUri:String="", var title:String="", var description:String="", var price:String="", var location:String="",
var new:Boolean=false, var used:Boolean=false, var negoYes:Boolean=false, var negoNo:Boolean=false,var stockAmount:String="")
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/BooksModel.kt | 687767858 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class PlotModel(var key:String="", var plotImage:String="", var title:String="", var description:String="", var location:String="", var price:String="", var rent:Boolean=false, var sale:Boolean = false, var kanal:Boolean=false, var marla:Boolean = false, var resid:Boolean=false, var commer:Boolean=false, var agri:Boolean=false, var personName:String="", var contactNumber:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/PlotModel.kt | 724519507 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class FurnitureModel(var key:String="", var image:String="", var title:String="", var manufacture:String="", var description:String="", var location:String="", var price:String="", var new:Boolean=false, var used:Boolean = false, var negoYes:Boolean=false, var negoNo:Boolean=false, var itemColor:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/FurnitureModel.kt | 679398643 |
package com.ese12.gilgitapp.Models
data class FruitsModel(var key:String="", var imageUri:String="", var title:String="", var description:String="", var price:String="", var location:String="",
var negoYes:Boolean=false, var negoNo:Boolean=false,var stockAmount:String="")
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/FruitsModel.kt | 2426249140 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class AppliancesModel(var key:String="", var image:String="", var title:String="",var manufacture:String="", var description:String="", var location:String="", var price:String="", var new:Boolean=false, var used:Boolean = false,var negoYes:Boolean=false, var negoNo:Boolean=false, var itemColor:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/AppliancesModel.kt | 1245311201 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class PetsModel(var key:String="",var imageUri:String="", var title:String="", var description:String="", var price:String="", var location:String="",
var male:Boolean=false, var female:Boolean=false, var negoYes:Boolean=false, var negoNo:Boolean=false, var petBreed:String="", var petAge:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/PetsModel.kt | 3170683584 |
package com.ese12.gilgitapp.Models
import android.content.Context
import android.text.format.DateUtils
import android.widget.Toast
class Callback(private val context: Context) {
fun onToast(string: String) {
Toast.makeText(context, string, Toast.LENGTH_SHORT).show()
}
fun elapsedCountDownTimer(time: Long): String {
return "Code verification resend in... " + DateUtils.formatElapsedTime(time).replace(".", ":")
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/Callback.kt | 1064901717 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class HouseModel(var key:String="",var image:String="",var title:String="",var description:String="",var price:String="",var location:String="",
var forSale:Boolean=false,var forRent:Boolean=false,var secuirtyDeposit:String="",var negoYes:Boolean=false,var negoNo:Boolean=false,var personName:String="",var contactNumber:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/HouseModel.kt | 3503858271 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class ShopModel(var key:String="", var image:String="", var title:String="", var description:String="", var price:String="", var location:String="",
var forSale:Boolean=false, var forRent:Boolean=false, var secuirtyDeposit:String="", var negoYes:Boolean=false, var negoNo:Boolean=false, var personName:String="", var contactNumber:String="",var stockAmount:String="" ):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/ShopModel.kt | 1244556069 |
package com.ese12.gilgitapp.Models
import android.location.Location
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class LaptopsModel(var key:String="",var img:String="",var title:String="",var description:String="",var manufacture:String="",var location:String="",
var price:String="",var conditionNew:Boolean=false,var conditionUsed:Boolean=false,var negoYes:Boolean=false,var negoNo:Boolean=false,var marchaYes:Boolean=false,var marchaNo:Boolean=false,var productLaptop:Boolean=false,var productAccessory:Boolean=false,var model:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/LaptopsModel.kt | 3541153083 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class MobileModels(var key:String="",var image:String="",var title:String="",var description:String="",var manufacture:String="",
var location:String="",var price:String="",var conditionNew:Boolean=false,var conditionUsed:Boolean=false,var warrantySevenDays:Boolean=false,
var fifDaysWar:Boolean=false,var thiryDaysWar:Boolean=false,var noWarr:Boolean=false,var negoYes:Boolean=false,var negoNo:Boolean=false,var marchaYes:Boolean=false,
var marchaNo:Boolean=false,var mobile:Boolean=false,var tablet:Boolean=false,var accessory:Boolean=false,var ram2Gb:Boolean=false,var ram3Gb:Boolean=false,var ram4Gb:Boolean=false,var ram8Gb:Boolean=false,var ram16Gb:Boolean=false,var ram32Gb:Boolean=false,var ram64Gb:Boolean=false,
var memory8Gb:Boolean=false,var memory16Gb:Boolean=false,var memory32Gb:Boolean=false,var memory64Gb:Boolean=false,var memory128Gb:Boolean=false,var memory256Gb:Boolean=false,var memory1Tb:Boolean=false,var etModel:String="",var stockAmount:String=""):Parcelable | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/MobileModels.kt | 2466308596 |
package com.ese12.gilgitapp.Models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class OfficeModel(var key:String="",var image:String="", var title:String="", var description:String="", var price:String="", var location:String="",
var forSale:Boolean=false, var forRent:Boolean=false, var secuirtyDeposit:String="", var negoYes:Boolean=false, var negoNo:Boolean=false,var numberOfRoom:String="", var personName:String="", var contactNumber:String="",var stockAmount:String=""):Parcelable
| Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Models/OfficeModel.kt | 3568186079 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.PetsDetails
import com.ese12.gilgitapp.Models.PetsModel
import com.ese12.gilgitapp.R
class PetsAdapter(var context: Context, private val list: List<PetsModel>) :
RecyclerView.Adapter<PetsAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_house_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.imageUri).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, PetsDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/PetsAdapter.kt | 4237177902 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.CarsSuvsDetails
import com.ese12.gilgitapp.Models.CarsSuvsModel
import com.ese12.gilgitapp.R
class CarsSuvsAdapter(var context: Context,private val list: List<CarsSuvsModel>) :
RecyclerView.Adapter<CarsSuvsAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_plot_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.carImage).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, CarsSuvsDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/CarsSuvsAdapter.kt | 1126706789 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.HouseDetails
import com.ese12.gilgitapp.Models.HouseModel
import com.ese12.gilgitapp.R
class HouseAdapter(var context: Context, private val list: List<HouseModel>) :
RecyclerView.Adapter<HouseAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_house_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.image).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, HouseDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/HouseAdapter.kt | 1545238639 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.OfficeDetails
import com.ese12.gilgitapp.Models.OfficeModel
import com.ese12.gilgitapp.R
class OfficeAdapter(var context: Context, private val list: List<OfficeModel>) :
RecyclerView.Adapter<OfficeAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_house_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.image).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, OfficeDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/OfficeAdapter.kt | 3281316368 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.MobilesDetails
import com.ese12.gilgitapp.Models.MobileModels
import com.ese12.gilgitapp.R
class MobilesAdapter(var context: Context, private val list: List<MobileModels>) :
RecyclerView.Adapter<MobilesAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_bike_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.image).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, MobilesDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/MobilesAdapter.kt | 3444758353 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.BikesDetails
import com.ese12.gilgitapp.Models.BikeModel
import com.ese12.gilgitapp.R
class BikesAdapter(var context: Context, private val list: List<BikeModel>) :
RecyclerView.Adapter<BikesAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_bike_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.bikeImage).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, BikesDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/BikesAdapter.kt | 2420615398 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.*
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.MakeAnOffer
import com.ese12.gilgitapp.R
import com.ese12.gilgitapp.domain.models.BuyerRequestModel
class BuyerRequestsAdapter(var context: Context, private val list: List<BuyerRequestModel>) :
RecyclerView.Adapter<BuyerRequestsAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.buyer_requests_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.profileImage).into(holder.profileImage)
holder.userName.text = data.userName
holder.price.text = "PKR "+data.price
holder.location.text = data.location
holder.lookingFor.text = data.looking_item
holder.category.text = data.category
holder.makeAnOffer.setOnClickListener {
val intent = Intent(context, MakeAnOffer::class.java)
intent.putExtra("uid",data.uid)
context.startActivity(intent)
}
//
// holder.itemView.setOnClickListener {
// val intent = Intent(context,BuyerDetails::class.java)
// intent.putExtra("list",data)
// context.startActivity(intent)
// }
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val profileImage = itemView.findViewById<ImageView>(R.id.buyerProfileImage)
val price = itemView.findViewById<TextView>(R.id.price)
val userName = itemView.findViewById<TextView>(R.id.userName)
val lookingFor = itemView.findViewById<TextView>(R.id.lookingFor)
val location = itemView.findViewById<TextView>(R.id.location)
val category = itemView.findViewById<TextView>(R.id.category)
val makeAnOffer = itemView.findViewById<TextView>(R.id.makeAnOffer)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/BuyerRequestsAdapter.kt | 1876096202 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.Activities.LaptopsDetails
import com.ese12.gilgitapp.Models.LaptopsModel
import com.ese12.gilgitapp.R
class LaptopsAdapter(var context: Context, private val list: List<LaptopsModel>) :
RecyclerView.Adapter<LaptopsAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_laptops_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.img).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, LaptopsDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/LaptopsAdapter.kt | 613063017 |
package com.ese12.gilgitapp.Adapters
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ese12.gilgitapp.R
import com.ese12.gilgitapp.Activities.ShopDetails
import com.ese12.gilgitapp.Models.ShopModel
class ShopAdapter(var context: Context, private val list: List<ShopModel>) :
RecyclerView.Adapter<ShopAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(context).inflate(R.layout.sample_house_row, parent, false)
return MyViewHolder(itemView)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val data = list[position]
Glide.with(context).load(data.image).into(holder.imageView)
holder.model.text = data.title
holder.price.text = "PKR "+data.price
holder.location.text = data.location
// holder.date.text = data.date
holder.itemView.setOnClickListener {
val intent = Intent(context, ShopDetails::class.java)
intent.putExtra("list",data)
context.startActivity(intent)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imageView = itemView.findViewById<ImageView>(R.id.img2)
val price = itemView.findViewById<TextView>(R.id.price)
val date = itemView.findViewById<TextView>(R.id.tv23)
val model = itemView.findViewById<TextView>(R.id.tv24)
val location = itemView.findViewById<TextView>(R.id.tv25)
}
} | Ghizer_App/app/src/main/java/com/ese12/gilgitapp/Adapters/ShopAdapter.kt | 284061419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.