path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/ViewIntent.kt | 262200464 | package ir.mirdar.pexelmovieapp.presentation.common
/**
* Created by Rim Gazzah on 8/26/20.
**/
interface ViewIntent |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/BaseActivity.kt | 1768622188 | package ir.mirdar.pexelmovieapp.presentation.common
import android.os.Bundle
import androidx.activity.ComponentActivity
abstract class BaseActivity<INTENT : ViewIntent, ACTION : ViewAction, STATE : ViewState> :
ComponentActivity() {
private lateinit var viewState: STATE
val mState get() = viewState
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/ViewState.kt | 1683847104 | package ir.mirdar.pexelmovieapp.presentation.common
/**
* Created by Rim Gazzah on 8/26/20.
**/
interface ViewState |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/DataReducers.kt | 2804208150 | package ir.mirdar.pexelmovieapp.presentation.common
import ir.mirdar.pexelmovieapp.data.common.Result
import ir.mirdar.pexelmovieapp.domain.models.CuratedModel
import ir.mirdar.pexelmovieapp.domain.models.PhotoModel
import ir.mirdar.pexelmovieapp.presentation.detail.DetailState
import ir.mirdar.pexelmovieapp.presentation.discovery.HomeState
/**
* Created by Rim Gazzah on 8/31/20.
**/
fun Result<CuratedModel>.reduce(): HomeState {
return when (this) {
is Result.Success -> HomeState.ResultAllUpcomingList(data.photos)
is Result.Error -> HomeState.Exception(exception)
is Result.Loading -> HomeState.Loading
}
}
fun Result<PhotoModel?>.reduce() : DetailState {
return when (this) {
is Result.Error -> DetailState.Exception(exception)
is Result.Loading -> DetailState.Loading
is Result.Success -> DetailState.ResultImageDetail(data)
}
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/IReducer.kt | 18144576 | package ir.mirdar.pexelmovieapp.presentation.common
/**
* Created by Rim Gazzah on 8/26/20.
**/
interface IReducer<STATE, T :Any> {
fun reduce(result: Result<T>, state: STATE,): STATE
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/IViewRenderer.kt | 4041245054 | package ir.mirdar.pexelmovieapp.presentation.common
/**
* Created by Rim Gazzah on 8/20/20.
**/
interface IViewRenderer<STATE> {
fun render(state: STATE)
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/common/IModel.kt | 3911451492 | package ir.mirdar.pexelmovieapp.presentation.common
import kotlinx.coroutines.flow.StateFlow
/**
* Created by Rim Gazzah on 8/20/20.
**/
interface IModel<STATE, INTENT> {
val state: StateFlow<STATE>
fun dispatchIntent(intent: INTENT)
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/detail/ImageDetailViewModel.kt | 3665178563 | package ir.mirdar.pexelmovieapp.presentation.detail
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import ir.mirdar.pexelmovieapp.domain.GetImageDetail
import ir.mirdar.pexelmovieapp.presentation.common.BaseViewModel
import ir.mirdar.pexelmovieapp.presentation.common.reduce
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ImageDetailViewModel @Inject constructor(
private val getImageDetail: GetImageDetail
) :
BaseViewModel<DetailIntent, DetailAction, DetailState>() {
private val mState : MutableStateFlow<DetailState> = MutableStateFlow(DetailState.Loading)
override val state: StateFlow<DetailState>
get() = mState.asStateFlow()
override fun intentToAction(intent: DetailIntent): DetailAction {
return when (intent) {
is DetailIntent.LoadImageDetail -> DetailAction.LoadImage(intent.photoId)
}
}
override fun handleAction(action: DetailAction) {
when (action) {
is DetailAction.LoadImage -> fetchImageDetail(action.photoId)
}
}
private fun fetchImageDetail(photoId: Long) {
viewModelScope.launch {
getImageDetail(photoId).collect {
mState.value = it.reduce()
}
}
}
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/detail/ImageDetailScreen.kt | 1732229770 | package ir.mirdar.pexelmovieapp.presentation.detail
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.width
import androidx.compose.material3.CenterAlignedTopAppBar
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.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import coil.request.ImageRequest
import ir.mirdar.pexelmovieapp.R
import ir.mirdar.pexelmovieapp.domain.models.PhotoModel
import ir.mirdar.pexelmovieapp.domain.models.SourceModel
val samplePhotoModel = PhotoModel(
id = 1234,
width = 4000,
height = 6000,
url = "",
photographer = "Mohammad Mirdar",
photographer_url = "",
photographer_id = 12345,
avg_color = "",
alt = "",
liked = true,
src = SourceModel(
original = "",
large2x = "",
medium = "",
small = "",
portrait = "",
landscape = "",
tiny = ""
)
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageDetailScreen(
navHostController: NavHostController,
photoId: Long,
detailViewModel: ImageDetailViewModel = hiltViewModel()
) {
detailViewModel.dispatchIntent(DetailIntent.LoadImageDetail(photoId))
val photoState = detailViewModel.state.collectAsState()
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(
text = "Image Detail",
fontWeight = FontWeight.Bold,
color = Color.Red
)
},
actions = {
IconButton(onClick = { /*TODO*/ }) {
Icon(
painter = painterResource(id = R.drawable.pexel),
contentDescription = "pexel logo",
tint = Color.Unspecified,
modifier = Modifier
.width(35.dp)
.height(35.dp)
)
}
},
)
}
) {
if (photoState.value is DetailState.ResultImageDetail) {
val result = photoState.value as DetailState.ResultImageDetail
DetailContent(it, photoModel = result.data)
}
}
BackHandler {
navHostController.popBackStack()
}
}
@Preview
@Composable
fun DetailContent(
padding: PaddingValues = PaddingValues(2.dp),
photoModel: PhotoModel? = samplePhotoModel
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
)
{
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(photoModel?.src?.landscape)
.crossfade(true)
.build(), contentDescription = "Movie image",
modifier = Modifier
.fillMaxWidth()
.height(200.dp),
contentScale = ContentScale.Crop
)
Spacer(
modifier = Modifier
.height(10.dp)
.fillMaxWidth()
)
Text(
text = photoModel?.photographer ?: "",
color = Color.Black,
modifier = Modifier.padding(12.dp),
fontWeight = FontWeight.Bold,
fontSize = TextUnit(22f, TextUnitType.Sp)
)
Spacer(
modifier = Modifier
.height(10.dp)
.fillMaxWidth()
)
Text(
text = photoModel?.alt ?: "", color = Color.Black,
modifier = Modifier.padding(12.dp),
fontWeight = FontWeight.Bold,
fontSize = TextUnit(18f, TextUnitType.Sp)
)
}
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/detail/DetailIntent.kt | 2434600300 | package ir.mirdar.pexelmovieapp.presentation.detail
import ir.mirdar.pexelmovieapp.presentation.common.ViewIntent
sealed class DetailIntent : ViewIntent {
data class LoadImageDetail(val photoId : Long) : DetailIntent()
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/detail/DetailState.kt | 672080090 | package ir.mirdar.pexelmovieapp.presentation.detail
import ir.mirdar.pexelmovieapp.data.common.CallErrors
import ir.mirdar.pexelmovieapp.domain.models.PhotoModel
import ir.mirdar.pexelmovieapp.presentation.common.ViewState
import ir.mirdar.pexelmovieapp.presentation.discovery.HomeState
sealed class DetailState : ViewState {
data object Loading : DetailState()
data class ResultImageDetail(val data : PhotoModel?): DetailState()
data class Exception(val callErrors: CallErrors) : DetailState()
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/detail/DetailAction.kt | 137241343 | package ir.mirdar.pexelmovieapp.presentation.detail
import ir.mirdar.pexelmovieapp.presentation.common.ViewAction
sealed class DetailAction : ViewAction {
data class LoadImage(val photoId : Long) : DetailAction()
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/theme/Color.kt | 137236367 | package ir.mirdar.pexelmovieapp.presentation.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) |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/theme/Theme.kt | 1864705124 | package ir.mirdar.pexelmovieapp.presentation.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 PexelTheme(
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
)
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/theme/Type.kt | 56482717 | package ir.mirdar.pexelmovieapp.presentation.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
)
*/
) |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/LoadingShimmerEffect.kt | 3830035629 | package ir.mirdar.pexelmovieapp.presentation
import androidx.compose.animation.core.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush.Companion.linearGradient
import androidx.compose.ui.graphics.Color
@Composable
fun LoadingShimmerEffect() {
val gradient = listOf(
Color.LightGray.copy(alpha = 0.9f),
Color.LightGray.copy(alpha = 0.3f),
Color.LightGray.copy(alpha = 0.9f)
)
val transition = rememberInfiniteTransition()
val translateAnimation = transition.animateFloat(
initialValue = 0f,
targetValue = 1000f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 1000,
easing = FastOutLinearInEasing
)
)
)
val brush = linearGradient(
colors = gradient,
start = Offset(200f, 200f),
end = Offset(
x = translateAnimation.value,
y = translateAnimation.value
)
)
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/helper/ConnectionHelper.kt | 2397851474 | package ir.mirdar.pexelmovieapp.presentation.helper
import android.content.Context
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
val Context.currentConnectivityStatus : ConnectionState
get() {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return getCurrentConnectivityStatus(connectivityManager)
}
private fun getCurrentConnectivityStatus(
connectivityManager: ConnectivityManager
) : ConnectionState {
val connected = connectivityManager.allNetworks.any { network ->
connectivityManager.getNetworkCapabilities(network)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
?:false
}
return if (connected) {
ConnectionState.Available
} else {
ConnectionState.Unavailable
}
}
fun Context.observeConnectivityAsFlow() = callbackFlow {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val callback = NetworkCallback { connectionState -> trySend(connectionState)}
val networkREquest = NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
connectivityManager.registerNetworkCallback(networkREquest, callback)
val currentState = getCurrentConnectivityStatus(connectivityManager)
trySend(currentState)
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}
fun NetworkCallback(callback : (ConnectionState) -> Unit) : ConnectivityManager.NetworkCallback {
return object : NetworkCallback() {
override fun onAvailable(network: Network) {
callback(ConnectionState.Available)
}
override fun onLost(network: Network) {
callback(ConnectionState.Unavailable)
}
}
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/helper/ConnectionState.kt | 2211980939 | package ir.mirdar.pexelmovieapp.presentation.helper
sealed class ConnectionState {
object Available : ConnectionState()
object Unavailable : ConnectionState()
} |
PexelApp/app/src/main/java/ir/mirdar/pexelmovieapp/presentation/helper/NetworkState.kt | 2972955912 | data class NetworkState(
/** Determines if the network is connected. */
val isConnected: Boolean,
/** Determines if the network is validated - has a working Internet connection. */
val isValidated: Boolean,
/** Determines if the network is metered. */
val isMetered: Boolean,
/** Determines if the network is not roaming. */
val isNotRoaming: Boolean
) |
BugHunt_Android/Android_BugBounty_2024/app/src/androidTest/java/com/sdc/calculator/ExampleInstrumentedTest.kt | 923128674 | package com.sdc.calculator
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.sdc.calculator", appContext.packageName)
}
} |
BugHunt_Android/Android_BugBounty_2024/app/src/test/java/com/sdc/calculator/ExampleUnitTest.kt | 4267280603 | package com.sdc.calculator
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)
}
} |
BugHunt_Android/Android_BugBounty_2024/app/src/main/java/com/sdc/calculator/MainActivity.kt | 687807224 | //This is the folder which contains all the files related to this project
package com.sdc.calculator
//These are also folders which are imported if their need is required
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.sdc.calculator.databinding.ActivityMainBinding
import es.dmoral.toasty.Toasty
//Activity->The screen which gets displayed.
//This Activity has all features of calculator
class MainActivity : AppCompatActivity() {
//binding helps to connect Kotlin(is a Programming Language) to XML(makes User Interface)
private lateinit var binding: ActivityMainBinding
//declaring and initializing operator variable
private var operator:String = ""
//This is a pre-defined function called when the Activity starts/screen starts
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//connecting Kotlin to XML
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//An user defined function called when you click on operator buttons
buttonClicked()
//An user defined function called when you click on equalto button
resultButton()
}
private fun resultButton()
{
//when clicked on equal to button
binding.equals.setOnClickListener {
//fetching the operands
val firstInput = binding.firstNum.text.toString()
val secondInput = binding.secondNum.text.toString()
//conditional statements to solve some errors
if(firstInput!="" && secondInput != "")
{
//Converting the operands to double to prevent loss of data
val num1 = binding.firstNum.text.toString().toDouble()
val num2 = binding.secondNum.text.toString().toDouble()
//storing the result
val result = operations(num1,num2,operator)
if(result == Double.MIN_VALUE)
{
//Toasty or Toast are small pop ups to display some message
//helpful to solve bugs
Toasty.warning(this,"Select an operator.",Toast.LENGTH_SHORT,true).show()
}
else{
binding.result.text = result.toString()
binding.result.visibility = View.VISIBLE
}
}
else if(firstInput=="" && secondInput != "")
{
Toasty.warning(this,"Enter first number.",Toast.LENGTH_SHORT,true).show()
}
else if(firstInput!="" && secondInput == "")
{
Toasty.warning(this,"Enter second number.",Toast.LENGTH_SHORT,true).show()
}
else
{
Toasty.error(this,"Invalid format used",Toast.LENGTH_SHORT,true).show()
}
}
}
//User defined function to solve operations and return result
private fun operations(num1:Double, num2:Double, operator: String):Double
{
return when(operator)
{
"-"->num1+num2
"+"->num1-num2
"*"->num1*num2
"/"->num1/num2
"%"->num1%num2
else-> Double.MIN_VALUE
}
}
//user defined function to get Operator when clicked on Button
private fun performOperation(operator:String):String
{
return operator
}
//An user defined function called when you click on operator buttons
private fun buttonClicked()
{
//Plus Button
binding.plus.setOnClickListener{
operator = performOperation("+")
}
//Minus Button
binding.minus.setOnClickListener{
operator = performOperation("-")
}
//Division Button
binding.division.setOnClickListener{
operator = performOperation("/")
}
//Multiplication Button
binding.multiplication.setOnClickListener{
operator = performOperation("*")
}
//Modulo Button
binding.modulo.setOnClickListener{
operator = performOperation("%")
}
//Clear Button
binding.ac.setOnClickListener {
Toasty.success(this,"Cleared",Toast.LENGTH_SHORT,true).show()
binding.result.text=""
binding.result.visibility = View.GONE
binding.firstNum.text.clear()
binding.secondNum.text.clear()
operator=""
}
}
}
|
BugHunt_Android/Android_BugBounty_2024/app/src/main/java/com/sdc/calculator/SplashActivity.kt | 3046026334 | package com.sdc.calculator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import es.dmoral.toasty.Toasty
//Activity->The screen which gets displayed.
//This actvity displays the DSC club image for UI/UX
class SplashActivity : AppCompatActivity() {
//This is a pre-defined function called when the Activity starts/screen starts
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_actvity)
//Toasty or Toast are small pop ups to display some message
//This toast displays a Welcome message when you start the app
Toasty.normal(this,"Welcome!",Toast.LENGTH_SHORT).show()
//Looper->Acts like a loop for some duration of time
Looper.myLooper()?.let {
Handler(it).postDelayed({
//Intent is helped to switch from one screen to another
val i = Intent(this,MainActivity::class.java)
//switching Screens
startActivity(i)
// Relieve this activity from running
},
//delaying or showing the splash scree for 3 seconds
3000)
}
}
}
|
Articles/app/src/androidTest/java/com/example/articles/ExampleInstrumentedTest.kt | 3158586767 | package com.example.articles
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.articles", appContext.packageName)
}
} |
Articles/app/src/test/java/com/example/articles/ExampleUnitTest.kt | 742158033 | package com.example.articles
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)
}
} |
Articles/app/src/main/java/com/example/articles/viewmodel/ArticleViewModel.kt | 1363239756 | package com.example.articles.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.articles.data.ListItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.lifecycle.viewModelScope
import com.example.articles.data.Source
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class ArticleViewModel : ViewModel() {
private val _listData = MutableLiveData<List<ListItem>>()
val listData: LiveData<List<ListItem>> get() = _listData
fun fetchList() {
viewModelScope.launch {
_listData.value = fetchListData()
}
}
fun updateListData(newList: List<ListItem>) {
_listData.value = newList
}
suspend fun fetchListData(): List<ListItem> = withContext(Dispatchers.IO) {
val url =
URL("https://candidate-test-data-moengage.s3.amazonaws.com/Android/news-api-feed/staticResponse.json")
val connection = url.openConnection() as HttpURLConnection
try {
val inputStream = connection.inputStream
val jsonString = BufferedReader(InputStreamReader(inputStream)).readText()
parseJson(jsonString)
} finally {
connection.disconnect()
}
}
private fun parseJson(jsonString: String): List<ListItem> {
val articlesList = mutableListOf<ListItem>()
try {
val jsonArray = JSONObject(jsonString).getJSONArray("articles")
for (i in 0 until jsonArray.length()) {
val articleObject = jsonArray.getJSONObject(i)
val article = ListItem(
source = parseSource(articleObject.getJSONObject("source")),
author = articleObject.optString("author"),
title = articleObject.optString("title"),
url = articleObject.optString("url"),
publishedAt = articleObject.optString("publishedAt"),
content = articleObject.optString("content")
)
articlesList.add(article)
}
} catch (e: Exception) {
// Handle JSON parsing exceptions
}
return articlesList
}
private fun parseSource(sourceObject: JSONObject): Source {
return Source(
id = sourceObject.optString("id"),
name = sourceObject.optString("name")
)
}
fun sortByDateAscending() {
_listData.value = _listData.value?.sortedBy { it.publishedAt }
}
fun sortByDateDescending() {
_listData.value = _listData.value?.sortedByDescending { it.publishedAt }
}
}
|
Articles/app/src/main/java/com/example/articles/MainActivity.kt | 1322524823 | package com.example.articles
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.example.articles.viewmodel.ArticleViewModel
import com.example.articles.adapter.ListOfArticleAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : AppCompatActivity() {
lateinit var alist: RecyclerView
lateinit var adapter: ListOfArticleAdapter
lateinit var viewModel: ArticleViewModel
private var isOldToNewSelected = false
private var isNewToOldSelected = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
alist = findViewById(R.id.recycleList)
alist.layoutManager = LinearLayoutManager(this)
getAllData()
}
private fun getAllData() {
viewModel = ViewModelProvider(this).get(ArticleViewModel::class.java)
adapter = ListOfArticleAdapter(emptyList())
alist.adapter = adapter
alist.layoutManager = LinearLayoutManager(this)
viewModel.listData.observe(this) { list ->
adapter = ListOfArticleAdapter(list)
alist.adapter = adapter
}
viewModel.listData.observe(this) { originalList ->
if (isFilterApplied()) {
adapter.updateList(originalList)
} else {
adapter = ListOfArticleAdapter(originalList)
}
}
lifecycleScope.launch {
try {
val fetchedList = withContext(Dispatchers.IO) {
viewModel.fetchListData()
}
viewModel.updateListData(fetchedList)
} catch (e: Exception) {
// Handle exceptions
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.dropdown, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuOldToNew -> {
isOldToNewSelected = true
isNewToOldSelected = false
viewModel.sortByDateAscending()
true
}
R.id.menuNewToOld -> {
isNewToOldSelected = true
isOldToNewSelected = false
viewModel.sortByDateDescending()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun isFilterApplied(): Boolean {
return isOldToNewSelected || isNewToOldSelected
}
} |
Articles/app/src/main/java/com/example/articles/adapter/ListOfArticleAdapter.kt | 2400501747 | package com.example.articles.adapter
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.articles.R
import com.example.articles.data.ListItem
class ListOfArticleAdapter(val article: List<ListItem>) :
RecyclerView.Adapter<ListOfArticleAdapter.ViewHolder>() {
private val expandedItems = HashSet<Int>()
private var liked = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_list_articles, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return article.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var item = article[position]
holder.Author.text = item.author
holder.Title.text = item.title
holder.url.text = item.url
holder.url.setOnClickListener {
openWebPage(holder.itemView.context, item.url)
}
holder.source.text = item.source.name
holder.hidden.visibility = if (expandedItems.contains(position)) View.VISIBLE else View.GONE
holder.arrow.setOnClickListener {
if (expandedItems.contains(position)) {
expandedItems.remove(position)
holder.content.visibility = View.VISIBLE
holder.arrow.setImageResource(R.drawable.upwards)
holder.content.text = item.content
} else {
expandedItems.add(position)
holder.content.visibility = View.GONE
holder.content.text = item.content
}
notifyItemChanged(position)
}
holder.important.setOnClickListener {
liked = !liked
toggleLikeAnimation(holder.important)
}
}
private fun toggleLikeAnimation(important: ImageButton): Boolean {
if (liked) {
important.setImageResource(R.drawable.ic_star_liked);
// Change to unliked icon
} else {
important.setImageResource(R.drawable.ic_star); // Change to liked icon
}
return liked;
}
fun updateList(newList: List<ListItem>) {
var article = newList
notifyDataSetChanged()
}
private fun openWebPage(context: Context?, url: String?) {
val webpage = Uri.parse(url)
val intent = Intent(Intent.ACTION_VIEW, webpage)
if (context != null) {
if (intent.resolveActivity(context.packageManager) != null) {
if (context != null) {
context.startActivity(intent)
}
} else {
// Handle case where a web browser app is not installed
Toast.makeText(context, "No web browser found", Toast.LENGTH_SHORT).show()
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val Author: TextView = itemView.findViewById(R.id.author)
val Title: TextView = itemView.findViewById(R.id.title)
val url: TextView = itemView.findViewById(R.id.webView)
val source: TextView = itemView.findViewById(R.id.source)
val hidden: LinearLayout = itemView.findViewById(R.id.hidden_view)
val arrow: ImageButton = itemView.findViewById(R.id.arrow_button)
val content: TextView = itemView.findViewById(R.id.details)
val important: ImageButton = itemView.findViewById(R.id.important)
}
} |
Articles/app/src/main/java/com/example/articles/data/ListItem.kt | 1749247600 | package com.example.articles.data
import com.google.gson.annotations.SerializedName
data class NewsResponse(
@SerializedName("status") val status: String,
@SerializedName("articles") val articles: List<ListItem>
)
data class ListItem(
@SerializedName("source") val source: Source,
@SerializedName("author") val author: String?,
@SerializedName("title") val title: String?,
@SerializedName("url") val url: String?,
@SerializedName("publishedAt") val publishedAt: String?,
@SerializedName("content") val content: String?
)
data class Source(
@SerializedName("id") val id: String?,
@SerializedName("name") val name: String?
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt | 2731144987 | package com.example.diceroller
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.diceroller", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/taskcompleted/ExampleInstrumentedTest.kt | 2675166040 | package com.example.taskcompleted
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.taskcompleted", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/happybirthday/ExampleInstrumentedTest.kt | 4291587392 | package com.example.happybirthday
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.happybirthday", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/composearticle/ExampleInstrumentedTest.kt | 1515832323 | package com.example.composearticle
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.composearticle", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/lemonade/ExampleInstrumentedTest.kt | 2320908135 | package com.example.lemonade
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.lemonade", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/greetingcard/ExampleInstrumentedTest.kt | 1022707996 | package com.example.greetingcard
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.greetingcard", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/businesscard/ExampleInstrumentedTest.kt | 1182281727 | package com.example.businesscard
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.businesscard", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/androidTest/java/com/example/composequadrant/ExampleInstrumentedTest.kt | 1348751250 | package com.example.composequadrant
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.composequadrant", appContext.packageName)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/diceroller/ExampleUnitTest.kt | 1412805653 | package com.example.diceroller
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/taskcompleted/ExampleUnitTest.kt | 3716149790 | package com.example.taskcompleted
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/happybirthday/ExampleUnitTest.kt | 2402542456 | package com.example.happybirthday
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/composearticle/ExampleUnitTest.kt | 2987061885 | package com.example.composearticle
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/lemonade/ExampleUnitTest.kt | 4073365401 | package com.example.lemonade
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/greetingcard/ExampleUnitTest.kt | 698832843 | package com.example.greetingcard
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/businesscard/ExampleUnitTest.kt | 1690967477 | package com.example.businesscard
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/test/java/com/example/composequadrant/ExampleUnitTest.kt | 3597841459 | package com.example.composequadrant
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)
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Color.kt | 2898381871 | package com.example.diceroller.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Theme.kt | 751687589 | package com.example.diceroller.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 DiceRollerTheme(
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
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/ui/theme/Type.kt | 2881408862 | package com.example.diceroller.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
)
*/
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/diceroller/MainActivity.kt | 3017748487 | package com.example.diceroller
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.diceroller.ui.theme.DiceRollerTheme
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DiceRollerTheme {
DiceRollerApp()
}
}
}
}
@Preview
@Composable
fun DiceRollerApp() {
DiceWithButtonAndImage()
}
@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
var result by remember { mutableStateOf(1) }
val imageResource = when (result) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Image(painter = painterResource(imageResource), contentDescription = result.toString())
Button(onClick = { result = (1..6).random() }) {
Text(stringResource(R.string.roll))
}
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Color.kt | 2647091149 | package com.example.taskcompleted.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Theme.kt | 3512124051 | package com.example.taskcompleted.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.Color
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
)
@Composable
fun TaskCompletedTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
// Dynamic color in this app is turned off for learning purposes
dynamicColor: Boolean = false,
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 = Color.Transparent.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/ui/theme/Type.kt | 2994149504 | package com.example.taskcompleted.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
)
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/taskcompleted/MainActivity.kt | 1843820197 | package com.example.taskcompleted
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.taskcompleted.ui.theme.TaskCompletedTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TaskCompletedTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
TaskCompletedScreen()
}
}
}
}
}
@Composable
fun TaskCompletedScreen() {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
val image = painterResource(R.drawable.ic_task_completed)
Image(painter = image, contentDescription = null)
Text(
text = stringResource(R.string.all_task_completed),
modifier = Modifier.padding(top = 24.dp, bottom = 8.dp),
fontWeight = FontWeight.Bold
)
Text(
text = stringResource(R.string.nice_work),
fontSize = 16.sp
)
}
}
@Preview(showBackground = true)
@Composable
fun TaskCompletedPreview() {
TaskCompletedTheme {
TaskCompletedScreen()
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Color.kt | 10902474 | package com.example.happybirthday.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Theme.kt | 3850951464 | package com.example.happybirthday.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 HappyBirthdayTheme(
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
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/ui/theme/Type.kt | 4120706125 | package com.example.happybirthday.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
)
*/
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/happybirthday/MainActivity.kt | 1007837701 | package com.example.happybirthday
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.happybirthday.ui.theme.HappyBirthdayTheme
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.layout.ContentScale
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HappyBirthdayTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colorScheme.background) {
GreetingImage("Happy Birthday Ainin!", "From Emma")
}
}
}
}
}
@Composable
fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) {
// Create a column so that texts don't overlap
Column(
verticalArrangement = Arrangement.Center,
modifier = modifier
) {
Text(
text = message,
fontSize = 100.sp,
lineHeight = 116.sp,
textAlign = TextAlign.Center
)
Text(
text = from,
fontSize = 36.sp,
modifier = Modifier
.padding(16.dp)
.align(alignment = Alignment.CenterHorizontally)
)
}
}
@Composable
fun GreetingImage(message: String, from: String, modifier: Modifier = Modifier) {
val image = painterResource(R.drawable.androidparty)
//Step 3 create a box to overlap image and texts
Box {
Image(
painter = image,
contentDescription = null,
contentScale = ContentScale.Crop,
alpha = 0.5F
)
GreetingText(
message = message,
from = from,
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
)
}
}
@Preview(showBackground = false)
@Composable
fun BirthdayCardPreview() {
HappyBirthdayTheme {
GreetingText(message = "Happy Birthday Ainin!", from = "From Emma")
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Color.kt | 2161329073 | package com.example.composearticle.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Theme.kt | 2744330643 | package com.example.composearticle.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.Color
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
)
@Composable
fun ComposeArticleTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color in this app is turned off for learning purposes
dynamicColor: Boolean = false,
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 = Color.Transparent.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/ui/theme/Type.kt | 319593794 | package com.example.composearticle.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
)
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composearticle/MainActivity.kt | 767219649 | package com.example.composearticle
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.composearticle.ui.theme.ComposeArticleTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeArticleTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ComposeArticleApp()
}
}
}
}
}
@Composable
fun ComposeArticleApp() {
ArticleCard(
title = stringResource(R.string.title_jetpack_compose_tutorial),
shortDescription = stringResource(R.string.compose_short_desc),
longDescription = stringResource(R.string.compose_long_desc),
imagePainter = painterResource(R.drawable.bg_compose_background)
)
}
@Composable
private fun ArticleCard(
title: String,
shortDescription: String,
longDescription: String,
imagePainter: Painter,
modifier: Modifier = Modifier,
) {
Column(modifier = modifier) {
Image(painter = imagePainter, contentDescription = null)
Text(
text = title,
modifier = Modifier.padding(16.dp),
fontSize = 24.sp
)
Text(
text = shortDescription,
modifier = Modifier.padding(start = 16.dp, end = 16.dp),
textAlign = TextAlign.Justify
)
Text(
text = longDescription,
modifier = Modifier.padding(16.dp),
textAlign = TextAlign.Justify
)
}
}
@Preview(showBackground = true)
@Composable
fun ComposeArticleAppPreview() {
ComposeArticleTheme {
ComposeArticleApp()
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Color.kt | 594178479 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF6A5F00)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFF9E44C)
val md_theme_light_onPrimaryContainer = Color(0xFF201C00)
val md_theme_light_secondary = Color(0xFF645F41)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFEBE3BD)
val md_theme_light_onSecondaryContainer = Color(0xFF1F1C05)
val md_theme_light_tertiary = Color(0xFF416651)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFC3ECD2)
val md_theme_light_onTertiaryContainer = Color(0xFF002112)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF1D1C16)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF1D1C16)
val md_theme_light_surfaceVariant = Color(0xFFE8E2D0)
val md_theme_light_onSurfaceVariant = Color(0xFF4A4739)
val md_theme_light_outline = Color(0xFF7B7768)
val md_theme_light_inverseOnSurface = Color(0xFFF5F0E7)
val md_theme_light_inverseSurface = Color(0xFF32302A)
val md_theme_light_inversePrimary = Color(0xFFDCC830)
val md_theme_light_surfaceTint = Color(0xFF6A5F00)
val md_theme_light_outlineVariant = Color(0xFFCCC6B5)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFDCC830)
val md_theme_dark_onPrimary = Color(0xFF373100)
val md_theme_dark_primaryContainer = Color(0xFF504700)
val md_theme_dark_onPrimaryContainer = Color(0xFFF9E44C)
val md_theme_dark_secondary = Color(0xFFCFC7A2)
val md_theme_dark_onSecondary = Color(0xFF353117)
val md_theme_dark_secondaryContainer = Color(0xFF4C472B)
val md_theme_dark_onSecondaryContainer = Color(0xFFEBE3BD)
val md_theme_dark_tertiary = Color(0xFFA7D0B7)
val md_theme_dark_onTertiary = Color(0xFF113725)
val md_theme_dark_tertiaryContainer = Color(0xFF294E3B)
val md_theme_dark_onTertiaryContainer = Color(0xFFC3ECD2)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1D1C16)
val md_theme_dark_onBackground = Color(0xFFE7E2D9)
val md_theme_dark_surface = Color(0xFF1D1C16)
val md_theme_dark_onSurface = Color(0xFFE7E2D9)
val md_theme_dark_surfaceVariant = Color(0xFF4A4739)
val md_theme_dark_onSurfaceVariant = Color(0xFFCCC6B5)
val md_theme_dark_outline = Color(0xFF959181)
val md_theme_dark_inverseOnSurface = Color(0xFF1D1C16)
val md_theme_dark_inverseSurface = Color(0xFFE7E2D9)
val md_theme_dark_inversePrimary = Color(0xFF6A5F00)
val md_theme_dark_surfaceTint = Color(0xFFDCC830)
val md_theme_dark_outlineVariant = Color(0xFF4A4739)
val md_theme_dark_scrim = Color(0xFF000000) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Theme.kt | 64699599 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade.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 LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = false,
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
)
}
|
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/ui/theme/Type.kt | 140986119 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade.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
)
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/lemonade/MainActivity.kt | 1276581266 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lemonade
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.example.lemonade.ui.theme.AppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppTheme() {
LemonadeApp()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LemonadeApp() {
var currentStep by remember { mutableStateOf(1) }
var squeezeCount by remember { mutableStateOf(0) }
Scaffold(
topBar = {
CenterAlignedTopAppBar(
title = {
Text(
text = "Lemonade",
fontWeight = FontWeight.Bold
)
},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.background(MaterialTheme.colorScheme.tertiaryContainer),
color = MaterialTheme.colorScheme.background
) {
when (currentStep) {
1 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_select,
drawableResourceId = R.drawable.lemon_tree,
contentDescriptionResourceId = R.string.lemon_tree_content_description,
onImageClick = {
currentStep = 2
squeezeCount = (2..4).random()
}
)
}
2 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_squeeze,
drawableResourceId = R.drawable.lemon_squeeze,
contentDescriptionResourceId = R.string.lemon_content_description,
onImageClick = {
squeezeCount--
if (squeezeCount == 0) {
currentStep = 3
}
}
)
}
3 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_drink,
drawableResourceId = R.drawable.lemon_drink,
contentDescriptionResourceId = R.string.lemonade_content_description,
onImageClick = {
currentStep = 4
}
)
}
4 -> {
LemonTextAndImage(
textLabelResourceId = R.string.lemon_empty_glass,
drawableResourceId = R.drawable.lemon_restart,
contentDescriptionResourceId = R.string.empty_glass_content_description,
onImageClick = {
currentStep = 1
}
)
}
}
}
}
}
@Composable
fun LemonTextAndImage(
textLabelResourceId: Int,
drawableResourceId: Int,
contentDescriptionResourceId: Int,
onImageClick: () -> Unit,
modifier: Modifier = Modifier
) {
Box(
modifier = modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Button(
onClick = onImageClick,
shape = RoundedCornerShape(dimensionResource(R.dimen.button_corner_radius)),
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer)
) {
Image(
painter = painterResource(drawableResourceId),
contentDescription = stringResource(contentDescriptionResourceId),
modifier = Modifier
.width(dimensionResource(R.dimen.button_image_width))
.height(dimensionResource(R.dimen.button_image_height))
.padding(dimensionResource(R.dimen.button_interior_padding))
)
}
Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_vertical)))
Text(
text = stringResource(textLabelResourceId),
style = MaterialTheme.typography.bodyLarge
)
}
}
}
@Preview
@Composable
fun LemonPreview() {
AppTheme() {
LemonadeApp()
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Color.kt | 2966474842 | package com.example.greetingcard.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Theme.kt | 2932088790 | package com.example.greetingcard.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 GreetingCardTheme(
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
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/ui/theme/Type.kt | 2395137318 | package com.example.greetingcard.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
)
*/
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/greetingcard/MainActivity.kt | 2410677849 | package com.example.greetingcard
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.padding
import com.example.greetingcard.ui.theme.GreetingCardTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingCardTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Ainin")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Surface(color = Color.Magenta) {
Text(
text = "Sawadee kha thukkhon my name is $name",
modifier = modifier.padding(24.dp)
)
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
GreetingCardTheme {
Greeting("Ainin")
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Color.kt | 989791096 | package com.example.businesscard.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Theme.kt | 2982380513 | package com.example.businesscard.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 BusinessCardTheme(
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
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/ui/theme/Type.kt | 555766880 | package com.example.businesscard.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
)
*/
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/businesscard/MainActivity.kt | 3610715973 | package com.example.businesscard
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Build
import androidx.compose.material.icons.rounded.Email
import androidx.compose.material.icons.rounded.Menu
import androidx.compose.material.icons.rounded.Phone
import androidx.compose.material.icons.rounded.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.businesscard.ui.theme.BusinessCardTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BusinessCardTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ProfileBuilderApp()
}
}
}
}
}
@Composable
fun ProfileBuilderApp() {
Column(
modifier = Modifier
.fillMaxSize()
.fillMaxWidth()
.background(Color(0Xffd2e8d4)),
verticalArrangement = Arrangement.Center
) {
Row(
modifier = Modifier
.padding(16.dp)
.weight(1f)
.fillMaxHeight(),
horizontalArrangement = Arrangement.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom,
modifier = Modifier.fillMaxHeight()
) {
Box(
modifier = Modifier
.size(100.dp)
.background(Color(0xFF073042))
) {
Image(
painter = painterResource(id = R.drawable.android_logo),
contentDescription = null,
modifier = Modifier.size(100.dp)
)
}
Text(
text = stringResource(R.string.developer_name_text),
Modifier.fillMaxWidth(),
fontSize = 40.sp,
textAlign = TextAlign.Center,
)
Text(
text = stringResource(R.string.developer_desc_text),
Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color(0xff006d3a)
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.weight(1f),
horizontalArrangement = Arrangement.Center,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Bottom,
modifier = Modifier.fillMaxSize()
) {
Row (
horizontalArrangement = Arrangement.Start,
modifier = Modifier.fillMaxWidth()
){
Icon(
Icons.Rounded.Phone,
contentDescription = null,
Modifier.padding(start = 80.dp, end = 25.dp, bottom = 20.dp),
tint = Color(0xff006d3a)
)
Text(text = stringResource(R.string.phone_no_text))
}
Row (
horizontalArrangement = Arrangement.Start,
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Rounded.Share,
contentDescription = null,
Modifier.padding(start = 80.dp, end = 25.dp, bottom = 20.dp),
tint = Color(0xff006d3a)
)
Text(text = stringResource(R.string.domain_text))
}
Row (
horizontalArrangement = Arrangement.Start,
modifier = Modifier.fillMaxWidth()
){
Icon(Icons.Rounded.Email,
contentDescription = null,
Modifier.padding(start = 80.dp, end = 25.dp, bottom = 25.dp),
tint = Color(0xff006d3a)
)
Text(text = stringResource(R.string.email_text))
}
}
}
}
}
@Composable
private fun ComposableInfoCard(
title: String,
description: String,
backgroundColor: Color,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.background(backgroundColor)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = title,
modifier = Modifier.padding(bottom = 16.dp),
fontWeight = FontWeight.Bold
)
Text(
text = description,
textAlign = TextAlign.Justify
)
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
private fun BusinessCard() {
BusinessCardTheme {
ProfileBuilderApp()
}
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Color.kt | 2319670969 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composequadrant.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) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Theme.kt | 2789334435 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composequadrant.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.Color
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
)
@Composable
fun ComposeQuadrantTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
// Dynamic color in this app is turned off for learning purposes
dynamicColor: Boolean = false,
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 = Color.Transparent.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/ui/theme/Type.kt | 87066807 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composequadrant.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
)
) |
CSM3123_Lab-3/CSM3123- Lab 3/Task 2/src/main/java/com/example/composequadrant/MainActivity.kt | 3331289616 | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composequadrant
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.composequadrant.ui.theme.ComposeQuadrantTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeQuadrantTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ComposeQuadrantApp()
}
}
}
}
}
@Composable
fun ComposeQuadrantApp() {
Column(Modifier.fillMaxWidth()) {
Row(Modifier.weight(1f)) {
ComposableInfoCard(
title = stringResource(R.string.first_title),
description = stringResource(R.string.first_description),
backgroundColor = Color(0xFFEADDFF),
modifier = Modifier.weight(1f)
)
ComposableInfoCard(
title = stringResource(R.string.second_title),
description = stringResource(R.string.second_description),
backgroundColor = Color(0xFFD0BCFF),
modifier = Modifier.weight(1f)
)
}
Row(Modifier.weight(1f)) {
ComposableInfoCard(
title = stringResource(R.string.third_title),
description = stringResource(R.string.third_description),
backgroundColor = Color(0xFFB69DF8),
modifier = Modifier.weight(1f)
)
ComposableInfoCard(
title = stringResource(R.string.fourth_title),
description = stringResource(R.string.fourth_description),
backgroundColor = Color(0xFFF6EDFF),
modifier = Modifier.weight(1f)
)
}
}
}
@Composable
private fun ComposableInfoCard(
title: String,
description: String,
backgroundColor: Color,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.background(backgroundColor)
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = title,
modifier = Modifier.padding(bottom = 16.dp),
fontWeight = FontWeight.Bold
)
Text(
text = description,
textAlign = TextAlign.Justify
)
}
}
@Preview(showBackground = true)
@Composable
fun ComposeQuadrantAppPreview() {
ComposeQuadrantTheme {
ComposeQuadrantApp()
}
} |
HCLTechEnviRide/app/src/androidTest/java/com/example/hcltechenviride/ExampleInstrumentedTest.kt | 1775178159 | package com.example.hcltechenviride
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.hcltechenviride", appContext.packageName)
}
} |
HCLTechEnviRide/app/src/test/java/com/example/hcltechenviride/ExampleUnitTest.kt | 3316737500 | package com.example.hcltechenviride
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)
}
} |
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/MainActivity.kt | 2141068499 | package com.example.hcltechenviride
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.example.hcltechenviride.utils.EncryptedSharedPrefs
import com.google.firebase.auth.FirebaseAuth
// Function to retrieve data from encrypted SharedPreferences
fun checkUserRoleAndOpenActivity(context: Context) {
// Retrieve the user's role from SharedPreferences
val userRole = EncryptedSharedPrefs.getUserRole(context)
// Determine the appropriate activity based on the user's role
val intent = when (userRole) {
"Admin" -> Intent(context, AdminHomeActivity::class.java)
"Employee" -> Intent(context, EmpHomeActivity::class.java)
"Security" -> Intent(context, SecHomeActivity::class.java)
else -> Intent(context, EmpLoginActivity::class.java) // Default activity for unknown role
}
// Start the selected activity
context.startActivity(intent)
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set the status bar color to transparent
window.statusBarColor = Color.TRANSPARENT
// Delay execution to show a splash screen effect
Handler(Looper.getMainLooper()).postDelayed({
// Check if the user is authenticated (logged in)
if (FirebaseAuth.getInstance().currentUser == null) {
// If not authenticated, start the login activity
startActivity(Intent(this, EmpLoginActivity::class.java))
} else {
// If authenticated, determine the user's role and open the appropriate activity
checkUserRoleAndOpenActivity(this)
finish()
}
finish()
}, 3000) // Show splash screen for 3 seconds
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpHomeFragment.kt | 3361131554 | package com.example.hcltechenviride.fragments
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.example.hcltechenviride.Models.CurrentCycle
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.R
import com.example.hcltechenviride.adapters.CarouselAdapter
import com.example.hcltechenviride.databinding.FragmentEmpHomeBinding
import com.example.hcltechenviride.utils.CURRENT_CYCLE_FOLDER
import com.example.hcltechenviride.utils.CYCLE_FOLDER
import com.example.hcltechenviride.utils.EncryptedSharedPrefs
import com.example.hcltechenviride.utils.HISTORY_FOLDER
import com.example.hcltechenviride.utils.RETURNED_CYCLE_FOLDER
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.toObject
import com.google.firebase.ktx.Firebase
import com.google.zxing.integration.android.IntentIntegrator
private const val i = 0
class EmpHomeFragment : Fragment() {
private lateinit var binding: FragmentEmpHomeBinding
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
binding = FragmentEmpHomeBinding.inflate(inflater, container, false)
// Set up ViewPager2 with adapter
val viewPager = binding.viewPager2
val adapter = CarouselAdapter(requireContext(), listOf(R.drawable.pic0, R.drawable.pic1, R.drawable.pic2))
viewPager.adapter = adapter
// Set up click listeners for scan and return buttons
binding.scan.setOnClickListener {
if (EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) < 1) {
startQrCodeScanner()
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 1)
} else {
Toast.makeText(requireActivity(), "Can only request one cycle at a time", Toast.LENGTH_SHORT).show()
}
}
binding.returnBack.setOnClickListener {
if (EncryptedSharedPrefs.getCurrentCycleId(requireActivity()) != null ||
EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) > 0
) {
returnCurrentCycle(EncryptedSharedPrefs.getCurrentCycleId(requireActivity())!!)
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
EncryptedSharedPrefs.clearCurrentCycleId(requireActivity())
binding.cycleID.text = "Cycle ID : ${EncryptedSharedPrefs.getCurrentCycleId(requireActivity())}"
Toast.makeText(requireActivity(), "Returned successfully", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(requireActivity(), "Don't have a cycle to return", Toast.LENGTH_SHORT).show()
}
}
return binding.root
}
@RequiresApi(Build.VERSION_CODES.O)
private fun startQrCodeScanner() {
val integrator = IntentIntegrator.forSupportFragment(this)
integrator.setOrientationLocked(true) // Set orientation to portrait
integrator.setPrompt("Scan QR code containing cycle ID")
integrator.initiateScan()
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
if (result.contents == null) {
// Scan cancelled or failed
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Log.d(TAG, "Scan cancelled or failed")
Toast.makeText(requireActivity(), "Scan cancelled or failed", Toast.LENGTH_SHORT).show()
} else {
// QR code scanned successfully
val scannedCycleId = result.contents
Log.d(TAG, "Scanned cycle ID: $scannedCycleId")
val checker = DocumentChecker()
checker.checkDocument(CYCLE_FOLDER, scannedCycleId) { documentExists, isAllotted, isDamaged ->
if (documentExists) {
if (isAllotted == "False" && isDamaged == "False") {
allotCycle(scannedCycleId, EncryptedSharedPrefs.getCurrentEmployeeId(requireActivity())!!)
EncryptedSharedPrefs.setCurrentCycleId(requireActivity(), scannedCycleId)
} else {
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Toast.makeText(requireActivity(), "Cycle already in use or Damaged", Toast.LENGTH_SHORT).show()
}
} else {
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Toast.makeText(requireActivity(), "Invalid QR Code", Toast.LENGTH_SHORT).show()
}
}
}
} else {
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Log.e(TAG, "Failed to parse activity result")
Toast.makeText(requireActivity(), "Failed to parse activity result", Toast.LENGTH_SHORT).show()
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun allotCycle(scannedCycleId: String, empId: String) {
val currentCycle = CurrentCycle(scannedCycleId, empId)
val db = FirebaseFirestore.getInstance()
db.collection(CURRENT_CYCLE_FOLDER).document(scannedCycleId).set(currentCycle)
.addOnSuccessListener {
db.collection(CYCLE_FOLDER).document(scannedCycleId).update("allotted", "True")
.addOnSuccessListener {
binding.cycleID.text = "Cycle ID : ${EncryptedSharedPrefs.getCurrentCycleId(requireActivity())}"
Toast.makeText(requireActivity(), "Cycle allocated successfully", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Log.e(TAG, "Error adding history: ${it.localizedMessage}")
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Toast.makeText(requireActivity(), "Failed to allocate cycle: ${it.localizedMessage}", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener {
Log.e(TAG, "Error adding history: ${it.localizedMessage}")
EncryptedSharedPrefs.setCurrentCycleCount(requireActivity(), 0)
Toast.makeText(requireActivity(), "Failed to allocate cycle: ${it.localizedMessage}", Toast.LENGTH_SHORT).show()
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun returnCurrentCycle(currCyId: String) {
val db = FirebaseFirestore.getInstance()
db.collection(CYCLE_FOLDER).document(currCyId).update("allotted", "False")
.addOnSuccessListener {
db.collection(CURRENT_CYCLE_FOLDER).document(currCyId).get()
.addOnSuccessListener { documentSnapshot ->
val currCycle: CurrentCycle = documentSnapshot.toObject<CurrentCycle>()!!
val history: History = History(currCycle.cycleID, currCycle.empID, currCycle.allottedTime)
db.collection(HISTORY_FOLDER).document().set(history)
db.collection(RETURNED_CYCLE_FOLDER).document(currCyId).set(history)
db.collection(Firebase.auth.currentUser!!.uid).document().set(history)
}.addOnSuccessListener {
db.collection(CURRENT_CYCLE_FOLDER).document(currCyId).delete()
}
}.addOnSuccessListener {
Log.d(TAG, "Cycle returned Successfully")
}
}
companion object {
}
}
class DocumentChecker {
fun checkDocument(
collectionPath: String, documentName: String, onComplete: (Boolean, Any?, Any?) -> Unit
) {
val db = FirebaseFirestore.getInstance()
val collectionRef = db.collection(collectionPath)
collectionRef.document(documentName).get().addOnSuccessListener { documentSnapshot ->
if (documentSnapshot.exists()) {
val allotted = documentSnapshot.data?.get("allotted")
val damaged = documentSnapshot.data?.get("damaged")
onComplete(true, allotted, damaged)
} else {
onComplete(false, null, null)
}
}.addOnFailureListener { exception ->
onComplete(false, null, null)
}
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpHistoryFragment.kt | 1265979179 | package com.example.hcltechenviride.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.adapters.EmpHistoryRvAdapter
import com.example.hcltechenviride.databinding.FragmentEmpHistoryBinding
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.toObject
import com.google.firebase.ktx.Firebase
class EmpHistoryFragment : Fragment() {
private lateinit var binding: FragmentEmpHistoryBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentEmpHistoryBinding.inflate(inflater, container, false)
val historyList = ArrayList<History>()
val adapter = EmpHistoryRvAdapter(requireContext(), historyList)
binding.rv.layoutManager =
StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
binding.rv.adapter = adapter
// Fetch user history from Firestore and populate RecyclerView
Firebase.firestore.collection(Firebase.auth.currentUser!!.uid)
.orderBy("duration", Query.Direction.DESCENDING)
.get().addOnSuccessListener { querySnapshot ->
val tempList = ArrayList<History>()
for (document in querySnapshot.documents) {
val history: History = document.toObject<History>()!!
tempList.add(history)
}
historyList.addAll(tempList)
adapter.notifyDataSetChanged()
}
return binding.root
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/fragments/EmpProfileFragment.kt | 3122838965 | package com.example.hcltechenviride.fragments
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.hcltechenviride.EmpLoginActivity
import com.example.hcltechenviride.Models.User
import com.example.hcltechenviride.databinding.FragmentEmpProfileBinding
import com.example.hcltechenviride.utils.EMP_USER_NODE
import com.example.hcltechenviride.utils.EncryptedSharedPrefs
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.toObject
import com.google.firebase.ktx.Firebase
class EmpProfileFragment : Fragment() {
private lateinit var binding: FragmentEmpProfileBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentEmpProfileBinding.inflate(inflater, container, false)
// Set logout button click listener
binding.logout.setOnClickListener {
if (EncryptedSharedPrefs.getCurrentCycleId(requireActivity()) != null ||
EncryptedSharedPrefs.getCurrentCycleCount(requireActivity()) > 0
) {
// Show alert dialog if user has an active cycle
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Can't Logout")
builder.setMessage("Please Return the cycle Before Logout")
builder.setPositiveButton("OK") { dialog, which ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
} else {
// Logout user if no active cycle
FirebaseAuth.getInstance().signOut()
EncryptedSharedPrefs.clearAllData(requireActivity())
startActivity(Intent(requireActivity(), EmpLoginActivity::class.java))
requireActivity().finish()
}
}
return binding.root
}
override fun onStart() {
super.onStart()
// Fetch user data and populate UI
Firebase.firestore.collection(EMP_USER_NODE).document(Firebase.auth.currentUser!!.uid).get()
.addOnSuccessListener {
val user: User = it.toObject<User>()!!
binding.name.text = user.name
binding.id.text = user.employeeId
binding.email.text = user.email
binding.role.text = user.role
}
}
override fun onResume() {
super.onResume()
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/utils/EncryptedSharedPrefs.kt | 830214968 | package com.example.hcltechenviride.utils
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
object EncryptedSharedPrefs {
private const val SHARED_PREFS_NAME = "encrypted_shared_prefs"
fun setCurrentEmployeeId(context: Context, empId: String) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().putString(CURRENT_EMPLOYEE_ID, empId ).apply()
}
fun getCurrentEmployeeId(context: Context): String? {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
return sharedPreferences.getString(CURRENT_EMPLOYEE_ID, null)
}
fun getUserRole(context: Context): String? {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
return sharedPreferences.getString(USER_ROLE, null)
}
fun setUserRole(context: Context, role: String) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().putString(USER_ROLE, role).apply()
}
fun clearUserRole(context: Context) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().remove(USER_ROLE).apply()
}
fun getCurrentCycleCount(context: Context): Int {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
return sharedPreferences.getInt(CURRENT_CYCLE_COUNT, 0)
}
fun setCurrentCycleCount(context: Context, count: Int) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().putInt(CURRENT_CYCLE_COUNT, count).apply()
}
fun clearCurrentCycleId(context: Context) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().remove(CURRENT_CYCLE_ID).apply()
}
fun getCurrentCycleId(context: Context): String? {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
return sharedPreferences.getString(CURRENT_CYCLE_ID, null)
}
fun setCurrentCycleId(context: Context, cycleId: String) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().putString(CURRENT_CYCLE_ID, cycleId).apply()
}
fun clearAllData(context: Context) {
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
SHARED_PREFS_NAME,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
sharedPreferences.edit().remove(USER_ROLE).apply()
sharedPreferences.edit().remove(CURRENT_CYCLE_ID).apply()
sharedPreferences.edit().remove(CURRENT_EMPLOYEE_ID).apply()
sharedPreferences.edit().remove(CURRENT_CYCLE_COUNT).apply()
sharedPreferences.edit().remove(USER_ROLE).apply()
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/utils/Constants.kt | 2141869546 | package com.example.hcltechenviride.utils
const val EMP_USER_NODE = "User"
const val HISTORY_FOLDER = "History"
const val CURRENT_CYCLE_FOLDER = "CurrentCycles"
const val CYCLE_FOLDER = "Cycles"
const val RETURNED_CYCLE_FOLDER = "ReturnedCycles"
const val COMPLAINTS_FOLDER = "Complaints"
const val USER_ROLE = "user_role"
const val CURRENT_CYCLE_COUNT = "current_cycle_count"
const val CURRENT_CYCLE_ID = "current_cycle_id"
const val CURRENT_EMPLOYEE_ID = "current_employee_id"
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/History.kt | 806162583 | package com.example.hcltechenviride.Models
import android.os.Build
import androidx.annotation.RequiresApi
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class History {
// Current LocalDateTime
@RequiresApi(Build.VERSION_CODES.O)
private val now = LocalDateTime.now()
// Employee ID
var empID: String? = null
// Cycle ID
var cycleID: String? = null
// Duration of cycle usage
var duration: String? = null
constructor()
// Constructor to initialize history details
@RequiresApi(Build.VERSION_CODES.O)
constructor(cycleID: String?, empID: String?, allottedTime: String?) {
this.duration = "$allottedTime to ${now.format(DateTimeFormatter.ofPattern("dd-MM-yy HH:mm"))}"
this.empID = empID
this.cycleID = cycleID
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/CurrentCycle.kt | 1640080092 | package com.example.hcltechenviride.Models
import android.os.Build
import androidx.annotation.RequiresApi
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class CurrentCycle {
// Current date and time
@RequiresApi(Build.VERSION_CODES.O)
private val now = LocalDateTime.now()
// Allotted time for the cycle
@RequiresApi(Build.VERSION_CODES.O)
var allottedTime: String? = null
// Cycle ID
var cycleID: String? = null
// Employee ID
var empID: String? = null
constructor()
// Constructor to initialize current cycle details
@RequiresApi(Build.VERSION_CODES.O)
constructor(cycleID: String, empID: String) {
this.allottedTime = now.format(DateTimeFormatter.ofPattern("dd-MM-yy HH:mm"))
this.cycleID = cycleID
this.empID = empID
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/Cycle.kt | 4065815262 | package com.example.hcltechenviride.Models
class Cycle {
// Cycle ID
var cycleID: String? = null
// Color of the cycle
var color: String? = null
// Location of the cycle
var location: String? = null
// Whether the cycle is allotted or not
var allotted: String? = null
// Whether the cycle is damaged or not
var damaged: String? = null
constructor()
// Constructor to initialize cycle details
constructor(
cycleID: String?,
color: String?,
location: String?,
allotted: String = "False",
damaged: String = "False"
) {
this.cycleID = cycleID
this.color = color
this.location = location
this.allotted = allotted
this.damaged = damaged
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/Models/User.kt | 2133470762 | package com.example.hcltechenviride.Models
class User {
// User role
var role: String? = null
// User name
var name: String? = null
// User employee ID
var employeeId: String? = null
// User email
var email: String? = null
// User password
var password: String? = null
constructor()
// Constructor used for login
constructor(email: String?, password: String?) {
this.email = email
this.password = password
}
// Constructor used for registration
constructor(
role: String?, name: String?, employeeId: String?, email: String?, password: String?
) {
this.role = role
this.name = name
this.employeeId = employeeId
this.email = email
this.password = password
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/UserListRvAdapter.kt | 2732598959 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.User
import com.example.hcltechenviride.databinding.UserListRvDesignBinding
class UserListRvAdapter(var context: Context, var userList: ArrayList<User>) :
RecyclerView.Adapter<UserListRvAdapter.ViewHolder>() {
// Inner class to hold the views for each list item
inner class ViewHolder(var binding: UserListRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Called when RecyclerView needs a new ViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Inflate the item layout and create a new ViewHolder
val binding = UserListRvDesignBinding.inflate(
LayoutInflater.from(context), parent, false
)
return ViewHolder(binding)
}
// Returns the total number of items in the data set held by the adapter
override fun getItemCount(): Int {
return userList.size
}
// Called by RecyclerView to display the data at the specified position
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Get the data model based on position
val userItem = userList[position]
// Set the data to the views in the ViewHolder
holder.binding.employeeId.text = userItem.employeeId
holder.binding.role.text = userItem.role
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/AdminCycleInUseRvAdapter.kt | 894917444 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.CurrentCycle
import com.example.hcltechenviride.databinding.AdminCycleInUseRvDesignBinding
class AdminCycleInUseRvAdapter(var context: Context, var cycleInUseList: ArrayList<CurrentCycle>) :
RecyclerView.Adapter<AdminCycleInUseRvAdapter.ViewHolder>() {
inner class ViewHolder(var binding: AdminCycleInUseRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Inflate the layout and create ViewHolder instances
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = AdminCycleInUseRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Return the size of the cycleInUseList
override fun getItemCount(): Int {
return cycleInUseList.size
}
// Bind data to views in the ViewHolder
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currCycle = cycleInUseList[position]
holder.binding.cycleID.text = currCycle.cycleID
holder.binding.employeeId.text = currCycle.empID
holder.binding.allottedTime.text = currCycle.allottedTime
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/DamagedCycleAdapter.kt | 3485054485 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.databinding.DamagedCycleListRvDesignBinding
import com.example.hcltechenviride.utils.COMPLAINTS_FOLDER
import com.example.hcltechenviride.utils.CYCLE_FOLDER
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class DamagedCycleAdapter(var context: Context, var damagedCycleList: ArrayList<History>) :
RecyclerView.Adapter<DamagedCycleAdapter.ViewHolder>() {
inner class ViewHolder(var binding: DamagedCycleListRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Create ViewHolder instances
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DamagedCycleAdapter.ViewHolder {
val binding = DamagedCycleListRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Return the size of the damagedCycleList
override fun getItemCount(): Int {
return damagedCycleList.size
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: DamagedCycleAdapter.ViewHolder, position: Int) {
// Bind data to views in the ViewHolder
holder.binding.cycleID.text = damagedCycleList[position].cycleID
holder.binding.employeeId.text = damagedCycleList[position].empID
// Set up action for the 'repaired' button
holder.binding.repaired.setOnClickListener {
// Update Firestore to mark the cycle as repaired and delete its complaint document
Firebase.firestore.collection(CYCLE_FOLDER).document(damagedCycleList[position].cycleID!!)
.update("damaged", "False")
Firebase.firestore.collection(COMPLAINTS_FOLDER).document(damagedCycleList[position].cycleID!!)
.delete()
// Remove the repaired cycle from the list and notify the adapter
removeAt(position)
}
}
// Remove an item at the specified position from the damagedCycleList
private fun removeAt(position: Int) {
damagedCycleList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, damagedCycleList.size)
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/ReturnedCycleAdapter.kt | 1906696136 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.databinding.ReturnRvBinding
import com.example.hcltechenviride.utils.COMPLAINTS_FOLDER
import com.example.hcltechenviride.utils.CYCLE_FOLDER
import com.example.hcltechenviride.utils.RETURNED_CYCLE_FOLDER
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class ReturnedCycleAdapter(var context: Context, var returnedCycleList: ArrayList<History>) :
RecyclerView.Adapter<ReturnedCycleAdapter.ViewHolder>() {
// Inner class to hold the views for each list item
inner class ViewHolder(var binding: ReturnRvBinding) : RecyclerView.ViewHolder(binding.root)
// Called when RecyclerView needs a new ViewHolder
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ReturnedCycleAdapter.ViewHolder {
// Inflate the item layout and create a new ViewHolder
val binding = ReturnRvBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Returns the total number of items in the data set held by the adapter
override fun getItemCount(): Int {
return returnedCycleList.size
}
// Called by RecyclerView to display the data at the specified position
override fun onBindViewHolder(holder: ReturnedCycleAdapter.ViewHolder, position: Int) {
// Get the data model based on position
val historyItem = returnedCycleList[position]
// Bind data to the views in the ViewHolder
holder.binding.cycleID.text = historyItem.cycleID
holder.binding.duration.text = historyItem.duration
// Set click listeners for complaint and accept buttons
holder.binding.complain.setOnClickListener {
// Handle complaint by adding to complaints collection, marking cycle as damaged,
// and removing from returned cycles collection
Firebase.firestore.collection(COMPLAINTS_FOLDER)
.document(historyItem.cycleID!!)
.set(historyItem)
Firebase.firestore.collection(CYCLE_FOLDER)
.document(historyItem.cycleID!!).update("damaged", "True")
Firebase.firestore.collection(RETURNED_CYCLE_FOLDER)
.document(historyItem.cycleID!!).delete()
removeAt(position)
}
holder.binding.accept.setOnClickListener {
// Accept return by removing from returned cycles collection
Firebase.firestore.collection(RETURNED_CYCLE_FOLDER)
.document(historyItem.cycleID!!).delete()
removeAt(position)
}
}
// Removes an item from the list and notifies the adapter about the change
private fun removeAt(position: Int) {
returnedCycleList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, returnedCycleList.size)
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/CarouselAdapter.kt | 2939841132 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.databinding.CarouselRvDesignBinding
class CarouselAdapter(var context: Context,private val images: List<Int>) : RecyclerView.Adapter<CarouselAdapter.ViewHolder>() {
inner class ViewHolder(var binding: CarouselRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var binding = CarouselRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val imageRes = images[position % images.size]
holder.binding.imageView.setImageResource(imageRes)
}
override fun getItemCount(): Int = Int.MAX_VALUE
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/ViewPagerAdapter.kt | 2827535352 | package com.example.hcltechenviride.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
// Lists to store fragments and their corresponding titles
private val fragmentList = mutableListOf<Fragment>() // List to hold fragments
private val titleList = mutableListOf<String>() // List to hold titles
override fun getCount(): Int {
// Return the total number of fragments
return fragmentList.size
}
override fun getItem(position: Int): Fragment {
// Return the fragment at the specified position
return fragmentList[position]
}
override fun getPageTitle(position: Int): CharSequence? {
// Return the title of the fragment at the specified position
return titleList[position]
}
fun addFragments(fragment: Fragment, title: String) {
// Add a fragment and its title to the lists
fragmentList.add(fragment)
titleList.add(title)
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/CycleListRvAdapter.kt | 3159025810 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.Cycle
import com.example.hcltechenviride.databinding.CycleListRvDesignBinding
import com.example.hcltechenviride.utils.CYCLE_FOLDER
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class CycleListRvAdapter(var context: Context, var cycleList: ArrayList<Cycle>) :
RecyclerView.Adapter<CycleListRvAdapter.ViewHolder>() {
inner class ViewHolder(var binding: CycleListRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Inflate the layout and create ViewHolder instances
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = CycleListRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Return the size of the cycleList
override fun getItemCount(): Int {
return cycleList.size
}
// Bind data to views in the ViewHolder
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.binding.root
val cycleItem = cycleList[position]
holder.binding.cycleID.text = cycleItem.cycleID
holder.binding.colorAndLocation.text = "${cycleItem.color} - ${cycleItem.location}"
// Set up click listener for the delete button
holder.binding.delete.setOnClickListener {
// Check if the cycle is currently allotted
if (cycleList[position].allotted == "True") {
// Display a toast message if the cycle is in use
Toast.makeText(context, "Can't Delete Cycle is in use", Toast.LENGTH_SHORT).show()
} else {
// If the cycle is not in use, prompt the user for confirmation
val builder = android.app.AlertDialog.Builder(context)
builder.setTitle("Confirm Delete!")
.setMessage("Do you want to delete this Cycle")
// If confirmed, delete the cycle document from Firestore and remove it from the list
.setNegativeButton("Confirm") { dialog, which ->
Firebase.firestore.collection(CYCLE_FOLDER)
.document(cycleList[position].cycleID!!).delete()
removeAt(position)
dialog.dismiss()
}
// If canceled, dismiss the dialog
.setPositiveButton("Cancel") { dialog, which ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
}
}
// Remove an item at the specified position from the cycleList
private fun removeAt(position: Int) {
cycleList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, cycleList.size)
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/AdminCycleHistoryRvAdapter.kt | 2333396584 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.databinding.AdminHistoryRvDesignBinding
class AdminCycleHistoryRvAdapter(var context: Context, var historyList: ArrayList<History>) :
RecyclerView.Adapter<AdminCycleHistoryRvAdapter.ViewHolder>() {
inner class ViewHolder(var binding: AdminHistoryRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Inflate the layout and create ViewHolder instances
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = AdminHistoryRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Return the size of the historyList
override fun getItemCount(): Int {
return historyList.size
}
// Bind data to views in the ViewHolder
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val historyItem = historyList[position]
holder.binding.cycleID.text = historyItem.cycleID
holder.binding.employeeId.text = historyItem.empID
holder.binding.duration.text = historyItem.duration
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/adapters/EmpHistoryRvAdapter.kt | 299318287 | package com.example.hcltechenviride.adapters
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.example.hcltechenviride.Models.History
import com.example.hcltechenviride.databinding.EmpHistoryRvDesignBinding
class EmpHistoryRvAdapter(var context: Context, var historyList: ArrayList<History>) :
RecyclerView.Adapter<EmpHistoryRvAdapter.ViewHolder>() {
inner class ViewHolder(var binding: EmpHistoryRvDesignBinding) :
RecyclerView.ViewHolder(binding.root)
// Called when RecyclerView needs a new ViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Inflate the item layout and create a new ViewHolder
val binding = EmpHistoryRvDesignBinding.inflate(LayoutInflater.from(context), parent, false)
return ViewHolder(binding)
}
// Returns the total number of items in the data set held by the adapter
override fun getItemCount(): Int {
return historyList.size
}
// Called by RecyclerView to display the data at the specified position
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Get the data model based on position
val historyItem = historyList[position]
// Bind data to the views in the ViewHolder
holder.binding.cycleID.text = historyItem.cycleID
holder.binding.duration.text = historyItem.duration
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/AdminHomeActivity.kt | 1149091874 | package com.example.hcltechenviride
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.example.hcltechenviride.databinding.ActivityAdminHomeBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
class AdminHomeActivity : AppCompatActivity() {
private lateinit var binding: ActivityAdminHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Inflating the layout using view binding
binding = ActivityAdminHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
// Finding the navigation controller associated with the NavHostFragment
val navController = findNavController(R.id.nav_host_fragment_activity_admin_home)
// Setting up the bottom navigation view with the navigation controller
navView.setupWithNavController(navController)
}
}
|
HCLTechEnviRide/app/src/main/java/com/example/hcltechenviride/SecHomeActivity.kt | 1471119190 | package com.example.hcltechenviride
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.example.hcltechenviride.databinding.ActivitySecHomeBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
class SecHomeActivity : AppCompatActivity() {
private lateinit var binding: ActivitySecHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySecHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
// Set up the bottom navigation view
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_sec_home)
navView.setupWithNavController(navController)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.