content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.a3lab3.ui.dashboard
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class DashboardViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is dashboard Fragment"
}
val text: LiveData<String> = _text
} | 3lab3/app/src/main/java/com/example/a3lab3/ui/dashboard/DashboardViewModel.kt | 1025561612 |
package com.example.a3lab3.ui
fun main() {
// 1. Работа с преобразованием строк
val str1 = "Hello"
val str2 = "World"
val result = str1 + " " + str2
println(result)
// 2. Базовая арифметика и вывод результата в консоль
val a = 5
val b = 3
val sum = a + b
val difference = a - b
val product = a * b
val quotient = a / b
println("Сумма: $sum")
println("Разница: $difference")
println("Произведение: $product")
println("Частное: $quotient")
// 3. Примеры интерполяции строк
val f = 10
val l = 20
val j = "Сумма $f и $l ${f + l}"
println(j) // Output: The sum of 10 and 20 is 30
// 4. Преобразование типов
val number: Int = 10
val doubleNumber: Double = number.toDouble()
println("Целое число: $number")
println("Дробное число: $doubleNumber")
// 5. Пример условных операторов (if else)
val x = 10
val y = 5
if (x > y) {
println("x больше y")
} else {
println("x меньше или равно y")
}
// 6. Пример цикла for
val names = arrayOf("Alice", "Bob", "Charlie")
for (name in names) {
println(name)
}
var count = 0
while (count < 5) {
println("Count: $count")
count++
}
// 7. Пример создания отдельной функции
fun greet() {
println("Привет!")
}
greet()
// 8. Пример работы с массивом
val numbers = arrayOf(1, 2, 3, 4, 5)
println(numbers[0]) // Выводит 1
println(numbers.size) // Выводит 5
} | 3lab3/app/src/main/java/com/example/a3lab3/ui/code.kt | 2689285623 |
package com.example.a3lab3.ui.notifications
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class NotificationsViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "This is notifications Fragment"
}
val text: LiveData<String> = _text
} | 3lab3/app/src/main/java/com/example/a3lab3/ui/notifications/NotificationsViewModel.kt | 4132464250 |
package com.example.a3lab3.ui.notifications
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.a3lab3.databinding.FragmentNotificationsBinding
class NotificationsFragment : Fragment() {
private var _binding: FragmentNotificationsBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val notificationsViewModel =
ViewModelProvider(this).get(NotificationsViewModel::class.java)
_binding = FragmentNotificationsBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textNotifications
notificationsViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 3lab3/app/src/main/java/com/example/a3lab3/ui/notifications/NotificationsFragment.kt | 2872488221 |
package com.example.a3lab3
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.a3lab3.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
} | 3lab3/app/src/main/java/com/example/a3lab3/MainActivity.kt | 1201584599 |
package com.example
import com.example.plugins.*
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureSerialization()
configureRouting()
}
| last-mile-planning-back/src/main/kotlin/com/example/Application.kt | 890665178 |
package com.example.plugins
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureRouting() {
routing {
}
}
| last-mile-planning-back/src/main/kotlin/com/example/plugins/Routing.kt | 1104596804 |
package com.example.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
routing {
}
}
| last-mile-planning-back/src/main/kotlin/com/example/plugins/Serialization.kt | 1667654157 |
package com.zybooks.pizzaparty
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.zybooks.pizzaparty", appContext.packageName)
}
} | PizzaParty3/app/src/androidTest/java/com/zybooks/pizzaparty/ExampleInstrumentedTest.kt | 1669830553 |
package com.zybooks.pizzaparty
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)
}
} | PizzaParty3/app/src/test/java/com/zybooks/pizzaparty/ExampleUnitTest.kt | 4247973823 |
package com.zybooks.pizzaparty.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) | PizzaParty3/app/src/main/java/com/zybooks/pizzaparty/ui/theme/Color.kt | 547053705 |
package com.zybooks.pizzaparty.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 PizzaPartyTheme(
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
)
} | PizzaParty3/app/src/main/java/com/zybooks/pizzaparty/ui/theme/Theme.kt | 1784509667 |
package com.zybooks.pizzaparty.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
)
*/
) | PizzaParty3/app/src/main/java/com/zybooks/pizzaparty/ui/theme/Type.kt | 3231808301 |
package com.zybooks.pizzaparty
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.zybooks.pizzaparty.ui.theme.PizzaPartyTheme
import kotlin.math.ceil
/**
* Number of slices per pizza.
*/
private const val KEY_TOTAL_PIZZAS = "totalPizzas"
/**
* MainActivity is the entry point for the Pizza Party app. It allows users to input the number of attendees,
* select their hunger level, and calculate the number of pizzas needed.
*/
class MainActivity : ComponentActivity() {
// Reference to the number of attendees input text field.
private lateinit var numAttendEditText: EditText
// Reference to the TextView that displays the number of pizzas needed.
private lateinit var numPizzasTextView: TextView
// Reference to the RadioGroup for selecting the hunger level.
private lateinit var howHungryRadioGroup: RadioGroup
private var totalPizzas = 0
/**
* Called when the activity is starting. This is where most initialization should go.
*
* If the activity is being re-initialized after previously being shut down,
* this contains the data it most recently supplied in onSaveInstanceState(Bundle).
* Otherwise, it is null.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
numAttendEditText = findViewById(R.id.num_attend_edit_text)
numPizzasTextView = findViewById(R.id.num_pizzas_text_view)
howHungryRadioGroup = findViewById(R.id.hungry_radio_group)
// Restore state
if (savedInstanceState != null) {
totalPizzas = savedInstanceState.getInt(KEY_TOTAL_PIZZAS)
displayTotal()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_TOTAL_PIZZAS, totalPizzas)
}
/**
* Called when the user taps the Calculate button. It reads the user input, calculates the number of pizzas,
* and updates the UI with the result.
*
*/
@SuppressLint("SetTextI18n")
fun calculateClick(view: View) {
// Get the text that was typed into the EditText
val numAttendStr = numAttendEditText.text.toString()
// Convert the text into an integer
val numAttend = numAttendStr.toIntOrNull() ?: 0
// Get hunger level selection
val hungerLevel = when (howHungryRadioGroup.checkedRadioButtonId) {
R.id.light_radio_button -> PizzaCalculator.HungerLevel.LIGHT
R.id.medium_radio_button -> PizzaCalculator.HungerLevel.MEDIUM
else -> PizzaCalculator.HungerLevel.RAVENOUS
}
// Get the number of pizzas needed
val calc = PizzaCalculator(numAttend, hungerLevel)
totalPizzas = calc.totalPizzas
displayTotal()
}
private fun displayTotal() {
// Construct a string that includes the total number of pizzas. getString() is used to fetch a string resource,
val totalText = getString(R.string.total_pizzas_num, totalPizzas)
// effectively displaying the total number of pizzas to the user.
numPizzasTextView.text = totalText
}
} | PizzaParty3/app/src/main/java/com/zybooks/pizzaparty/MainActivity.kt | 181030741 |
package com.zybooks.pizzaparty
import kotlin.math.ceil
// Define a constant representing the number of slices in each pizza.
const val SLICES_PER_PIZZA = 8
// Define a class named PizzaCalculator to calculate the number of pizzas needed for a party.
class PizzaCalculator (partySize: Int, var hungerLevel: HungerLevel) {
// Define a variable for party size with initial setter logic to prevent negative values.
var partySize = 0
set(value) {
field = if (value >= 0) value else 0
}
enum class HungerLevel(var numSlices: Int) {
LIGHT(2), MEDIUM(3), RAVENOUS(4)
}
// Define a computed property to calculate the total number of pizzas needed
val totalPizzas: Int
get() {
// Calculate total slices needed, divide by slices per pizza, and round up to get the total number of pizzas.
return ceil(partySize * hungerLevel.numSlices / SLICES_PER_PIZZA.toDouble()).toInt()
}
// Initialize the class by setting the party size.
init {
this.partySize = partySize
}
} | PizzaParty3/app/src/main/java/com/zybooks/pizzaparty/PizzaCalculator.kt | 427436102 |
package com.weatherapplication
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.weatherapplication", appContext.packageName)
}
} | WeatherAppSample/app/src/androidTest/java/com/weatherapplication/ExampleInstrumentedTest.kt | 3702660538 |
package himanshu.benjwal.weather.ui
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule constructor(
private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
} | WeatherAppSample/app/src/test/java/himanshu/benjwal/weather/ui/MainDispatcherRule.kt | 2297212185 |
package himanshu.benjwal.weather.ui
import app.cash.turbine.test
import junit.framework.TestCase.assertEquals
import himanshu.benjwal.weather.data.repository.FakeWeatherRepository
import himanshu.benjwal.weather.data.repository.WeatherRepository
import himanshu.benjwal.weather.data.repository.fakeWeather
import himanshu.benjwal.weather.ui.weather.WeatherUiState
import himanshu.benjwal.weather.ui.weather.WeatherViewModel
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class WeatherViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private lateinit var viewModel: WeatherViewModel
private val weatherRepository: WeatherRepository = FakeWeatherRepository
@Before
fun setUp() {
viewModel = WeatherViewModel(weatherRepository)
}
@Test
fun `when getWeather completes, it should emit success state`() = runTest {
viewModel.uiState.test {
assertEquals(WeatherUiState(weather = fakeWeather), awaitItem())
}
}
@Test
fun `when getWeather completes, it should emit success state with humidity of 60`() = runTest {
viewModel.uiState.test {
assertEquals(WeatherUiState(weather = fakeWeather), awaitItem())
assertEquals(WeatherUiState(weather = fakeWeather).weather?.humidity, 60)
}
}
} | WeatherAppSample/app/src/test/java/himanshu/benjwal/weather/ui/WeatherViewModelTest.kt | 3173222564 |
package himanshu.benjwal.weather.data.repository
import io.mockk.coEvery
import io.mockk.mockk
import junit.framework.TestCase.assertEquals
import himanshu.benjwal.weather.data.model.toWeather
import himanshu.benjwal.weather.data.network.WeatherApi
import himanshu.benjwal.weather.data.sampleForecastResponse
import himanshu.benjwal.weather.model.Weather
import himanshu.benjwal.weather.utils.Result
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
class DefaultWeatherRepositoryTest {
private lateinit var repository: DefaultWeatherRepository
private val weatherApi = mockk<WeatherApi>()
@Before
fun setup() {
repository = DefaultWeatherRepository(weatherApi)
}
@Test
fun `when getWeatherForecast is called, it should emit loading state and then success state`() =
runTest {
coEvery {
weatherApi.getWeatherForecast(
any(),
any(),
any()
)
} returns sampleForecastResponse
val results = mutableListOf<Result<Weather>>()
repository.getWeatherForecast("India").collect { result ->
results.add(result)
}
assertEquals(Result.Loading, results[0])
assertEquals(Result.Success(sampleForecastResponse.toWeather()), results[1])
}
} | WeatherAppSample/app/src/test/java/himanshu/benjwal/weather/data/repository/DefaultWeatherRepositoryTest.kt | 2921812485 |
package himanshu.benjwal.weather.data.repository
import himanshu.benjwal.weather.data.model.ForecastResponse.Current.Condition
import himanshu.benjwal.weather.model.Forecast
import himanshu.benjwal.weather.model.Hour
import himanshu.benjwal.weather.model.Weather
import himanshu.benjwal.weather.utils.Result
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
object FakeWeatherRepository : WeatherRepository {
override fun getWeatherForecast(city: String): Flow<Result<Weather>> {
return flow {
emit(Result.Loading)
emit(Result.Success(fakeWeather))
}
}
}
val fakeWeather = Weather(
temperature = 20,
date = "2023-10-15",
wind = 10,
humidity = 60,
feelsLike = 25,
condition = Condition(200, "sunny-icon", "Sunny"),
uv = 5,
name = "San Francisco",
forecasts = listOf(
Forecast(
date = "2023-10-15",
maxTemp = "25",
minTemp = "15",
sunrise = "06:30 AM",
sunset = "06:30 PM",
icon = "sunny-icon",
hour = listOf(
Hour("08:00 AM", "sunny-icon", "Sunny"),
Hour("09:00 AM", "sunny-icon", "Sunny"),
Hour("10:00 AM", "sunny-icon", "Sunny")
)
)
)
)
| WeatherAppSample/app/src/test/java/himanshu/benjwal/weather/data/repository/FakeWeatherRepository.kt | 2042039331 |
package himanshu.benjwal.weather.data
import himanshu.benjwal.weather.data.model.ForecastResponse
import himanshu.benjwal.weather.data.model.ForecastResponse.Current
import himanshu.benjwal.weather.data.model.ForecastResponse.Location
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast.NetworkForecastday.Astro
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast.NetworkForecastday.Day
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast.NetworkForecastday.Day.Condition
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast.NetworkForecastday.NetworkHour
val sampleForecastResponse: ForecastResponse
get() = ForecastResponse(
current = Current(
cloud = 50,
condition = Current.Condition(
code = 200,
icon = "sunny-icon",
text = "Sunny"
),
feelslikeC = 25.0,
feelslikeF = 77.0,
gustKph = 10.0,
gustMph = 6.2,
humidity = 60,
isDay = 1,
lastUpdated = "2023-10-14 12:00 PM",
lastUpdatedEpoch = 1634217600,
precipIn = 0.0,
precipMm = 0.0,
pressureIn = 29.92,
pressureMb = 1013.25,
tempC = 20.0,
tempF = 68.0,
uv = 5.0,
visKm = 10.0,
visMiles = 6.2,
windDegree = 180,
windDir = "S",
windKph = 10.0,
windMph = 6.2
),
forecast = NetworkForecast(
forecastday = listOf(
NetworkForecast.NetworkForecastday(
astro = Astro(
isMoonUp = 1,
isSunUp = 1,
moonIllumination = "100%",
moonPhase = "Full Moon",
moonrise = "06:30 PM",
moonset = "06:30 AM",
sunrise = "06:30 AM",
sunset = "06:30 PM"
),
date = "2023-10-15",
dateEpoch = 1634299200,
day = Day(
avghumidity = 60.0,
avgtempC = 20.0,
avgtempF = 68.0,
avgvisKm = 10.0,
avgvisMiles = 6.2,
condition = Condition(
code = 200,
icon = "sunny-icon",
text = "Sunny"
),
dailyChanceOfRain = 10,
dailyChanceOfSnow = 0,
dailyWillItRain = 1,
dailyWillItSnow = 0,
maxtempC = 25.0,
maxtempF = 77.0,
maxwindKph = 15.0,
maxwindMph = 9.3,
mintempC = 15.0,
mintempF = 59.0,
totalprecipIn = 0.0,
totalprecipMm = 0.0,
totalsnowCm = 0.0,
uv = 5.0
),
hour = listOf(
NetworkHour(
chanceOfRain = 10,
chanceOfSnow = 0,
cloud = 50,
condition = NetworkHour.Condition(
code = 200,
icon = "sunny-icon",
text = "Sunny"
),
dewpointC = 15.0,
dewpointF = 59.0,
feelslikeC = 20.0,
feelslikeF = 68.0,
gustKph = 15.0,
gustMph = 9.3,
heatindexC = 20.0,
heatindexF = 68.0,
humidity = 60,
isDay = 1,
precipIn = 0.0,
precipMm = 0.0,
pressureIn = 29.92,
pressureMb = 1013.25,
tempC = 20.0,
tempF = 68.0,
time = "08:00 AM",
timeEpoch = 1634313600,
uv = 5.0,
visKm = 10.0,
visMiles = 6.2,
willItRain = 1,
willItSnow = 0,
windDegree = 180,
windDir = "S",
windKph = 15.0,
windMph = 9.3,
windchillC = 20.0,
windchillF = 68.0
)
)
)
)
),
location = Location(
country = "US",
lat = 37.7749,
localtime = "2023-10-14 12:00 PM",
localtimeEpoch = 1634217600,
lon = -122.4194,
name = "San Francisco",
region = "California",
tzId = "America/Los_Angeles"
)
)
| WeatherAppSample/app/src/test/java/himanshu/benjwal/weather/data/SampleForecastResponse.kt | 3137705249 |
package com.weatherapplication
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)
}
} | WeatherAppSample/app/src/test/java/com/weatherapplication/ExampleUnitTest.kt | 3743695232 |
package himanshu.benjwal.weather.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) | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/theme/Color.kt | 2498201547 |
package himanshu.benjwal.weather.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 WeatherTheme(
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
)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/theme/Theme.kt | 3913899802 |
package himanshu.benjwal.weather.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
)
*/
) | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/theme/Type.kt | 2222523535 |
package himanshu.benjwal.weather.ui.weather
import himanshu.benjwal.weather.model.Weather
data class WeatherUiState(
val weather: Weather? = null,
val isLoading: Boolean = false,
val errorMessage: String = "",
)
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/WeatherUiState.kt | 4057808617 |
package himanshu.benjwal.weather.ui.weather
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import himanshu.benjwal.weather.data.repository.WeatherRepository
import himanshu.benjwal.weather.utils.DEFAULT_WEATHER_DESTINATION
import himanshu.benjwal.weather.utils.Result
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import javax.inject.Inject
@HiltViewModel
class WeatherViewModel @Inject constructor(
private val repository: WeatherRepository,
) : ViewModel() {
private val _uiState: MutableStateFlow<WeatherUiState> =
MutableStateFlow(WeatherUiState(isLoading = true))
val uiState: StateFlow<WeatherUiState> = _uiState.asStateFlow()
private val _searchWidgetState: MutableState<SearchWidgetState> =
mutableStateOf(value = SearchWidgetState.CLOSED)
val searchWidgetState: State<SearchWidgetState> = _searchWidgetState
private val _searchTextState: MutableState<String> = mutableStateOf(value = "")
val searchTextState: State<String> = _searchTextState
fun updateSearchWidgetState(newValue: SearchWidgetState) {
_searchWidgetState.value = newValue
}
fun updateSearchTextState(newValue: String) {
_searchTextState.value = newValue
}
init {
getWeather()
}
fun getWeather(city: String = DEFAULT_WEATHER_DESTINATION) {
repository.getWeatherForecast(city).map { result ->
when (result) {
is Result.Success -> {
_uiState.value = WeatherUiState(weather = result.data)
}
is Result.Error -> {
_uiState.value = WeatherUiState(errorMessage = result.errorMessage)
}
Result.Loading -> {
_uiState.value = WeatherUiState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/WeatherViewModel.kt | 1022653101 |
package himanshu.benjwal.weather.ui.weather
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices.PIXEL_XL
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import himanshu.benjwal.weather.R
import himanshu.benjwal.weather.data.model.ForecastResponse.Current.Condition
import himanshu.benjwal.weather.model.Forecast
import himanshu.benjwal.weather.model.Hour
import himanshu.benjwal.weather.model.Weather
import himanshu.benjwal.weather.ui.theme.WeatherTheme
import himanshu.benjwal.weather.ui.weather.components.Animation
import himanshu.benjwal.weather.ui.weather.components.ForecastComponent
import himanshu.benjwal.weather.ui.weather.components.HourlyComponent
import himanshu.benjwal.weather.ui.weather.components.WeatherComponent
import himanshu.benjwal.weather.utils.DateUtil.toFormattedDate
import java.util.Locale
import kotlin.random.Random
/**
* Weather screen
*
* @param modifier
* @param viewModel
*/
@Composable
fun WeatherScreen(
modifier: Modifier = Modifier,
viewModel: WeatherViewModel = hiltViewModel(),
) {
val searchWidgetState by viewModel.searchWidgetState
val searchTextState by viewModel.searchTextState
val uiState: WeatherUiState by viewModel.uiState.collectAsStateWithLifecycle()
Scaffold(
topBar = {
WeatherTopAppBar(
searchWidgetState = searchWidgetState,
searchTextState = searchTextState,
onTextChange = { viewModel.updateSearchTextState(it) },
onCloseClicked = { viewModel.updateSearchWidgetState(SearchWidgetState.CLOSED) },
onSearchClicked = { viewModel.getWeather(it) },
onSearchTriggered = {
viewModel.updateSearchWidgetState(newValue = SearchWidgetState.OPENED)
}
)
},
content = { paddingValues ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues),
color = MaterialTheme.colorScheme.background
) {
WeatherScreenContent(uiState = uiState, modifier = modifier, viewModel = viewModel)
}
},
)
}
/**
* Weather screen content
*
* @param uiState
* @param modifier
* @param viewModel
*/
@Composable
fun WeatherScreenContent(
uiState: WeatherUiState,
modifier: Modifier = Modifier,
viewModel: WeatherViewModel?,
) {
when {
uiState.isLoading -> {
Animation(modifier = Modifier.fillMaxSize(), animation = R.raw.animation_loading)
}
uiState.errorMessage.isNotEmpty() -> {
WeatherErrorState(uiState = uiState, viewModel = viewModel)
}
else -> {
WeatherSuccessState(modifier = modifier, uiState = uiState)
}
}
}
@Composable
private fun WeatherErrorState(
modifier: Modifier = Modifier,
uiState: WeatherUiState,
viewModel: WeatherViewModel?,
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Animation(
modifier = Modifier
.fillMaxWidth()
.weight(8f),
animation = R.raw.animation_error,
)
Button(onClick = { viewModel?.getWeather() }) {
Icon(
imageVector = Icons.Filled.Refresh,
contentDescription = "Retry",
)
Text(
modifier = Modifier.padding(horizontal = 8.dp),
style = MaterialTheme.typography.titleMedium,
text = stringResource(R.string.retry),
fontWeight = FontWeight.Bold,
)
}
Text(
modifier = modifier
.weight(2f)
.alpha(0.5f)
.padding(horizontal = 16.dp, vertical = 16.dp),
text = "Something went wrong: ${uiState.errorMessage}",
textAlign = TextAlign.Center,
)
}
}
@Composable
private fun WeatherSuccessState(
modifier: Modifier,
uiState: WeatherUiState,
) {
Column(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
modifier = Modifier.padding(top = 12.dp),
text = uiState.weather?.name.orEmpty(),
style = MaterialTheme.typography.headlineMedium
)
Text(
text = uiState.weather?.date?.toFormattedDate().orEmpty(),
style = MaterialTheme.typography.bodyLarge
)
AsyncImage(
modifier = Modifier.size(64.dp),
model = stringResource(
R.string.icon_image_url,
uiState.weather?.condition?.icon.orEmpty(),
),
contentScale = ContentScale.FillBounds,
contentDescription = null,
error = painterResource(id = R.drawable.ic_placeholder),
placeholder = painterResource(id = R.drawable.ic_placeholder),
)
Text(
text = stringResource(
R.string.temperature_value_in_celsius,
uiState.weather?.temperature.toString()
),
style = MaterialTheme.typography.headlineLarge,
fontWeight = FontWeight.Bold,
)
Text(
modifier = Modifier.padding(start = 12.dp, end = 12.dp),
text = uiState.weather?.condition?.text.orEmpty(),
style = MaterialTheme.typography.bodyMedium,
)
Text(
modifier = Modifier.padding(bottom = 4.dp),
text = stringResource(
R.string.feels_like_temperature_in_celsius,
uiState.weather?.feelsLike.toString()
),
style = MaterialTheme.typography.bodySmall
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Image(painter = painterResource(id = R.drawable.ic_sunrise), contentDescription = null)
Text(
modifier = Modifier.padding(start = 4.dp),
text = uiState.weather?.forecasts?.get(0)?.sunrise?.lowercase(Locale.US).orEmpty(),
style = MaterialTheme.typography.bodySmall,
)
Spacer(modifier = Modifier.width(16.dp))
Image(painter = painterResource(id = R.drawable.ic_sunset), contentDescription = null)
Text(
modifier = Modifier.padding(start = 4.dp),
text = uiState.weather?.forecasts?.get(0)?.sunset?.lowercase(Locale.US).orEmpty(),
style = MaterialTheme.typography.bodySmall,
)
}
Spacer(Modifier.height(16.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp),
) {
WeatherComponent(
modifier = Modifier.weight(1f),
weatherLabel = stringResource(R.string.wind_speed_label),
weatherValue = uiState.weather?.wind.toString(),
weatherUnit = stringResource(R.string.wind_speed_unit),
iconId = R.drawable.ic_wind,
)
WeatherComponent(
modifier = Modifier.weight(1f),
weatherLabel = stringResource(R.string.uv_index_label),
weatherValue = uiState.weather?.uv.toString(),
weatherUnit = stringResource(R.string.uv_unit),
iconId = R.drawable.ic_uv,
)
WeatherComponent(
modifier = Modifier.weight(1f),
weatherLabel = stringResource(R.string.humidity_label),
weatherValue = uiState.weather?.humidity.toString(),
weatherUnit = stringResource(R.string.humidity_unit),
iconId = R.drawable.ic_humidity,
)
}
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(R.string.today),
style = MaterialTheme.typography.bodyMedium,
modifier = modifier
.align(Alignment.Start)
.padding(horizontal = 16.dp),
)
LazyRow(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(top = 8.dp, start = 16.dp),
) {
uiState.weather?.forecasts?.get(0)?.let { forecast ->
items(forecast.hour) { hour ->
HourlyComponent(
time = hour.time,
icon = hour.icon,
temperature = stringResource(
R.string.temperature_value_in_celsius,
hour.temperature,
)
)
}
}
}
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(R.string.forecast),
style = MaterialTheme.typography.bodyMedium,
modifier = modifier
.align(Alignment.Start)
.padding(horizontal = 16.dp),
)
LazyRow(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(top = 8.dp, start = 16.dp),
) {
uiState.weather?.let { weather ->
items(weather.forecasts) { forecast ->
ForecastComponent(
date = forecast.date,
icon = forecast.icon,
minTemp = stringResource(
R.string.temperature_value_in_celsius,
forecast.minTemp
),
maxTemp = stringResource(
R.string.temperature_value_in_celsius,
forecast.maxTemp,
),
)
}
}
}
Spacer(Modifier.height(16.dp))
}
}
/**
* Weather screen content preview
*
*/
@Preview(name = "Light Mode", showBackground = true, showSystemUi = true)
@Preview(
name = "Dark Mode",
uiMode = Configuration.UI_MODE_NIGHT_YES,
showSystemUi = true,
showBackground = true,
device = PIXEL_XL
)
@Composable
fun WeatherScreenContentPreview() {
val hourlyForecast = mutableListOf<Hour>()
for (i in 0 until 24) {
hourlyForecast.add(
Hour(
"yyyy-mm-dd ${String.format("%02d", i)}",
"",
"${Random.nextInt(18, 21)}"
)
)
}
val forecasts = mutableListOf<Forecast>()
for (i in 0..9) {
forecasts.add(
Forecast(
"2023-10-${String.format("%02d", i)}",
"${Random.nextInt(18, 21)}",
"${Random.nextInt(10, 15)}",
"07:20 am",
"06:40 pm",
"",
hourlyForecast
)
)
}
WeatherTheme {
Surface {
WeatherScreenContent(
WeatherUiState(
Weather(
temperature = 19,
date = "Oct 7",
wind = 22,
humidity = 35,
feelsLike = 18,
condition = Condition(10, "", "Cloudy"),
uv = 2,
name = "Munich",
forecasts = forecasts,
),
), viewModel = null
)
}
}
}
/**
* Weather top app bar
*
* @param searchWidgetState
* @param searchTextState
* @param onTextChange
* @param onCloseClicked
* @param onSearchClicked
* @param onSearchTriggered
* @receiver
* @receiver
* @receiver
* @receiver
*/
@Composable
fun WeatherTopAppBar(
searchWidgetState: SearchWidgetState,
searchTextState: String,
onTextChange: (String) -> Unit,
onCloseClicked: () -> Unit,
onSearchClicked: (String) -> Unit,
onSearchTriggered: () -> Unit
) {
when (searchWidgetState) {
SearchWidgetState.CLOSED -> {
DefaultAppBar(
onSearchClicked = onSearchTriggered
)
}
SearchWidgetState.OPENED -> {
SearchAppBar(
text = searchTextState,
onTextChange = onTextChange,
onCloseClicked = onCloseClicked,
onSearchClicked = onSearchClicked
)
}
}
}
/**
* Default app bar
*
* @param onSearchClicked
* @receiver
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DefaultAppBar(onSearchClicked: () -> Unit) {
TopAppBar(
title = {
Text(
text = stringResource(id = R.string.app_name),
fontWeight = FontWeight.Bold,
)
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.onBackground,
),
actions = {
IconButton(
onClick = { onSearchClicked() }
) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.search_icon),
)
}
}
)
}
/**
* Search app bar
*
* @param text
* @param onTextChange
* @param onCloseClicked
* @param onSearchClicked
* @receiver
* @receiver
* @receiver
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SearchAppBar(
text: String,
onTextChange: (String) -> Unit,
onCloseClicked: () -> Unit,
onSearchClicked: (String) -> Unit,
) {
val keyboardController = LocalSoftwareKeyboardController.current
Surface(
modifier = Modifier
.fillMaxWidth()
.height(64.dp),
color = MaterialTheme.colorScheme.primary,
) {
TextField(
modifier = Modifier.fillMaxWidth(),
value = text,
onValueChange = { onTextChange(it) },
placeholder = {
Text(
modifier = Modifier.alpha(0.5f),
text = stringResource(R.string.search_hint),
)
},
textStyle = TextStyle(
fontSize = MaterialTheme.typography.titleMedium.fontSize
),
singleLine = true,
leadingIcon = {
IconButton(
modifier = Modifier.alpha(0.7f),
onClick = {}
) {
Icon(
imageVector = Icons.Default.Search,
contentDescription = stringResource(R.string.search_icon),
)
}
},
trailingIcon = {
IconButton(
onClick = {
if (text.isNotEmpty()) {
onTextChange("")
} else {
onCloseClicked()
}
}
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = stringResource(R.string.close_icon),
)
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Search
),
keyboardActions = KeyboardActions(
onSearch = {
onSearchClicked(text)
keyboardController?.hide()
},
),
)
}
}
/**
* Default app bar preview
*
*/
@Composable
@Preview
fun DefaultAppBarPreview() {
DefaultAppBar(onSearchClicked = {})
}
/**
* Search app bar preview
*
*/
@Composable
@Preview
fun SearchAppBarPreview() {
SearchAppBar(
text = "Search for a city",
onTextChange = {},
onCloseClicked = {},
onSearchClicked = {}
)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/WeatherScreen.kt | 1529448671 |
package himanshu.benjwal.weather.ui.weather.components
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import himanshu.benjwal.weather.R
@Composable
fun WeatherComponent(
modifier: Modifier = Modifier,
weatherLabel: String,
weatherValue: String,
weatherUnit: String,
iconId: Int,
) {
ElevatedCard(
modifier = modifier
.padding(end = 16.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = weatherLabel,
style = MaterialTheme.typography.bodySmall,
)
Image(
painter = painterResource(id = iconId),
contentDescription = null,
contentScale = ContentScale.Crop,
)
Text(
text = weatherValue,
style = MaterialTheme.typography.titleMedium,
)
Text(
text = weatherUnit,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
@Preview(uiMode = UI_MODE_NIGHT_YES)
@Composable
fun WeatherComponentPreview() {
WeatherComponent(
weatherLabel = "wind speed",
weatherValue = "22",
weatherUnit = "km/h",
iconId = R.drawable.ic_wind
)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/components/WeatherComponent.kt | 2794029643 |
package himanshu.benjwal.weather.ui.weather.components
import android.content.res.Configuration
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
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.layout.ContentScale
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 coil.compose.AsyncImage
import himanshu.benjwal.weather.R
import himanshu.benjwal.weather.ui.theme.WeatherTheme
@Composable
fun HourlyComponent(
modifier: Modifier = Modifier,
time: String,
icon: String,
temperature: String,
) {
ElevatedCard(
modifier = modifier.padding(end = 12.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = time.substring(11, 13),
style = MaterialTheme.typography.titleMedium,
)
AsyncImage(
modifier = Modifier.size(42.dp),
model = stringResource(R.string.icon_image_url, icon),
contentDescription = null,
contentScale = ContentScale.Crop,
error = painterResource(id = R.drawable.ic_placeholder),
placeholder = painterResource(id = R.drawable.ic_placeholder),
)
Text(
text = temperature,
style = MaterialTheme.typography.bodyMedium,
)
}
}
}
@Preview
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun HourlyComponentPreview() {
Surface {
WeatherTheme {
HourlyComponent(
time = "2023-10-07 13:00",
icon = "116.png",
temperature = "23",
)
}
}
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/components/HourlyComponent.kt | 1042938432 |
package himanshu.benjwal.weather.ui.weather.components
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
@Composable
fun Animation(modifier: Modifier = Modifier, animation: Int) {
val composition by rememberLottieComposition(
LottieCompositionSpec.RawRes(animation)
)
val progress by animateLottieCompositionAsState(
composition = composition,
iterations = LottieConstants.IterateForever,
isPlaying = true,
speed = 2f,
)
LottieAnimation(
composition = composition,
progress = { progress },
modifier = modifier,
)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/components/Animation.kt | 2676804850 |
package himanshu.benjwal.weather.ui.weather.components
import android.content.res.Configuration
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedCard
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.layout.ContentScale
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 coil.compose.AsyncImage
import himanshu.benjwal.weather.R
import himanshu.benjwal.weather.ui.theme.WeatherTheme
import himanshu.benjwal.weather.utils.DateUtil.toFormattedDay
@Composable
fun ForecastComponent(
modifier: Modifier = Modifier,
date: String,
icon: String,
minTemp: String,
maxTemp: String,
) {
ElevatedCard(
modifier = modifier.padding(end = 16.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp
),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
modifier = Modifier.padding(start = 4.dp, end = 4.dp),
text = date.toFormattedDay().orEmpty(),
style = MaterialTheme.typography.titleMedium
)
AsyncImage(
modifier = Modifier.size(42.dp),
model = stringResource(R.string.icon_image_url, icon),
contentDescription = null,
contentScale = ContentScale.Crop,
error = painterResource(id = R.drawable.ic_placeholder),
placeholder = painterResource(id = R.drawable.ic_placeholder),
)
Text(
text = maxTemp,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold,
)
Spacer(Modifier.width(4.dp))
Text(
text = minTemp, style = MaterialTheme.typography.bodySmall
)
}
}
}
@Preview
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun ForecastComponentPreview() {
Surface {
WeatherTheme {
ForecastComponent(
date = "2023-10-07",
icon = "116.png",
minTemp = "12",
maxTemp = "28",
)
}
}
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/components/ForecastComponent.kt | 2965087133 |
package himanshu.benjwal.weather.ui.weather
enum class SearchWidgetState {
OPENED,
CLOSED
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/ui/weather/SearchWidgetState.kt | 3670031610 |
package himanshu.benjwal.weather
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import dagger.hilt.android.AndroidEntryPoint
import himanshu.benjwal.weather.ui.theme.WeatherTheme
import himanshu.benjwal.weather.ui.weather.WeatherScreen
/**
* Main activity
*
*/
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WeatherTheme {
WeatherScreen()
}
}
}
}
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/MainActivity.kt | 3948532228 |
package himanshu.benjwal.weather.di
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import himanshu.benjwal.weather.BuildConfig
import himanshu.benjwal.weather.data.network.WeatherApi
import himanshu.benjwal.weather.utils.BASE_URL
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Singleton
@Provides
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor =
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
@Singleton
@Provides
fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
val okHttpClient = OkHttpClient.Builder()
return if (BuildConfig.DEBUG) {
okHttpClient.addInterceptor(httpLoggingInterceptor).build()
} else {
okHttpClient.build()
}
}
@Singleton
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.client(okHttpClient)
.build()
@Singleton
@Provides
fun provideWeatherApi(retrofit: Retrofit): WeatherApi = retrofit
.create(WeatherApi::class.java)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/di/NetworkModule.kt | 2343836048 |
package himanshu.benjwal.weather.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import himanshu.benjwal.weather.data.network.WeatherApi
import himanshu.benjwal.weather.data.repository.DefaultWeatherRepository
import himanshu.benjwal.weather.data.repository.WeatherRepository
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {
@Singleton
@Provides
fun provideRepository(weatherApi: WeatherApi): WeatherRepository =
DefaultWeatherRepository(weatherApi)
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/di/RepositoryModule.kt | 260927633 |
package himanshu.benjwal.weather.utils
sealed class Result<out T : Any> {
object Loading : Result<Nothing>()
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val errorMessage: String) : Result<Nothing>()
}
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/utils/Result.kt | 3052140867 |
package himanshu.benjwal.weather.utils
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
object DateUtil {
fun String.toFormattedDate(): String {
val inputDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val outputDateFormat = SimpleDateFormat("MMM d", Locale.getDefault())
try {
val date = inputDateFormat.parse(this)
if (date != null) {
return outputDateFormat.format(date)
}
} catch (e: Exception) {
Timber.e(e)
}
return this
}
fun String.toFormattedDay(): String? {
val dateComponents = this.split("-")
return if (dateComponents.size == 3) {
val year = dateComponents[0].toInt()
val month = dateComponents[1].toInt() - 1
val day = dateComponents[2].toInt()
val calendar = Calendar.getInstance()
calendar.set(year, month, day)
val outputDateFormat = SimpleDateFormat("EE", Locale.getDefault())
return outputDateFormat.format(calendar.time)
} else null
}
}
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/utils/DateUtil.kt | 839344005 |
package himanshu.benjwal.weather.utils
const val BASE_URL = "https://api.weatherapi.com/v1/"
const val DEFAULT_WEATHER_DESTINATION = "India"
const val NUMBER_OF_DAYS = 10 | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/utils/Constants.kt | 937311943 |
package himanshu.benjwal.weather.model
data class Hour(
val time: String,
val icon: String,
val temperature: String,
)
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/model/Hour.kt | 2468313259 |
package himanshu.benjwal.weather.model
/**
* Forecast
*
* @property date
* @property maxTemp
* @property minTemp
* @property sunrise
* @property sunset
* @property icon
* @property hour
* @constructor Create empty Forecast
*/
data class Forecast(
val date: String,
val maxTemp: String,
val minTemp: String,
val sunrise: String,
val sunset: String,
val icon: String,
val hour: List<Hour>,
)
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/model/Forecast.kt | 845870237 |
package himanshu.benjwal.weather.model
import himanshu.benjwal.weather.data.model.ForecastResponse.Current.Condition
data class Weather(
val temperature: Int,
val date: String,
val wind: Int,
val humidity: Int,
val feelsLike: Int,
val condition: Condition,
val uv: Int,
val name: String,
val forecasts: List<Forecast>
)
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/model/Weather.kt | 723757097 |
package himanshu.benjwal.weather.data.repository
import himanshu.benjwal.weather.model.Weather
import himanshu.benjwal.weather.utils.Result
import kotlinx.coroutines.flow.Flow
interface WeatherRepository {
fun getWeatherForecast(city: String): Flow<Result<Weather>>
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/data/repository/WeatherRepository.kt | 2392337589 |
package himanshu.benjwal.weather.data.repository
import himanshu.benjwal.weather.data.model.toWeather
import himanshu.benjwal.weather.data.network.WeatherApi
import himanshu.benjwal.weather.model.Weather
import himanshu.benjwal.weather.utils.Result
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
/**
* Default weather repository
*
* @property weatherApi
* @property dispatcher
* @constructor Create empty Default weather repository
*/
class DefaultWeatherRepository @Inject constructor(
private val weatherApi: WeatherApi,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO,
) : WeatherRepository {
override fun getWeatherForecast(city: String): Flow<Result<Weather>> = flow {
emit(Result.Loading)
try {
val result = weatherApi.getWeatherForecast(city = city).toWeather()
emit(Result.Success(result))
} catch (exception: HttpException) {
emit(Result.Error(exception.message.orEmpty()))
} catch (exception: IOException) {
emit(Result.Error("Please check your network connection and try again!"))
}
}.flowOn(dispatcher)
}
| WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/data/repository/DefaultWeatherRepository.kt | 3926562188 |
package himanshu.benjwal.weather.data.network
import himanshu.benjwal.weather.BuildConfig
import himanshu.benjwal.weather.data.model.ForecastResponse
import himanshu.benjwal.weather.utils.DEFAULT_WEATHER_DESTINATION
import himanshu.benjwal.weather.utils.NUMBER_OF_DAYS
import retrofit2.http.GET
import retrofit2.http.Query
/**
* Weather api
*
* @constructor Create empty Weather api
*/
interface WeatherApi {
/**
* Get weather forecast
*
* @param key
* @param city
* @param days
* @return
*/
@GET("forecast.json")
suspend fun getWeatherForecast(
@Query("key") key: String = BuildConfig.API_KEY,
@Query("q") city: String = DEFAULT_WEATHER_DESTINATION,
@Query("days") days: Int = NUMBER_OF_DAYS,
): ForecastResponse
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/data/network/WeatherApi.kt | 640878800 |
package himanshu.benjwal.weather.data.model
import com.google.gson.annotations.SerializedName
import himanshu.benjwal.weather.data.model.ForecastResponse.NetworkForecast.NetworkForecastday
import himanshu.benjwal.weather.model.Forecast
import himanshu.benjwal.weather.model.Hour
import himanshu.benjwal.weather.model.Weather
/**
* Forecast response
*
* @property current
* @property forecast
* @property location
* @constructor Create empty Forecast response
*/
data class ForecastResponse(
@SerializedName("current") val current: Current,
@SerializedName("forecast") val forecast: NetworkForecast,
@SerializedName("location") val location: Location
) {
/**
* Current
*
* @property cloud
* @property condition
* @property feelslikeC
* @property feelslikeF
* @property gustKph
* @property gustMph
* @property humidity
* @property isDay
* @property lastUpdated
* @property lastUpdatedEpoch
* @property precipIn
* @property precipMm
* @property pressureIn
* @property pressureMb
* @property tempC
* @property tempF
* @property uv
* @property visKm
* @property visMiles
* @property windDegree
* @property windDir
* @property windKph
* @property windMph
* @constructor Create empty Current
*/
data class Current(
@SerializedName("cloud") val cloud: Int,
@SerializedName("condition") val condition: Condition,
@SerializedName("feelslike_c") val feelslikeC: Double,
@SerializedName("feelslike_f") val feelslikeF: Double,
@SerializedName("gust_kph") val gustKph: Double,
@SerializedName("gust_mph") val gustMph: Double,
@SerializedName("humidity") val humidity: Int,
@SerializedName("is_day") val isDay: Int,
@SerializedName("last_updated") val lastUpdated: String,
@SerializedName("last_updated_epoch") val lastUpdatedEpoch: Int,
@SerializedName("precip_in") val precipIn: Double,
@SerializedName("precip_mm") val precipMm: Double,
@SerializedName("pressure_in") val pressureIn: Double,
@SerializedName("pressure_mb") val pressureMb: Double,
@SerializedName("temp_c") val tempC: Double,
@SerializedName("temp_f") val tempF: Double,
@SerializedName("uv") val uv: Double,
@SerializedName("vis_km") val visKm: Double,
@SerializedName("vis_miles") val visMiles: Double,
@SerializedName("wind_degree") val windDegree: Int,
@SerializedName("wind_dir") val windDir: String,
@SerializedName("wind_kph") val windKph: Double,
@SerializedName("wind_mph") val windMph: Double
) {
/**
* Condition
*
* @property code
* @property icon
* @property text
* @constructor Create empty Condition
*/
data class Condition(
@SerializedName("code") val code: Int,
@SerializedName("icon") val icon: String,
@SerializedName("text") val text: String
)
}
/**
* Network forecast
*
* @property forecastday
* @constructor Create empty Network forecast
*/
data class NetworkForecast(
@SerializedName("forecastday") val forecastday: List<NetworkForecastday>
) {
/**
* Network forecastday
*
* @property astro
* @property date
* @property dateEpoch
* @property day
* @property hour
* @constructor Create empty Network forecastday
*/
data class NetworkForecastday(
@SerializedName("astro") val astro: Astro,
@SerializedName("date") val date: String,
@SerializedName("date_epoch") val dateEpoch: Int,
@SerializedName("day") val day: Day,
@SerializedName("hour") val hour: List<NetworkHour>
) {
/**
* Astro
*
* @property isMoonUp
* @property isSunUp
* @property moonIllumination
* @property moonPhase
* @property moonrise
* @property moonset
* @property sunrise
* @property sunset
* @constructor Create empty Astro
*/
data class Astro(
@SerializedName("is_moon_up") val isMoonUp: Int,
@SerializedName("is_sun_up") val isSunUp: Int,
@SerializedName("moon_illumination") val moonIllumination: String,
@SerializedName("moon_phase") val moonPhase: String,
@SerializedName("moonrise") val moonrise: String,
@SerializedName("moonset") val moonset: String,
@SerializedName("sunrise") val sunrise: String,
@SerializedName("sunset") val sunset: String
)
/**
* Day
*
* @property avghumidity
* @property avgtempC
* @property avgtempF
* @property avgvisKm
* @property avgvisMiles
* @property condition
* @property dailyChanceOfRain
* @property dailyChanceOfSnow
* @property dailyWillItRain
* @property dailyWillItSnow
* @property maxtempC
* @property maxtempF
* @property maxwindKph
* @property maxwindMph
* @property mintempC
* @property mintempF
* @property totalprecipIn
* @property totalprecipMm
* @property totalsnowCm
* @property uv
* @constructor Create empty Day
*/
data class Day(
@SerializedName("avghumidity") val avghumidity: Double,
@SerializedName("avgtemp_c") val avgtempC: Double,
@SerializedName("avgtemp_f") val avgtempF: Double,
@SerializedName("avgvis_km") val avgvisKm: Double,
@SerializedName("avgvis_miles") val avgvisMiles: Double,
@SerializedName("condition") val condition: Condition,
@SerializedName("daily_chance_of_rain") val dailyChanceOfRain: Int,
@SerializedName("daily_chance_of_snow") val dailyChanceOfSnow: Int,
@SerializedName("daily_will_it_rain") val dailyWillItRain: Int,
@SerializedName("daily_will_it_snow") val dailyWillItSnow: Int,
@SerializedName("maxtemp_c") val maxtempC: Double,
@SerializedName("maxtemp_f") val maxtempF: Double,
@SerializedName("maxwind_kph") val maxwindKph: Double,
@SerializedName("maxwind_mph") val maxwindMph: Double,
@SerializedName("mintemp_c") val mintempC: Double,
@SerializedName("mintemp_f") val mintempF: Double,
@SerializedName("totalprecip_in") val totalprecipIn: Double,
@SerializedName("totalprecip_mm") val totalprecipMm: Double,
@SerializedName("totalsnow_cm") val totalsnowCm: Double,
@SerializedName("uv") val uv: Double
) {
/**
* Condition
*
* @property code
* @property icon
* @property text
* @constructor Create empty Condition
*/
data class Condition(
@SerializedName("code") val code: Int,
@SerializedName("icon") val icon: String,
@SerializedName("text") val text: String
)
}
/**
* Network hour
*
* @property chanceOfRain
* @property chanceOfSnow
* @property cloud
* @property condition
* @property dewpointC
* @property dewpointF
* @property feelslikeC
* @property feelslikeF
* @property gustKph
* @property gustMph
* @property heatindexC
* @property heatindexF
* @property humidity
* @property isDay
* @property precipIn
* @property precipMm
* @property pressureIn
* @property pressureMb
* @property tempC
* @property tempF
* @property time
* @property timeEpoch
* @property uv
* @property visKm
* @property visMiles
* @property willItRain
* @property willItSnow
* @property windDegree
* @property windDir
* @property windKph
* @property windMph
* @property windchillC
* @property windchillF
* @constructor Create empty Network hour
*/
data class NetworkHour(
@SerializedName("chance_of_rain") val chanceOfRain: Int,
@SerializedName("chance_of_snow") val chanceOfSnow: Int,
@SerializedName("cloud") val cloud: Int,
@SerializedName("condition") val condition: Condition,
@SerializedName("dewpoint_c") val dewpointC: Double,
@SerializedName("dewpoint_f") val dewpointF: Double,
@SerializedName("feelslike_c") val feelslikeC: Double,
@SerializedName("feelslike_f") val feelslikeF: Double,
@SerializedName("gust_kph") val gustKph: Double,
@SerializedName("gust_mph") val gustMph: Double,
@SerializedName("heatindex_c") val heatindexC: Double,
@SerializedName("heatindex_f") val heatindexF: Double,
@SerializedName("humidity") val humidity: Int,
@SerializedName("is_day") val isDay: Int,
@SerializedName("precip_in") val precipIn: Double,
@SerializedName("precip_mm") val precipMm: Double,
@SerializedName("pressure_in") val pressureIn: Double,
@SerializedName("pressure_mb") val pressureMb: Double,
@SerializedName("temp_c") val tempC: Double,
@SerializedName("temp_f") val tempF: Double,
@SerializedName("time") val time: String,
@SerializedName("time_epoch") val timeEpoch: Int,
@SerializedName("uv") val uv: Double,
@SerializedName("vis_km") val visKm: Double,
@SerializedName("vis_miles") val visMiles: Double,
@SerializedName("will_it_rain") val willItRain: Int,
@SerializedName("will_it_snow") val willItSnow: Int,
@SerializedName("wind_degree") val windDegree: Int,
@SerializedName("wind_dir") val windDir: String,
@SerializedName("wind_kph") val windKph: Double,
@SerializedName("wind_mph") val windMph: Double,
@SerializedName("windchill_c") val windchillC: Double,
@SerializedName("windchill_f") val windchillF: Double
) {
/**
* Condition
*
* @property code
* @property icon
* @property text
* @constructor Create empty Condition
*/
data class Condition(
@SerializedName("code") val code: Int,
@SerializedName("icon") val icon: String,
@SerializedName("text") val text: String
)
}
}
}
/**
* Location
*
* @property country
* @property lat
* @property localtime
* @property localtimeEpoch
* @property lon
* @property name
* @property region
* @property tzId
* @constructor Create empty Location
*/
data class Location(
@SerializedName("country") val country: String,
@SerializedName("lat") val lat: Double,
@SerializedName("localtime") val localtime: String,
@SerializedName("localtime_epoch") val localtimeEpoch: Int,
@SerializedName("lon") val lon: Double,
@SerializedName("name") val name: String,
@SerializedName("region") val region: String,
@SerializedName("tz_id") val tzId: String
)
}
/**
* To weather
*
* @return
*/
fun ForecastResponse.toWeather(): Weather = Weather(
temperature = current.tempC.toInt(),
date = forecast.forecastday[0].date,
wind = current.windKph.toInt(),
humidity = current.humidity,
feelsLike = current.feelslikeC.toInt(),
condition = current.condition,
uv = current.uv.toInt(),
name = location.name,
forecasts = forecast.forecastday.map { networkForecastday ->
networkForecastday.toWeatherForecast()
}
)
/**
* To weather forecast
*
* @return
*/
fun NetworkForecastday.toWeatherForecast(): Forecast = Forecast(
date = date,
maxTemp = day.maxtempC.toInt().toString(),
minTemp = day.mintempC.toInt().toString(),
sunrise = astro.sunrise,
sunset = astro.sunset,
icon = day.condition.icon,
hour = hour.map { networkHour ->
networkHour.toHour()
}
)
/**
* To hour
*
* @return
*/
fun NetworkForecastday.NetworkHour.toHour(): Hour = Hour(
time = time,
icon = condition.icon,
temperature = tempC.toInt().toString(),
) | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/data/model/ForecastResponse.kt | 2308023667 |
package himanshu.benjwal.weather
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
import timber.log.Timber
import timber.log.Timber.Forest.plant
@HiltAndroidApp
class WeatherApplication : Application() {
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
plant(Timber.DebugTree())
}
}
} | WeatherAppSample/app/src/main/java/himanshu/benjwal/weather/WeatherApplication.kt | 1078930391 |
package com.example.flutter_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| Develop/Dart/flutter_app/android/app/src/main/kotlin/com/example/flutter_app/MainActivity.kt | 2067279882 |
package com.example.jettodo
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.jettodo", appContext.packageName)
}
} | Develop/AndroidStudioProjects/GetCal/app/src/androidTest/java/com/example/jettodo/ExampleInstrumentedTest.kt | 2836936559 |
package com.example.jettodo
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)
}
} | Develop/AndroidStudioProjects/GetCal/app/src/test/java/com/example/jettodo/ExampleUnitTest.kt | 130015116 |
package com.example.jettodo
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import java.time.Month
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
private val taskDao: TaskDao,
) : ViewModel() {
var title by mutableStateOf("")
var description by mutableStateOf("")
var calorie by mutableStateOf(0)
var isShowDialog by mutableStateOf(false)
var tabSelected by mutableStateOf(Screen.CALORIE)
private var editingTask: Task? = null
// New or Update task
val isEditing: Boolean
get() = editingTask != null
// Day task
fun setEditingTask(
task: Task,
) {
editingTask = task
title = task.title
description = task.description
calorie = task.calorie
}
// Task data
val tasks = taskDao.loadAllTask().distinctUntilChanged()
// DAY
fun createTask() {
// insertTask is suspend
viewModelScope.launch {
val newTask = Task(title = title, description = description, calorie = calorie)
taskDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteTask(task: Task) {
viewModelScope.launch {
taskDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateTask() {
editingTask?.let { task ->
viewModelScope.launch {
task.title = title
task.description = description
task.calorie = calorie
taskDao.updateTask(task)
}
}
}
fun resetProperties() {
editingTask = null
title = ""
description = ""
calorie = 0
}
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/MainViewModel.kt | 574445058 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/ui/theme/Shape.kt | 1694886992 |
package com.example.jettodo.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/ui/theme/Color.kt | 1957149236 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun JetToDoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/ui/theme/Theme.kt | 2880959256 |
package com.example.jettodo.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/ui/theme/Type.kt | 3646947797 |
package com.example.jettodo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application() {
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/App.kt | 3361042148 |
package com.example.jettodo
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.jettodo.components.*
import com.example.jettodo.ui.theme.JetToDoTheme
import dagger.hilt.android.AndroidEntryPoint
import java.time.DayOfWeek
import java.time.Year
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetToDoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Row(
modifier = Modifier.padding(5.dp),
verticalAlignment = Alignment.Top,
) {
// Tab
TabScreen()
}
}
}
}
}
}
@Composable
fun TabScreen(viewModel: MainViewModel = hiltViewModel()) {
Column {
TabRow(
selectedTabIndex = viewModel.tabSelected.ordinal,
backgroundColor = Color.LightGray,
contentColor = Color.Red,
modifier = Modifier.align(androidx.compose.ui.Alignment.Start,)
) {
Screen.values().map { it.name }.forEachIndexed { index, title ->
Tab(
text = { Text(text = "LIST") },
selected = viewModel.tabSelected.ordinal == index,
onClick = { viewModel.tabSelected = Screen.values()[index] },
unselectedContentColor = Color.Blue
)
}
}
MainContent()
}
}
enum class Screen {
CALORIE
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainContent(viewModel: MainViewModel = hiltViewModel()) {
if (viewModel.isShowDialog) {
EditDialog()
}
Scaffold(floatingActionButton = {
FloatingActionButton(onClick = { viewModel.isShowDialog = true }) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Create new")
}
})
{
val tasks by viewModel.tasks.collectAsState(initial = emptyList())
if (viewModel.tabSelected == Screen.CALORIE) {
TaskList(
tasks = tasks,
onClickRow = {
viewModel.setEditingTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteTask(it) },
)
}
}
}
| Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/MainActivity.kt | 4183745259 |
package com.example.jettodo
import android.content.Context
import androidx.room.Room
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@dagger.Module
@InstallIn(SingletonComponent::class)
object Module {
@Provides
fun provideDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabase::class.java, "task_database").build()
@Provides
fun provideDao(db: AppDatabase) = db.taskDao()
}
| Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/Module.kt | 3977477113 |
package com.example.jettodo.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import com.example.jettodo.Task
@Composable
fun TaskList(
tasks:List<Task>,
onClickRow:(Task) -> Unit,
onClickDelete:(Task) -> Unit,
){
LazyColumn {
items(tasks) { task ->
TaskRow(
task = task,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
}
| Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/components/TaskList.kt | 2096301942 |
package com.example.jettodo.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.MainViewModel
import com.example.jettodo.Screen
@Composable
fun EditDialog(viewModel: MainViewModel = hiltViewModel()) {
DisposableEffect(Unit)
{
// Called when the dialog is closed
onDispose {
viewModel.resetProperties()
}
}
AlertDialog(
// Tap outside the screen
onDismissRequest = { viewModel.isShowDialog = false },
title = {
Text(
text =
if (viewModel.isEditing) {
GetEditText("update")
} else {
GetEditText("create")
}
)
},
text = {
Column {
Text(text = "Title")
TextField(
value = viewModel.title,
onValueChange = { viewModel.title = it }
)
Text(text = "Detail")
TextField(
value = viewModel.description,
onValueChange = { viewModel.description = it }
)
Text(text = "Calory")
// TextField(
// value = viewModel.calorie.toString(),
// onValueChange = { viewModel.calorie = 0 },
// keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
// )
}
},
buttons = {
Row(
modifier = Modifier.padding(8.dp),
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = { viewModel.isShowDialog = false }
) {
Text(text = "Cancel")
}
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {
viewModel.isShowDialog = false
if (viewModel.isEditing && viewModel.tabSelected == Screen.CALORIE) {
viewModel.updateTask()
} else {
if (viewModel.tabSelected == Screen.CALORIE) {
viewModel.createTask()
}
}
}
) {
Text(text = if (viewModel.isEditing) "Update" else "Create")
}
}
},
)
}
@Composable
fun GetEditText(
kind: String,
viewModel: MainViewModel = hiltViewModel()
): String {
var text: String
if (viewModel.tabSelected == Screen.CALORIE) {
text = "Day task"
} else {
text = "Day task"
}
return text + " " + kind
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/components/EditDialog.kt | 803508431 |
package com.example.jettodo.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jettodo.Task
@Composable
fun TaskRow(
task: Task,
onClickRow: (Task) -> Unit,
onClickDelete: (Task) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Preview
@Composable
fun TaskRowPreview(){
TaskRow(
task = Task(title = "preview", description = "", calorie = 0),
onClickRow = {},
) {}
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/components/TaskRow.kt | 4250812122 |
package com.example.jettodo
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/AppDatabase.kt | 3995376048 |
package com.example.jettodo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Task(
// DataEntity is an object for operating sqlite
// Table structure
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
var calorie: Int
)
| Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/Task.kt | 2936678856 |
package com.example.jettodo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface TaskDao {
// suspend is an asynchronous process
// Defined by annotation
@Insert
suspend fun insertTask(task: Task)
@Query("SELECT * FROM Task")
fun loadAllTask(): Flow<List<Task>>
@Update
suspend fun updateTask(task: Task)
@Delete
suspend fun deleteTask(task: Task)
} | Develop/AndroidStudioProjects/GetCal/app/src/main/java/com/example/jettodo/TaskDao.kt | 1453956965 |
package com.example.jettodo
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.jettodo", appContext.packageName)
}
} | Develop/AndroidStudioProjects/Cal/app/src/androidTest/java/com/example/jettodo/ExampleInstrumentedTest.kt | 2836936559 |
package com.example.jettodo
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)
}
} | Develop/AndroidStudioProjects/Cal/app/src/test/java/com/example/jettodo/ExampleUnitTest.kt | 130015116 |
package com.example.jettodo
import android.util.Log
import androidx.compose.material.Colors
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(private val callistdao: CalListDao) :ViewModel() {
var title by mutableStateOf("")
var description by mutableStateOf("")
var calorie by mutableStateOf("")
var isShowDialog by mutableStateOf(false)
private var editingCalList:CalList?= null
// New or Update callist
val isEditing:Boolean
get() = editingCalList != null
fun setEditingCalList(callist: CalList){
editingCalList = callist
title = callist.title
description = callist.description
calorie = callist.calorie
}
// CalList data
val callists = callistdao.loadAllTask().distinctUntilChanged()
fun createTask(){
// insertList is suspend
viewModelScope.launch {
val newTask = CalList(title = title, description = description, calorie = calorie)
callistdao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create callist")
}
}
fun deleteTask (callist: CalList){
viewModelScope.launch {
callistdao.deleteTask(callist)
Log.d(MainViewModel::class.simpleName, "success delete callistdao")
}
}
fun updateTask(){
editingCalList?.let{ callist ->
viewModelScope.launch {
callist.title = title
callist.description = description
callist.calorie = calorie
callistdao.updateTask(callist)
}
}
}
fun resetProperties()
{
editingCalList = null
title = ""
description = ""
calorie = ""
}
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/MainViewModel.kt | 1312732250 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/ui/theme/Shape.kt | 1694886992 |
package com.example.jettodo.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/ui/theme/Color.kt | 1957149236 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun JetToDoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/ui/theme/Theme.kt | 2880959256 |
package com.example.jettodo.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/ui/theme/Type.kt | 3646947797 |
package com.example.jettodo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application() {
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/App.kt | 3361042148 |
package com.example.jettodo
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.components.EditDialog
import com.example.jettodo.components.CalList
import com.example.jettodo.ui.theme.JetToDoTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(
savedInstanceState: Bundle?,
) {
super.onCreate(savedInstanceState)
setContent {
JetToDoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Row(
modifier = Modifier.padding(5.dp),
verticalAlignment = Alignment.Top,
) {
// Tab
CalorieScreen()
}
}
}
}
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainContent(
viewModel: MainViewModel = hiltViewModel(),
darkTheme: Boolean = isSystemInDarkTheme(),
) {
if (viewModel.isShowDialog) {
EditDialog()
}
Scaffold(
floatingActionButtonPosition = FabPosition.Center,
floatingActionButton = {
FloatingActionButton(
onClick = { viewModel.isShowDialog = true },
backgroundColor = Color.DarkGray,
contentColor = Color.White,
shape = MaterialTheme.shapes.small,
modifier = Modifier.height(50.dp).fillMaxWidth()
) {
Row(
modifier = Modifier.padding(
vertical = 5.dp,
horizontal = 10.dp,
)
) {
Text(
text = "ADD MENU",
fontSize = 20.sp,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.W300,
)
}
}
}
) {
val callists by viewModel.callists.collectAsState(initial = emptyList())
// tatal calorie
var cnt:Int = 0
callists.forEach { elem ->
if (!elem.calorie.isNullOrEmpty()){
var cal = elem.calorie.toIntOrNull()
if (cal != null){
cnt += cal
}
}
}
var cal = cnt.toString()
Column(
modifier = Modifier.padding(
vertical = 5.dp,
horizontal = 5.dp,
)
) {
Spacer(modifier = Modifier.height(20.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
){
Text(
text = "Total Calorie",
modifier = Modifier.padding(
vertical = 0.dp,
horizontal = 20.dp,
),
fontSize = 20.sp,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.W300,
)
Text(
text = cal,
modifier = Modifier.padding(
vertical = 3.dp,
horizontal = 20.dp,
),
fontSize = 35.sp,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.Bold,
lineHeight = TextUnit.Unspecified,
color = if(darkTheme) {
Color.Cyan
}else{
Color.Blue
}
)
Row(
horizontalArrangement = Arrangement.End,
) {
Text(
text = "kcal",
modifier = Modifier.padding(
vertical = 0.dp,
horizontal = 0.dp,
),
fontSize = 20.sp,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.W300,
)
}
}
Spacer(modifier = Modifier.height(20.dp))
CalList(
callists = callists,
onClickRow = {
viewModel.setEditingCalList(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteTask(it) },
)
Spacer(modifier = Modifier.height(20.dp))
}
}
}
@Composable
fun CalorieScreen() {
var tabSelected by rememberSaveable { mutableStateOf(Screen.CALST) }
Column {
TabRow(
selectedTabIndex = tabSelected.ordinal,
backgroundColor = Color.DarkGray,
contentColor = Color.White,
modifier = Modifier.height(80.dp)
) {
Screen.values().map { it.name }.forEachIndexed { index, title ->
Tab(
text = {
Text(
text = title,
modifier = Modifier.padding(
vertical = 0.dp,
horizontal = 20.dp,
),
fontSize = 40.sp,
fontFamily = FontFamily.Cursive,
fontWeight = FontWeight.W100,
)
},
selected = tabSelected.ordinal == index,
onClick = { tabSelected = Screen.values()[index] },
)
}
}
when (tabSelected) {
Screen.CALST -> CalScreen()
}
}
}
enum class Screen {
CALST
}
@Composable
fun CalScreen() {
MainContent()
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/MainActivity.kt | 2083502098 |
package com.example.jettodo
import android.content.Context
import androidx.room.Room
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@dagger.Module
@InstallIn(SingletonComponent::class)
object Module {
@Provides
fun provideDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabaseCalList::class.java, "caList_database").build()
@Provides
fun provideDao(db: AppDatabaseCalList) = db.callistDao()
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/Module.kt | 3880057746 |
package com.example.jettodo.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.room.Delete
import com.example.jettodo.CalList
import com.example.jettodo.MainViewModel
@Composable
fun CalList(
callists:List<CalList>,
onClickRow:(CalList) -> Unit,
onClickDelete:(CalList) -> Unit,
){
LazyColumn {
items(callists) { callist ->
CalListRow(
calList = callist,
onClickRow = onClickRow,
onClickDelete = onClickDelete
)
}
}
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/components/TaskList.kt | 2820651540 |
package com.example.jettodo.components
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.MainViewModel
@Composable
fun EditDialog(viewModel: MainViewModel = hiltViewModel(), ){
DisposableEffect(Unit)
{
// Called when the dialog is closed
onDispose {
viewModel.resetProperties()
}
}
AlertDialog(
// Tap outside the screen
onDismissRequest = {viewModel.isShowDialog = false},
title = { Text(text = if(viewModel.isEditing)"Menu Update" else "Add Menu")},
text = {
Column {
Text(text = "Menu")
TextField(
value = viewModel.title,
onValueChange = {viewModel.title = it}
)
Text(text = "Calorie")
TextField(
value = viewModel.calorie,
onValueChange = {viewModel.calorie = it},
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number)
)
Text(text = "Detail")
TextField(
value = viewModel.description,
onValueChange = {viewModel.description = it}
)
}
},
buttons = {
Row(
modifier = Modifier.padding(8.dp),
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {viewModel.isShowDialog = false}
){
Text(text = "Cancel")
}
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {
viewModel.isShowDialog = false
if(viewModel.isEditing){
viewModel.updateTask()
} else {
viewModel.createTask()
}
}
){
Text(text = if(viewModel.isEditing)"Update" else "Create")
}
}
},
)
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/components/EditDialog.kt | 2650678096 |
package com.example.jettodo.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
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.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
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 androidx.room.Delete
import com.example.jettodo.CalList
@Composable
fun CalListRow(
calList: CalList,
onClickRow: (CalList) -> Unit,
onClickDelete: (CalList) -> Unit,
darkTheme: Boolean = isSystemInDarkTheme(),
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(calList) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp),
/*.clickable { onClickRow(task) }*/
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = calList.calorie,
fontWeight = FontWeight.Bold,
color = if(darkTheme) {
Color.Magenta
}else{
Color.Red
},
fontSize = 25.sp,
fontStyle = FontStyle.Italic,
)
Text(
text = " kcal",
fontWeight = FontWeight.Bold,
color = Color.Gray,
fontSize = 20.sp,
fontStyle = FontStyle.Italic,
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = calList.title,
fontWeight = FontWeight.Bold,
color = Color.Gray,
fontSize = 17.sp,
fontStyle = FontStyle.Normal,
fontFamily = FontFamily.Monospace,
)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(calList) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Preview
@Composable
fun TaskRowPreview() {
CalListRow(
calList = CalList(title = "preview", description = "", calorie = ""),
onClickRow = {},
onClickDelete = {},
)
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/components/TaskRow.kt | 265323166 |
package com.example.jettodo
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [CalList::class], version = 1, exportSchema = false)
abstract class AppDatabaseCalList : RoomDatabase() {
abstract fun callistDao(): CalListDao
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/AppDatabase.kt | 4142173568 |
package com.example.jettodo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class CalList(
// DataEntity is an object for operating sqlite
// Table structure
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
var calorie:String
)
| Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/Task.kt | 2109059994 |
package com.example.jettodo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface CalListDao {
// suspend is an asynchronous process
// Defined by annotation
@Insert
suspend fun insertTask(callist: CalList)
@Query("SELECT * FROM CalList")
fun loadAllTask(): Flow<List<CalList>>
@Update
suspend fun updateTask(callist: CalList)
@Delete
suspend fun deleteTask(callist: CalList)
} | Develop/AndroidStudioProjects/Cal/app/src/main/java/com/example/jettodo/TaskDao.kt | 1091939901 |
package com.example.jettodo
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.jettodo", appContext.packageName)
}
} | Develop/AndroidStudioProjects/ToDoList/app/src/androidTest/java/com/example/jettodo/ExampleInstrumentedTest.kt | 2836936559 |
package com.example.jettodo
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)
}
} | Develop/AndroidStudioProjects/ToDoList/app/src/test/java/com/example/jettodo/ExampleUnitTest.kt | 130015116 |
package com.example.jettodo
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(private val taskDao: TaskDao) :ViewModel() {
var title by mutableStateOf("")
var description by mutableStateOf("")
var isShowDialog by mutableStateOf(false)
private var editingTask:Task?= null
// New or Update task
val isEditing:Boolean
get() = editingTask != null
fun setEditingTask(task: Task){
editingTask = task
title = task.title
description = task.description
}
// Task data
val tasks = taskDao.loadAllTask().distinctUntilChanged()
fun createTask(){
// insertTask is suspend
viewModelScope.launch {
val newTask = Task(title = title, description = description)
taskDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteTask (task: Task){
viewModelScope.launch {
taskDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateTask(){
editingTask?.let{ task ->
viewModelScope.launch {
task.title = title
task.description = description
taskDao.updateTask(task)
}
}
}
fun resetProperties()
{
editingTask = null
title = ""
description = ""
}
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/MainViewModel.kt | 1524667605 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/ui/theme/Shape.kt | 1694886992 |
package com.example.jettodo.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5) | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/ui/theme/Color.kt | 1957149236 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun JetToDoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/ui/theme/Theme.kt | 2880959256 |
package com.example.jettodo.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/ui/theme/Type.kt | 3646947797 |
package com.example.jettodo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application() {
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/App.kt | 3361042148 |
package com.example.jettodo
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.components.EditDialog
import com.example.jettodo.components.TaskList
import com.example.jettodo.ui.theme.JetToDoTheme
import dagger.hilt.android.AndroidEntryPoint
import java.time.DayOfWeek
import java.time.Year
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
JetToDoTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Row(
modifier = Modifier.padding(5.dp),
verticalAlignment = Alignment.Top,
) {
// Tab
StudyReportScreen()
}
}
}
}
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainContent(viewModel:MainViewModel = hiltViewModel()) {
if (viewModel.isShowDialog){
EditDialog()
}
Scaffold(floatingActionButton = {
FloatingActionButton(onClick = {viewModel.isShowDialog = true}){
Icon(imageVector = Icons.Default.Add, contentDescription = "Create new")
}
}) {
val tasks by viewModel.tasks.collectAsState(initial = emptyList())
TaskList(
tasks = tasks,
onClickRow = {
viewModel.setEditingTask(it)
viewModel.isShowDialog = true
},
onClickDelete = { viewModel.deleteTask(it) },
)
}
}
@Composable
fun StudyReportScreen() {
var tabSelected by rememberSaveable { mutableStateOf(Screen.DAY) }
Column {
TabRow(
selectedTabIndex = tabSelected.ordinal,
backgroundColor = Color.LightGray,
contentColor = Color.Blue,
) {
Screen.values().map { it.name }.forEachIndexed { index, title ->
Tab(
text = { Text(text = title) },
selected = tabSelected.ordinal == index,
onClick = { tabSelected = Screen.values()[index] }
)
}
}
when (tabSelected) {
Screen.DAY -> DayScreen()
Screen.WEEK -> WeekScreen()
Screen.MONTH -> MonthScreen()
Screen.YEAR -> YaerScreen()
}
}
}
enum class Screen {
DAY, WEEK, MONTH, YEAR
}
@Composable
fun DayScreen() {
MainContent()
}
@Composable
fun WeekScreen() {
MainContent()
}
@Composable
fun MonthScreen(){
MainContent()
}
@Composable
fun YaerScreen(){
MainContent()
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/MainActivity.kt | 3848544736 |
package com.example.jettodo
import android.content.Context
import androidx.room.Room
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@dagger.Module
@InstallIn(SingletonComponent::class)
object Module {
@Provides
fun provideDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(context, AppDatabase::class.java, "task_database").build()
@Provides
fun provideDao(db: AppDatabase) = db.taskDao()
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/Module.kt | 2761075116 |
package com.example.jettodo.components
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.room.Delete
import com.example.jettodo.Task
@Composable
fun TaskList(
tasks:List<Task>,
onClickRow:(Task) -> Unit,
onClickDelete:(Task) -> Unit,
){
LazyColumn {
items(tasks) { task ->
TaskRow(
task = task,
onClickRow = onClickRow,
onClickDelete = onClickDelete)
}
}
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/components/TaskList.kt | 2329623240 |
package com.example.jettodo.components
import androidx.compose.foundation.layout.*
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.jettodo.MainViewModel
@Composable
fun EditDialog(viewModel: MainViewModel = hiltViewModel(), ){
DisposableEffect(Unit)
{
// Called when the dialog is closed
onDispose {
viewModel.resetProperties()
}
}
AlertDialog(
// Tap outside the screen
onDismissRequest = {viewModel.isShowDialog = false},
title = { Text(text = if(viewModel.isEditing)"Task update" else "Task create")},
text = {
Column {
Text(text = "Title")
TextField(
value = viewModel.title,
onValueChange = {viewModel.title = it}
)
Text(text = "Detail")
TextField(
value = viewModel.description,
onValueChange = {viewModel.description = it}
)
}
},
buttons = {
Row(
modifier = Modifier.padding(8.dp),
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {viewModel.isShowDialog = false}
){
Text(text = "Cancel")
}
Spacer(modifier = Modifier.weight(1f))
Button(
modifier = Modifier.width(120.dp),
onClick = {
viewModel.isShowDialog = false
if(viewModel.isEditing){
viewModel.updateTask()
} else {
viewModel.createTask()
}
}
){
Text(text = if(viewModel.isEditing)"Update" else "Create")
}
}
},
)
}
| Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/components/EditDialog.kt | 2783197392 |
package com.example.jettodo.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.room.Delete
import com.example.jettodo.Task
@Composable
fun TaskRow(
task:Task,
onClickRow:(Task) -> Unit,
onClickDelete:(Task) -> Unit,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.clickable { onClickRow(task) },
elevation = 5.dp,
) {
Row(
modifier = Modifier
.padding(10.dp)
/*.clickable { onClickRow(task) }*/,
verticalAlignment = Alignment.CenterVertically,
){
Text(text = task.title)
Spacer(modifier = Modifier.weight(1f))
IconButton(onClick = { onClickDelete(task) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete")
}
}
}
}
@Preview
@Composable
fun TaskRowPreview(){
TaskRow(
task = Task(title = "preview", description = ""),
onClickRow = {},
onClickDelete = {},
)
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/components/TaskRow.kt | 1233591071 |
package com.example.jettodo
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/AppDatabase.kt | 3995376048 |
package com.example.jettodo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Task(
// DataEntity is an object for operating sqlite
// Table structure
@PrimaryKey(autoGenerate = true) val id: Int = 0,
var title: String,
var description: String,
)
| Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/Task.kt | 3919697217 |
package com.example.jettodo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface TaskDao {
// suspend is an asynchronous process
// Defined by annotation
@Insert
suspend fun insertTask(task: Task)
@Query("SELECT * FROM Task")
fun loadAllTask(): Flow<List<Task>>
@Update
suspend fun updateTask(task: Task)
@Delete
suspend fun deleteTask(task: Task)
} | Develop/AndroidStudioProjects/ToDoList/app/src/main/java/com/example/jettodo/TaskDao.kt | 414021510 |
package com.example.jettodo
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.jettodo", appContext.packageName)
}
} | Develop/AndroidStudioProjects/KindTodo/app/src/androidTest/java/com/example/jettodo/ExampleInstrumentedTest.kt | 2836936559 |
package com.example.jettodo
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)
}
} | Develop/AndroidStudioProjects/KindTodo/app/src/test/java/com/example/jettodo/ExampleUnitTest.kt | 130015116 |
package com.example.jettodo
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import java.time.Month
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
private val taskDao: TaskDao,
private val weekDao: WeekTaskDao,
private val monthDao: MonthTaskDao,
private val yearDao: YearTaskDao,
) : ViewModel() {
var title by mutableStateOf("")
var description by mutableStateOf("")
var isShowDialog by mutableStateOf(false)
var tabSelected by mutableStateOf(Screen.DAY)
private var editingTask: Task? = null
private var editingWeekTask: WeekTask? = null
private var editingMonthTask: MonthTask? = null
private var editingYearTask: YearTask? = null
// New or Update task
val isEditing: Boolean
get() = editingTask != null
val isEditingWeek: Boolean
get() = editingWeekTask != null
val isEditingMonth: Boolean
get() = editingMonthTask != null
val isEditingYear: Boolean
get() = editingYearTask != null
// Day task
fun setEditingTask(
task: Task,
) {
editingTask = task
title = task.title
description = task.description
}
// Week task
fun setEditingWeekTask(
weekTask: WeekTask,
) {
editingWeekTask = weekTask
title = weekTask.title
description = weekTask.description
}
// Month task
fun setEditingMonthTask(
monthTask: MonthTask,
) {
editingMonthTask = monthTask
title = monthTask.title
description = monthTask.description
}
// Year task
fun setEditingYearTask(
yearTask: YearTask,
) {
editingYearTask = yearTask
title = yearTask.title
description = yearTask.description
}
// Task data
val tasks = taskDao.loadAllTask().distinctUntilChanged()
val tasksWeek = weekDao.loadAllTask().distinctUntilChanged()
val tasksMonth = monthDao.loadAllTask().distinctUntilChanged()
val tasksYear = yearDao.loadAllTask().distinctUntilChanged()
// DAY
fun createTask() {
// insertTask is suspend
viewModelScope.launch {
val newTask = Task(title = title, description = description)
taskDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteTask(task: Task) {
viewModelScope.launch {
taskDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateTask() {
editingTask?.let { task ->
viewModelScope.launch {
task.title = title
task.description = description
taskDao.updateTask(task)
}
}
}
// WEEK
fun createWeekTask() {
viewModelScope.launch {
val newTask = WeekTask(title = title, description = description)
weekDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteWeekTask(task: WeekTask) {
viewModelScope.launch {
weekDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateWeekTask() {
editingWeekTask?.let { task ->
viewModelScope.launch {
task.title = title
task.description = description
weekDao.updateTask(task)
}
}
}
// MONTH
fun createMonthTask() {
viewModelScope.launch {
val newTask = MonthTask(title = title, description = description)
monthDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteMonthTask(task: MonthTask) {
viewModelScope.launch {
monthDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateMonthTask() {
editingMonthTask?.let { task ->
viewModelScope.launch {
task.title = title
task.description = description
monthDao.updateTask(task)
}
}
}
// YEAR
fun createYearTask() {
viewModelScope.launch {
val newTask = YearTask(title = title, description = description)
yearDao.insertTask(newTask)
Log.d(MainViewModel::class.simpleName, "success create task")
}
}
fun deleteYearTask(task: YearTask) {
viewModelScope.launch {
yearDao.deleteTask(task)
Log.d(MainViewModel::class.simpleName, "success delete task")
}
}
fun updateYearTask() {
editingYearTask?.let { task ->
viewModelScope.launch {
task.title = title
task.description = description
yearDao.updateTask(task)
}
}
}
fun resetProperties() {
editingTask = null
title = ""
description = ""
}
fun resetPropertiesWeek() {
editingWeekTask = null
title = ""
description = ""
}
fun resetPropertiesMonth() {
editingMonthTask = null
title = ""
description = ""
}
fun resetPropertiesYear() {
editingYearTask = null
title = ""
description = ""
}
} | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/MainViewModel.kt | 102572848 |
package com.example.jettodo.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | Develop/AndroidStudioProjects/KindTodo/app/src/main/java/com/example/jettodo/ui/theme/Shape.kt | 1694886992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.