content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.control_work2.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | control-work-2/app/src/main/java/com/example/control_work2/ui/theme/Color.kt | 2703139200 |
package com.example.control_work2.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun Control_Work2Theme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | control-work-2/app/src/main/java/com/example/control_work2/ui/theme/Theme.kt | 1604080317 |
package com.example.control_work2.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | control-work-2/app/src/main/java/com/example/control_work2/ui/theme/Type.kt | 2121359486 |
package com.example.control_work2
import androidx.compose.foundation.Image
import android.os.Bundle
import android.service.autofill.OnClickAction
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.control_work2.ui.theme.Control_Work2Theme
import androidx.compose.material3.Button
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Control_Work2Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting()
}
}
}
}
}
@Composable
fun Greeting(modifier: Modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center))
{ var result by remember { mutableStateOf(1)
}
val imageResource = when (result) {
1 -> R.drawable.image_1
2 -> R.drawable.image_2
3 -> R.drawable.image_3
4 -> R.drawable.image_4
5 -> R.drawable.image_5
else -> R.drawable.ic_launcher_background
}
val desc = when (result) {
1 -> "Image 1"
2 -> "Image 2"
3 -> "Image 3"
4 -> "Image 4"
5 -> "Image 5"
else -> "Error:Image not found"
}
val author = when (result) {
1 -> "Hanz Zimmer"
2 -> "Maxym Melnyk"
3 -> "Vincent Van Gog"
4 -> "Michelangelo"
5 -> "Rick Astley"
else -> "Developer is retard, sorry"
}
fun ImageScrollerForward():Int
{
if(result == 5)result = 1
else result++;
return 0;
}
fun ImageScrollerBackward():Int
{
if(result == 1)result = 5
else result--;
return 0;
}
Column (
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
)
{
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.height(500.dp)
.fillMaxWidth()
) {
Image(
painter = painterResource(id = imageResource),
contentDescription = result.toString()
)
}
Column(horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.background(Color.LightGray)
.fillMaxWidth()) {
Text(text = desc, fontSize = 36.sp)
Text(text = author, fontSize = 14.sp)
}
Row(horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Bottom,
modifier = Modifier
.fillMaxSize()
.padding(top = 50.dp)
){
Button(
onClick = {ImageScrollerBackward()})
{
Text("Previous")
}
Button(
onClick = {ImageScrollerForward()})
{
Text("Next")
}
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Control_Work2Theme {
Greeting()
}
} | control-work-2/app/src/main/java/com/example/control_work2/MainActivity.kt | 4007439546 |
package com.example.voicechangerpal
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.voicechangerpal", appContext.packageName)
}
} | VoiceChangerPal/app/src/androidTest/java/com/example/voicechangerpal/ExampleInstrumentedTest.kt | 4030856445 |
package com.example.voicechangerpal
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)
}
} | VoiceChangerPal/app/src/test/java/com/example/voicechangerpal/ExampleUnitTest.kt | 4124030755 |
package com.example.voicechangerpal
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 androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
//Версия с работающей сетОнКликЛистенер но которая просто выводит тост
class MainActivity : AppCompatActivity(),MyAdapter.OnItemClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val itemList = listOf(
Item(R.drawable.elephant, "Піл"),
Item(R.drawable.wolf, "Қасқыр"),
// добавьте больше элементов по мере необходимости
)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
recyclerView.adapter = MyAdapter(itemList,this)
val mainButton=findViewById<Button>(R.id.main_button)
mainButton.setOnClickListener {
val editText1 = findViewById<EditText>(R.id.main_editText)
val text = editText1.text.toString()
val intent = Intent(this, ChangeActivity::class.java)
intent.putExtra("key", text)
startActivity(intent)
}
}
override fun onItemClick(item: Item) {
// Обработка нажатия на элемент (например, открытие второй активити)
// Используйте объект item для получения данных
Toast.makeText(this, "${item.text} нажато", Toast.LENGTH_SHORT).show()
}
} | VoiceChangerPal/app/src/main/java/com/example/voicechangerpal/MainActivity.kt | 713371153 |
package com.example.voicechangerpal
data class Item(val image:Int, val text:String)
| VoiceChangerPal/app/src/main/java/com/example/voicechangerpal/Item.kt | 3714749505 |
package com.example.voicechangerpal
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ChangeActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.change_activity)
val intent = getIntent()
val text = intent.getStringExtra("key")
val editText2 = findViewById<EditText>(R.id.change_editText)
editText2.setText(text)
}
} | VoiceChangerPal/app/src/main/java/com/example/voicechangerpal/ChangeActivity.kt | 347035142 |
package com.example.voicechangerpal
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter (private val itemList: List<Item>,private val itemClickListener: OnItemClickListener) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val image: ImageView = view.findViewById(R.id.image)
val text: TextView = view.findViewById(R.id.text)
init {
view.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
itemClickListener.onItemClick(itemList[position])
}
}
}
}
interface OnItemClickListener {
fun onItemClick(item: Item,)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = itemList[position]
holder.image.setImageResource(currentItem.image)
holder.text.text = currentItem.text
}
override fun getItemCount() = itemList.size
}
| VoiceChangerPal/app/src/main/java/com/example/voicechangerpal/MyAdapter.kt | 1472668899 |
package com.bluetoothliteexample
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "BluetoothLiteExample"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
| react-native-bluetooth-lite/example/android/app/src/main/java/com/bluetoothliteexample/MainActivity.kt | 2918221934 |
package com.bluetoothliteexample
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
| react-native-bluetooth-lite/example/android/app/src/main/java/com/bluetoothliteexample/MainApplication.kt | 3902865933 |
package com.bluetoothlite.types
enum class EventType {
CONNECTION_STATE,
ADAPTER_STATE,
DEVICE_FOUND,
NOTIFICATION,
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/types/EventType.kt | 3786649192 |
package com.bluetoothlite.types
enum class PromiseType {
SCAN,
STOP_SCAN,
CONNECT,
DISCONNECT,
MTU,
DISCOVER_SERVICES,
READ,
WRITE,
NOTIFICATIONS,
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/types/PromiseType.kt | 3404280101 |
package com.bluetoothlite.types
enum class Error {
DEVICE_NOT_FOUND,
BLE_IS_OFF,
SCAN_ERROR,
GATT_ERROR,
IS_NOT_CONNECTED,
IS_ALREADY_SCANNING,
IS_NOT_SCANNING,
SERVICE_NOT_FOUND,
CHARACTERISTIC_NOT_FOUND,
TRANSACTION_ERROR,
READ_ERROR,
WRITE_ERROR,
NOTIFICATIONS_ERROR,
TIMEOUT
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/types/Error.kt | 3948407309 |
package com.bluetoothlite.types
enum class ConnectionState {
DISCONNECTED,
CONNECTING,
CONNECTED,
DISCONNECTING,
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/types/ConnectionState.kt | 894551430 |
package com.bluetoothlite.types
enum class AdapterState {
OFF,
TURNING_OFF,
TURNING_ON,
ON
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/types/AdapterState.kt | 2762814882 |
package com.bluetoothlite
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import com.bluetoothlite.Strings.characteristic
import com.bluetoothlite.Strings.value
import com.bluetoothlite.types.Error
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
object Utils {
object CharacteristicProperties {
const val uuid = Strings.uuid
const val read = Strings.read
const val write = Strings.write
const val writeWithoutResponse = Strings.writeWithoutResponse
const val notify = Strings.notify
}
fun prepareServicesForJS(services: List<BluetoothGattService>): WritableMap {
val jsResponse = Arguments.createMap().apply {
putNull(Strings.error)
}
val servicesMap = Arguments.createMap()
services.forEach { service ->
with(service) {
val characteristicsMap = Arguments.createMap()
characteristics.forEach { characteristic ->
val propertiesMap = Arguments.createMap()
val properties = characteristic.properties
propertiesMap.putBoolean(
CharacteristicProperties.read,
hasProperty(properties, BluetoothGattCharacteristic.PROPERTY_READ)
)
propertiesMap.putBoolean(
CharacteristicProperties.writeWithoutResponse,
hasProperty(properties, BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)
)
propertiesMap.putBoolean(
CharacteristicProperties.write,
hasProperty(properties, BluetoothGattCharacteristic.PROPERTY_WRITE)
)
propertiesMap.putBoolean(
CharacteristicProperties.notify,
hasProperty(properties, BluetoothGattCharacteristic.PROPERTY_WRITE)
)
characteristicsMap.putMap(characteristic.uuid.toString(), propertiesMap)
}
servicesMap.putMap(service.uuid.toString(), characteristicsMap)
}
}
jsResponse.putMap(Strings.services, servicesMap)
return jsResponse
}
private fun hasProperty(properties: Int, property: Int): Boolean {
return (properties and property) > 0
}
private fun decodeBytes(bytes: ByteArray): String {
val charset = Charsets.UTF_8
return bytes.toString(charset)
}
fun getTransactionResponse(
characteristic: BluetoothGattCharacteristic?,
error: Error?,
shouldDecodeBytes: Boolean
): WritableMap {
val response = Arguments.createMap().apply {
putNull(Strings.service)
putNull(Strings.characteristic)
putNull(Strings.value)
putNull(Strings.error)
}
val service = characteristic?.service
if (service != null) response.putString(Strings.service, service.uuid.toString())
if (characteristic != null) response.putString(
Strings.characteristic,
characteristic.uuid.toString()
)
putDecodedValue(characteristic?.value, response, shouldDecodeBytes)
if (error != null) response.putString(Strings.error, error.toString())
return response
}
private fun putDecodedValue(value: ByteArray?, response: WritableMap, shouldDecodeBytes: Boolean) {
if (value == null) {
response.putNull(
Strings.value,
)
return
}
if (shouldDecodeBytes) {
response.putString(
Strings.value,
decodeBytes(value)
)
return
}
response.putArray(
Strings.value,
bytesToWritableArray(value)
)
}
fun arrayToBytes(payload: ReadableArray): ByteArray {
val bytes = ByteArray(payload.size())
for (i in 0 until payload.size()) {
bytes[i] = Integer.valueOf(payload.getInt(i)).toByte()
}
return bytes
}
private fun bytesToWritableArray(bytes: ByteArray): WritableArray? {
val value = Arguments.createArray()
for (i in bytes.indices) value.pushInt(bytes[i].toInt() and 0xFF)
return value
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Utils.kt | 1681119229 |
package com.bluetoothlite
import com.bluetoothlite.GlobalOptions.Companion.Keys.autoDecodeBytes
import com.bluetoothlite.constants.Constants
import com.facebook.react.bridge.ReadableMap
class GlobalOptions(options: ReadableMap?) {
var autoDecode = false
var timeoutDuration = Constants.DEFAULT_TIMEOUT
init {
if (options != null) {
autoDecode = getAutoDecode(options)
timeoutDuration = getTimeout(options)
}
}
private fun getTimeout(options: ReadableMap): Int {
if (options.hasKey(Keys.timeoutDuration)) {
return options.getInt(Keys.timeoutDuration)
}
return Constants.DEFAULT_TIMEOUT
}
private fun getAutoDecode(options: ReadableMap): Boolean {
if (options.hasKey(autoDecodeBytes)) {
return options.getBoolean(autoDecodeBytes)
}
return false
}
companion object {
object Keys {
const val autoDecodeBytes = "autoDecodeBytes"
const val timeoutDuration = "timeoutDuration"
}
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/GlobalOptions.kt | 1481209683 |
package com.bluetoothlite
object Strings {
const val state = "state"
const val isEnabled = "isEnabled"
const val isConnected = "isConnected"
const val mtu = "mtu"
const val error = "error"
const val service = "service"
const val characteristic = "characteristic"
const val services = "services"
const val isScanning = "isScanning"
const val name = "name"
const val address = "address"
const val rssi = "rssi"
const val connectionState = "connectionState"
const val adapterState = "adapterState"
const val value = "value"
const val bytes = "bytes"
const val uuid = "uuid"
const val read = "read"
const val write = "write"
const val writeWithoutResponse = "writeWithoutResponse"
const val notify = "notify"
const val devices = "devices"
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Strings.kt | 4155753167 |
package com.bluetoothlite.constants
import android.bluetooth.BluetoothAdapter
import com.bluetoothlite.types.AdapterState
object Constants {
const val DEFAULT_TIMEOUT = 10
val AdapterStateMap: HashMap<Int, AdapterState> = HashMap<Int, AdapterState>().apply {
put(BluetoothAdapter.STATE_OFF, AdapterState.OFF)
put(BluetoothAdapter.STATE_TURNING_ON, AdapterState.ON)
put(BluetoothAdapter.STATE_ON, AdapterState.TURNING_ON)
put(BluetoothAdapter.STATE_TURNING_OFF, AdapterState.TURNING_OFF)
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/constants/Constants.kt | 1136708684 |
package com.bluetoothlite
import com.bluetoothlite.Strings.address
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
class BluetoothLiteModule(
reactContext: ReactApplicationContext,
) :
ReactContextBaseJavaModule(reactContext) {
private val adapter: Adapter
private val events: Events
private val promiseManager = PromiseManager(HashMap())
private val scanner: Scanner
private val gatt: Gatt
private val adapterStateReceiver: AdapterStateReceiver
init {
adapter = Adapter(reactContext)
events = Events(reactContext)
gatt = Gatt(reactContext, adapter, promiseManager, events)
scanner = Scanner(adapter, promiseManager, events)
adapterStateReceiver = AdapterStateReceiver(reactContext, gatt, scanner, promiseManager, events)
adapterStateReceiver.start()
}
@ReactMethod
private fun setOptions(options: ReadableMap?) {
val globalOptions = GlobalOptions(options)
gatt.globalOptions = globalOptions
scanner.globalOptions = globalOptions
}
@ReactMethod
private fun startScan(options: ReadableMap?, promise: Promise) {
scanner.startScan(options, promise)
}
@ReactMethod
private fun stopScan(promise: Promise) {
scanner.stopScan(promise)
}
@ReactMethod
private fun connect(address: String, options: ReadableMap?, promise: Promise) {
gatt.connect(address, options, promise)
}
@ReactMethod
private fun disconnect(promise: Promise) {
gatt.disconnect(promise)
}
@ReactMethod
private fun requestMtu(size: Int?, promise: Promise) {
gatt.requestMtu(size, promise)
}
@ReactMethod
private fun discoverServices(services: ReadableMap?, promise: Promise) {
gatt.discoverServices(promise)
}
@ReactMethod
private fun writeString(
service: String,
characteristic: String,
payload: String,
promise: Promise
) {
gatt.writeString(service, characteristic, payload, promise)
}
@ReactMethod
private fun writeStringWithoutResponse(
service: String,
characteristic: String,
payload: String,
promise: Promise
) {
gatt.writeStringWithoutResponse(service, characteristic, payload, promise)
}
@ReactMethod
private fun write(
service: String,
characteristic: String,
payload: ReadableArray,
promise: Promise
) {
gatt.write(service, characteristic, payload, promise)
}
@ReactMethod
private fun writeWithoutResponse(
service: String,
characteristic: String,
payload: ReadableArray,
promise: Promise
) {
gatt.writeWithoutResponse(service, characteristic, payload, promise)
}
@ReactMethod
private fun read(service: String, characteristic: String, promise: Promise) {
gatt.read(service, characteristic, promise)
}
@ReactMethod
private fun enableNotifications(service: String, characteristic: String, promise: Promise) {
gatt.enableNotifications(service, characteristic, promise)
}
@ReactMethod
private fun disableNotifications(service: String, characteristic: String, promise: Promise) {
gatt.disableNotifications(service, characteristic, promise)
}
@ReactMethod
private fun isEnabled(promise: Promise) {
gatt.isEnabled(promise)
}
@ReactMethod
private fun getAdapterState(promise: Promise) {
gatt.getAdapterState(promise)
}
@ReactMethod
private fun getConnectionState(promise: Promise) {
gatt.getConnectionState(promise)
}
@ReactMethod
private fun isConnected(promise: Promise) {
gatt.isConnected(promise)
}
@ReactMethod
private fun destroy() {
adapterStateReceiver.stop()
gatt.destroyGatt()
}
@ReactMethod
fun addListener(eventName: String?) {
}
@ReactMethod
fun removeListeners(count: Int?) {
}
override fun getName(): String {
return NAME
}
companion object {
const val NAME = "BluetoothLite"
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/BluetoothLiteModule.kt | 806186408 |
package com.bluetoothlite
import com.bluetoothlite.types.Error
import com.bluetoothlite.types.PromiseType
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.WritableMap
class PromiseManager(private val pendingPromises: HashMap<PromiseType, MutableList<Pair<Promise, Timeout?>>>) {
fun resolvePromise(promiseType: PromiseType, payload: WritableMap) {
val (promise, timeout) = getNextPromise(promiseType) ?: return
timeout?.cancel()
promise.resolve(payload)
}
fun addPromise(promiseType: PromiseType, promise: Promise?, timeout: Int?) {
if (promise == null) return
if (pendingPromises[promiseType] == null) {
pendingPromises[promiseType] = mutableListOf()
}
val promiseTimeout = getTimeout(promiseType, timeout)
pendingPromises[promiseType]?.add(Pair(promise, promiseTimeout))
}
private fun getTimeout (promiseType: PromiseType, duration: Int?): Timeout? {
if (duration == null || duration <= 0) {
return null
}
val onTimeout = Runnable {
val response = Arguments.createMap().apply { putString(Strings.error, Error.TIMEOUT.toString()) }
resolvePromise(promiseType, response)
}
val timeout = Timeout()
timeout.set(onTimeout, duration)
return timeout
}
private fun getNextPromise(promiseType: PromiseType): Pair<Promise, Timeout?>? {
val list = pendingPromises[promiseType]
if (list.isNullOrEmpty()) {
return null
}
val nextPromise = list.first()
list.removeFirst()
return nextPromise
}
fun resolveAllWithError(error: Error) {
val response = Arguments.createMap().apply {
putString(Strings.error, error.toString())
}
pendingPromises.values.forEach(){ promiseList ->
promiseList.forEach{item ->
val (promise, timeout) = item
timeout?.cancel()
promise.resolve(response)
}
}
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/PromiseManager.kt | 620834988 |
package com.bluetoothlite
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothProfile
import com.bluetoothlite.Utils.arrayToBytes
import com.bluetoothlite.Utils.getTransactionResponse
import com.bluetoothlite.types.ConnectionState
import com.bluetoothlite.types.Error
import com.bluetoothlite.types.PromiseType
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import java.util.UUID
@SuppressLint("MissingPermission")
class Gatt(
private val reactContext: ReactApplicationContext,
private val adapter: Adapter,
private val promiseManager: PromiseManager,
private val events: Events
) {
private var connectionState: ConnectionState = ConnectionState.DISCONNECTED
private val timeout = Timeout()
private var bluetoothGatt: BluetoothGatt? = null
private lateinit var connectionOptions: ConnectionOptions
var globalOptions = GlobalOptions(null)
fun getAdapterState(promise: Promise) {
val response = Arguments.createMap().apply {
putString(Strings.adapterState, adapter.getState().toString())
}
promise.resolve(response)
}
fun isEnabled(promise: Promise) {
val response = Arguments.createMap().apply {
putBoolean(Strings.isEnabled, adapter.isEnabled())
}
promise.resolve(response)
}
fun getConnectionState(promise: Promise) {
val response = Arguments.createMap().apply {
putString(Strings.state, connectionState.toString())
}
promise.resolve(response)
}
fun isConnected(promise: Promise) {
val isConnected = connectionState == ConnectionState.CONNECTED
val response = Arguments.createMap().apply {
putBoolean(Strings.isConnected, isConnected)
}
promise.resolve(response)
}
private fun getDevice(address: String, promise: Promise): BluetoothDevice? {
val gattDevice = bluetoothGatt?.device
val isDeviceFound = gattDevice != null && gattDevice.address.toString() == address
if (!isDeviceFound) {
destroyGatt()
}
val device = if (isDeviceFound) gattDevice else adapter.getDevice(address)
if (device == null) {
promise.resolve(Arguments.createMap().apply {
putBoolean(Strings.isConnected, connectionState == ConnectionState.CONNECTED)
})
return null
}
return device
}
fun connect(address: String, options: ReadableMap?, promise: Promise) {
if (!adapter.isEnabled()) {
onAdapterDisabled(promise)
return
}
if (connectionState != ConnectionState.DISCONNECTED) {
promise.resolve(Arguments.createMap().apply {
putBoolean(Strings.isConnected, connectionState == ConnectionState.CONNECTED)
})
return
}
connectionOptions = ConnectionOptions(options)
setConnectionTimeout()
val device = getDevice(address, promise) ?: return
promiseManager.addPromise(PromiseType.CONNECT, promise, null)
if (bluetoothGatt != null) {
bluetoothGatt?.connect()
return
}
bluetoothGatt = device.connectGatt(reactContext, false, gattCallback)
}
private fun setConnectionTimeout() {
val onTimeout = Runnable {
disconnect(null)
resolveConnectionPromise()
destroyGatt()
}
timeout.set(onTimeout, connectionOptions.connectionDuration)
}
private fun onAdapterDisabled(promise: Promise) {
val response =
Arguments.createMap().apply { putString(Strings.error, Error.BLE_IS_OFF.toString()) }
promise.resolve(response)
}
private fun onConnected() {
timeout.cancel()
resolveConnectionPromise()
}
private fun onDisconnected() {
resolveDisconnectPromise()
promiseManager.resolveAllWithError(Error.IS_NOT_CONNECTED)
}
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
if (status != BluetoothGatt.GATT_SUCCESS) {
promiseManager.resolveAllWithError(Error.GATT_ERROR)
}
connectionState = ConnectionStateMap[newState] ?: ConnectionState.DISCONNECTED
events.emitStateChangeEvent(connectionState)
if (connectionState == ConnectionState.CONNECTED) onConnected()
if (connectionState == ConnectionState.DISCONNECTED) onDisconnected()
}
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
val payload = Arguments.createMap().apply {
putInt(Strings.mtu, mtu)
putNull(Strings.error)
}
promiseManager.resolvePromise(PromiseType.MTU, payload)
}
override fun onCharacteristicRead(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
if (status == BluetoothGatt.GATT_SUCCESS) {
promiseManager.resolvePromise(
PromiseType.READ,
getTransactionResponse(characteristic, null, globalOptions.autoDecode)
)
return
}
promiseManager.resolvePromise(
PromiseType.READ,
getTransactionResponse(characteristic, Error.READ_ERROR, globalOptions.autoDecode)
)
}
override fun onCharacteristicWrite(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
if (status != BluetoothGatt.GATT_SUCCESS) {
promiseManager.resolvePromise(
PromiseType.WRITE, getTransactionResponse(
characteristic,
Error.WRITE_ERROR, globalOptions.autoDecode
)
)
return
}
promiseManager.resolvePromise(
PromiseType.WRITE, getTransactionResponse(
characteristic,
null, globalOptions.autoDecode
)
)
}
override fun onDescriptorWrite(
gatt: BluetoothGatt?,
descriptor: BluetoothGattDescriptor?,
status: Int
) {
if (status == BluetoothGatt.GATT_SUCCESS) {
promiseManager.resolvePromise(
PromiseType.NOTIFICATIONS,
getTransactionResponse(descriptor?.characteristic, null, globalOptions.autoDecode)
)
return
}
promiseManager.resolvePromise(
PromiseType.NOTIFICATIONS,
getTransactionResponse(
descriptor?.characteristic,
Error.NOTIFICATIONS_ERROR,
globalOptions.autoDecode
)
)
}
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic
) {
events.emitNotificationEvent(getTransactionResponse(characteristic, null, globalOptions.autoDecode))
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
sendServicesToJS(gatt.services)
}
}
private fun getCharacteristicAndCheckConnection(
serviceId: String,
characteristicId: String,
promise: Promise,
): BluetoothGattCharacteristic? {
val response = Arguments.createMap().apply {
putString(Strings.service, serviceId)
putString(Strings.characteristic, characteristicId)
putNull(Strings.error)}
if (!adapter.isEnabled()) {
response.putString(Strings.error, Error.BLE_IS_OFF.toString())
promise.resolve(response)
return null
}
if (connectionState != ConnectionState.CONNECTED) {
response.putString(Strings.error, Error.IS_NOT_CONNECTED.toString())
promise.resolve(response)
return null
}
return getCharacteristic(serviceId, characteristicId, promise)
}
fun writeString(serviceId: String, characteristicId: String, payload: String, promise: Promise) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
writeCharacteristic(characteristic, payload.toByteArray(), null, promise)
}
fun writeStringWithoutResponse(
serviceId: String,
characteristicId: String,
payload: String,
promise: Promise
) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
writeCharacteristic(
characteristic,
payload.toByteArray(),
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
promise
)
}
fun write(serviceId: String, characteristicId: String, payload: ReadableArray, promise: Promise) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
writeCharacteristic(characteristic, arrayToBytes(payload), null, promise)
}
fun writeWithoutResponse(
serviceId: String,
characteristicId: String,
payload: ReadableArray,
promise: Promise
) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
writeCharacteristic(
characteristic,
arrayToBytes(payload),
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE,
promise,
)
}
private fun writeCharacteristic(
characteristic: BluetoothGattCharacteristic,
value: ByteArray,
writeType: Int?,
promise: Promise
) {
characteristic.value = value
characteristic.writeType = writeType ?: BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
promiseManager.addPromise(PromiseType.WRITE, promise, globalOptions.timeoutDuration)
try {
bluetoothGatt?.writeCharacteristic(characteristic)
} catch (error: Throwable) {
promiseManager.resolvePromise(
PromiseType.WRITE, getTransactionResponse(
characteristic,
Error.WRITE_ERROR, globalOptions.autoDecode
)
)
}
}
fun read(serviceId: String, characteristicId: String, promise: Promise) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
promiseManager.addPromise(PromiseType.READ, promise, globalOptions.timeoutDuration)
try {
bluetoothGatt?.readCharacteristic(characteristic)
} catch (error: Throwable) {
promise.resolve(getTransactionResponse(
characteristic,
Error.READ_ERROR,
globalOptions.autoDecode
))
}
}
fun enableNotifications(serviceId: String, characteristicId: String, promise: Promise) {
toggleNotifications(serviceId, characteristicId, true, promise)
}
fun disableNotifications(serviceId: String, characteristicId: String, promise: Promise) {
toggleNotifications(serviceId, characteristicId, false, promise)
}
private fun toggleNotifications(
serviceId: String,
characteristicId: String,
enable: Boolean,
promise: Promise
) {
val characteristic = getCharacteristicAndCheckConnection(
serviceId,
characteristicId,
promise
) ?: return
val descriptorUUID = characteristic.descriptors?.firstOrNull()?.uuid
val payload =
if (enable) BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE else BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
try {
characteristic.getDescriptor(descriptorUUID).let { cccDescriptor ->
if (bluetoothGatt?.setCharacteristicNotification(characteristic, true) == false) {
promise.resolve(
getTransactionResponse(characteristic, Error.NOTIFICATIONS_ERROR, globalOptions.autoDecode)
)
return
}
cccDescriptor.value = payload
promiseManager.addPromise(PromiseType.NOTIFICATIONS, promise, globalOptions.timeoutDuration)
bluetoothGatt?.writeDescriptor(cccDescriptor)
}
} catch (error: Throwable) {
promiseManager.resolvePromise(
PromiseType.NOTIFICATIONS,
getTransactionResponse(characteristic, Error.NOTIFICATIONS_ERROR, globalOptions.autoDecode)
)
}
}
fun requestMtu(size: Int?, promise: Promise) {
if (connectionState != ConnectionState.CONNECTED) {
promise.resolve(Arguments.createMap().apply {
putString(Strings.error, Error.IS_NOT_CONNECTED.toString())
putNull(Strings.mtu)
})
return
}
promiseManager.addPromise(PromiseType.MTU, promise, globalOptions.timeoutDuration)
bluetoothGatt?.requestMtu(size ?: GATT_MAX_MTU_SIZE)
}
fun discoverServices(promise: Promise) {
if (connectionState != ConnectionState.CONNECTED) {
val response = Arguments.createMap().apply {
putString(Strings.error, Error.IS_NOT_CONNECTED.toString())
putNull(Strings.services)
}
promise.resolve(response)
return
}
promiseManager.addPromise(PromiseType.DISCOVER_SERVICES, promise, globalOptions.timeoutDuration)
bluetoothGatt?.discoverServices()
}
private fun resolveConnectionPromise() {
val payload = Arguments.createMap().apply {
putBoolean(Strings.isConnected, connectionState == ConnectionState.CONNECTED)
}
promiseManager.resolvePromise(PromiseType.CONNECT, payload)
}
private fun resolveDisconnectPromise() {
val payload = Arguments.createMap().apply {
putBoolean(Strings.isConnected, connectionState == ConnectionState.CONNECTED)
}
promiseManager.resolvePromise(PromiseType.DISCONNECT, payload)
}
private fun getCharacteristic(
serviceId: String,
characteristicId: String,
promise: Promise,
): BluetoothGattCharacteristic? {
val service = bluetoothGatt?.getService(UUID.fromString(serviceId.lowercase()))
if (service == null) {
promise.resolve(getTransactionResponse(
null,
Error.SERVICE_NOT_FOUND,
globalOptions.autoDecode
))
}
val characteristic = service?.getCharacteristic(UUID.fromString(characteristicId.lowercase()))
if (characteristic == null) {
promise.resolve(getTransactionResponse(
null, Error.CHARACTERISTIC_NOT_FOUND, globalOptions.autoDecode
))
return null
}
return characteristic
}
private fun sendServicesToJS(services: List<BluetoothGattService>) {
val jsResponse = Utils.prepareServicesForJS(services)
promiseManager.resolvePromise(PromiseType.DISCOVER_SERVICES, jsResponse)
}
fun disconnect(promise: Promise?) {
if (connectionState != ConnectionState.CONNECTED) {
promise?.resolve(Arguments.createMap().apply {
putBoolean(Strings.isConnected, connectionState == ConnectionState.CONNECTED)
})
} else {
promiseManager.addPromise(PromiseType.DISCONNECT, promise, globalOptions.timeoutDuration)
}
bluetoothGatt?.disconnect()
}
fun destroyGatt() {
bluetoothGatt?.disconnect()
bluetoothGatt?.close()
bluetoothGatt = null
connectionState = ConnectionState.DISCONNECTED
events.emitStateChangeEvent(ConnectionState.DISCONNECTED)
}
companion object {
private const val GATT_MAX_MTU_SIZE = 517
private val ConnectionStateMap = hashMapOf(
BluetoothProfile.STATE_DISCONNECTED to ConnectionState.DISCONNECTED,
BluetoothProfile.STATE_CONNECTING to ConnectionState.CONNECTING,
BluetoothProfile.STATE_CONNECTED to ConnectionState.CONNECTED,
BluetoothProfile.STATE_DISCONNECTING to ConnectionState.DISCONNECTING,
)
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Gatt.kt | 3569481700 |
package com.bluetoothlite
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.bluetoothlite.types.AdapterState
import com.bluetoothlite.types.Error
import com.facebook.react.bridge.ReactApplicationContext
class AdapterStateReceiver(
private val reactContext: ReactApplicationContext,
gatt: Gatt,
scanner: Scanner,
private val promiseManager: PromiseManager,
events: Events
) {
private val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
private var isRegistered = false
private val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
if (intent?.action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
when (intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
BluetoothAdapter.STATE_OFF -> {
events.emitAdapterStateChangeEvent(AdapterState.OFF)
gatt.destroyGatt()
promiseManager.resolveAllWithError(Error.BLE_IS_OFF)
}
BluetoothAdapter.STATE_TURNING_OFF -> {
events.emitAdapterStateChangeEvent(AdapterState.TURNING_OFF)
gatt.disconnect(null)
scanner.stopScan(null)
}
BluetoothAdapter.STATE_TURNING_ON -> {
events.emitAdapterStateChangeEvent(AdapterState.TURNING_ON)
}
BluetoothAdapter.STATE_ON -> {
events.emitAdapterStateChangeEvent(AdapterState.ON)
}
}
}
}
}
fun start() {
if (isRegistered) return
reactContext.registerReceiver(broadCastReceiver, filter)
}
fun stop() {
if (!isRegistered) return
reactContext.unregisterReceiver(broadCastReceiver)
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/AdapterStateReceiver.kt | 3253920931 |
package com.bluetoothlite
import android.annotation.SuppressLint
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import com.bluetoothlite.types.Error
import com.bluetoothlite.types.PromiseType
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.WritableMap
import com.facebook.react.bridge.WritableNativeArray
@SuppressLint("MissingPermission")
class Scanner(
private val adapter: Adapter,
private val promiseManager: PromiseManager,
private val events: Events,
) {
private var isScanning = false
private val timeout = Timeout()
private lateinit var scanOptions: ScanOptions
private var devices: HashMap<String, ScanResult> = HashMap()
var globalOptions = GlobalOptions(null)
fun startScan(options: ReadableMap?, promise: Promise) {
if (isScanning) {
promise.resolve(
Arguments.createMap().apply { putString( Strings.error, Error.IS_ALREADY_SCANNING.toString()) })
return
}
if (!adapter.isEnabled()) {
onAdapterDisabled(promise)
return
}
scanOptions = ScanOptions(options)
devices.clear()
isScanning = true
promiseManager.addPromise(PromiseType.SCAN, promise, null)
adapter.startScan(scanOptions.filters, scanCallback)
setScanTimeout()
}
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
if (devices[result.device.address] != null) return
events.emitDeviceFoundEvent(prepareDiscoveredData(result))
devices[result.device.address] = result
if (scanOptions.shouldFindOne) {
stopScan(null)
}
}
override fun onScanFailed(errorCode: Int) {
onScanStopped()
}
}
fun stopScan(promise: Promise?) {
cancelErrorTimeout()
if (!isScanning) {
promise?.resolve(Arguments.createMap().apply {
putString(Strings.error, Error.IS_NOT_SCANNING.toString())
putBoolean(Strings.isScanning, isScanning)
})
return
}
promiseManager.addPromise(PromiseType.STOP_SCAN, promise, globalOptions.timeoutDuration)
adapter.stopScan(scanCallback)
onScanStopped()
}
fun onScanStopped() {
isScanning = false
val scanResponse = WritableNativeArray()
devices.forEach { entry ->
scanResponse.pushMap(prepareDiscoveredData(entry.value))
}
val scanResult = Arguments.createMap().apply {
putArray(Strings.devices, scanResponse)
putNull(Strings.error)
}
promiseManager.resolvePromise(PromiseType.SCAN, scanResult)
val stopScanResponse = Arguments.createMap().apply {
putBoolean(Strings.isScanning, isScanning)
putNull(Strings.error)
}
promiseManager.resolvePromise(PromiseType.STOP_SCAN, stopScanResponse)
}
private fun onAdapterDisabled(promise: Promise) {
val response = Arguments.createMap().apply { putString( Strings.error, Error.BLE_IS_OFF.toString()) }
promise.resolve(response)
}
private fun setScanTimeout() {
val callback = Runnable {
stopScan(null)
}
timeout.set(callback, scanOptions.scanDuration)
}
private fun cancelErrorTimeout() {
timeout.cancel()
}
private fun prepareDiscoveredData(result: ScanResult): WritableMap {
return Arguments.createMap().apply {
putString(Strings.name, result.device.name)
putString(Strings.address, result.device.address)
putString(Strings.rssi, result.rssi.toString())
}
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Scanner.kt | 236557109 |
package com.bluetoothlite
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class BluetoothLitePackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return listOf(BluetoothLiteModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList()
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/BluetoothLitePackage.kt | 3309284750 |
package com.bluetoothlite
import android.bluetooth.le.ScanFilter
import com.facebook.react.bridge.ReadableMap
class ScanOptions(options: ReadableMap?) {
var filters: List<ScanFilter>? = null
var scanDuration: Int = 0
var shouldFindOne: Boolean = false
init {
if (options != null) {
filters = getScanFilters(options)
scanDuration = getScanDuration(options)
shouldFindOne = getFindOne(options)
}
}
private fun getFindOne(options: ReadableMap): Boolean {
if (options.hasKey(findOne)) {
return options.getBoolean(findOne)
}
return false
}
private fun getScanDuration(options: ReadableMap): Int {
if (options.hasKey(duration)) {
return options.getInt(duration)
}
return 0
}
private fun getScanFilters(options: ReadableMap): List<ScanFilter>? {
val name = options.getString(name)
val address = options.getString(address)
if (name == null && address == null) {
return null
}
val filter = ScanFilter.Builder()
if (name != null) {
filter.setDeviceName(name)
}
if (address != null) {
filter.setDeviceAddress(address)
}
return listOf(filter.build())
}
companion object {
const val name = "name"
const val address = "address"
const val duration = "duration"
const val findOne = "findOne"
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/ScanOptions.kt | 1448994997 |
package com.bluetoothlite
import com.facebook.react.bridge.ReadableMap
class ConnectionOptions(options: ReadableMap?) {
var connectionDuration: Int = 0
init {
if (options != null) {
connectionDuration = getDuration(options)
}
}
private fun getDuration(options: ReadableMap): Int {
if (options.hasKey(duration)) {
return options.getInt(duration)
}
return 0
}
companion object {
const val duration = "duration"
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/ConnectionOptions.kt | 2121020390 |
package com.bluetoothlite
import android.os.Handler
import android.os.Looper
import kotlin.reflect.KFunction
class Timeout {
private var handler: Handler? = null
fun cancel() {
handler?.removeCallbacksAndMessages(null)
}
fun set(callback: Runnable, duration: Int = 0) {
if (handler == null) {
handler = Handler(Looper.getMainLooper())
}
cancel()
if (duration == 0) {
return
}
val durationInMilliseconds = duration * 1000
handler?.postDelayed(callback, durationInMilliseconds.toLong())
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Timeout.kt | 1155902543 |
package com.bluetoothlite
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanSettings
import android.content.Context
import com.bluetoothlite.constants.Constants.AdapterStateMap
import com.bluetoothlite.types.AdapterState
import com.facebook.react.bridge.ReactApplicationContext
@SuppressLint("MissingPermission")
class Adapter (reactContext: ReactApplicationContext) {
private val bluetoothManager: BluetoothManager by lazy {
reactContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
}
private val bluetoothAdapter: BluetoothAdapter by lazy {
bluetoothManager.adapter
}
private val bleScanner by lazy {
bluetoothAdapter.bluetoothLeScanner
}
private val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
fun startScan (filter: List<ScanFilter>?, callback: ScanCallback) {
bleScanner.startScan(filter, scanSettings, callback)
}
fun stopScan (callback: ScanCallback) {
bleScanner.stopScan(callback)
}
fun isEnabled (): Boolean {
return bluetoothAdapter.isEnabled
}
fun getState(): AdapterState {
return AdapterStateMap[bluetoothAdapter.state] ?: AdapterState.OFF
}
fun getDevice(address: String): BluetoothDevice? {
return bluetoothAdapter.getRemoteDevice(address)
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Adapter.kt | 66295725 |
package com.bluetoothlite
import android.bluetooth.BluetoothGattCharacteristic
import com.bluetoothlite.types.AdapterState
import com.bluetoothlite.types.ConnectionState
import com.bluetoothlite.types.EventType
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
class Events (private val reactContext: ReactApplicationContext) {
private fun sendEvent(eventName: EventType, params: WritableMap?) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(eventName.toString(), params)
}
fun emitStateChangeEvent(newState: ConnectionState) {
val params = Arguments.createMap().apply {
putString(Strings.connectionState, newState.toString())
}
sendEvent(EventType.CONNECTION_STATE, params)
}
fun emitAdapterStateChangeEvent(newState: AdapterState) {
val params = Arguments.createMap().apply {
putString(Strings.adapterState, newState.toString())
}
sendEvent(EventType.ADAPTER_STATE, params)
}
fun emitDeviceFoundEvent(deviceScanData: WritableMap) {
sendEvent(EventType.DEVICE_FOUND, deviceScanData)
}
fun emitNotificationEvent(data: WritableMap) {
sendEvent(EventType.NOTIFICATION, data)
}
}
| react-native-bluetooth-lite/android/src/main/java/com/bluetoothlite/Events.kt | 1182525085 |
package com.example.averagemarkcompose
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.averagemarkcompose", appContext.packageName)
}
} | AverageMarkCompose/app/src/androidTest/java/com/example/averagemarkcompose/ExampleInstrumentedTest.kt | 595139732 |
package com.example.averagemarkcompose
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)
}
} | AverageMarkCompose/app/src/test/java/com/example/averagemarkcompose/ExampleUnitTest.kt | 2330312951 |
package com.example.averagemarkcompose.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
| AverageMarkCompose/app/src/main/java/com/example/averagemarkcompose/ui/theme/Color.kt | 882792180 |
package com.example.averagemarkcompose.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AverageMarkComposeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | AverageMarkCompose/app/src/main/java/com/example/averagemarkcompose/ui/theme/Theme.kt | 2991507221 |
package com.example.averagemarkcompose.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | AverageMarkCompose/app/src/main/java/com/example/averagemarkcompose/ui/theme/Type.kt | 2405560545 |
package com.example.averagemarkcompose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clipScrollableContainer
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ShapeDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.modifier.modifierLocalConsumer
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.averagemarkcompose.ui.theme.AverageMarkComposeTheme
import java.time.format.TextStyle
import kotlin.math.roundToInt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.dark(
android.graphics.Color.TRANSPARENT
)
)
super.onCreate(savedInstanceState)
setContent {
AverageMarkComposeTheme {
MainScreen()
}
}
}
}
private fun removeLastNchars(str: String, n: Int): String {
return str.substring(0, str.length - n)
}
var FinalRes: String = "0"
var FinalCount: String = ""
var res = 0f
var cou = 0f
var num = 0f
var Numbers = arrayListOf(cou)
@Composable
fun MainScreen (){
val FinalRess = remember {
mutableStateOf("0")
}
val FinalCountt = remember {
mutableStateOf("")
}
Box (
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.secondary),
){
Column {
Card (
modifier = Modifier
.fillMaxWidth()
.height(580.dp),
colors = CardDefaults.cardColors(MaterialTheme.colorScheme.primary),
shape = RoundedCornerShape(0.dp),
elevation = CardDefaults.cardElevation(15.dp)
){
Column (
modifier = Modifier
.fillMaxSize()
){
Card (
modifier = Modifier
.fillMaxWidth()
.height(480.dp),
colors = CardDefaults.cardColors(MaterialTheme.colorScheme.background),
shape = RoundedCornerShape(0.dp),
elevation = CardDefaults.cardElevation(15.dp)
){
Column (
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Bottom
){
Box (
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(end = 40.dp),
contentAlignment = Alignment.CenterEnd
){
Text (
text = FinalRess.value,
fontSize = 60.sp,
color = MaterialTheme.colorScheme.onBackground
)
}
Box (
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(end = 40.dp, start = 40.dp),
contentAlignment = Alignment.CenterEnd
){
Text (
text = FinalCountt.value,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontSize = 30.sp,
color = MaterialTheme.colorScheme.onBackground,
)
}
}
}
Row (
modifier = Modifier
.fillMaxSize(),
horizontalArrangement = Arrangement.End
){
Button(
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
res = 0f
cou = 0f
num = 0f
Numbers = arrayListOf(cou)
FinalRes = "0"
FinalCount = ""
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
){
Text(
text = "CE",
fontSize = 30.sp,
color = Color(0xFFF2F2F2)
)
}
Button(
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
if(cou > 0f){
FinalCount = removeLastNchars(FinalCount, 2)
Numbers.remove(Numbers[cou.toInt()])
cou -= 1f
res = Numbers.sum()
var s = (res / cou)
if (s.isNaN())
s = 0f
else
s = ((s * 10).roundToInt() / 10.0).toFloat()
FinalRes = s.toString()
if(FinalRes == "0.0")
FinalRes = "0"
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
}
){
Image(
painter = painterResource(id = R.drawable.ic_delete),
contentDescription = "BackIcn"
)
}
}
}
}
Row (
modifier = Modifier
.fillMaxSize(),
horizontalArrangement = Arrangement.End
) {
Button( //2 button
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
num = 2f
Numbers.add(num)
cou++
FinalCount += "${num.toInt()} "
res = Numbers.sum()
var s = (res / cou)
if (s.isNaN())
s = 0f
else
s = ((s * 10).roundToInt() / 10.0).toFloat()
FinalRes = s.toString()
if(FinalRes == "0.0")
FinalRes = "0"
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
) {
Text(
text = "2",
fontSize = 30.sp,
color = Color(0xFFF2F2F2)
)
}
Button( //3 button
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
num = 3f
Numbers.add(num)
cou++
FinalCount += "${num.toInt()} "
res = Numbers.sum()
var s = (res / cou)
if (s.isNaN())
s = 0f
else
s = ((s * 10).roundToInt() / 10.0).toFloat()
FinalRes = s.toString()
if(FinalRes == "0.0")
FinalRes = "0"
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
) {
Text(
text = "3",
fontSize = 30.sp,
color = Color(0xFFF2F2F2)
)
}
Button( //4 button
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
num = 4f
Numbers.add(num)
cou++
FinalCount += "${num.toInt()} "
res = Numbers.sum()
var s = (res / cou)
if (s.isNaN())
s = 0f
else
s = ((s * 10).roundToInt() / 10.0).toFloat()
FinalRes = s.toString()
if(FinalRes == "0.0")
FinalRes = "0"
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
) {
Text(
text = "4",
fontSize = 30.sp,
color = Color(0xFFF2F2F2)
)
}
Button( //5 button
modifier = Modifier
.size(102.dp, 100.dp),
shape = RectangleShape,
colors = ButtonDefaults.buttonColors(Color.Transparent),
onClick = {
num = 5f
Numbers.add(num)
cou++
FinalCount += "${num.toInt()} "
res = Numbers.sum()
var s = (res / cou)
if (s.isNaN())
s = 0f
else
s = ((s * 10).roundToInt() / 10.0).toFloat()
FinalRes = s.toString()
if(FinalRes == "0.0")
FinalRes = "0"
FinalRess.value = FinalRes
FinalCountt.value = FinalCount
}
) {
Text(
text = "5",
fontSize = 30.sp,
color = Color(0xFFF2F2F2)
)
}
}
}
}
} | AverageMarkCompose/app/src/main/java/com/example/averagemarkcompose/MainActivity.kt | 150229266 |
package dev.gerlot.screenlit.extension
import android.app.Activity
import dev.gerlot.systembarcolorist.SystemBarColorist
fun Activity.setSystemBarBackgrounds(statusBarColor: Int, navigationBarColor: Int) {
SystemBarColorist.colorSystemBarsOfWindow(window, statusBarColor, navigationBarColor)
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/extension/ActivityExtension.kt | 1457488707 |
package dev.gerlot.screenlit.util
import kotlin.math.abs
class ScreenBrightnessManager {
private var screenBrightnessChangeStart: Float? = null
private var screenBrightnessAtChangeStart: Float? = null
val changingBrightness: Boolean
get() = screenBrightnessChangeStart != null
fun onStartScreenBrightnessChange(startCoordinate: Float, currentScreenBrightness: Float?) {
currentScreenBrightness?.let { brightness ->
screenBrightnessChangeStart = startCoordinate
screenBrightnessAtChangeStart = Math.round(brightness * 1000f) / 1000f
}
}
fun onScreenBrightnessChangeRequest(viewHeight: Int, y: Float, onChangeScreenBrightness: (newBrightness: Float) -> Unit) {
screenBrightnessChangeStart?.let { start ->
val normalizedStart = calculateNormalizedScreenPosition(start, viewHeight)
if (!isSmallMove(start, y, viewHeight)) { // Ignore small movement that can be an imprecise tap
val normalizedScreenPosition = calculateNormalizedScreenPosition(y, viewHeight)
val screenBrightnessChange = Math.round((normalizedScreenPosition - normalizedStart) * 1000f) / 1000f * 1.2f
val previousBrightness = screenBrightnessAtChangeStart
previousBrightness?.let {
val newBrightness = (Math.round((it + screenBrightnessChange) * 1000f) / 1000f).coerceIn(0f, 1f)
onChangeScreenBrightness(newBrightness)
}
}
}
}
fun onEndScreenBrightnessChange() {
screenBrightnessChangeStart = null
screenBrightnessAtChangeStart = null
}
private fun calculateNormalizedScreenPosition(y: Float, viewHeight: Int) = Math.round(1f.minus(Math.round((y / viewHeight) * 1000f) / 1000f) * 1000f) / 1000f
private fun isSmallMove(start: Float, y: Float, viewHeight: Int): Boolean {
val distance = abs(start - y)
val threshold = viewHeight / CHANGE_THRESHOLD_DIVISOR
return distance < threshold
}
companion object {
private const val CHANGE_THRESHOLD_DIVISOR = 160f
}
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/util/ScreenBrightnessManager.kt | 2891595885 |
package dev.gerlot.screenlit.util
import android.animation.Animator
open class SimpleAnimatorListener : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationEnd(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) {}
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/util/SimpleAnimatorListener.kt | 1208045918 |
package dev.gerlot.screenlit.util
import android.graphics.Color
import androidx.annotation.ColorInt
enum class ColorDarkness {
BRIGHT, DARK
}
fun calculateColorDarkness(@ColorInt color: Int): ColorDarkness {
val luminance = calculateColorLuminance(color)
return if (luminance < 0.5) {
ColorDarkness.BRIGHT
} else {
ColorDarkness.DARK
}
}
fun calculateColorLuminance(@ColorInt color: Int): Double {
return 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/util/ColorUtil.kt | 2073895872 |
package dev.gerlot.screenlit
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.preference.PreferenceManager
import dev.gerlot.screenlit.extension.setSystemBarBackgrounds
import dev.gerlot.screenlit.util.ScreenBrightnessManager
import dev.gerlot.screenlit.util.SimpleAnimatorListener
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
class ScreenLitActivity : AppCompatActivity() {
private lateinit var fullscreenContent: FrameLayout
private lateinit var onScreenTutorial: LinearLayout
private lateinit var tutorialLine1: TextView
private lateinit var tutorialLine2: TextView
private lateinit var tutorialLine3: TextView
private lateinit var appName: TextView
private lateinit var fullscreenContentControls: LinearLayout
private val hideHandler = Handler(Looper.myLooper()!!)
@SuppressLint("InlinedApi")
private val hidePart2Runnable = Runnable {
// Delayed removal of status and navigation bar
WindowInsetsControllerCompat(window, window.decorView).apply {
// Hide the status bar
hide(WindowInsetsCompat.Type.statusBars() or WindowInsetsCompat.Type.navigationBars())
// Allow showing the status bar with swiping from top to bottom
systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
/*if (Build.VERSION.SDK_INT >= 30) {
fullscreenContent.windowInsetsController?.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
fullscreenContent.systemUiVisibility =
View.SYSTEM_UI_FLAG_LOW_PROFILE or
View.SYSTEM_UI_FLAG_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
}*/
}
private val showPart2Runnable = Runnable {
// Delayed display of UI elements
supportActionBar?.show()
fullscreenContentControls.visibility = View.VISIBLE
//gestureDescriptionTv.visibility = View.VISIBLE
onScreenTutorial.visibility = View.VISIBLE
appName.visibility = View.VISIBLE
}
private var isFullscreen: Boolean = false
private val hideRunnable = Runnable { hide() }
private var isNightVision: Boolean = false
private var screenBrightnessManager = ScreenBrightnessManager()
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private val delayHideTouchListener = View.OnTouchListener { view, motionEvent ->
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS)
}
MotionEvent.ACTION_UP -> view.performClick()
else -> {
}
}
false
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fullscreen)
val statusBarColor = ResourcesCompat.getColor(resources, R.color.grey_100, null)
val navigationBarColor = ResourcesCompat.getColor(resources, R.color.grey_100, null)
setSystemBarBackgrounds(statusBarColor, navigationBarColor)
WindowCompat.setDecorFitsSystemWindows(window, false)
isFullscreen = true
// Set up the user interaction to manually show or hide the system UI.
fullscreenContent = findViewById(R.id.fullscreen_content)
val gestureDetector = GestureDetector(this, object : SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
return true
}
override fun onDoubleTap(e: MotionEvent): Boolean {
toggleNightVisionMode()
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
toggle()
return true
}
})
fullscreenContent.setOnTouchListener { view, motionEvent ->
gestureDetector.onTouchEvent(motionEvent)
when(motionEvent.actionMasked) {
MotionEvent.ACTION_DOWN -> {
val y = motionEvent.y
if (isWithinActiveBounds(y, view.height)) { // Ignore movement starting out-of-bound
screenBrightnessManager.onStartScreenBrightnessChange(
startCoordinate = motionEvent.y,
currentScreenBrightness = window?.attributes?.screenBrightness
)
}
}
MotionEvent.ACTION_MOVE -> {
if (screenBrightnessManager.changingBrightness) {
screenBrightnessManager.onScreenBrightnessChangeRequest(
view.height,
motionEvent.y,
onChangeScreenBrightness = { newScreenBrightness ->
window?.attributes?.let { layoutParams ->
layoutParams.screenBrightness = newScreenBrightness
window?.attributes = layoutParams
}
}
)
}
}
MotionEvent.ACTION_UP -> {
if (screenBrightnessManager.changingBrightness) {
screenBrightnessManager.onEndScreenBrightnessChange()
}
}
}
true
}
onScreenTutorial = findViewById(R.id.on_screen_tutorial)
tutorialLine1 = findViewById(R.id.tutorial_line1)
tutorialLine2 = findViewById(R.id.tutorial_line2)
tutorialLine3 = findViewById(R.id.tutorial_line3)
appName = findViewById(R.id.app_name)
fullscreenContentControls = findViewById(R.id.fullscreen_content_controls)
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById<Button>(R.id.dummy_button).setOnTouchListener(delayHideTouchListener)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (isFirstLaunch()) {
onFirstLaunch()
} else {
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(INITIAL_AUTO_HIDE_DELAY_MILLIS)
}
}
private fun isFirstLaunch() = !PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_LAUNCHED_BEFORE, false)
private fun onFirstLaunch() {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean(KEY_LAUNCHED_BEFORE, true)
.apply()
}
private fun isWithinActiveBounds(y: Float, viewHeight: Int): Boolean {
val topInset = Math.round((viewHeight / TOP_INSET_DIVISOR) * 1000f) / 1000f
val bottomInset = Math.round((viewHeight - (viewHeight / BOTTOM_INSET_DIVISOR)) * 1000f) / 1000f
return y in topInset..bottomInset
}
private fun toggleNightVisionMode() {
crossFadeUi(
currentBackgroundColor = if (isNightVision) Color.RED else Color.WHITE,
newBackgroundColor = if (isNightVision) Color.WHITE else Color.RED,
newStatusBarColor = if (isNightVision) ResourcesCompat.getColor(resources, R.color.grey_100, null) else Color.RED,
newNavigationBarColor = if (isNightVision) ResourcesCompat.getColor(resources, R.color.grey_100, null) else Color.RED,
newTextColor = if (isNightVision) ResourcesCompat.getColor(resources, R.color.grey_500, null) else ResourcesCompat.getColor(resources, R.color.grey_100, null),
onAnimationEnd = {
isNightVision = !isNightVision
}
)
}
private fun crossFadeUi(
@ColorInt currentBackgroundColor: Int,
@ColorInt newBackgroundColor: Int,
@ColorInt newStatusBarColor: Int,
@ColorInt newNavigationBarColor: Int,
@ColorInt newTextColor: Int,
onAnimationEnd: () -> Unit,
) {
val tutorialLine1TextColorAnimator = createTextViewTextColorAnimator(tutorialLine1, newTextColor)
val tutorialLine1DrawableTintAnimator = createTextViewCompoundDrawableStartTintAnimator(tutorialLine1, newTextColor)
val tutorialLine2TextColorAnimator = createTextViewTextColorAnimator(tutorialLine2, newTextColor)
val tutorialLine2DrawableTintAnimator = createTextViewCompoundDrawableStartTintAnimator(tutorialLine2, newTextColor)
val tutorialLine3TextColorAnimator = createTextViewTextColorAnimator(tutorialLine3, newTextColor)
val tutorialLine3DrawableTintAnimator = createTextViewCompoundDrawableStartTintAnimator(tutorialLine3, newTextColor)
val appNameTextColorAnimator = createTextViewTextColorAnimator(appName, newTextColor)
val statusBarColorAnimator = ObjectAnimator.ofObject(
window,
"statusBarColor",
ArgbEvaluator(),
currentBackgroundColor,
newBackgroundColor
).apply {
duration = UI_MODE_CROSSFADE_DURATION_MILLIS
}
val navigationBarColorAnimator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ObjectAnimator.ofObject(
window,
"navigationBarColor",
ArgbEvaluator(),
currentBackgroundColor,
newBackgroundColor
).apply {
duration = UI_MODE_CROSSFADE_DURATION_MILLIS
}
} else null
val backgroundAnimator = ObjectAnimator.ofObject(
fullscreenContent,
"backgroundColor",
ArgbEvaluator(),
currentBackgroundColor,
newBackgroundColor
).apply {
duration = UI_MODE_CROSSFADE_DURATION_MILLIS
}
val animationsToPlay = mutableListOf(
tutorialLine1TextColorAnimator,
tutorialLine1DrawableTintAnimator,
tutorialLine2TextColorAnimator,
tutorialLine2DrawableTintAnimator,
tutorialLine3TextColorAnimator,
tutorialLine3DrawableTintAnimator,
appNameTextColorAnimator,
statusBarColorAnimator,
backgroundAnimator
)
navigationBarColorAnimator?.let { animationsToPlay.add(it) }
AnimatorSet().apply {
playTogether(animationsToPlay.toList())
start()
addListener(object : SimpleAnimatorListener() {
override fun onAnimationEnd(animation: Animator) {
setSystemBarBackgrounds(newStatusBarColor, newNavigationBarColor)
onAnimationEnd()
}
})
}
}
private fun createTextViewTextColorAnimator(textView: TextView, @ColorInt newColor: Int) = ObjectAnimator.ofObject(
textView,
"textColor",
ArgbEvaluator(),
textView.currentTextColor,
newColor
).apply {
duration = UI_MODE_CROSSFADE_DURATION_MILLIS
}
private fun createTextViewCompoundDrawableStartTintAnimator(textView: TextView, @ColorInt newColor: Int) = ObjectAnimator.ofObject(
textView.compoundDrawables[0],
"tint",
ArgbEvaluator(),
textView.currentTextColor,
newColor
).apply {
duration = UI_MODE_CROSSFADE_DURATION_MILLIS
}
private fun toggle() {
hideHandler.removeCallbacks(hideRunnable)
if (isFullscreen) {
hide()
} else {
show()
}
}
private fun hide() {
// Hide UI first
supportActionBar?.hide()
fullscreenContentControls.visibility = View.GONE
//gestureDescriptionTv.visibility = View.GONE
onScreenTutorial.visibility = View.GONE
appName.visibility = View.GONE
isFullscreen = false
// Schedule a runnable to remove the status and navigation bar after a delay
hideHandler.removeCallbacks(showPart2Runnable)
hideHandler.postDelayed(hidePart2Runnable, UI_ANIMATION_DELAY_MILLIS.toLong())
}
private fun show() {
// Show the system bar
if (Build.VERSION.SDK_INT >= 30) {
fullscreenContent.windowInsetsController?.show(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
} else {
fullscreenContent.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
}
isFullscreen = true
// Schedule a runnable to display UI elements after a delay
hideHandler.removeCallbacks(hidePart2Runnable)
hideHandler.postDelayed(showPart2Runnable, UI_ANIMATION_DELAY_MILLIS.toLong())
}
/**
* Schedules a call to hide() in [delayMillis], canceling any
* previously scheduled calls.
*/
private fun delayedHide(delayMillis: Int) {
hideHandler.removeCallbacks(hideRunnable)
hideHandler.postDelayed(hideRunnable, delayMillis.toLong())
}
companion object {
private const val KEY_LAUNCHED_BEFORE = "launched_before"
/**
* Whether or not the system UI should be auto-hidden after
* [AUTO_HIDE_DELAY_MILLIS] milliseconds.
*/
private const val AUTO_HIDE = true
/**
* If [AUTO_HIDE] is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private const val AUTO_HIDE_DELAY_MILLIS = 3000
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private const val UI_ANIMATION_DELAY_MILLIS = 300
private const val UI_MODE_CROSSFADE_DURATION_MILLIS = 400L
private const val INITIAL_AUTO_HIDE_DELAY_MILLIS = 4000
private const val TOP_INSET_DIVISOR = 10f
private const val BOTTOM_INSET_DIVISOR = 10f
fun newIntent(context: Context) = Intent(context, ScreenLitActivity::class.java)
}
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/ScreenLitActivity.kt | 3032256020 |
package dev.gerlot.screenlit
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.service.quicksettings.TileService
class ScreenLitTileService: TileService() {
@SuppressLint("StartActivityAndCollapseDeprecated")
override fun onClick() {
super.onClick()
val launchIntent = ScreenLitActivity.newIntent(this)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
val pendingIntent = PendingIntent.getActivity(this, 0, launchIntent,
PendingIntent.FLAG_IMMUTABLE)
startActivityAndCollapse(pendingIntent)
} else {
startActivityAndCollapse(launchIntent)
}
}
}
| ScreenLit/app/src/main/java/dev/gerlot/screenlit/ScreenLitTileService.kt | 11804385 |
package com.ucne.tiposoportesapp
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.ucne.tiposoportesapp", appContext.packageName)
}
} | TipoSoportesApp/app/src/androidTest/java/com/ucne/tiposoportesapp/ExampleInstrumentedTest.kt | 672401583 |
package com.ucne.tiposoportesapp
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)
}
} | TipoSoportesApp/app/src/test/java/com/ucne/tiposoportesapp/ExampleUnitTest.kt | 688971643 |
package com.ucne.tiposoportesapp.ui.TipoSoporte
import android.os.Build
import androidx.annotation.RequiresExtension
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
@Composable
fun Consulta(
tipoSoporteViewModel: TipoSoporteViewModel = hiltViewModel()
){
var tiposSoportes = tipoSoporteViewModel.stateTipoSoporte.value.tiposSoporte
Column (modifier = Modifier.padding(5.dp).fillMaxSize()){
Column {
Text(text = "Descripcion : 1")
Text(text = "Precio Base : 2")
}
LazyColumn(){
items(tiposSoportes) {tipoSoporte ->
ElevatedCard(modifier = Modifier.padding(6.dp)) {
Column {
Text(text = "Descripcion : ${tipoSoporte.descripcion}")
Text(text = "Precio Base : ${tipoSoporte.precioBase}")
}
}
}
}
}
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/ui/TipoSoporte/TipoSoporteScreen.kt | 2754491546 |
package com.ucne.tiposoportesapp.ui.TipoSoporte
import android.os.Build
import androidx.annotation.RequiresExtension
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.State
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ucne.tiposoportesapp.data.repository.TiposSoportesRepository
import com.ucne.tiposoportesapp.util.Resource
import com.ucne.tiposoportesapp.util.TiposSoporteListState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
@HiltViewModel
class TipoSoporteViewModel @Inject constructor(
private val tiposSoportesRepository: TiposSoportesRepository
) : ViewModel() {
var descripcion by mutableStateOf("")
var precioBase by mutableFloatStateOf(0f)
var descripcionError by mutableStateOf(true)
var precioBaseError by mutableStateOf(true)
fun OnDescriptionChange(text : String){
descripcion = text
descripcionError = descripcion.isBlank()
}
fun OnPrecioChange(text:Float){
precioBase=text
precioBaseError = precioBase<0
}
private var _stateTipoSoporte = mutableStateOf(TiposSoporteListState())
val stateTipoSoporte: State<TiposSoporteListState> = _stateTipoSoporte
init {
load()
}
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
fun load(){
tiposSoportesRepository.getTiposSoportes().onEach{ result ->
when (result) {
is Resource.Loading -> {
_stateTipoSoporte.value = TiposSoporteListState(isLoading = true)
}
is Resource.Success -> {
_stateTipoSoporte.value = TiposSoporteListState(tiposSoporte = result.data ?: emptyList())
}
is Resource.Error -> {
_stateTipoSoporte.value = TiposSoporteListState(error = result.message ?: "Error desconocido")
}
else -> {}
}
}.launchIn(viewModelScope)
}
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/ui/TipoSoporte/TipoSoporteViewModel.kt | 3584567007 |
package com.ucne.tiposoportesapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/ui/theme/Color.kt | 2071725939 |
package com.ucne.tiposoportesapp.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun TipoSoportesAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/ui/theme/Theme.kt | 706175180 |
package com.ucne.tiposoportesapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/ui/theme/Type.kt | 3387705734 |
package com.ucne.tiposoportesapp
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresExtension
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.ucne.tiposoportesapp.ui.TipoSoporte.Consulta
import com.ucne.tiposoportesapp.ui.theme.TipoSoportesAppTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TipoSoportesAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Consulta()
}
}
}
}
}
| TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/MainActivity.kt | 3626615847 |
package com.ucne.tiposoportesapp.di
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.ucne.tiposoportesapp.data.remote.TiposSoporteApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Singleton
@Module
@InstallIn( SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideMoshi(): Moshi {
return Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
}
@Provides
@Singleton
fun provideTiposAportesApi(moshi: Moshi, ): TiposSoporteApi {
return Retrofit.Builder()
.baseUrl("https://sag-api.azurewebsites.net/api/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
.create(TiposSoporteApi::class.java)
}
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/di/AppModule.kt | 4220067737 |
package com.ucne.tiposoportesapp.util
import com.ucne.tiposoportesapp.data.remote.dto.TipoSoportesDto
data class TiposSoporteListState(
val isLoading: Boolean = false,
val tiposSoporte: List<TipoSoportesDto> = emptyList(),
val error: String = ""
) | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/util/TiposSoporteListState.kt | 1804603031 |
package com.ucne.tiposoportesapp.util
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Loading<T>(data: T? = null) : Resource<T>(data)
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/util/Resource.kt | 3073665404 |
package com.ucne.tiposoportesapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class TipoSoporteComoseApp: Application() {
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/TipoSoporteComoseApp.kt | 220240458 |
package com.ucne.tiposoportesapp.data.repository
import android.os.Build
import androidx.annotation.RequiresExtension
import com.ucne.tiposoportesapp.data.remote.TiposSoporteApi
import com.ucne.tiposoportesapp.data.remote.dto.TipoSoportesDto
import com.ucne.tiposoportesapp.util.Resource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
class TiposSoportesRepository @Inject constructor(
private val api: TiposSoporteApi
) {
@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
fun getTiposSoportes(): Flow<Resource<List<TipoSoportesDto>?>> = flow {
try {
emit(Resource.Loading())
val tiposSoportes = api.getTiposSoportes()
emit(Resource.Success(tiposSoportes))
} catch (e: HttpException) {
emit(Resource.Error(e.message ?: "Error HTTP GENERAL"))
} catch (e: IOException) {
emit(Resource.Error(e.message ?: "verificar tu conexion a internet"))
}
}
suspend fun postTipoSoporte(tipoSoportesDto: TipoSoportesDto) : TipoSoportesDto?{
val response = api.postTiposSoporte(tipoSoportesDto)
if (response.isSuccessful) {
response.body()
}
return tipoSoportesDto
}
suspend fun getTipoSoporteById(idTipo: Int ) : TipoSoportesDto?{
val response = api.getTiposSoporteById(idTipo)
if (response.isSuccessful) {
response.body()
}
return response.body()
}
suspend fun putTipoSoporte(tipoSoportesDto: TipoSoportesDto,idTipo: Int) : TipoSoportesDto?{
val response = api.putTiposSoporte(tipoSoportesDto, idTipo)
if (response.isSuccessful) {
response.body()
}
return tipoSoportesDto
}
suspend fun deleteTipoSoporte(id: Int) : TipoSoportesDto? {
return api.deleteTiposSoporte(id).body()
}
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/data/repository/TiposSoportesRepository.kt | 2410380777 |
package com.ucne.tiposoportesapp.data.remote.dto
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class TipoSoportesDto (
@Json(name = "idTipo")
val idTipo : Int?= 0,
@Json(name = "descripcion")
val descripcion : String = "",
@Json(name = "precioBase")
val precioBase : Int?= 0
) | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/data/remote/dto/TipoSoportesDto.kt | 298072102 |
package com.ucne.tiposoportesapp.data.remote
import com.ucne.tiposoportesapp.data.remote.dto.TipoSoportesDto
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.PUT
import retrofit2.http.DELETE
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Body
import retrofit2.http.Headers
interface TiposSoporteApi {
@GET("TiposSoportes")
@Headers("X-API-Key: test")
suspend fun getTiposSoportes():List<TipoSoportesDto>
@GET("TiposSoportes/{idTipo}")
@Headers("X-API-Key: test")
suspend fun getTiposSoporteById(@Path("idTipo")idTipo : Int): Response<TipoSoportesDto>
@POST("TiposSoportes")
@Headers("X-API-Key: test")
suspend fun postTiposSoporte(@Body tipoSoportesDto: TipoSoportesDto): Response<TipoSoportesDto>
@PUT("TiposSoportes/{idTipo}")
@Headers("X-API-Key: test")
suspend fun putTiposSoporte(@Body tipoSoportesDto: TipoSoportesDto, @Path("idTipo")idTipo : Int): Response<TipoSoportesDto>
@DELETE("TiposSoportes/{id}")
@Headers("X-API-Key: test")
suspend fun deleteTiposSoporte(@Path("id") id: Int): Response<TipoSoportesDto>
} | TipoSoportesApp/app/src/main/java/com/ucne/tiposoportesapp/data/remote/TiposSoporteAPI.kt | 1982473195 |
package com.example.empty
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.empty", appContext.packageName)
}
} | postfix_calculator/calciusingpostfix-master/app/src/androidTest/java/com/example/empty/ExampleInstrumentedTest.kt | 4249847115 |
package com.example.empty
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)
}
} | postfix_calculator/calciusingpostfix-master/app/src/test/java/com/example/empty/ExampleUnitTest.kt | 199985683 |
package com.example.empty
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var tvOne= findViewById<Button>(R.id.btn_one)
var tvTwo= findViewById<Button>(R.id.btn_two)
var tvThree= findViewById<Button>(R.id.btn_three)
var tvFour= findViewById<Button>(R.id.btn_four)
var tvFive= findViewById<Button>(R.id.btn_five)
var tvSix= findViewById<Button>(R.id.btn_six)
var tvSeven= findViewById<Button>(R.id.btn_seven)
var tvEight= findViewById<Button>(R.id.btn_eight)
var tvNine= findViewById<Button>(R.id.btn_nine)
var tvZero= findViewById<Button>(R.id.btn_zero)
var tvPlus= findViewById<Button>(R.id.btn_plus)
var tvMinus= findViewById<Button>(R.id.btn_sub)
var tvMul= findViewById<Button>(R.id.btn_mul)
var tvDivide= findViewById<Button>(R.id.btn_slash)
var tvPercent= findViewById<Button>(R.id.btn_percent)
var tvlb= findViewById<Button>(R.id.btn_lb)
var tvrb= findViewById<Button>(R.id.btn_rb)
var tvAllclear= findViewById<Button>(R.id.btn_ac)
var tvEquals= findViewById<Button>(R.id.btn_equal)
var tvvalue= findViewById<TextView>(R.id.calcs)
var tvResult= findViewById<TextView>(R.id.result)
var tvBack =findViewById<Button>(R.id.btn_back)
var value= StringBuilder("")
/*Number Buttons*/
tvOne.setOnClickListener {
value.append("1")
tvvalue.text=value
}
tvTwo.setOnClickListener {
value.append("2")
tvvalue.text=value
}
tvThree.setOnClickListener {
value.append("3")
tvvalue.text=value
}
tvFour.setOnClickListener {
value.append("4")
tvvalue.text=value
}
tvFive.setOnClickListener {
value.append("5")
tvvalue.text=value
}
tvSix.setOnClickListener {
value.append("6")
tvvalue.text=value
}
tvSeven.setOnClickListener {
value.append("7")
tvvalue.text=value
}
tvEight.setOnClickListener {
value.append("8")
tvvalue.text=value
}
tvNine.setOnClickListener {
value.append("9")
tvvalue.text=value
}
tvZero.setOnClickListener {
value.append("0")
tvvalue.text=value
}
/*Operators*/
tvPlus.setOnClickListener {
value.append("+")
tvvalue.text=value
}
tvMinus.setOnClickListener {
value.append("-")
tvvalue.text=value
}
tvMul.setOnClickListener {
value.append("*")
tvvalue.text=value
}
tvDivide.setOnClickListener {
value.append("/")
tvvalue.text=value
}
tvPercent.setOnClickListener {
value.append("%")
tvvalue.text=value
}
tvBack.setOnClickListener{
value.deleteCharAt(value.length-1)
tvvalue.text=value
}
tvrb.setOnClickListener {
value.append(")")
tvvalue.text=value
}
tvlb.setOnClickListener {
value.append("(")
tvvalue.text=value
}
tvAllclear.setOnClickListener {
tvvalue.text = ""
tvResult.text = ""
value.clear()
}
tvEquals.setOnClickListener{
var input1 = tvvalue.text.toString()
var a="ha"
var opr= mapOf(Pair("*",2), Pair("%",4), Pair("/",2), Pair("+",1), Pair("-",1))
var stack="("
val postfix= mutableListOf<String>()
input1+=')'
val input= mutableListOf<String>()
while(input1!="")
{
var symbol=input1[0]
var ra=""
if(symbol.isDigit())
{
var a=input1
var b=0
while ( a[b].isDigit())
{
ra+=a[b]
print(symbol+"ha")
b+=1
}
println()
input1=input1.drop(b)
}
else
{
ra+=symbol
input1=input1.drop(1)
}
println(ra)
input+=ra
}
for (i in input)
{
print(i+" ")
}
a+="wa"
while (input.isNotEmpty()){
var symbol=input[0]
print("symbol=$symbol ,")
// add (
if(symbol=="(" )
{
stack+=symbol
}
if (symbol.toIntOrNull()!=null)
{
postfix+=symbol
}
if (symbol in opr.keys)
{
var last =stack.last().toString()
while (last in opr.keys)
{
if(opr[last]!!>opr[symbol]!!){
postfix+=last
stack=stack.dropLast(1)
}
else
{
break
}
last=stack.last().toString()
println("stuck")
}
stack+=symbol
}
if (symbol==")"){
var last =stack.last().toString()
while(last!="(")
{
postfix+=last
stack=stack.dropLast(1)
last=stack.last().toString()
}
stack=stack.dropLast(1)
}
input.removeFirst()
println("stack=$stack , postfix=$postfix")
}
println(stack)
println(postfix)
postfix+=")"
var stack2= mutableListOf<Int>()
var value=0
var start =postfix[0]
while(start!=")")
{
if (start.toIntOrNull()!=null)
{
stack2 +=start.toInt()
}
else{
val prevind=stack2.indexOf(stack2.last())-1
when(start){
"+"->stack2[prevind]+=stack2[prevind+1]
"-"->stack2[prevind]-=stack2[prevind+1]
"*"->stack2[prevind]*=stack2[prevind+1]
"/"->stack2[prevind]/=stack2[prevind+1]
"%"->stack2[prevind]%=stack2[prevind+1]
}
stack2.removeLast()
}
postfix.removeFirst()
start=postfix[0]
}
tvResult.text="="+stack2[0].toString()
}
}
} | postfix_calculator/calciusingpostfix-master/app/src/main/java/com/example/empty/MainActivity.kt | 564445693 |
package com.example.questcreator
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.questcreator", appContext.packageName)
}
} | QuestCreator/app/src/androidTest/java/com/example/questcreator/ExampleInstrumentedTest.kt | 1106314506 |
package com.example.questcreator
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)
}
} | QuestCreator/app/src/test/java/com/example/questcreator/ExampleUnitTest.kt | 4078234354 |
package com.example.questcreator.creator
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.questcreator.navigation.Screen
import com.example.questcreator.ui.theme.QuestCreatorTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreatorSignUpScreen(navController: NavController) {
var username by rememberSaveable {mutableStateOf("")}
var password by rememberSaveable {mutableStateOf("")}
var passwordVisible by rememberSaveable { mutableStateOf(false) }
var passwordConfirm by rememberSaveable {mutableStateOf("")}
var passwordConfirmVisible by rememberSaveable { mutableStateOf(false) }
val context = LocalContext.current
Surface(color = MaterialTheme.colorScheme.background) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Sign Up",
color = MaterialTheme.colorScheme.primary,
fontSize = 46.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
fontStyle = FontStyle.Italic,
)
Spacer(modifier = Modifier.height(60.dp))
OutlinedTextField(
value = username,
onValueChange = { username = it },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outline,
disabledIndicatorColor = MaterialTheme.colorScheme.surfaceVariant,
),
singleLine = true,
label = {
Text("Email", fontSize = 16.sp)
},
shape = RoundedCornerShape(8.dp),
modifier = Modifier.imePadding()
)
Spacer(modifier = Modifier.height(20.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outline,
disabledIndicatorColor = MaterialTheme.colorScheme.surfaceVariant,
),
singleLine = true,
label = {
Text("Create password", fontSize = 16.sp)
},
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val image = if (passwordVisible)
Icons.Filled.Visibility
else Icons.Filled.VisibilityOff
val description = if (passwordVisible) "Hide password" else "Show password"
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(imageVector = image, description)
}
},
shape = RoundedCornerShape(8.dp),
modifier = Modifier.imePadding()
)
Spacer(modifier = Modifier.height(20.dp))
OutlinedTextField(
value = passwordConfirm,
onValueChange = { passwordConfirm = it },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outline,
disabledIndicatorColor = MaterialTheme.colorScheme.surfaceVariant,
),
singleLine = true,
label = {
Text("Confirm password", fontSize = 16.sp)
},
visualTransformation = if (passwordConfirmVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val image = if (passwordConfirmVisible)
Icons.Filled.Visibility
else Icons.Filled.VisibilityOff
val description = if (passwordConfirmVisible) "Hide password" else "Show password"
IconButton(onClick = { passwordConfirmVisible = !passwordConfirmVisible }) {
Icon(imageVector = image, description)
}
},
shape = RoundedCornerShape(8.dp),
modifier = Modifier.imePadding()
)
Spacer(modifier = Modifier.height(30.dp))
ExtendedFloatingActionButton(
onClick = {
//TODO write login logic
},
content = { Text("Create", fontSize = 24.sp, color = MaterialTheme.colorScheme.onPrimary) },
containerColor = MaterialTheme.colorScheme.primary,
modifier = Modifier
.wrapContentWidth()
.height(50.dp),
)
Spacer(modifier = Modifier.height(60.dp))
Text(text = "Already have an account? Login",
fontSize = 16.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
modifier = Modifier.clickable {
navController.navigate(Screen.CreatorLoginScreen.route)
},
color = MaterialTheme.colorScheme.secondary
)
}
}
}
/**
* Preview function
*/
@Preview(showBackground = true)
@Composable
fun PreviewCreator() {
QuestCreatorTheme() {
val context = LocalContext.current
CreatorSignUpScreen(navController = NavController(context))
}
} | QuestCreator/app/src/main/java/com/example/questcreator/creator/CreatorSignUpPage.kt | 2148833634 |
package com.example.questcreator.creator
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.questcreator.navigation.Screen
import com.example.questcreator.ui.theme.QuestCreatorTheme
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreatorLoginScreen(navController: NavController) {
var username by rememberSaveable {mutableStateOf("")}
var password by rememberSaveable {mutableStateOf("")}
var passwordVisible by rememberSaveable { mutableStateOf(false) }
val context = LocalContext.current
Surface(color = MaterialTheme.colorScheme.background) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Login",
color = MaterialTheme.colorScheme.primary,
fontSize = 46.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
fontStyle = FontStyle.Italic,
)
Spacer(modifier = Modifier.height(60.dp))
OutlinedTextField(
value = username,
onValueChange = { username = it },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outline,
disabledIndicatorColor = MaterialTheme.colorScheme.surfaceVariant,
),
singleLine = true,
label = {
Text("Email", fontSize = 16.sp)
},
shape = RoundedCornerShape(8.dp),
modifier = Modifier.imePadding()
)
Spacer(modifier = Modifier.height(20.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.onPrimary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outline,
disabledIndicatorColor = MaterialTheme.colorScheme.surfaceVariant,
),
singleLine = true,
label = {
Text("Password", fontSize = 16.sp)
},
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val image = if (passwordVisible)
Icons.Filled.Visibility
else Icons.Filled.VisibilityOff
val description = if (passwordVisible) "Hide password" else "Show password"
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(imageVector = image, description)
}
},
shape = RoundedCornerShape(8.dp),
modifier = Modifier.imePadding()
)
Spacer(modifier = Modifier.height(20.dp))
Text(text = "Forgot password?",
fontSize = 16.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
modifier = Modifier.clickable {
Toast.makeText(context, "In progress...", Toast.LENGTH_SHORT).show()
},
color = MaterialTheme.colorScheme.secondary
)
Spacer(modifier = Modifier.height(30.dp))
ExtendedFloatingActionButton(
onClick = {
//TODO write login logic
},
content = { Text("Login", fontSize = 24.sp, color = MaterialTheme.colorScheme.onPrimary) },
containerColor = MaterialTheme.colorScheme.primary,
modifier = Modifier
.wrapContentWidth()
.height(50.dp),
)
Spacer(modifier = Modifier.height(60.dp))
Text(text = "Do not have an account? Sign up",
fontSize = 16.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
modifier = Modifier.clickable {
navController.navigate(Screen.CreatorSignUpScreen.route)
},
color = MaterialTheme.colorScheme.secondary
)
}
}
}
/**
* Preview function
*/
@Preview(showBackground = true)
@Composable
fun PreviewCreatorLogin() {
QuestCreatorTheme() {
val context = LocalContext.current
CreatorLoginScreen(navController = NavController(context))
}
} | QuestCreator/app/src/main/java/com/example/questcreator/creator/CreatorLoginPage.kt | 2891881682 |
package com.example.questcreator.ui.theme
import androidx.compose.ui.graphics.Color
// Generated with https://m3.material.io/theme-builder#/custom
val md_theme_light_primary = Color(0xFF006A69)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFF6FF7F4)
val md_theme_light_onPrimaryContainer = Color(0xFF00201F)
val md_theme_light_secondary = Color(0xFF4A6362)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFCCE8E6)
val md_theme_light_onSecondaryContainer = Color(0xFF051F1F)
val md_theme_light_tertiary = Color(0xFF4A607C)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFD2E4FF)
val md_theme_light_onTertiaryContainer = Color(0xFF031C35)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFAFDFC)
val md_theme_light_onBackground = Color(0xFF191C1C)
val md_theme_light_surface = Color(0xFFFAFDFC)
val md_theme_light_onSurface = Color(0xFF191C1C)
val md_theme_light_surfaceVariant = Color(0xFFDAE5E3)
val md_theme_light_onSurfaceVariant = Color(0xFF3F4948)
val md_theme_light_outline = Color(0xFF6F7978)
val md_theme_light_inverseOnSurface = Color(0xFFEFF1F0)
val md_theme_light_inverseSurface = Color(0xFF2D3131)
val md_theme_light_inversePrimary = Color(0xFF4DDAD8)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF006A69)
val md_theme_light_outlineVariant = Color(0xFFBEC9C8)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF4DDAD8)
val md_theme_dark_onPrimary = Color(0xFF003736)
val md_theme_dark_primaryContainer = Color(0xFF00504F)
val md_theme_dark_onPrimaryContainer = Color(0xFF6FF7F4)
val md_theme_dark_secondary = Color(0xFFB0CCCA)
val md_theme_dark_onSecondary = Color(0xFF1B3534)
val md_theme_dark_secondaryContainer = Color(0xFF324B4A)
val md_theme_dark_onSecondaryContainer = Color(0xFFCCE8E6)
val md_theme_dark_tertiary = Color(0xFFB2C8E8)
val md_theme_dark_onTertiary = Color(0xFF1B324B)
val md_theme_dark_tertiaryContainer = Color(0xFF334863)
val md_theme_dark_onTertiaryContainer = Color(0xFFD2E4FF)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF191C1C)
val md_theme_dark_onBackground = Color(0xFFE0E3E2)
val md_theme_dark_surface = Color(0xFF191C1C)
val md_theme_dark_onSurface = Color(0xFFE0E3E2)
val md_theme_dark_surfaceVariant = Color(0xFF3F4948)
val md_theme_dark_onSurfaceVariant = Color(0xFFBEC9C8)
val md_theme_dark_outline = Color(0xFF889392)
val md_theme_dark_inverseOnSurface = Color(0xFF191C1C)
val md_theme_dark_inverseSurface = Color(0xFFE0E3E2)
val md_theme_dark_inversePrimary = Color(0xFF006A69)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF4DDAD8)
val md_theme_dark_outlineVariant = Color(0xFF3F4948)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF005C5B)
| QuestCreator/app/src/main/java/com/example/questcreator/ui/theme/Color.kt | 3337872466 |
package com.example.questcreator.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun QuestCreatorTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = false,
// Dynamic color is available on Android 12+
// For the test version the predefined colors will be used
// dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | QuestCreator/app/src/main/java/com/example/questcreator/ui/theme/Theme.kt | 2104486122 |
package com.example.questcreator.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | QuestCreator/app/src/main/java/com/example/questcreator/ui/theme/Type.kt | 776628949 |
package com.example.questcreator.general
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.questcreator.navigation.Screen
import com.example.questcreator.ui.theme.QuestCreatorTheme
@Composable
fun LandingScreen(navController: NavController) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Landing page",
fontSize = 48.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium,
fontFamily = FontFamily.Default
)
Spacer(modifier = Modifier.height(30.dp))
ExtendedFloatingActionButton(
onClick = {
navController.navigate(Screen.CreatorLoginScreen.route)
},
content = { Text("I am creator", fontSize = 24.sp, color = Color(0xFFC9CBD5),) },
modifier = Modifier
.wrapContentWidth()
.height(50.dp), containerColor = Color(0xFF07103F),
)
Spacer(modifier = Modifier.height(30.dp))
ExtendedFloatingActionButton(
onClick = {
navController.navigate(Screen.LoginScreen.route)
},
content = { Text("I am player", fontSize = 24.sp, color = Color(0xFFC9CBD5),) },
modifier = Modifier
.wrapContentWidth()
.height(50.dp),
containerColor = Color(0xFF07103F),
)
}
}
/**
* Preview function
*/
@Preview(showBackground = true)
@Composable
fun PreviewLanding() {
QuestCreatorTheme() {
val context = LocalContext.current
LandingScreen(navController = NavController(context))
}
} | QuestCreator/app/src/main/java/com/example/questcreator/general/LandingPage.kt | 392010539 |
package com.example.questcreator.navigation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.questcreator.ui.theme.QuestCreatorTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuestCreatorTheme {
Navigation()
}
}
}
} | QuestCreator/app/src/main/java/com/example/questcreator/navigation/MainActivity.kt | 1487835877 |
package com.example.questcreator.navigation
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.questcreator.creator.CreatorLoginScreen
import com.example.questcreator.creator.CreatorSignUpScreen
import com.example.questcreator.general.LandingScreen
import com.example.questcreator.player.LoginScreen
@Composable
fun Navigation(navController: NavHostController = rememberNavController()) {
NavHost(navController = navController, startDestination = Screen.LandingScreen.route) {
composable(route = Screen.LandingScreen.route) {
LandingScreen(navController = navController)
}
composable(route = Screen.LoginScreen.route) {
LoginScreen(navController = navController)
}
composable(route = Screen.CreatorLoginScreen.route) {
CreatorLoginScreen(navController = navController)
}
composable(route = Screen.CreatorSignUpScreen.route) {
CreatorSignUpScreen(navController = navController)
}
}
}
//Function that disables autorotation
@Composable
fun LockScreenOrientation(orientation: Int) {
val context = LocalContext.current
DisposableEffect(Unit) {
val activity = context.findActivity() ?: return@DisposableEffect onDispose {}
val originalOrientation = activity.requestedOrientation
activity.requestedOrientation = orientation
onDispose {
// restore original orientation when view disappears
activity.requestedOrientation = originalOrientation
}
}
}
fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
| QuestCreator/app/src/main/java/com/example/questcreator/navigation/Navigation.kt | 3783738067 |
package com.example.questcreator.navigation
sealed class Screen(val route: String) {
object LoginScreen : Screen("login")
object LandingScreen : Screen("landing")
object CreatorLoginScreen : Screen("creator_login")
object CreatorSignUpScreen : Screen("creator_sign_up")
} | QuestCreator/app/src/main/java/com/example/questcreator/navigation/Screen.kt | 3602351218 |
package com.example.questcreator.player
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import com.example.questcreator.ui.theme.QuestCreatorTheme
@Composable
fun LoginScreen(navController: NavController) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Login page",
)
}
}
/**
* Preview function
*/
@Preview(showBackground = true)
@Composable
fun PreviewLogin() {
QuestCreatorTheme() {
val context = LocalContext.current
LoginScreen(navController = NavController(context))
}
}
| QuestCreator/app/src/main/java/com/example/questcreator/player/LoginPage.kt | 2915255936 |
package com.yusufarisoy.n11case
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.yusufarisoy.n11case", appContext.packageName)
}
} | n11-case/app/src/androidTest/java/com/yusufarisoy/n11case/ExampleInstrumentedTest.kt | 1081808253 |
package com.yusufarisoy.n11case
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)
}
} | n11-case/app/src/test/java/com/yusufarisoy/n11case/ExampleUnitTest.kt | 4226303985 |
package com.yusufarisoy.n11case.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.yusufarisoy.n11case.R
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/MainActivity.kt | 3600037997 |
package com.yusufarisoy.n11case.ui.search
import androidx.lifecycle.viewModelScope
import com.yusufarisoy.n11case.core.BaseViewModel
import com.yusufarisoy.n11case.core.secureLaunch
import com.yusufarisoy.n11case.data.repository.GithubRepository
import com.yusufarisoy.n11case.domain.model.SearchUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val repository: GithubRepository
) : BaseViewModel() {
private val _stateFlow: MutableStateFlow<SearchUiModel> = MutableStateFlow(SearchUiModel())
val stateFlow: StateFlow<SearchUiModel>
get() = _stateFlow.asStateFlow()
private val _queryFlow: MutableStateFlow<String> = MutableStateFlow(EMPTY_QUERY)
private val queryFlow: StateFlow<String>
get() = _queryFlow.asStateFlow()
init {
observeQuery()
}
fun onQueryChanged(query: String?) {
secureLaunch {
_queryFlow.emit(query ?: EMPTY_QUERY)
}
}
@OptIn(FlowPreview::class)
private fun observeQuery() {
queryFlow
.debounce(DEBOUNCE)
.distinctUntilChanged()
.onEach { query ->
if (query.length > 2) {
search(query)
} else {
clearPage()
}
}
.launchIn(viewModelScope)
}
private fun search(query: String) {
secureLaunch {
val response = withContext(Dispatchers.IO) {
repository.searchUser(query)
}
if (response.totalCount == 0) {
onError(Throwable(message = "No result found"))
} else {
_stateFlow.emit(response)
}
}
}
private fun clearPage() {
secureLaunch {
_stateFlow.emit(SearchUiModel(totalCount = 0))
}
}
companion object {
private const val DEBOUNCE = 300L
private const val EMPTY_QUERY = ""
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/search/SearchViewModel.kt | 1822408367 |
package com.yusufarisoy.n11case.ui.search
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yusufarisoy.n11case.R
import com.yusufarisoy.n11case.databinding.RecyclerItemUserSearchBinding
import com.yusufarisoy.n11case.domain.model.UserUiModel
class UserSearchAdapter : RecyclerView.Adapter<UserSearchAdapter.UserSearchViewHolder>() {
private val differ = AsyncListDiffer(
this,
diffCallback
)
fun setData(items: List<UserUiModel>) {
differ.submitList(items)
}
override fun onBindViewHolder(holder: UserSearchViewHolder, position: Int) {
val user = differ.currentList[position]
holder.bind(user)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserSearchViewHolder {
return UserSearchViewHolder.from(parent)
}
override fun getItemCount(): Int {
return differ.currentList.size
}
companion object {
private val diffCallback = object : DiffUtil.ItemCallback<UserUiModel>() {
override fun areItemsTheSame(
oldItem: UserUiModel,
newItem: UserUiModel
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: UserUiModel,
newItem: UserUiModel
): Boolean {
return oldItem == newItem
}
}
}
class UserSearchViewHolder(
private val binding: RecyclerItemUserSearchBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(user: UserUiModel) {
Glide.with(binding.root).load(user.avatar).into(binding.imageAvatar)
binding.textUsername.text = user.login
user.score?.let { score ->
binding.textScore.text = binding.root.resources.getString(R.string.search_score, score)
}
}
companion object {
fun from(parent: ViewGroup): UserSearchViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = RecyclerItemUserSearchBinding.inflate(inflater, parent, false)
return UserSearchViewHolder(binding)
}
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/search/UserSearchAdapter.kt | 575715598 |
package com.yusufarisoy.n11case.ui.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView.OnQueryTextListener
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.yusufarisoy.n11case.R
import com.yusufarisoy.n11case.core.BaseFragment
import com.yusufarisoy.n11case.core.hide
import com.yusufarisoy.n11case.core.show
import com.yusufarisoy.n11case.databinding.FragmentSearchBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SearchFragment : BaseFragment() {
private val viewModel: SearchViewModel by viewModels()
private lateinit var binding: FragmentSearchBinding
private lateinit var adapter: UserSearchAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSearchBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRecyclerAdapter()
initViews()
observeStateFlow()
observeErrorFlow()
}
private fun initRecyclerAdapter() {
adapter = UserSearchAdapter()
binding.recyclerUserSearch.layoutManager = GridLayoutManager(context, 2)
binding.recyclerUserSearch.adapter = adapter
}
private fun initViews() {
binding.searchView.setOnQueryTextListener(
object : OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
viewModel.onQueryChanged(newText)
return false
}
}
)
}
private fun observeStateFlow() {
viewModel.stateFlow.collectIn { searchUiModel ->
if (searchUiModel.totalCount >= 0) {
binding.textSearchResult.show()
binding.recyclerUserSearch.show()
binding.textNoResult.hide()
binding.textSearchResult.text = resources.getString(R.string.search_result_count, searchUiModel.totalCount)
adapter.setData(searchUiModel.users)
}
}
}
private fun observeErrorFlow() {
viewModel.errorFlow.collectIn { message ->
if (!message.isNullOrEmpty()) {
binding.textSearchResult.hide()
binding.recyclerUserSearch.hide()
binding.textNoResult.show()
binding.textNoResult.text = message
}
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/search/SearchFragment.kt | 219213058 |
package com.yusufarisoy.n11case.ui.detail
import androidx.lifecycle.SavedStateHandle
import com.yusufarisoy.n11case.core.BaseViewModel
import com.yusufarisoy.n11case.core.secureLaunch
import com.yusufarisoy.n11case.data.repository.GithubRepository
import com.yusufarisoy.n11case.domain.model.UserUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class DetailViewModel @Inject constructor(
private val repository: GithubRepository,
private val savedStateHandle: SavedStateHandle
) : BaseViewModel() {
private val _stateFlow: MutableStateFlow<UserUiModel?> = MutableStateFlow(null)
val stateFlow: StateFlow<UserUiModel?>
get() = _stateFlow.asStateFlow()
private val _eventFlow: MutableSharedFlow<DetailEvent> = MutableSharedFlow()
val eventFlow: SharedFlow<DetailEvent>
get() = _eventFlow.asSharedFlow()
init {
fetchUser()
}
private fun fetchUser() {
val id: Int? = savedStateHandle[KEY_USER_ID]
val username: String? = savedStateHandle[KEY_USERNAME]
if (id != null && !username.isNullOrEmpty()) {
secureLaunch {
val response = withContext(Dispatchers.IO) {
repository.getUserDetail(id, username)
}
_stateFlow.emit(response)
}
}
}
fun onFavoriteClicked() {
secureLaunch {
val currentState = _stateFlow.value
if (currentState != null) {
val updatedState = currentState.copy(favorite = !currentState.favorite)
repository.updateLocalUser(updatedState)
_eventFlow.emit(DetailEvent.UpdateFavorite(updatedState.id)) // Send update to SharedViewModel
_stateFlow.emit(updatedState)
}
}
}
companion object {
const val KEY_USER_ID = "userId"
const val KEY_USERNAME = "username"
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/detail/DetailViewModel.kt | 4218839259 |
package com.yusufarisoy.n11case.ui.detail
sealed interface DetailEvent {
data class UpdateFavorite(val userId: Int): DetailEvent
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/detail/DetailEvent.kt | 3665209389 |
package com.yusufarisoy.n11case.ui.detail
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.google.android.material.imageview.ShapeableImageView
@BindingAdapter("url")
fun ShapeableImageView.loadImage(url: String?) {
url?.let {
Glide.with(context).load(it).into(this)
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/detail/BindingAdapter.kt | 296922203 |
package com.yusufarisoy.n11case.ui.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.yusufarisoy.n11case.R
import com.yusufarisoy.n11case.core.BaseFragment
import com.yusufarisoy.n11case.databinding.FragmentDetailBinding
import com.yusufarisoy.n11case.ui.SharedViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class DetailFragment : BaseFragment() {
private val viewModel: DetailViewModel by viewModels()
private val sharedViewModel: SharedViewModel by activityViewModels()
private lateinit var binding: FragmentDetailBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeStateFlow()
observeEventFlow()
initViews()
}
private fun observeStateFlow() {
viewModel.stateFlow.collectIn { userUiModel ->
userUiModel?.let {
binding.user = it
val icon = if (it.favorite) R.drawable.ic_bookmark_filled else R.drawable.ic_bookmark
binding.buttonFavorite.setImageResource(icon)
}
}
}
private fun observeEventFlow() {
viewModel.eventFlow.collectIn { event ->
when (event) {
is DetailEvent.UpdateFavorite -> sharedViewModel.updateFavorite(event.userId)
}
}
}
private fun initViews() {
binding.buttonFavorite.setOnClickListener {
viewModel.onFavoriteClicked()
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/detail/DetailFragment.kt | 194242847 |
package com.yusufarisoy.n11case.ui.listing
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.yusufarisoy.n11case.R
import com.yusufarisoy.n11case.core.BaseFragment
import com.yusufarisoy.n11case.databinding.FragmentListingBinding
import com.yusufarisoy.n11case.ui.SharedViewModel
import com.yusufarisoy.n11case.ui.detail.DetailViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ListingFragment : BaseFragment() {
private val viewModel: ListingViewModel by viewModels()
private val sharedViewModel: SharedViewModel by activityViewModels()
private lateinit var binding: FragmentListingBinding
private lateinit var adapter: UserListingAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentListingBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRecyclerAdapter()
initViews()
observeStateFlow()
observeEventFlow()
observeErrorFlow()
observeSharedUpdateFlow()
}
private fun initRecyclerAdapter() {
adapter = UserListingAdapter(userListingCallbacks())
binding.recyclerUserListing.layoutManager = LinearLayoutManager(context)
binding.recyclerUserListing.adapter = adapter
}
private fun initViews() {
binding.searchView.setOnClickListener {
viewModel.onSearchClicked()
}
}
private fun observeStateFlow() {
viewModel.stateFlow.collectIn { users ->
adapter.setData(users)
}
}
private fun observeEventFlow() {
viewModel.eventFlow.collectIn { event ->
when (event) {
is ListingEvent.NavigateToDetail -> navigateToDetail(event.id, event.username)
is ListingEvent.NavigateToSearch -> findNavController().navigate(R.id.searchFragment)
}
}
}
private fun observeErrorFlow() {
viewModel.errorFlow.collectIn {message ->
if (!message.isNullOrEmpty()) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}
}
// SharedFlow can't be collected in ListingFragment because lifeCycleState.STARTED used and
// emitted value can't be sent when there are no observers.
// StateFlow needs to set null to prevent redundant updates
private fun observeSharedUpdateFlow() {
sharedViewModel.favoriteUpdateFlow.collectIn { userId ->
userId?.let {
viewModel.updateFavorite(it)
sharedViewModel.updateFavorite(userId = null)
}
}
}
private fun navigateToDetail(userId: Int, username: String) {
val bundle = Bundle()
bundle.putInt(DetailViewModel.KEY_USER_ID, userId)
bundle.putString(DetailViewModel.KEY_USERNAME, username)
findNavController().navigate(R.id.detailFragment, bundle)
}
private fun userListingCallbacks() = object : UserListingAdapterCallbacks {
override fun onUserClicked(id: Int, username: String) {
viewModel.onUserClicked(id, username)
}
override fun onFavoriteClicked(id: Int) {
viewModel.onFavoriteClicked(id)
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/listing/ListingFragment.kt | 1659618937 |
package com.yusufarisoy.n11case.ui.listing
import com.yusufarisoy.n11case.core.BaseViewModel
import com.yusufarisoy.n11case.core.secureLaunch
import com.yusufarisoy.n11case.data.repository.GithubRepository
import com.yusufarisoy.n11case.domain.model.UserUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class ListingViewModel @Inject constructor(
private val repository: GithubRepository
) : BaseViewModel() {
private val _stateFlow: MutableStateFlow<List<UserUiModel>> = MutableStateFlow(emptyList())
val stateFlow: StateFlow<List<UserUiModel>>
get() = _stateFlow.asStateFlow()
private val _eventFlow = MutableSharedFlow<ListingEvent>()
val eventFlow: SharedFlow<ListingEvent>
get() = _eventFlow.asSharedFlow()
init {
fetchUsers()
}
private fun fetchUsers() {
secureLaunch {
val response = withContext(Dispatchers.IO) {
repository.getUsers()
}
_stateFlow.emit(response)
}
}
fun onSearchClicked() {
secureLaunch {
_eventFlow.emit(ListingEvent.NavigateToSearch)
}
}
fun onUserClicked(id: Int, username: String) {
secureLaunch {
_eventFlow.emit(ListingEvent.NavigateToDetail(id, username))
}
}
fun onFavoriteClicked(id: Int) {
updateFavorite(id, updateLocal = true)
}
fun updateFavorite(userId: Int, updateLocal: Boolean = false) {
secureLaunch {
val currentState = _stateFlow.value
if (currentState.isNotEmpty()) {
val updatedState = currentState.map { user ->
if (user.id == userId) {
val updatedUser = user.copy(favorite = !user.favorite)
if (updateLocal) { // Don't update if sent from SharedViewModel
repository.updateLocalUser(updatedUser)
}
updatedUser
} else {
user
}
}
_stateFlow.emit(updatedState)
}
}
}
override fun onError(e: Throwable) {
super.onError(e)
// Handle if needed
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/listing/ListingViewModel.kt | 3176207893 |
package com.yusufarisoy.n11case.ui.listing
sealed interface ListingEvent {
data object NavigateToSearch : ListingEvent
data class NavigateToDetail(val id: Int, val username: String) : ListingEvent
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/listing/ListingEvent.kt | 790849125 |
package com.yusufarisoy.n11case.ui.listing
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yusufarisoy.n11case.R
import com.yusufarisoy.n11case.databinding.RecyclerItemUserListingBinding
import com.yusufarisoy.n11case.domain.model.UserUiModel
interface UserListingAdapterCallbacks {
fun onUserClicked(id: Int, username: String)
fun onFavoriteClicked(id: Int)
}
private sealed interface UserChangePayload {
data class Favorite(val favorite: Boolean) : UserChangePayload
}
class UserListingAdapter(
private val callbacks: UserListingAdapterCallbacks
) : RecyclerView.Adapter<UserListingAdapter.UserViewHolder>() {
private val differ = AsyncListDiffer(
this,
diffCallback
)
fun setData(items: List<UserUiModel>) {
differ.submitList(items)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val user = differ.currentList[position]
holder.bind(user, callbacks::onUserClicked, callbacks::onFavoriteClicked)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int, payloads: List<Any>) {
when (val payload = payloads.lastOrNull()) {
is UserChangePayload.Favorite -> holder.bindFavoriteButton(payload.favorite)
else -> onBindViewHolder(holder, position)
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
return UserViewHolder.from(parent)
}
companion object {
private val diffCallback = object : DiffUtil.ItemCallback<UserUiModel>() {
override fun areItemsTheSame(
oldItem: UserUiModel,
newItem: UserUiModel
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: UserUiModel,
newItem: UserUiModel
): Boolean {
return oldItem == newItem
}
override fun getChangePayload(oldItem: UserUiModel, newItem: UserUiModel): Any? {
return if (oldItem.favorite != newItem.favorite) {
UserChangePayload.Favorite(newItem.favorite)
} else {
super.getChangePayload(oldItem, newItem)
}
}
}
}
class UserViewHolder(
private val binding: RecyclerItemUserListingBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(
user: UserUiModel,
onUserClicked: (Int, String) -> Unit,
onFavoriteClicked: (Int) -> Unit
) {
Glide.with(binding.root).load(user.avatar).into(binding.imageAvatar)
binding.textUsername.text = user.login
bindFavoriteButton(user.favorite)
binding.itemLayout.setOnClickListener {
onUserClicked(user.id, user.login)
}
binding.buttonFavorite.setOnClickListener {
onFavoriteClicked(user.id)
}
}
fun bindFavoriteButton(favorite: Boolean) {
val icon = if (favorite) R.drawable.ic_bookmark_filled else R.drawable.ic_bookmark
binding.buttonFavorite.setImageResource(icon)
}
companion object {
fun from(parent: ViewGroup): UserViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = RecyclerItemUserListingBinding.inflate(inflater, parent, false)
return UserViewHolder(binding)
}
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/listing/UserListingAdapter.kt | 2234188478 |
package com.yusufarisoy.n11case.ui
import com.yusufarisoy.n11case.core.BaseViewModel
import com.yusufarisoy.n11case.core.secureLaunch
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
@HiltViewModel
class SharedViewModel @Inject constructor() : BaseViewModel() {
private val _favoriteUpdateFlow: MutableStateFlow<Int?> = MutableStateFlow(null)
val favoriteUpdateFlow: StateFlow<Int?>
get() = _favoriteUpdateFlow.asStateFlow()
fun updateFavorite(userId: Int?) {
secureLaunch {
_favoriteUpdateFlow.emit(userId)
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/ui/SharedViewModel.kt | 4284418968 |
package com.yusufarisoy.n11case
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class App : Application()
| n11-case/app/src/main/java/com/yusufarisoy/n11case/App.kt | 2346854439 |
package com.yusufarisoy.n11case.di
import com.yusufarisoy.n11case.data.repository.GithubRepository
import com.yusufarisoy.n11case.data.repository.GithubRepositoryImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
interface DataModule {
@Singleton
@Binds
fun provideGithubRepository(githubRepositoryImpl: GithubRepositoryImpl): GithubRepository
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/di/DataModule.kt | 1603036535 |
package com.yusufarisoy.n11case.di
import com.google.gson.Gson
import com.yusufarisoy.n11case.data.api.GithubApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
@Provides
@Singleton
fun provideGithubApi(retrofit: Retrofit): GithubApi {
return retrofit.create(GithubApi::class.java)
}
@Provides
@Singleton
fun provideRetrofit(gson: Gson): Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
@Provides
@Singleton
fun provideGson(): Gson = Gson()
companion object {
private const val BASE_URL = "https://api.github.com/"
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/di/NetworkModule.kt | 2193740381 |
package com.yusufarisoy.n11case.di
import android.content.Context
import androidx.room.Room
import com.yusufarisoy.n11case.data.local.UsersDao
import com.yusufarisoy.n11case.data.local.UsersDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class LocalModule {
@Provides
fun provideCartDao(usersDatabase: UsersDatabase): UsersDao = usersDatabase.usersDao()
@Provides
fun provideDatabase(@ApplicationContext context: Context): UsersDatabase {
return Room
.databaseBuilder(context, UsersDatabase::class.java, "UsersDatabase")
.build()
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/di/LocalModule.kt | 3740289084 |
package com.yusufarisoy.n11case.core
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
abstract class BaseViewModel : ViewModel() {
private val _errorFlow: MutableStateFlow<String?> = MutableStateFlow(null)
val errorFlow: StateFlow<String?>
get() = _errorFlow.asStateFlow()
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
onError(throwable)
}
open fun onError(e: Throwable) {
viewModelScope.launch {
_errorFlow.emit(e.message)
}
}
}
fun BaseViewModel.secureLaunch(
dispatcher: CoroutineDispatcher = Dispatchers.Main,
block: suspend CoroutineScope.() -> Unit
) {
viewModelScope.launch(
context = dispatcher + exceptionHandler
) {
block()
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/core/BaseViewModel.kt | 3997695028 |
package com.yusufarisoy.n11case.core
import android.view.View
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/core/ViewExt.kt | 4230016447 |
package com.yusufarisoy.n11case.core
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
abstract class BaseFragment : Fragment() {
protected fun <T> Flow<T>.collectIn(
owner: LifecycleOwner = viewLifecycleOwner,
lifecycleState: Lifecycle.State = Lifecycle.State.STARTED,
action: suspend CoroutineScope.(T) -> Unit = {}
) {
owner.lifecycleScope.launch {
repeatOnLifecycle(lifecycleState) {
collect { action(it) }
}
}
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/core/BaseFragment.kt | 3719497675 |
package com.yusufarisoy.n11case.core
import retrofit2.Response
suspend fun <T : Any> networkCall(
call: suspend () -> Response<T>
): T {
val response = call()
if (response.isSuccessful) {
val body = response.body()
if (body != null) {
return body
} else {
throw Throwable(message = response.message())
}
} else {
throw Throwable(message = response.message())
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/core/NetworkCall.kt | 95650499 |
package com.yusufarisoy.n11case.core
interface Mapper<in Input, out Output> {
fun map(input: Input): Output
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/core/Mapper.kt | 4041650584 |
package com.yusufarisoy.n11case.data.repository
import com.yusufarisoy.n11case.domain.model.SearchUiModel
import com.yusufarisoy.n11case.domain.model.UserUiModel
interface GithubRepository {
suspend fun getUsers(): List<UserUiModel>
suspend fun searchUser(query: String): SearchUiModel
suspend fun getUserDetail(id: Int, username: String): UserUiModel
// Local
suspend fun updateLocalUser(user: UserUiModel)
suspend fun deleteLocalUser(user: UserUiModel)
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/data/repository/GithubRepository.kt | 1810687970 |
package com.yusufarisoy.n11case.data.repository
import com.yusufarisoy.n11case.core.networkCall
import com.yusufarisoy.n11case.data.api.GithubApi
import com.yusufarisoy.n11case.data.local.UsersDao
import com.yusufarisoy.n11case.domain.mapper.LocalUserToUserUiModelMapper
import com.yusufarisoy.n11case.domain.mapper.SearchResponseToSearchUiModelMapper
import com.yusufarisoy.n11case.domain.mapper.UserDetailResponseToUserUiModelMapper
import com.yusufarisoy.n11case.domain.mapper.UserResponseToUserUiModelMapper
import com.yusufarisoy.n11case.domain.mapper.UserUiModelToLocalUserMapper
import com.yusufarisoy.n11case.domain.model.SearchUiModel
import com.yusufarisoy.n11case.domain.model.UserUiModel
import javax.inject.Inject
class GithubRepositoryImpl @Inject constructor(
private val githubApi: GithubApi,
private val usersDao: UsersDao,
private val userResponseToUserUiModelMapper: UserResponseToUserUiModelMapper,
private val searchResponseToSearchUiModelMapper: SearchResponseToSearchUiModelMapper,
private val userDetailResponseToUserUiModelMapper: UserDetailResponseToUserUiModelMapper,
private val localUserToUserUiModelMapper: LocalUserToUserUiModelMapper,
private val userUiModelToLocalUserMapper: UserUiModelToLocalUserMapper
) : GithubRepository {
override suspend fun getUsers(): List<UserUiModel> {
val cachedUsers = usersDao.getUsers()
if (cachedUsers.isEmpty()) {
val response = networkCall { githubApi.getUsers(20) }
val userUiModels = userResponseToUserUiModelMapper.map(response)
val localUsers = userUiModels.map { userUiModelToLocalUserMapper.map(it) }
usersDao.insert(localUsers)
return userUiModels
}
return cachedUsers.map { localUserToUserUiModelMapper.map(it) }
}
override suspend fun searchUser(query: String): SearchUiModel {
val response = networkCall { githubApi.searchUsers(query) }
return searchResponseToSearchUiModelMapper.map(response)
}
override suspend fun getUserDetail(id: Int, username: String): UserUiModel {
val cachedUser = usersDao.getUserById(id)
if (cachedUser.following == null || cachedUser.followers == null) {
val response = networkCall { githubApi.getUserDetail(username) }
val userUiModel = userDetailResponseToUserUiModelMapper.map(response).copy(favorite = cachedUser.favorite)
usersDao.update(userUiModelToLocalUserMapper.map(userUiModel))
return userUiModel
}
return localUserToUserUiModelMapper.map(cachedUser)
}
override suspend fun updateLocalUser(user: UserUiModel) {
val localUser = userUiModelToLocalUserMapper.map(user)
usersDao.update(localUser)
}
override suspend fun deleteLocalUser(user: UserUiModel) {
val localUser = userUiModelToLocalUserMapper.map(user)
usersDao.delete(localUser)
}
}
| n11-case/app/src/main/java/com/yusufarisoy/n11case/data/repository/GithubRepositoryImpl.kt | 1618723042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.