content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.myapplication import android.content.Context import android.net.wifi.WifiManager import android.os.Build import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class EnableWifiLatest : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_enable_wifi_latest) enableWifi() } private fun enableWifi() { val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager if (!wifiManager.isWifiEnabled) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { wifiManager.startScan() } } wifiManager.isWifiEnabled = true } }
AndroidSem8/app/src/main/java/com/example/myapplication/EnableWifiLatest.kt
1251907445
package com.example.myapplication import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import android.location.LocationManager import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.provider.Settings import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.core.app.ActivityCompat import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import java.util.Locale class MainActivity10 : AppCompatActivity() { lateinit var latitude: TextView lateinit var longitude: TextView lateinit var country: TextView lateinit var locality: TextView lateinit var address: TextView lateinit var btnSubmit: Button lateinit var btnOpenMap: Button private lateinit var mFusedLocationClient: FusedLocationProviderClient private val permissionId = 2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main10) latitude = findViewById(R.id.latitude) longitude = findViewById(R.id.longtitude) country = findViewById(R.id.country) locality = findViewById(R.id.locality) address = findViewById(R.id.address) btnSubmit = findViewById(R.id.btnSubmit) btnOpenMap = findViewById(R.id.btnOpenMap) mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) btnSubmit.setOnClickListener { getLocation() } btnOpenMap.setOnClickListener { Handler().postDelayed({ val gmmIntentUri = Uri.parse("geo:0,0?q=") val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) mapIntent.setPackage("com.google.android.apps.maps") startActivity(mapIntent) }, 1000) } } private fun getLocation() { if (checkPermission()) { if (isLocationEnabled()) { mFusedLocationClient.lastLocation.addOnSuccessListener { location: Location? -> location?.let { val geocoder = Geocoder(this, Locale.getDefault()) val list: List<Address> = geocoder.getFromLocation(location.latitude, location.longitude, 1)!! latitude.text = "Latitude\n${list[0].latitude}" longitude.text = "Longitude\n${list[0].longitude}" country.text = "Country Name\n${list[0].countryName}" locality.text = "Locality\n${list[0].locality}" address.text = "Address\n${list[0].getAddressLine(0)}" } } } else { Toast.makeText(this, "Please turn on location", Toast.LENGTH_SHORT).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) } } else { requestPermissions() } } private fun isLocationEnabled(): Boolean { val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } private fun checkPermission(): Boolean { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { return true } return false } private fun requestPermissions() { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), permissionId) } @SuppressLint("MissingSuperCall") override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if(requestCode == permissionId) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { getLocation() } } } }
AndroidSem8/app/src/main/java/com/example/myapplication/MainActivity10.kt
2910693565
package com.example.myapplication import android.annotation.SuppressLint import android.bluetooth.BluetoothAdapter import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class BluetoothEnableDisable : AppCompatActivity() { @SuppressLint("MissingPermission") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bluetooth_enable_disable) val btnGet = findViewById<Button>(R.id.btnGet) val tv = findViewById<TextView>(R.id.tv) val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() btnGet.setOnClickListener { if (mBluetoothAdapter.isEnabled) { mBluetoothAdapter.disable() tv.text = "Bluetooth is OFF" } else { mBluetoothAdapter.enable() tv.text = "Bluetooth is ON" } } } }
AndroidSem8/app/src/main/java/com/example/myapplication/BluetoothEnableDisable.kt
3239167909
package com.example.myapplication import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class AcceloDemo : AppCompatActivity() { private var sm: SensorManager?= null private var textView: TextView ?= null private var list: List<Sensor> ?= null private val sel: SensorEventListener = object : SensorEventListener { override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} override fun onSensorChanged(event: SensorEvent?) { val values = event!!.values textView?.text = "x: ${values[0]}\ny: ${values[1]}\nz: ${values[2]}" } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_accelo_demo) sm = getSystemService(Context.SENSOR_SERVICE) as SensorManager textView = findViewById(R.id.textView) list = sm?.getSensorList(Sensor.TYPE_ACCELEROMETER) if (list?.isNotEmpty() == true) { sm?.registerListener(sel, list?.get(0), SensorManager.SENSOR_DELAY_NORMAL) } else { Toast.makeText(this, "Error: No Acceleromoter", Toast.LENGTH_SHORT).show() } } override fun onStop() { if (list?.isNotEmpty() == true) { sm?.unregisterListener(sel) } super.onStop() } }
AndroidSem8/app/src/main/java/com/example/myapplication/AcceloDemo.kt
159888764
package com.example.myapplication import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.view.MotionEvent import android.view.View class CustomViewFan(context: Context?) : View(context) { var p: Paint=Paint() var x = 100 var y = 20 override fun onDraw(canvas: Canvas) { canvas.drawColor(Color.BLACK) p.color = Color.GRAY canvas.drawRect(100f+y, 100f, 500f+y, 500f, p) p.color = Color.GRAY canvas.drawArc(500f, 500f, 800f, 800f, x.toFloat(), 30f,true, p) canvas.drawArc(500f, 500f, 800f, 800f, (x + 120).toFloat(), 30f, true, p) canvas.drawArc(500f, 500f, 800f, 800f, (x + 240).toFloat(), 30f, true, p) canvas.drawOval(200f, 500f+y, 500f, 600f+y, p) } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> startFan() MotionEvent.ACTION_UP -> stopFan() } return true } fun stopFan() { } fun startFan() { x = x + 5 y = y + 10 invalidate() } }
AndroidSem8/app/src/main/java/com/example/myapplication/CustomViewFan.kt
308978183
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException import com.google.firebase.auth.PhoneAuthCredential import com.google.firebase.auth.PhoneAuthProvider class Otp : AppCompatActivity() { // get reference of the firebase auth lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_otp) auth=FirebaseAuth.getInstance() // get storedVerificationId from the intent val storedVerificationId= intent.getStringExtra("storedVerificationId") // fill otp and call the on click on button findViewById<Button>(R.id.login).setOnClickListener { val otp = findViewById<EditText>(R.id.et_otp).text.trim().toString() if(otp.isNotEmpty()){ val credential : PhoneAuthCredential = PhoneAuthProvider.getCredential(storedVerificationId.toString(), otp) signInWithPhoneAuthCredential(credential) }else{ Toast.makeText(this,"Enter OTP", Toast.LENGTH_SHORT).show() } } } // verifies if the code matches sent by firebase if success start the new activity in our case it is main Activity private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) { auth.signInWithCredential(credential).addOnCompleteListener(this) { task -> if (task.isSuccessful) { val intent = Intent(this ,PhOtpMain::class.java) startActivity(intent) finish() } else { // Sign in failed, display a message and update the UI if (task.exception is FirebaseAuthInvalidCredentialsException) { // The verification code entered was invalid Toast.makeText(this,"Invalid OTP", Toast.LENGTH_SHORT).show() } } } } }
AndroidSem8/app/src/main/java/com/example/myapplication/Otp.kt
853701240
package com.example.myapplication import android.os.Bundle import android.webkit.WebSettings import android.webkit.WebView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity14 : AppCompatActivity() { private lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main14) webView = findViewById(R.id.webview) val webSettings: WebSettings = webView.settings webSettings.javaScriptEnabled = true webView.loadUrl("https://myhosieryshop.netlify.app/") } override fun onBackPressed() { if (webView.canGoBack()) { webView.goBack() } else { super.onBackPressed() } } }
AndroidSem8/app/src/main/java/com/example/myapplication/MainActivity14.kt
2033194117
package com.apps10x.weatherx 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.apps10x.weatherx", appContext.packageName) } }
WeatherX/app/src/androidTest/java/com/apps10x/weatherx/ExampleInstrumentedTest.kt
1092812198
package com.apps10x.weatherx.data import com.apps10x.weatherx.helpers.FORECASTS_LIST_SIZE import com.apps10x.weatherx.helpers.createMockForecastData import com.apps10x.weatherx.helpers.createMockWeatherResponse import com.apps10x.weatherx.network.WeatherApiService import com.apps10x.weatherx.utils.ApiResult import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations import retrofit2.Response class WeatherRepositoryTest { @Mock lateinit var weatherApiService: WeatherApiService private lateinit var weatherRepository: WeatherRepository @Before fun setup() { MockitoAnnotations.openMocks(this) weatherRepository = WeatherRepository(weatherApiService) } @Test fun `test getWeatherToday success`() { runBlocking { val city = "New York" val mockResponse = Response.success(createMockWeatherResponse(city, 0)) `when`(weatherApiService.getWeatherToday(city = city)).thenReturn(mockResponse) val result = weatherRepository.getWeatherToday(city) assert(result is ApiResult.Success) val data = (result as ApiResult.Success<WeatherResponse>).data assertEquals("New York", data?.city) // Add more assertions as needed } } @Test fun `test getWeatherForecast success`() { runBlocking { val city = "New York" val mockResponse = Response.success(createMockForecastData(city)) `when`(weatherApiService.getWeatherForecast(city = city)).thenReturn(mockResponse) val result = weatherRepository.getWeatherForecast(city) assert(result is ApiResult.Success) val data = (result as ApiResult.Success<WeatherForecastResponse>).data assertEquals(FORECASTS_LIST_SIZE, data?.list?.size) } } }
WeatherX/app/src/test/java/com/apps10x/weatherx/data/WeatherRepositoryTest.kt
2462701299
package com.apps10x.weatherx.domain import com.apps10x.weatherx.data.DailyWeatherForecast import com.apps10x.weatherx.data.WeatherForecastResponse import com.apps10x.weatherx.data.WeatherRepository import com.apps10x.weatherx.helpers.createMockForecastData import com.apps10x.weatherx.utils.ApiResult import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations import java.time.LocalDate class WeatherForecastsUseCaseTest { @Mock lateinit var weatherRepository: WeatherRepository private lateinit var weatherForecastsUseCase: WeatherForecastsUseCase companion object { private const val FORECAST_COUNT = 4L private const val NO_DATA_ERROR = "No data found" } @Before fun setup() { MockitoAnnotations.openMocks(this) weatherForecastsUseCase = WeatherForecastsUseCase(weatherRepository) } @Test fun `test successful retrieval of weather forecasts`() { runBlocking { val city = "New York" val mockForecastData = createMockForecastData(city) `when`(weatherRepository.getWeatherForecast(city)).thenReturn( ApiResult.Success(mockForecastData) ) val result = weatherForecastsUseCase(city) assert(result is ApiResult.Success) val data = (result as ApiResult.Success<List<DailyWeatherForecast>>).data // Ensure the correct number of daily weather forecasts is returned assertEquals(4, data?.size) val currentDate = LocalDate.now() // Ensure averages are correct mockForecastData.list.filter { it.date?.isAfter(currentDate) == true && (it.date ?: currentDate.plusDays( FORECAST_COUNT + 1 )) <= currentDate.plusDays(FORECAST_COUNT) }.groupBy { it.date }.values.forEachIndexed { i, it -> assertEquals( it.map { it.temperatureData.tempCelsius }.average(), data?.get(i)?.avgTemp ) } } } @Test fun `test no data error handling`() { runBlocking { val city = "Unknown City" `when`(weatherRepository.getWeatherForecast(city)).thenReturn( ApiResult.Success(WeatherForecastResponse(listOf())) ) val result = weatherForecastsUseCase(city) assert(result is ApiResult.Error) assertEquals(NO_DATA_ERROR, (result as ApiResult.Error).error) } } @Test fun `test error handling`() { runBlocking { val city = "Unknown City" `when`(weatherRepository.getWeatherForecast(city)).thenReturn(ApiResult.Error("error message")) val result = weatherForecastsUseCase(city) assert(result is ApiResult.Error) assertEquals("error message", (result as ApiResult.Error).error) } } }
WeatherX/app/src/test/java/com/apps10x/weatherx/domain/WeatherForecastsUseCaseTest.kt
1899524382
package com.apps10x.weatherx.helpers import com.apps10x.weatherx.data.Temperature import com.apps10x.weatherx.data.WeatherForecastResponse import com.apps10x.weatherx.data.WeatherResponse import java.time.LocalDate import java.time.format.DateTimeFormatter import kotlin.random.Random const val FORECASTS_LIST_SIZE = 40 fun createMockWeatherResponse(city: String, i: Int): WeatherResponse { val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") return WeatherResponse( city, Temperature(Random.nextDouble(296.0, 313.0)), formatter.format(LocalDate.now().plusDays((i / 8).toLong()).atTime(i % 8, 0)) ) } fun createMockForecastData(city: String): WeatherForecastResponse { val forecasts = mutableListOf<WeatherResponse>() for (i in 0 until FORECASTS_LIST_SIZE) { forecasts.add(createMockWeatherResponse(city, i)) } return WeatherForecastResponse(forecasts) }
WeatherX/app/src/test/java/com/apps10x/weatherx/helpers/MockData.kt
851585668
package com.apps10x.weatherx.ui import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.apps10x.weatherx.data.DailyWeatherForecast import com.apps10x.weatherx.data.WeatherRepository import com.apps10x.weatherx.data.WeatherResponse import com.apps10x.weatherx.domain.WeatherForecastsUseCase import com.apps10x.weatherx.utils.ApiResult import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class WeatherViewModel @Inject constructor( private val repository: WeatherRepository, ) : ViewModel() { private val _weatherTodayResponse = MutableLiveData<ApiResult<WeatherResponse>>() val weatherTodayResponse: LiveData<ApiResult<WeatherResponse>> = _weatherTodayResponse private val _dailyAverageForecasts = MutableLiveData<ApiResult<List<DailyWeatherForecast>>?>() val dailyAverageForecasts: LiveData<ApiResult<List<DailyWeatherForecast>>?> = _dailyAverageForecasts fun getWeatherToday(city: String) { viewModelScope.launch { _weatherTodayResponse.postValue(repository.getWeatherToday(city)) } } fun getWeatherForecast(city: String) = viewModelScope.launch { _dailyAverageForecasts.postValue(WeatherForecastsUseCase(repository).invoke(city)) } }
WeatherX/app/src/main/java/com/apps10x/weatherx/ui/WeatherViewModel.kt
1249037164
package com.apps10x.weatherx.ui.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.apps10x.weatherx.data.DailyWeatherForecast import com.apps10x.weatherx.databinding.ItemWeatherForecastBinding import com.apps10x.weatherx.ui.viewholders.WeatherForecastViewHolder class WeatherForecastAdapter( private val aysAvgWeatherList: List<DailyWeatherForecast>, ) : RecyclerView.Adapter<WeatherForecastViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherForecastViewHolder = WeatherForecastViewHolder( ItemWeatherForecastBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun getItemCount() = aysAvgWeatherList.size override fun onBindViewHolder(holder: WeatherForecastViewHolder, position: Int) { holder.bind(aysAvgWeatherList[position]) } }
WeatherX/app/src/main/java/com/apps10x/weatherx/ui/adapters/WeatherForecastAdapter.kt
975359594
package com.apps10x.weatherx.ui import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.recyclerview.widget.LinearLayoutManager import com.apps10x.weatherx.R import com.apps10x.weatherx.databinding.ActivityWeatherBinding import com.apps10x.weatherx.ui.adapters.WeatherForecastAdapter import com.apps10x.weatherx.utils.ApiResult import com.apps10x.weatherx.utils.hide import com.apps10x.weatherx.utils.setTextAndShow import com.apps10x.weatherx.utils.show import com.apps10x.weatherx.utils.showIndefiniteSnackBarWithAction import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class WeatherActivity : AppCompatActivity() { private var _binding: ActivityWeatherBinding? = null private val binding get() = _binding!! private val weatherViewModel: WeatherViewModel by viewModels() companion object { private const val CITY = "Bengaluru" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() _binding = ActivityWeatherBinding.inflate(layoutInflater) setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } setObservers() getWeatherData() } private fun getWeatherData() { binding.loader.show() weatherViewModel.getWeatherToday(CITY) weatherViewModel.getWeatherForecast(CITY) } private fun setObservers() { weatherViewModel.weatherTodayResponse.observe(this) { binding.loader.hide() when (it) { is ApiResult.Success -> { binding.tvTemperature.setTextAndShow( getString( R.string.temperature_celsius, it.data?.temperatureData?.tempCelsius?.toInt() ) ) binding.tvCity.setTextAndShow(it.data?.city) } is ApiResult.Error -> { binding.root.showIndefiniteSnackBarWithAction( it.error ?: getString(R.string.something_went_wrong), getString(R.string.retry), ) { weatherViewModel.getWeatherToday(CITY) } } } } weatherViewModel.dailyAverageForecasts.observe(this) { binding.loader.hide() when (it) { is ApiResult.Success -> { it.data?.let { forecasts -> binding.rvForecasts.apply { setHasFixedSize(true) adapter = WeatherForecastAdapter(forecasts) layoutManager = LinearLayoutManager(context) show() } } } is ApiResult.Error -> { binding.root.showIndefiniteSnackBarWithAction( it.error ?: getString(R.string.something_went_wrong), getString(R.string.retry), ) { weatherViewModel.getWeatherForecast(CITY) } } null -> { binding.root.showIndefiniteSnackBarWithAction( getString(R.string.something_went_wrong), getString(R.string.retry), ) { weatherViewModel.getWeatherForecast(CITY) } } } } } }
WeatherX/app/src/main/java/com/apps10x/weatherx/ui/WeatherActivity.kt
3162167235
package com.apps10x.weatherx.ui.viewholders import androidx.recyclerview.widget.RecyclerView import com.apps10x.weatherx.R import com.apps10x.weatherx.data.DailyWeatherForecast import com.apps10x.weatherx.databinding.ItemWeatherForecastBinding import com.apps10x.weatherx.utils.setTextAndShow class WeatherForecastViewHolder( private val binding: ItemWeatherForecastBinding, ) : RecyclerView.ViewHolder(binding.root) { fun bind(dailyWeatherForecast: DailyWeatherForecast?) { dailyWeatherForecast?.let { binding.tvDay.setTextAndShow(it.dayOfWeek) binding.tvTemperature.setTextAndShow( itemView.context.getString( R.string.temperature_celsius, it.avgTemp.toInt() ) ) } } }
WeatherX/app/src/main/java/com/apps10x/weatherx/ui/viewholders/WeatherForecastViewHolder.kt
1121627035
package com.apps10x.weatherx.di import com.apps10x.weatherx.BuildConfig import com.apps10x.weatherx.network.WeatherApiService import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class ApplicationModule { @Singleton @Provides fun providesOkHttpClient(): OkHttpClient = OkHttpClient .Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() @Singleton @Provides fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() return Retrofit.Builder() .baseUrl(BuildConfig.baseUrl) .addConverterFactory(MoshiConverterFactory.create(moshi).asLenient()) .client(okHttpClient) .build() } @Singleton @Provides fun provideWeatherApiService(retrofit: Retrofit): WeatherApiService = retrofit.create(WeatherApiService::class.java) }
WeatherX/app/src/main/java/com/apps10x/weatherx/di/ApplicationModule.kt
2311482667
package com.apps10x.weatherx.network import com.apps10x.weatherx.BuildConfig import com.apps10x.weatherx.data.WeatherForecastResponse import com.apps10x.weatherx.data.WeatherResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface WeatherApiService { @GET("weather") suspend fun getWeatherToday( @Query("APPID") apiKey: String = BuildConfig.appId, @Query("q") city: String, ): Response<WeatherResponse> @GET("forecast") suspend fun getWeatherForecast( @Query("APPID") apiKey: String = BuildConfig.appId, @Query("q") city: String, ): Response<WeatherForecastResponse> }
WeatherX/app/src/main/java/com/apps10x/weatherx/network/WeatherApiService.kt
2459382127
package com.apps10x.weatherx.utils import android.graphics.Color import android.view.View import android.widget.TextView import com.google.android.material.snackbar.Snackbar import retrofit2.Response import java.net.UnknownHostException fun View.hide() { visibility = View.GONE } fun View.show() { visibility = View.VISIBLE } fun TextView.setTextAndShow(value: String?) { if (value.isNullOrBlank()) hide() else { show() text = value } } fun View?.showIndefiniteSnackBarWithAction(message: String, action: String, onAction: () -> Unit) { this?.let { Snackbar.make(it, message, Snackbar.LENGTH_INDEFINITE) .setAnimationMode(Snackbar.ANIMATION_MODE_SLIDE) .setAction(action) { onAction.invoke() } .setTextColor(Color.BLACK) .setActionTextColor(Color.RED) .show() } } suspend inline fun <reified T : Any> doSafeApiRequest( crossinline call: suspend () -> Response<*>, ): ApiResult<T> { return try { call.invoke().let { response -> if (response.isSuccessful) { ApiResult.Success(response.body() as? T) } else { ApiResult.Error(error = response.message()) } } } catch (e: Exception) { return if (e is UnknownHostException) ApiResult.Error(error = "There is no internet connection. Connect to the internet and try again.") else { ApiResult.Error(error = null) } } }
WeatherX/app/src/main/java/com/apps10x/weatherx/utils/Extensions.kt
18660341
package com.apps10x.weatherx.utils sealed class ApiResult<out T : Any> { data class Success<out T : Any>(val data: T?) : ApiResult<T>() data class Error(val error: String?) : ApiResult<Nothing>() }
WeatherX/app/src/main/java/com/apps10x/weatherx/utils/ApiResult.kt
922587468
package com.apps10x.weatherx import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class WeatherXApplication : Application()
WeatherX/app/src/main/java/com/apps10x/weatherx/WeatherXApplication.kt
3204536192
package com.apps10x.weatherx.data import com.apps10x.weatherx.network.WeatherApiService import com.apps10x.weatherx.utils.doSafeApiRequest import javax.inject.Inject class WeatherRepository @Inject constructor(private val weatherApiService: WeatherApiService) { suspend fun getWeatherToday(city: String) = doSafeApiRequest<WeatherResponse> { weatherApiService.getWeatherToday(city = city) } suspend fun getWeatherForecast(city: String) = doSafeApiRequest<WeatherForecastResponse> { weatherApiService.getWeatherForecast(city = city) } }
WeatherX/app/src/main/java/com/apps10x/weatherx/data/WeatherRepository.kt
2263144558
package com.apps10x.weatherx.data import com.squareup.moshi.Json data class WeatherForecastResponse( @Json(name = "list") val list: List<WeatherResponse> )
WeatherX/app/src/main/java/com/apps10x/weatherx/data/WeatherForecastResponse.kt
669136620
package com.apps10x.weatherx.data import com.squareup.moshi.Json import java.time.LocalDate import java.time.format.DateTimeFormatter data class WeatherResponse( @Json(name = "name") val city: String?, @Json(name = "main") val temperatureData: Temperature, @Json(name = "dt_txt") val dateTimeText: String? ) { companion object { private const val DATE_PATTERN = "yyyy-MM-dd HH:mm:ss" } @Transient private val dateFormatter = DateTimeFormatter.ofPattern(DATE_PATTERN) @Transient val date = dateTimeText?.let { LocalDate.parse(it, dateFormatter) } }
WeatherX/app/src/main/java/com/apps10x/weatherx/data/WeatherResponse.kt
2040880242
package com.apps10x.weatherx.data data class DailyWeatherForecast( val avgTemp: Double, val dayOfWeek: String )
WeatherX/app/src/main/java/com/apps10x/weatherx/data/DailyWeatherForecast.kt
3887045552
package com.apps10x.weatherx.data import com.squareup.moshi.Json data class Temperature( @Json(name = "temp") val tempKelvin: Double ) { companion object { private const val KELVIN_TO_CELSIUS = 273.15 } val tempCelsius: Double get() = tempKelvin.minus(KELVIN_TO_CELSIUS) }
WeatherX/app/src/main/java/com/apps10x/weatherx/data/Temperature.kt
3682101856
package com.apps10x.weatherx.domain import com.apps10x.weatherx.data.DailyWeatherForecast import com.apps10x.weatherx.data.WeatherRepository import com.apps10x.weatherx.utils.ApiResult import java.time.LocalDate import java.time.format.TextStyle import java.util.Locale import javax.inject.Inject class WeatherForecastsUseCase @Inject constructor(private val weatherRepository: WeatherRepository) { companion object { private const val FORECAST_COUNT = 4L private const val NO_DATA_ERROR = "No data found" } suspend operator fun invoke(city: String): ApiResult<List<DailyWeatherForecast>>? { val listDailyWeatherForecast = mutableListOf<DailyWeatherForecast>() val forecasts = weatherRepository.getWeatherForecast(city) return if (forecasts is ApiResult.Success) { val currentDate = LocalDate.now() forecasts.data?.list?.filter { it.date?.isAfter(currentDate) == true && it.date <= currentDate.plusDays(FORECAST_COUNT) }?.groupBy { it.date }?.values?.forEach { weatherResponses -> listDailyWeatherForecast.add( DailyWeatherForecast( weatherResponses.map { it.temperatureData.tempCelsius }.average(), weatherResponses.firstOrNull()?.date?.dayOfWeek?.getDisplayName( TextStyle.FULL, Locale.getDefault() ) ?: "-" ) ) } if (listDailyWeatherForecast.size > 0) { ApiResult.Success(data = listDailyWeatherForecast) } else { ApiResult.Error(NO_DATA_ERROR) } } else { forecasts as? ApiResult.Error } } }
WeatherX/app/src/main/java/com/apps10x/weatherx/domain/WeatherForecastsUseCase.kt
1222870221
package com.jagveer.weathercast 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.jagveer.weathercast", appContext.packageName) } }
Weather-Cast/WeatherCast/app/src/androidTest/java/com/jagveer/weathercast/ExampleInstrumentedTest.kt
465146809
package com.jagveer.weathercast 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) } }
Weather-Cast/WeatherCast/app/src/test/java/com/jagveer/weathercast/ExampleUnitTest.kt
3526799556
package com.jagveer.weathercast import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.SearchView import com.jagveer.weathercast.databinding.ActivityMainBinding import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.sql.Timestamp import java.text.SimpleDateFormat import java.util.Locale import java.util.Date // b8e4a6469cd41a0febd413b3f0827f38 class MainActivity : AppCompatActivity() { private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) fetchWeatherData("Mumbai") SearchCity() } private fun SearchCity() { val searchView = binding.searchView searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { if (query != null) { fetchWeatherData(query) } return true } override fun onQueryTextChange(newText: String?): Boolean { return true } }) } private fun fetchWeatherData(cityName: String) { val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://api.openweathermap.org/data/2.5/") .build().create(ApiInterface::class.java) val response = retrofit.getWeatherData(cityName, appid = "b8e4a6469cd41a0febd413b3f0827f38", units = "metric") response.enqueue(object : Callback<WeatherCast> { override fun onResponse(call: Call<WeatherCast>, response: Response<WeatherCast>) { val responseBody = response.body() if (response.isSuccessful && responseBody != null) { val temperature = responseBody.main.temp.toString() val humidity = responseBody.main.humidity val windSpeed = responseBody.wind.speed val sunRise = responseBody.sys.sunrise.toLong() val sunSet= responseBody.sys.sunset.toLong() val seaLevel = responseBody.main.pressure val condition = responseBody.weather.firstOrNull()?.main?:"unknow" val maxTemp = responseBody.main.temp_max val minTemp = responseBody.main.temp_min binding.temperature.text = "$temperature °C" binding.weather.text = condition binding.maxTemp.text = "Max Temp: $maxTemp °C" binding.minTemp.text = "Min Temp: $minTemp °C" binding.Humidity.text = "$humidity %" // Fix the case sensitivity here binding.windSpeed.text = "$windSpeed m/s" binding.sunRise.text = "${time(sunRise)}" binding.sunset.text= "${time(sunSet)}" binding.sea.text = "$seaLevel hPa" binding.condition.text = condition binding.day.text=dayName(System.currentTimeMillis()) binding.date.text = date() binding.cityName.text="$cityName" // Log.d("TAG", "onResponse: $temperature") changeImagesAccordingToWeatherCondition(condition) } } override fun onFailure(call: Call<WeatherCast>, t: Throwable) { // Handle failure here // You might want to display an error message to the user or log the error } }) } private fun changeImagesAccordingToWeatherCondition(conditions: String) { when(conditions){ "Clear Sky", "Sunny", "Clear" ->{ binding.root.setBackgroundResource(R.drawable.sunny_background) binding.lottieAnimationView.setAnimation(R.raw.sun) } "Partly Clouds", "Clouds", "Overcast", "Mist", "Foggy" ->{ binding.root.setBackgroundResource(R.drawable.colud_background) binding.lottieAnimationView.setAnimation(R.raw.cloud) } "Light Rain", "Drizzle", "Moderate Rain", "Showers", "Heavy Rain", "Thunderstorm", "Rain" ->{ binding.root.setBackgroundResource(R.drawable.rain_background) binding.lottieAnimationView.setAnimation(R.raw.rain) } "Light Snow", "Moderate Snow", "Heavy Snow", "Blizzard", "Snow" ->{ binding.root.setBackgroundResource(R.drawable.snow_background) binding.lottieAnimationView.setAnimation(R.raw.snow) } else -> { binding.root.setBackgroundResource(R.drawable.sunny_background) binding.lottieAnimationView.setAnimation(R.raw.sun) } } binding.lottieAnimationView.playAnimation() } private fun date(): String { val sdf = SimpleDateFormat("dd MMMM yyyy", Locale.getDefault()) return sdf.format(Date()) } private fun time(timestamp: Long): String { val sdf = SimpleDateFormat("HH:mm", Locale.getDefault()) return sdf.format(Date(timestamp*1000)) } fun dayName(timestamp: Long): String { val sdf = SimpleDateFormat("EEEE", Locale.getDefault()) return sdf.format(Date()) } }
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/MainActivity.kt
851522556
package com.jagveer.weathercast import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface ApiInterface { @GET("weather") fun getWeatherData( @Query("q") city: String, @Query("appid") appid: String, @Query("units") units: String ): Call<WeatherCast> }
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/ApiInterface.kt
2576036009
package com.jagveer.weathercast data class Clouds( val all: Int )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Clouds.kt
3647801111
package com.jagveer.weathercast data class Sys( val country: String, val id: Int, val sunrise: Int, val sunset: Int, val type: Int )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Sys.kt
682217695
package com.jagveer.weathercast data class Main( val feels_like: Double, val humidity: Int, val pressure: Int, val temp: Double, val temp_max: Double, val temp_min: Double )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Main.kt
1161333472
package com.jagveer.weathercast data class WeatherCast( val base: String, val clouds: Clouds, val cod: Int, val coord: Coord, val dt: Int, val id: Int, val main: Main, val name: String, val sys: Sys, val timezone: Int, val visibility: Int, val weather: List<Weather>, val wind: Wind )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/WeatherCast.kt
3575497923
package com.jagveer.weathercast data class Weather( val description: String, val icon: String, val id: Int, val main: String )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Weather.kt
2256177423
package com.jagveer.weathercast data class Wind( val deg: Int, val speed: Double )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Wind.kt
137717983
package com.jagveer.weathercast import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) Handler(Looper.getMainLooper()).postDelayed({ val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() },3000) } }
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/SplashActivity.kt
653207508
package com.jagveer.weathercast data class Coord( val lat: Double, val lon: Double )
Weather-Cast/WeatherCast/app/src/main/java/com/jagveer/weathercast/Coord.kt
3814204888
package com.topic2.android.notes 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.raywenderlich.android.jetnotes", appContext.packageName) } }
lab-2.3/app/src/androidTest/java/com/topic2/android/notes/ExampleInstrumentedTest.kt
2896918724
package com.topic2.android.notes 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) } }
lab-2.3/app/src/test/java/com/topic2/android/notes/ExampleUnitTest.kt
1163277849
package ui.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box //import androidx.compose.foundation.layout.RowScopeInstance.align //import androidx.compose.foundation.layout.RowScopeInstance.align //import androidx.compose.foundation.layout.RowScopeInstance.align //import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable //import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier //import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp //import androidx.compose.ui.unit.Dp //import androidx.compose.ui.unit.dp //import com.topic2.android.notes.theme.rwGreen val rwGreen = Color(0xFF00FF00) @Composable fun NoteColor(modifier: Modifier = Modifier, color: Color, size: Dp, border: Dp) { Box( modifier = modifier .size(size) .clip(CircleShape) .background(color) .border( BorderStroke( border, SolidColor(Color.Black) ), CircleShape ) ) } @Preview @Composable fun NoteColorPreview(){ }
lab-2.3/app/src/main/java/ui/components/NoteColor.kt
3163040121
package ui.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable //import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column //import androidx.compose.foundation.layout.ColumnScopeInstance.weight import androidx.compose.foundation.layout.Row //import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth //import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding //import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Checkbox import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier //import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp //import com.topic2.android.notes.R //import androidx.compose.foundation.foundation.layout.* import androidx.compose.material.Text import androidx.compose.ui.Alignment import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color //import androidx.compose.ui.graphics.Color.Companion.White import androidx.compose.ui.graphics.Shape import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.topic2.android.notes.domain.model.NoteModel //import androidx.compose.ui.res.colorResource //import androidx.compose.ui.unit.min import com.topic2.android.notes.theme.rwGreen import com.topic2.android.notes.util.fromHex //import androidx.compose.ui.modifier.modifierLocalOf @Composable fun Note( note: NoteModel, onNoteClick: (NoteModel) -> Unit = {}, onNoteCheckedChange: (NoteModel) -> Unit = {} ) { val backgroundShape: Shape = RoundedCornerShape(4.dp) Row( modifier = Modifier .padding(8.dp) .shadow(1.dp, backgroundShape) .fillMaxWidth() .heightIn(min = 64.dp) .background(Color.White, backgroundShape) .clickable(onClick = { onNoteClick(note) }) ) { NoteColor( modifier = Modifier .align(Alignment.CenterVertically) .padding(start = 16.dp, end = 16.dp), color = Color.fromHex(note.color.hex), size = 40.dp, border = 1.dp ) Column(modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) ) { Text(text = note.title, color = Color.Black, maxLines = 1, style = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp, letterSpacing = 0.15.sp ) ) Text( text = note.content, color = Color.Black.copy(alpha = 0.75f), maxLines = 1, style = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp, letterSpacing = 0.25.sp ) ) } if (note.isCheckedOff !=null) Checkbox( checked = note.isCheckedOff, onCheckedChange = {isChecked -> val newNote = note.copy(isCheckedOff = isChecked) onNoteCheckedChange(newNote) }, modifier = Modifier .padding(16.dp) .align(Alignment.CenterVertically) ) } } @Preview @Composable private fun NotePreview() { Note( note = NoteModel( 1, "Заметка 1", "Содержимое 1", null) ) }
lab-2.3/app/src/main/java/ui/components/Note.kt
3358924340
package ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.List import androidx.compose.material.primarySurface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.topic2.android.notes.theme.NotesTheme @Composable fun TopAppBar( title: String, icon: ImageVector, onIconClick: () -> Unit, ){ Row( modifier = Modifier .fillMaxWidth() .height(56.dp) .background(color = MaterialTheme.colors.primarySurface) ){ Image( imageVector = icon, contentDescription = "Top App Bar Icon", colorFilter = ColorFilter .tint(MaterialTheme.colors.onPrimary), modifier = Modifier .clickable(onClick = onIconClick) .padding(16.dp) .align(Alignment.CenterVertically) ) Text( text = title, color = MaterialTheme.colors.onPrimary, style = TextStyle( fontWeight = FontWeight.Medium, fontSize = 20.sp, letterSpacing = 0.15.sp, ), modifier = Modifier .fillMaxWidth() .align(Alignment.CenterVertically) .padding(start = 16.dp, end = 16.dp) ) } } @Preview @Composable private fun TopAppBarPreview(){ NotesTheme { TopAppBar( title = "Заметки", icon = Icons.Filled.List, onIconClick = {} ) } }
lab-2.3/app/src/main/java/ui/components/TopAppBar.kt
1753246538
package ui.components.screens import androidx.compose.foundation.layout.Row import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.util.fromHex import ui.components.NoteColor import java.lang.reflect.Modifier import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.fillMaxWidth @Composable private fun ColorPicker( colors: List<ColorModel>, onColorSelect: (ColorModel) -> Unit ){ Column ( modifier = androidx.compose.ui.Modifier.fillMaxWidth() ){ Text( text = "Color picker", fontSize = 18.sp, fontWeight = FontWeight.Bold, modifier = androidx.compose.ui.Modifier.padding(8.dp) ) LazyColumn( modifier = androidx.compose.ui.Modifier.fillMaxWidth() ){ items( colors.size ){ itemIdex -> val color = colors[itemIdex] ColorItem( color = color, onColorSelect = onColorSelect ) } } } } @Composable fun ColorItem( color: ColorModel, onColorSelect: (ColorModel) -> Unit ){ Row( modifier = androidx.compose.ui.Modifier .fillMaxWidth() .clickable( onClick = { onColorSelect(color) } ) ){ NoteColor( modifier = androidx.compose.ui.Modifier .padding(10.dp), color = Color.fromHex(color.hex), size = 90.dp, border = 2.dp ) Text( text = color.name, fontSize = 22.sp, modifier = androidx.compose.ui.Modifier .padding(horizontal = 16.dp) .align(Alignment.CenterVertically) ) } } @Preview @Composable fun ColorItemPreview(){ ColorItem(ColorModel.DEFAULT){} } @Preview @Composable fun ColorPickerPreview(){ ColorPicker( colors = listOf( ColorModel.DEFAULT, ColorModel.DEFAULT, ColorModel.DEFAULT ) ){} }
lab-2.3/app/src/main/java/ui/components/screens/SaveNoteScreen.kt
4164264203
package ui.components.screens import android.graphics.drawable.Icon import androidx.compose.foundation.layout.Column import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import com.topic2.android.notes.domain.model.NoteModel import com.topic2.android.notes.viewmodel.MainViewModel import ui.components.Note import ui.components.TopAppBar import androidx.compose.material.icons.filled.List import androidx.compose.ui.tooling.preview.Preview @Composable fun NotesScreen( viewModel: MainViewModel ) { val notes: List<NoteModel> by viewModel .notesNotInTrash .observeAsState(listOf()) Column { TopAppBar(title = "Заметки", icon = Icons.Filled.List, onIconClick = {} ) NotesList( notes = notes, onNoteCheckedChange = { viewModel.onNoteCheckedChange(it) }, onNoteClick = { viewModel.onNoteClick(it) }) } } @Composable private fun NotesList( notes: List<NoteModel>, onNoteCheckedChange: (NoteModel) -> Unit, onNoteClick:(NoteModel) -> Unit ){ LazyColumn{ items(count = notes.size){noteIndex -> val note = notes[noteIndex] Note(note = note, onNoteClick = onNoteClick, onNoteCheckedChange = onNoteCheckedChange ) } } } @Preview @Composable private fun NotesListPreview(){ NotesList( notes = listOf( NoteModel(1,"Note 1", "Content 1", null), NoteModel(2,"Note 2", "Content 2", false) , NoteModel(3,"Note 1", "Content 3", true) ), onNoteCheckedChange = {}, onNoteClick = {} ) }
lab-2.3/app/src/main/java/ui/components/screens/NotesScreen.kt
1769956040
package ui.components //import android.graphics.ColorFilter import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.* import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Delete import androidx.compose.foundation.clickable import androidx.compose.runtime.Composable //import androidx.compose.runtime.ComposableOpenTarget 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.compose.foundation.layout.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import com.topic2.android.notes.routing.NotesRouter import com.topic2.android.notes.routing.Screen //import com.topic2.android.notes.routing.NotesRouter //import com.topic2.android.notes.routing.Screen import com.topic2.android.notes.theme.NotesTheme import com.topic2.android.notes.theme.NotesThemeSettings //import com.topic2.android.notes.theme.NotesThemeSettings @Composable @Preview private fun AppDrawerHeader(){ Row(modifier = Modifier.fillMaxWidth()){ Image(imageVector = Icons.Filled.Menu, contentDescription = "Drawer Header Icon", colorFilter = androidx.compose.ui.graphics.ColorFilter .tint(MaterialTheme.colors.onSurface), modifier = Modifier.padding(16.dp) ) Text(text = "Заметки", modifier = Modifier .align(alignment = Alignment.CenterVertically)) } } @Preview @Composable fun AppDrawerHeaderPreview(){ NotesTheme{ AppDrawerHeader() } } @Composable private fun ScreenNavigationButton( icon: ImageVector, label: String, isSelected: Boolean, onClick: () -> Unit ) { val colors = MaterialTheme.colors val imageAlpha = if (isSelected){ 1f } else{ 0.6f } val purpleColor = Color(0xFFBB86FC) val textColor = if (isSelected) { purpleColor } else { colors.onSurface.copy(alpha = 0.6f) } val backgroundColor = if (isSelected) { purpleColor.copy(alpha = 0.12f) } else { colors.surface } Surface( modifier = Modifier .fillMaxWidth() .padding(start = 8.dp, end = 8.dp, top = 8.dp), color = backgroundColor, shape = MaterialTheme.shapes.small ) { Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clickable(onClick = onClick) .fillMaxWidth() .padding(4.dp) ) { Image( imageVector = icon , contentDescription = "Screen Navigation Button", colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(textColor), alpha = imageAlpha ) Spacer(Modifier.width(16.dp)) Text( text = label, style = MaterialTheme.typography.body2, color = textColor, modifier = Modifier.fillMaxWidth() ) } } } @Preview @Composable fun ScreenNavigationButtonPreview(){ NotesTheme { ScreenNavigationButton( icon = Icons.Filled.Home, label = "Заметки", isSelected = true, onClick = {} ) } } @Composable private fun LightDarkThemeItem(){ Row( Modifier .padding(8.dp) ){ Text(text = "Включить темную тему", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f), modifier = Modifier .weight(1f) .padding(start = 8.dp, top = 8.dp, end = 8.dp, bottom = 8.dp) .align(alignment = Alignment.CenterVertically) ) Switch(checked = NotesThemeSettings.isDarkThemeEnabled, onCheckedChange = { NotesThemeSettings.isDarkThemeEnabled = it}, modifier = Modifier .padding(start = 8.dp, end = 8.dp) .align(alignment = Alignment.CenterVertically) ) } } @Preview @Composable fun LightDarkThemeItemPreview(){ NotesTheme { LightDarkThemeItem() } } @Composable fun AppDrawer( currentScreen: Screen, closeDrawerAction: () -> Unit ){ Column(modifier = Modifier.fillMaxSize()) { AppDrawerHeader() Divider(color = MaterialTheme.colors.onSurface.copy(alpha = .2f)) ScreenNavigationButton( icon = Icons.Filled.Home, label ="Заметки" , isSelected = currentScreen == Screen.Notes, onClick = { NotesRouter.navigateTo(Screen.Notes) closeDrawerAction() } ) ScreenNavigationButton( icon = Icons.Filled.Delete , label = "Корзина", isSelected = currentScreen == Screen.Trash, onClick = { NotesRouter.navigateTo(Screen.Trash) closeDrawerAction() } ) LightDarkThemeItem() } } @Preview @Composable fun AppDrawerPreview(){ NotesTheme { AppDrawer(Screen.Notes, {}) } }
lab-2.3/app/src/main/java/ui/components/AppDrawer.kt
3105676369
package screens import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding //import com.example.notes.domain.model.ColorModel import androidx.compose.foundation.layout.Row import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment 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.compose.ui.unit.sp import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.util.fromHex import ui.components.NoteColor import java.lang.reflect.Modifier @Composable private fun ColorPicker( colors: List<ColorModel>, onColorSelect: (ColorModel) -> Unit ){ Column ( modifier = androidx.compose.ui.Modifier.fillMaxWidth() ){ Text( text = "Color picker", fontSize = 18.sp, fontWeight = FontWeight.Bold, modifier = androidx.compose.ui.Modifier.padding(8.dp) ) LazyColumn( modifier = androidx.compose.ui.Modifier.fillMaxWidth() ){ items( colors.size ){ itemIdex -> val color = colors[itemIdex] ColorItem( color = color, onColorSelect = onColorSelect ) } } } } @Composable fun ColorItem( color: ColorModel, onColorSelect: (ColorModel) -> Unit ){ Row( modifier = androidx.compose.ui.Modifier .fillMaxWidth() .clickable( onClick = { onColorSelect(color) } ) ){ NoteColor( modifier = androidx.compose.ui.Modifier .padding(10.dp), color = Color.fromHex(color.hex), size = 90.dp, border = 2.dp ) Text( text = color.name, fontSize = 22.sp, modifier = androidx.compose.ui.Modifier .padding(horizontal = 16.dp) .align(Alignment.CenterVertically) ) } } @Preview @Composable fun ColorItemPreview(){ ColorItem(ColorModel.DEFAULT){} } @Preview @Composable fun ColorPickerPreview(){ ColorPicker( colors = listOf( ColorModel.DEFAULT, ColorModel.DEFAULT, ColorModel.DEFAULT ) ){} }
lab-2.3/app/src/main/java/screens/SaveNoteScreen.kt
1562263702
package com.topic2.android.notes.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.topic2.android.notes.data.repository.Repository import com.topic2.android.notes.domain.model.NoteModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * Модель просмотра, используемая для хранения глобального состояния приложения. * * Эта модель просмотра используется для всех экранов. */ class MainViewModel(private val repository: Repository) : ViewModel() { val notesNotInTrash: LiveData<List<NoteModel>> by lazy { repository.getAllNotesNotInTrash() } fun onCreateNewNoteClick() { //// } fun onNoteCheckedChange(note: NoteModel) { viewModelScope.launch(Dispatchers.Default) { repository.insertNote(note) } } fun onNoteClick(note: NoteModel) { ///// } }
lab-2.3/app/src/main/java/com/topic2/android/notes/viewmodel/MainViewModel.kt
2309970710
package com.topic2.android.notes.viewmodel import android.os.Bundle import androidx.lifecycle.AbstractSavedStateViewModelFactory import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.savedstate.SavedStateRegistryOwner import com.topic2.android.notes.data.repository.Repository @Suppress("UNCHECKED_CAST") class MainViewModelFactory( owner: SavedStateRegistryOwner, private val repository: Repository, private val defaultArgs: Bundle? = null ) : AbstractSavedStateViewModelFactory(owner, defaultArgs) { override fun <T : ViewModel?> create( key: String, modelClass: Class<T>, handle: SavedStateHandle ): T { return MainViewModel(repository) as T } }
lab-2.3/app/src/main/java/com/topic2/android/notes/viewmodel/MainViewModelFactory.kt
2303834820
package com.topic2.android.notes //import android.annotation.SuppressLint import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.activity.compose.setContent //import androidx.compose.material.Scaffold //import androidx.compose.material.ScaffoldState //import androidx.compose.material.rememberScaffoldState //import androidx.compose.runtime.rememberCoroutineScope //import com.topic2.android.notes.routing.Screen import com.topic2.android.notes.theme.NotesTheme import com.topic2.android.notes.viewmodel.MainViewModel import com.topic2.android.notes.viewmodel.MainViewModelFactory //import kotlinx.coroutines.launch //import ui.components.AppDrawer //import ui.components.Note import ui.components.screens.NotesScreen /** * Main activity приложения. */ class MainActivity : AppCompatActivity() { private val viewModel: MainViewModel by viewModels(factoryProducer = { MainViewModelFactory( this, (application as NotesApplication).dependencyInjector.repository ) }) @SuppressLint("UnusedMaterialScaffoldPaddingParameter") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NotesTheme { NotesScreen(viewModel = viewModel) } } } }
lab-2.3/app/src/main/java/com/topic2/android/notes/MainActivity.kt
3429464390
package com.topic2.android.notes.util import androidx.compose.ui.graphics.Color fun Color.Companion.fromHex(hex: String): Color { return Color(android.graphics.Color.parseColor(hex)) }
lab-2.3/app/src/main/java/com/topic2/android/notes/util/Extensions.kt
986981021
package com.topic2.android.notes.theme import androidx.compose.ui.graphics.Color val rwGreen = Color(0xFF006837) val rwGreenDark = Color(0xFF004012) val rwRed = Color(0xFFC75F00)
lab-2.3/app/src/main/java/com/topic2/android/notes/theme/Color.kt
865501888
package com.topic2.android.notes.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue private val LightThemeColors = lightColors( primary = rwGreen, primaryVariant = rwGreenDark, secondary = rwGreen ) private val DarkThemeColors = lightColors( primary = rwGreen, primaryVariant = rwGreenDark, secondary = rwGreen ) /** * Отвечает за переключение цветовой палитры для темной и светлой темы. */ @Composable fun NotesTheme(content: @Composable () -> Unit) { val isDarkThemeEnabled = isSystemInDarkTheme() || NotesThemeSettings.isDarkThemeEnabled val colors = if (isDarkThemeEnabled) DarkThemeColors else LightThemeColors MaterialTheme(colors = colors, content = content) } /** * Позволяет переключаться между светлой и темной темой в настройках приложения. */ object NotesThemeSettings { var isDarkThemeEnabled by mutableStateOf(false) }
lab-2.3/app/src/main/java/com/topic2/android/notes/theme/Theme.kt
85960176
package com.topic2.android.notes.routing import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue /** * Класс, определяющий все возможные экраны в приложении. */ sealed class Screen { object Notes : Screen() object SaveNote : Screen() object Trash : Screen() } /** * Позволяет менять экран в [MainActivity] * * Также отслеживает текущий экран. */ object NotesRouter { var currentScreen: Screen by mutableStateOf(Screen.Notes) fun navigateTo(destination: Screen) { currentScreen = destination } }
lab-2.3/app/src/main/java/com/topic2/android/notes/routing/NotesRouter.kt
2091457956
package com.topic2.android.notes.data.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.topic2.android.notes.data.database.model.NoteDbModel /** * Dao для управления таблицей Note в базе данных. */ @Dao interface NoteDao { @Query("SELECT * FROM NoteDbModel") fun getAllSync(): List<NoteDbModel> @Query("SELECT * FROM NoteDbModel WHERE id IN (:noteIds)") fun getNotesByIdsSync(noteIds: List<Long>): List<NoteDbModel> @Query("SELECT * FROM NoteDbModel WHERE id LIKE :id") fun findById(id: Long): LiveData<NoteDbModel> @Query("SELECT * FROM NoteDbModel WHERE id LIKE :id") fun findByIdSync(id: Long): NoteDbModel @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(noteDbModel: NoteDbModel) @Insert fun insertAll(vararg noteDbModel: NoteDbModel) @Query("DELETE FROM NoteDbModel WHERE id LIKE :id") fun delete(id: Long) @Query("DELETE FROM NoteDbModel WHERE id IN (:noteIds)") fun delete(noteIds: List<Long>) }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/dao/NoteDao.kt
1403686308
package com.topic2.android.notes.data.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.topic2.android.notes.data.database.model.ColorDbModel /** * Dao для управления таблицей цветов в базе данных. */ @Dao interface ColorDao { @Query("SELECT * FROM ColorDbModel") fun getAll(): LiveData<List<ColorDbModel>> @Query("SELECT * FROM ColorDbModel") fun getAllSync(): List<ColorDbModel> @Query("SELECT * FROM ColorDbModel WHERE id LIKE :id") fun findById(id: Long): LiveData<ColorDbModel> @Query("SELECT * FROM ColorDbModel WHERE id LIKE :id") fun findByIdSync(id: Long): ColorDbModel @Insert fun insertAll(vararg colorDbModels: ColorDbModel) }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/dao/ColorDao.kt
3295878923
package com.topic2.android.notes.data.database import androidx.room.Database import androidx.room.RoomDatabase import com.topic2.android.notes.data.database.dao.ColorDao import com.topic2.android.notes.data.database.dao.NoteDao import com.topic2.android.notes.data.database.model.ColorDbModel import com.topic2.android.notes.data.database.model.NoteDbModel /** * База данных приложения. * * Он содержит две таблицы: таблицу заметок и таблицу цветов. */ @Database(entities = [NoteDbModel::class, ColorDbModel::class], version = 1) abstract class AppDatabase : RoomDatabase() { companion object { const val DATABASE_NAME = "note-maker-database" } abstract fun noteDao(): NoteDao abstract fun colorDao(): ColorDao }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/AppDatabase.kt
1856257275
package com.topic2.android.notes.data.database.dbmapper import com.topic2.android.notes.data.database.model.ColorDbModel import com.topic2.android.notes.data.database.model.NoteDbModel import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.domain.model.NoteModel interface DbMapper { // NoteDbModel -> NoteModel fun mapNotes( noteDbModels: List<NoteDbModel>, colorDbModels: Map<Long, ColorDbModel> ): List<NoteModel> fun mapNote(noteDbModel: NoteDbModel, colorDbModel: ColorDbModel): NoteModel // ColorDbModel -> ColorModel fun mapColors(colorDbModels: List<ColorDbModel>): List<ColorModel> fun mapColor(colorDbModel: ColorDbModel): ColorModel // NoteModel -> NoteDbModel fun mapDbNote(note: NoteModel): NoteDbModel // ColorModel -> ColorDbModel fun mapDbColors(colors: List<ColorModel>): List<ColorDbModel> fun mapDbColor(color: ColorModel): ColorDbModel }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/dbmapper/DbMapper.kt
898888460
package com.topic2.android.notes.data.database.dbmapper import com.topic2.android.notes.data.database.model.ColorDbModel import com.topic2.android.notes.data.database.model.NoteDbModel import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.domain.model.NEW_NOTE_ID import com.topic2.android.notes.domain.model.NoteModel class DbMapperImpl : DbMapper { override fun mapNotes( noteDbModels: List<NoteDbModel>, colorDbModels: Map<Long, ColorDbModel> ): List<NoteModel> = noteDbModels.map { val colorDbModel = colorDbModels[it.colorId] ?: throw RuntimeException("Color for colorId: ${it.colorId} was not found. Make sure that all colors are passed to this method") mapNote(it, colorDbModel) } override fun mapNote(noteDbModel: NoteDbModel, colorDbModel: ColorDbModel): NoteModel { val color = mapColor(colorDbModel) val isCheckedOff = with(noteDbModel) { if (canBeCheckedOff) isCheckedOff else null } return with(noteDbModel) { NoteModel(id, title, content, isCheckedOff, color) } } override fun mapColors(colorDbModels: List<ColorDbModel>): List<ColorModel> = colorDbModels.map { mapColor(it) } override fun mapColor(colorDbModel: ColorDbModel): ColorModel = with(colorDbModel) { ColorModel(id, name, hex) } override fun mapDbNote(note: NoteModel): NoteDbModel = with(note) { val canBeCheckedOff = isCheckedOff != null val isCheckedOff = isCheckedOff ?: false if (id == NEW_NOTE_ID) NoteDbModel( title = title, content = content, canBeCheckedOff = canBeCheckedOff, isCheckedOff = isCheckedOff, colorId = color.id, isInTrash = false ) else NoteDbModel(id, title, content, canBeCheckedOff, isCheckedOff, color.id, false) } override fun mapDbColors(colors: List<ColorModel>): List<ColorDbModel> = colors.map { mapDbColor(it) } override fun mapDbColor(color: ColorModel): ColorDbModel = with(color) { ColorDbModel(id, hex, name) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/dbmapper/DbMapperImpl.kt
3224799606
package com.topic2.android.notes.data.database.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class ColorDbModel( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name = "hex") val hex: String, @ColumnInfo(name = "name") val name: String ) { companion object { val DEFAULT_COLORS = listOf( ColorDbModel(1, "#FFFFFF", "White"), ColorDbModel(2, "#E57373", "Red"), ColorDbModel(3, "#F06292", "Pink"), ColorDbModel(4, "#CE93D8", "Purple"), ColorDbModel(5, "#2196F3", "Blue"), ColorDbModel(6, "#00ACC1", "Cyan"), ColorDbModel(7, "#26A69A", "Teal"), ColorDbModel(8, "#4CAF50", "Green"), ColorDbModel(9, "#8BC34A", "Light Green"), ColorDbModel(10, "#CDDC39", "Lime"), ColorDbModel(11, "#FFEB3B", "Yellow"), ColorDbModel(12, "#FF9800", "Orange"), ColorDbModel(13, "#BCAAA4", "Brown"), ColorDbModel(14, "#9E9E9E", "Gray") ) val DEFAULT_COLOR = DEFAULT_COLORS[0] } }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/model/ColorDbModel.kt
3321843050
package com.topic2.android.notes.data.database.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class NoteDbModel( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "content") val content: String, @ColumnInfo(name = "can_be_checked_off") val canBeCheckedOff: Boolean, @ColumnInfo(name = "is_checked_off") val isCheckedOff: Boolean, @ColumnInfo(name = "color_id") val colorId: Long, @ColumnInfo(name = "in_trash") val isInTrash: Boolean ) { companion object { val DEFAULT_NOTES = listOf( NoteDbModel(1, "RW Meeting", "Prepare sample project", false, false, 1, false), NoteDbModel(2, "Bills", "Pay by tomorrow", false, false, 2, false), NoteDbModel(3, "Pancake recipe", "Milk, eggs, salt, flour...", false, false, 3, false), NoteDbModel(4, "Workout", "Running, push ups, pull ups, squats...", false, false, 4, false), NoteDbModel(5, "Title 5", "Content 5", false, false, 5, false), NoteDbModel(6, "Title 6", "Content 6", false, false, 6, false), NoteDbModel(7, "Title 7", "Content 7", false, false, 7, false), NoteDbModel(8, "Title 8", "Content 8", false, false, 8, false), NoteDbModel(9, "Title 9", "Content 9", false, false, 9, false), NoteDbModel(10, "Title 10", "Content 10", false, false, 10, false), NoteDbModel(11, "Title 11", "Content 11", true, false, 11, false), NoteDbModel(12, "Title 12", "Content 12", true, false, 12, false) ) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/database/model/NoteDbModel.kt
3443277402
package com.topic2.android.notes.data.repository import androidx.lifecycle.LiveData import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.domain.model.NoteModel /** * Позволяет общаться с базой данных приложения. */ interface Repository { // notes fun getAllNotesNotInTrash(): LiveData<List<NoteModel>> fun getAllNotesInTrash(): LiveData<List<NoteModel>> fun getNote(id: Long): LiveData<NoteModel> fun insertNote(note: NoteModel) fun deleteNote(id: Long) fun deleteNotes(noteIds: List<Long>) fun moveNoteToTrash(noteId: Long) fun restoreNotesFromTrash(noteIds: List<Long>) // colors fun getAllColors(): LiveData<List<ColorModel>> fun getAllColorsSync(): List<ColorModel> fun getColor(id: Long): LiveData<ColorModel> fun getColorSync(id: Long): ColorModel }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/repository/Repository.kt
4161751214
package com.topic2.android.notes.data.repository import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import com.topic2.android.notes.data.database.dao.ColorDao import com.topic2.android.notes.data.database.dao.NoteDao import com.topic2.android.notes.data.database.dbmapper.DbMapper import com.topic2.android.notes.data.database.model.ColorDbModel import com.topic2.android.notes.data.database.model.NoteDbModel import com.topic2.android.notes.domain.model.ColorModel import com.topic2.android.notes.domain.model.NoteModel import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch /** * {@inheritDoc} */ class RepositoryImpl( private val noteDao: NoteDao, private val colorDao: ColorDao, private val dbMapper: DbMapper ) : Repository { private val notesNotInTrashLiveData: MutableLiveData<List<NoteModel>> by lazy { MutableLiveData<List<NoteModel>>() } private val notesInTrashLiveData: MutableLiveData<List<NoteModel>> by lazy { MutableLiveData<List<NoteModel>>() } init { initDatabase(this::updateNotesLiveData) } /** * Заполняет базу данных цветами, если она пуста. */ private fun initDatabase(postInitAction: () -> Unit) { GlobalScope.launch { // Prepopulate colors val colors = ColorDbModel.DEFAULT_COLORS.toTypedArray() val dbColors = colorDao.getAllSync() if (dbColors.isNullOrEmpty()) { colorDao.insertAll(*colors) } // Prepopulate notes val notes = NoteDbModel.DEFAULT_NOTES.toTypedArray() val dbNotes = noteDao.getAllSync() if (dbNotes.isNullOrEmpty()) { noteDao.insertAll(*notes) } postInitAction.invoke() } } override fun getAllNotesNotInTrash(): LiveData<List<NoteModel>> = notesNotInTrashLiveData override fun getAllNotesInTrash(): LiveData<List<NoteModel>> = notesInTrashLiveData private fun getAllNotesDependingOnTrashStateSync(inTrash: Boolean): List<NoteModel> { val colorDbModels: Map<Long, ColorDbModel> = colorDao.getAllSync().map { it.id to it }.toMap() val dbNotesNotInTrash: List<NoteDbModel> = noteDao.getAllSync().filter { it.isInTrash == inTrash } return dbMapper.mapNotes(dbNotesNotInTrash, colorDbModels) } override fun getNote(id: Long): LiveData<NoteModel> = Transformations.map(noteDao.findById(id)) { val colorDbModel = colorDao.findByIdSync(it.colorId) dbMapper.mapNote(it, colorDbModel) } override fun insertNote(note: NoteModel) { noteDao.insert(dbMapper.mapDbNote(note)) updateNotesLiveData() } override fun deleteNote(id: Long) { noteDao.delete(id) updateNotesLiveData() } override fun deleteNotes(noteIds: List<Long>) { noteDao.delete(noteIds) updateNotesLiveData() } override fun moveNoteToTrash(noteId: Long) { val dbNote = noteDao.findByIdSync(noteId) val newDbNote = dbNote.copy(isInTrash = true) noteDao.insert(newDbNote) updateNotesLiveData() } override fun restoreNotesFromTrash(noteIds: List<Long>) { val dbNotesInTrash = noteDao.getNotesByIdsSync(noteIds) dbNotesInTrash.forEach { val newDbNote = it.copy(isInTrash = false) noteDao.insert(newDbNote) } updateNotesLiveData() } override fun getAllColors(): LiveData<List<ColorModel>> = Transformations.map(colorDao.getAll()) { dbMapper.mapColors(it) } override fun getAllColorsSync(): List<ColorModel> = dbMapper.mapColors(colorDao.getAllSync()) override fun getColor(id: Long): LiveData<ColorModel> = Transformations.map(colorDao.findById(id)) { dbMapper.mapColor(it) } override fun getColorSync(id: Long): ColorModel = dbMapper.mapColor(colorDao.findByIdSync(id)) private fun updateNotesLiveData() { notesNotInTrashLiveData.postValue(getAllNotesDependingOnTrashStateSync(false)) val newNotesInTrashLiveData = getAllNotesDependingOnTrashStateSync(true) notesInTrashLiveData.postValue(newNotesInTrashLiveData) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/data/repository/RepositoryImpl.kt
813605910
package com.topic2.android.notes.domain.model const val NEW_NOTE_ID = -1L /** * Класс модели, представляющий одну заметку */ data class NoteModel( val id: Long = NEW_NOTE_ID, // This value is used for new notes val title: String = "", val content: String = "", val isCheckedOff: Boolean? = null, // null represents that the note can't be checked off val color: ColorModel = ColorModel.DEFAULT )
lab-2.3/app/src/main/java/com/topic2/android/notes/domain/model/NoteModel.kt
1812332240
package com.topic2.android.notes.domain.model import com.topic2.android.notes.data.database.model.ColorDbModel /** * Класс модели для одного цвета */ data class ColorModel( val id: Long, val name: String, val hex: String ) { companion object { val DEFAULT = with(ColorDbModel.DEFAULT_COLOR) { ColorModel(id, name, hex) } } }
lab-2.3/app/src/main/java/com/topic2/android/notes/domain/model/ColorModel.kt
1081593978
package com.topic2.android.notes.dependencyinjection import android.content.Context import androidx.room.Room import com.topic2.android.notes.data.database.AppDatabase import com.topic2.android.notes.data.database.dbmapper.DbMapper import com.topic2.android.notes.data.database.dbmapper.DbMapperImpl import com.topic2.android.notes.data.repository.Repository import com.topic2.android.notes.data.repository.RepositoryImpl /** * Обеспечивает зависимости приложения. */ class DependencyInjector(applicationContext: Context) { val repository: Repository by lazy { provideRepository(database) } private val database: AppDatabase by lazy { provideDatabase(applicationContext) } private val dbMapper: DbMapper = DbMapperImpl() private fun provideDatabase(applicationContext: Context): AppDatabase = Room.databaseBuilder( applicationContext, AppDatabase::class.java, AppDatabase.DATABASE_NAME ).build() private fun provideRepository(database: AppDatabase): Repository { val noteDao = database.noteDao() val colorDao = database.colorDao() return RepositoryImpl(noteDao, colorDao, dbMapper) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/dependencyinjection/DependencyInjector.kt
339349706
package com.topic2.android.notes import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.appcompat.app.AppCompatActivity /** * Экран-заставка со значком приложения и названием в центре. * * Это также экран запуска. * * Он откроет [MainActivity] после определенной задержки. */ class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) showMainActivityWithDelay() } private fun showMainActivityWithDelay() { // Использование обработчика для задержки загрузки MainActivity Handler(Looper.getMainLooper()).postDelayed({ // Start activity startActivity(Intent(this, MainActivity::class.java)) // Анимируем загрузку новой активности overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) // Close this activity finish() }, 2000) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/SplashActivity.kt
2850463636
package com.topic2.android.notes import android.app.Application import com.topic2.android.notes.dependencyinjection.DependencyInjector /** * Класс приложения, отвечающий за инициализацию и выполнение зависимостей. */ class NotesApplication : Application() { lateinit var dependencyInjector: DependencyInjector override fun onCreate() { super.onCreate() initDependencyInjector() } private fun initDependencyInjector() { dependencyInjector = DependencyInjector(this) } }
lab-2.3/app/src/main/java/com/topic2/android/notes/NotesApplication.kt
812608426
package io.github.zeqky.catan.plugin import io.github.monun.kommand.getValue import io.github.monun.kommand.kommand import io.github.zeqky.catan.process.CatanPreProcess import org.bukkit.World import org.bukkit.entity.Player import org.bukkit.plugin.java.JavaPlugin class CatanPlugin : JavaPlugin() { var process: CatanPreProcess? = null private set override fun onEnable() { dataFolder.mkdirs() saveResource("lands.txt", false) saveResource("roads.txt", false) saveResource("towns.txt", false) saveDefaultConfig() kommand { "catan" { "start"("world" to dimension(), "players" to players()) { executes { val world: World by it val players: Collection<Player> by it startProcess(world, players.toSet()) } } "stop" { executes { stopProcess() } } } } } private fun startProcess(world: World, players: Set<Player>) { require(process == null) { "Process is already running!" } process = CatanPreProcess(this, world).also { it.launch(players) } } private fun stopProcess() { val process = requireNotNull(process) { "Process is not running!" } process.stop() this.process = null } }
catan/src/main/kotlin/io/github/zeqky/catan/plugin/CatanPlugin.kt
304258365
package io.github.zeqky.catan.process import io.github.monun.heartbeat.coroutines.HeartbeatScope import io.github.monun.tap.fake.FakeEntityServer import io.github.zeqky.catan.plugin.CatanPlugin import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.World import org.bukkit.entity.Player import org.bukkit.event.HandlerList import org.bukkit.scheduler.BukkitTask import java.io.BufferedReader import java.io.File import java.io.FileReader class CatanPreProcess(val plugin: CatanPlugin, val world: World) { lateinit var scope: CoroutineScope private set lateinit var fakeEntityServer: FakeEntityServer private set lateinit var listener: CatanListener private set lateinit var process: CatanProcess private set lateinit var zones: List<CatanZone> lateinit var lands: List<CatanLand> lateinit var players: List<CatanPlayer> lateinit var task: BukkitTask val dices = arrayListOf<Dice>() fun launch(players: Set<Player>) { scope = HeartbeatScope() fakeEntityServer = FakeEntityServer.create(plugin) listener = CatanListener().apply { Bukkit.getPluginManager().registerEvents(this, plugin) } process = CatanProcess(this) task = Bukkit.getScheduler().runTaskTimer(plugin, process::update, 0L, 1L) initializeZones() initializeLands() initializePlayers(players) scope.launch { process.launch(scope) } } fun initializeZones() { val roadsFile = File(plugin.dataFolder, "roads.txt") val townsFile = File(plugin.dataFolder, "towns.txt") val reader1 = BufferedReader(FileReader(roadsFile)) val reader2 = BufferedReader(FileReader(townsFile)) val list = arrayListOf<CatanZone>() reader1.readLines().forEach { val s = it.split(" ") list += CatanZone().apply { type = ZoneType.ROAD loc = Location(world, s[0].toDouble(), -60.0, s[1].toDouble()) } } reader2.readLines().forEach { val s = it.split(" ") list += CatanZone().apply { type = ZoneType.TOWN loc = Location(world, s[0].toDouble(), -60.0, s[1].toDouble()) } } zones = list } fun initializeLands() { val landsFile = File(plugin.dataFolder, "lands.txt") val reader = BufferedReader(FileReader(landsFile)) val list = arrayListOf<CatanLand>() reader.readLines().forEach { val s = it.split(" ") list += CatanLand().apply { loc = Location(world, s[0].toDouble(), -60.0, s[1].toDouble()) } } lands = list } fun initializePlayers(players: Set<Player>) { val list = arrayListOf<CatanPlayer>() players.forEach { list += CatanPlayer(it) } this.players = list } fun spawnDice(player: CatanPlayer) { dices += Dice(this, player) } fun stop() { HandlerList.unregisterAll(plugin) fakeEntityServer.clear() scope.cancel() task.cancel() } }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanPreProcess.kt
1631836554
package io.github.zeqky.catan.process import org.bukkit.entity.Player class CatanPlayer(val player: Player) { }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanPlayer.kt
27978191
package io.github.zeqky.catan.process import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch class CatanProcess(val prep: CatanPreProcess) { fun launch(scope: CoroutineScope) { scope.launch { } } fun update() { prep.fakeEntityServer.update() } }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanProcess.kt
3308348581
package io.github.zeqky.catan.process.dialog class PhaseTradeAndBuild { }
catan/src/main/kotlin/io/github/zeqky/catan/process/dialog/PhaseTradeAndBuild.kt
268837465
package io.github.zeqky.catan.process.dialog import io.github.zeqky.catan.process.CatanPlayer open class CatanPhase { open fun button() { } open fun timeout() { } open fun message() { } open suspend fun request(player: CatanPlayer): Any { return 0 } }
catan/src/main/kotlin/io/github/zeqky/catan/process/dialog/CatanPhase.kt
3989670292
package io.github.zeqky.catan.process.dialog class PhaseOnlyBuild { }
catan/src/main/kotlin/io/github/zeqky/catan/process/dialog/PhaseOnlyBuild.kt
224069721
package io.github.zeqky.catan.process.dialog import io.github.zeqky.catan.process.CatanPlayer class PhaseDice: CatanPhase() { override suspend fun request(player: CatanPlayer): Int { //TODO 주사위 만든 후 업뎃 예정 return 0 } }
catan/src/main/kotlin/io/github/zeqky/catan/process/dialog/PhaseDice.kt
1984686445
package io.github.zeqky.catan.process class Thief { }
catan/src/main/kotlin/io/github/zeqky/catan/process/Thief.kt
590107754
package io.github.zeqky.catan.process import org.bukkit.Location class CatanLand { lateinit var loc: Location }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanLand.kt
2377667470
package io.github.zeqky.catan.process import org.bukkit.event.Listener class CatanListener : Listener { }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanListener.kt
1421050749
package io.github.zeqky.catan.process import org.bukkit.Location import org.bukkit.Material import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.entity.ArmorStand import org.bukkit.inventory.ItemStack import java.io.File class Dice(val process: CatanPreProcess, catanPlayer: CatanPlayer) { val spawnLoc: Location val dice = process.fakeEntityServer.spawnEntity(catanPlayer.player.location, ArmorStand::class.java).apply { updateMetadata { isInvisible = true isInvulnerable = true } updateEquipment { setHelmet(ItemStack(Material.PAPER).apply { editMeta { it.setCustomModelData(1) } }, true) } } init { val yaml = YamlConfiguration.loadConfiguration(File(process.plugin.dataFolder, "config.yml")).getConfigurationSection("dice-loc") spawnLoc = Location(process.world, yaml?.getDouble("x")!!, yaml.getDouble("y"), yaml.getDouble("z")) } fun roll() { } fun update() { } }
catan/src/main/kotlin/io/github/zeqky/catan/process/Dice.kt
2081595023
package io.github.zeqky.catan.process import org.bukkit.Location class CatanZone() { lateinit var type: ZoneType lateinit var loc: Location } enum class ZoneType { ROAD, TOWN }
catan/src/main/kotlin/io/github/zeqky/catan/process/CatanZone.kt
4088497389
package com.ars.wakeup 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.ars.wakeup", appContext.packageName) } }
WakeUp/app/src/androidTest/java/com/ars/wakeup/ExampleInstrumentedTest.kt
2979088072
package com.ars.wakeup 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) } }
WakeUp/app/src/test/java/com/ars/wakeup/ExampleUnitTest.kt
833197733
package com.ars.wakeup.database import androidx.room.TypeConverter import java.util.Date class Converters { @TypeConverter fun fromTimestamp(value: Long?): Date? { return value?.let { Date(it) } } @TypeConverter fun dateToTimestamp(date: Date?): Long? { return date?.time } }
WakeUp/app/src/main/java/com/ars/wakeup/database/Converters.kt
3370734221
package com.ars.wakeup.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters @Database(entities = [WakeUpHistory::class], version = 1) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun wakeUpDao(): WakeUpDao }
WakeUp/app/src/main/java/com/ars/wakeup/database/AppDatabase.kt
37934523
package com.ars.wakeup.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.util.Date @Entity(tableName = "history") data class WakeUpHistory( @PrimaryKey val id: Int, @ColumnInfo(name = "date_start") val dateStart: Date, @ColumnInfo(name = "date_end") val dateEnd: Date, @ColumnInfo(name = "travel_minutes") val travelMinutes: Int?, @ColumnInfo(name = "travel_occurrences") val travelOccurrences: Int? ) {}
WakeUp/app/src/main/java/com/ars/wakeup/database/WakeUpHistory.kt
183433976
package com.ars.wakeup.database import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface WakeUpDao { @Query("SELECT * FROM history") fun getAll(): List<WakeUpHistory> @Insert fun insertAll(vararg history: WakeUpHistory) }
WakeUp/app/src/main/java/com/ars/wakeup/database/WakeUpDao.kt
199106869
package com.ars.wakeup import android.Manifest import android.app.AlertDialog import android.content.ContentValues import android.content.pm.PackageManager import android.media.MediaPlayer import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.ImageButton import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.MediaStoreOutputOptions import androidx.camera.video.Quality import androidx.camera.video.QualitySelector import androidx.camera.video.Recorder import androidx.camera.video.Recording import androidx.camera.video.VideoCapture import androidx.camera.video.VideoRecordEvent import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.room.Room import com.ars.wakeup.data.WakeUpAdapter import com.ars.wakeup.database.AppDatabase import com.ars.wakeup.database.WakeUpHistory import com.ars.wakeup.databinding.ActivityMainBinding import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class MainActivity : AppCompatActivity() { private lateinit var viewBinding: ActivityMainBinding private lateinit var db: AppDatabase private lateinit var wakeUpList: ArrayList<WakeUpHistory> private lateinit var wakeUpAdapter: WakeUpAdapter private var mediaPlayer: MediaPlayer? = null private var videoCapture: VideoCapture<Recorder>? = null private var recording: Recording? = null private lateinit var cameraExecutor: ExecutorService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(viewBinding.root) // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { requestPermissions() } // Set up the listener for video capture button viewBinding.btVideoStart.setOnClickListener { captureVideo() } viewBinding.btHistoric.setOnClickListener { showHistoricModal() } wakeUpList = ArrayList() cameraExecutor = Executors.newSingleThreadExecutor() initDatabase() viewBinding.btAlarm1.setOnClickListener { toggleAlarm(viewBinding.btAlarm1, R.raw.music_1) } viewBinding.btAlarm2.setOnClickListener { toggleAlarm(viewBinding.btAlarm2, R.raw.music_2) } } private fun captureVideo() { val videoCapture = this.videoCapture ?: return viewBinding.btVideoStart.isEnabled = false viewBinding.btHistoric.isActivated = false val curRecording = recording if (curRecording != null) { // Stop the current recording session. curRecording.stop() recording = null return } // create and start a new recording session val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { viewBinding.btHistoric.apply { isVisible = false } viewBinding.btAlarm1.apply { isVisible = true } viewBinding.btAlarm2.apply { isVisible = true } viewBinding.btVideoStart.apply { contentDescription = getString(R.string.stop_capture) setImageResource(R.drawable.ic_stop_video) layoutParams.width = resources.getDimensionPixelSize(R.dimen.button_100) layoutParams.height = resources.getDimensionPixelSize(R.dimen.button_100) isEnabled = true } } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { val msg = "Video capture succeeded: " + "${recordEvent.outputResults.outputUri}" Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT) .show() Log.d(TAG, msg) } else { recording?.close() recording = null Log.e(TAG, "Video capture ends with error: " + "${recordEvent.error}") } if (viewBinding.btAlarm1.isActivated || viewBinding.btAlarm2.isActivated) { stopAlarm() } viewBinding.btHistoric.apply { isVisible = true } viewBinding.btAlarm1.apply { isVisible = false } viewBinding.btAlarm2.apply { isVisible = false } viewBinding.btVideoStart.apply { contentDescription = getString(R.string.start_capture) setImageResource(R.drawable.ic_start_video) layoutParams.width = resources.getDimensionPixelSize(R.dimen.button_150) layoutParams.height = resources.getDimensionPixelSize(R.dimen.button_150) isEnabled = true } val qtd = if (wakeUpList.isNotEmpty()) wakeUpList.count() + 1 else 1 // used to generate random values val wakeUpHistory = WakeUpHistory(id = qtd, dateStart = Date(System.currentTimeMillis()), dateEnd = Date(System.currentTimeMillis() + 60 * 60 * 1000), travelMinutes = kotlin.random.Random.nextInt(30, 1000), travelOccurrences = kotlin.random.Random.nextInt(1, 10)) saveData(wakeUpHistory) } } } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(viewBinding.pvFinder.surfaceProvider) } val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.HIGHEST)) .build() videoCapture = VideoCapture.withOutput(recorder) // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera cameraProvider.bindToLifecycle( this, cameraSelector, preview, videoCapture) } catch(exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } private fun requestPermissions() { activityResultLauncher.launch(REQUIRED_PERMISSIONS) } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CameraXApp" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA ).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } private val activityResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { permissions -> // Handle Permission granted/rejected var permissionGranted = true permissions.entries.forEach { if (it.key in REQUIRED_PERMISSIONS && !it.value) permissionGranted = false } if (!permissionGranted) { Toast.makeText(baseContext, "Permission request denied", Toast.LENGTH_SHORT).show() } else { startCamera() } } private fun showHistoricModal() { val dialogView = layoutInflater.inflate(R.layout.historic_layout, null) val rv = dialogView.findViewById<RecyclerView>(R.id.rv_history) setupRecyclerView(rv) val builder = AlertDialog.Builder(this) builder.setView(dialogView) val alertDialog = builder.create() alertDialog.show() loadData() } private fun toggleAlarm(button: ImageButton, soundResource: Int) { if (button.isActivated) { stopAlarm() } else { startAlarm(soundResource) } button.isActivated = !button.isActivated } private fun startAlarm(soundResource: Int) { if (soundResource != 0) { mediaPlayer = MediaPlayer.create(this, soundResource) mediaPlayer?.isLooping = true mediaPlayer?.start() } } private fun stopAlarm() { mediaPlayer?.apply { if (isPlaying) { stop() } release() } mediaPlayer = null } private fun initDatabase() { db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "database-history" ) .allowMainThreadQueries() .build() } private fun setupRecyclerView(rv: RecyclerView) { rv.layoutManager = LinearLayoutManager(this) wakeUpList = ArrayList() wakeUpAdapter = WakeUpAdapter(wakeUpList, 1) rv.adapter = wakeUpAdapter } private fun loadData() { wakeUpList.clear() wakeUpList.addAll(db.wakeUpDao().getAll() as ArrayList<WakeUpHistory>) } private fun saveData(value: WakeUpHistory) { db.wakeUpDao().insertAll(value) } }
WakeUp/app/src/main/java/com/ars/wakeup/MainActivity.kt
2678160738
package com.ars.wakeup.data import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.ars.wakeup.R import com.ars.wakeup.database.WakeUpHistory import java.text.SimpleDateFormat import java.util.Locale class WakeUpAdapter(private val dataSet: List<WakeUpHistory>, i: Int) : RecyclerView.Adapter<WakeUpAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.rv_history, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = dataSet[position] holder.bind(item) } override fun getItemCount(): Int { return dataSet.size } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val tvHistory: TextView = itemView.findViewById(R.id.tv_history) fun bind(history: WakeUpHistory) { val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault()) val formattedDateStart = dateFormat.format(history.dateStart) val formattedDateEnd = dateFormat.format(history.dateEnd) val occurrences = history.travelOccurrences val minutes = history.travelMinutes val historyText = "Start: $formattedDateStart - " + "End: $formattedDateEnd | " + "$minutes min | " + "$occurrences" tvHistory.text = historyText } } }
WakeUp/app/src/main/java/com/ars/wakeup/data/WakeUpAdapter.kt
3322932400
package com.example.moviekmm.util import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers internal class IosDispatcher: Dispatcher { override val io: CoroutineDispatcher get() = Dispatchers.Default } internal actual fun provideDispatcher(): Dispatcher = IosDispatcher()
MovieKMM/shared/src/iosMain/kotlin/com/example/moviekmm/util/Dispatcher.kt
3487996046
package com.example.moviekmm.util import com.example.moviekmm.di.getSharedModules import org.koin.core.context.startKoin fun initKoin() { startKoin { modules(getSharedModules()) } }
MovieKMM/shared/src/iosMain/kotlin/com/example/moviekmm/util/KoinHelper.kt
3479125056
package com.example.moviekmm.di import com.example.moviekmm.data.remote.MovieService import com.example.moviekmm.data.remote.RemoteDataSource import com.example.moviekmm.data.repository.MovieRepositoryImpl import com.example.moviekmm.domain.repository.MovieRepository import com.example.moviekmm.domain.usecases.GetMovieUseCase import com.example.moviekmm.domain.usecases.GetMoviesUseCase import com.example.moviekmm.util.provideDispatcher import org.koin.dsl.module private val dataModule = module { factory { RemoteDataSource(get(), get()) } factory { MovieService() } } private val utilModule = module { factory { provideDispatcher() } } private val domainModule = module { factory { GetMovieUseCase() } factory { GetMoviesUseCase() } single <MovieRepository> {MovieRepositoryImpl(get())} } private val sharedModules = listOf(dataModule, utilModule, domainModule) fun getSharedModules() = sharedModules
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/di/SharedModules.kt
2069658632
package com.example.moviekmm.util import kotlinx.coroutines.CoroutineDispatcher internal interface Dispatcher { val io: CoroutineDispatcher } internal expect fun provideDispatcher(): Dispatcher
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/util/Dispatcher.kt
436142568
package com.example.moviekmm.data.repository import com.example.moviekmm.data.remote.RemoteDataSource import com.example.moviekmm.data.util.toMovie import com.example.moviekmm.domain.model.Movie import com.example.moviekmm.domain.repository.MovieRepository internal class MovieRepositoryImpl( private val remoteDataSource: RemoteDataSource ): MovieRepository { override suspend fun getMovies(page: Int): List<Movie> { return remoteDataSource.getMovies(page = page).results.map { it.toMovie() } } override suspend fun getMovie(movieId: Int): Movie { return remoteDataSource.getMovie(movieId = movieId).toMovie() } }
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/repository/MovieRepositoryImpl.kt
1062971522
package com.example.moviekmm.data.util import com.example.moviekmm.data.remote.MovieDetail import com.example.moviekmm.domain.model.Movie internal fun MovieDetail.toMovie(): Movie { return Movie( id = id, title = title, description = overview, image = getImage(postImage), releaseDate = releaseDate ) } private fun getImage(postImage: String) = "https://www.themoviedb.org/t/p/w500/${postImage}"
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/util/Mapper.kt
310670750
package com.example.moviekmm.data.remote import com.example.moviekmm.util.Dispatcher import kotlinx.coroutines.withContext internal class RemoteDataSource( private val apiService: MovieService, private val dispatcher: Dispatcher ) { suspend fun getMovies(page: Int) = withContext(dispatcher.io) { apiService.getMovies(page) } suspend fun getMovie(movieId: Int) = withContext(dispatcher.io) { apiService.getMovie(movieId) } }
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/remote/RemoteDataSource.kt
43078186
package com.example.moviekmm.data.remote import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class MovieDetail( val id: Int, val title: String, val overview: String, @SerialName("poster_path") val postImage: String, @SerialName("release_date") val releaseDate: String, )
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/remote/MovieDetail.kt
2323822663
package com.example.moviekmm.data.remote import io.ktor.client.call.body import io.ktor.client.request.get import io.ktor.client.request.parameter internal class MovieService : KtorApi() { suspend fun getMovies(page: Int = 1): MoviesResponse = client.get { pathUrl("movie/popular") parameter("page", page) }.body() suspend fun getMovie(movieId: Int): MovieDetail = client.get { pathUrl("movie/${movieId}") }.body() }
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/remote/MovieService.kt
3146146779
package com.example.moviekmm.data.remote import io.ktor.client.HttpClient import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.parameter import io.ktor.http.path import io.ktor.http.takeFrom import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.json.Json //d42c2f458c5fd151773ae1c9e28bdff8 //https://api.themoviedb.org/3/movie/603692?api_key=d42c2f458c5fd151773ae1c9e28bdff8 //https://api.themoviedb.org/3/movie/popular?page=1&api_key=d42c2f458c5fd151773ae1c9e28bdff8 private const val BASE_URL = "https://api.themoviedb.org/" private const val API_KEY = "d42c2f458c5fd151773ae1c9e28bdff8" internal abstract class KtorApi { val client = HttpClient { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true useAlternativeNames = false }) } } fun HttpRequestBuilder.pathUrl(endPoint: String) { url { takeFrom(BASE_URL) path("3", endPoint) parameter("api_key", API_KEY) } } }
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/remote/KtorApi.kt
3231582421
package com.example.moviekmm.data.remote import kotlinx.serialization.Serializable @Serializable internal data class MoviesResponse( val results: List<MovieDetail> )
MovieKMM/shared/src/commonMain/kotlin/com/example/moviekmm/data/remote/MoviesResponse.kt
1018326412