content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.shopping 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) } }
lab3_shopping/shopping/app/src/test/java/com/example/shopping/ExampleUnitTest.kt
2105854171
package com.example.shopping.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)
lab3_shopping/shopping/app/src/main/java/com/example/shopping/ui/theme/Color.kt
4073774771
package com.example.shopping.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 ShoppingTheme( 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 ) }
lab3_shopping/shopping/app/src/main/java/com/example/shopping/ui/theme/Theme.kt
869757754
package com.example.shopping.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 ) */ )
lab3_shopping/shopping/app/src/main/java/com/example/shopping/ui/theme/Type.kt
2977952750
package com.example.shopping import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowForward import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf 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.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.example.shopping.ui.theme.ShoppingTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ShoppingTheme { ShoppingCartApp() } } } } @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun ShoppingCartApp(){ var data = remember { mutableStateListOf<String>() } var isShowDialog = remember { mutableStateOf(false) } if(isShowDialog.value){ InputDialog( onCancel = { isShowDialog.value = false }, onAddButtonClick = { newItemName -> data.add(newItemName) isShowDialog.value = false } ) } Scaffold( topBar = { TopAppBar( title = { Text("Shopping Cart")}, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = Color.LightGray, titleContentColor = Color.Magenta )) }, floatingActionButton = { FloatingActionButton( onClick = { isShowDialog.value = true }, containerColor = Color.Magenta) { Icon(Icons.Filled.Add, "Add new Items", tint = Color.White) } } ){ LazyColumn(modifier = Modifier.padding(it)) { items(data) {item -> CartItem(item) } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun InputDialog( onCancel: () -> Unit, onAddButtonClick: (String) -> Unit ){ Dialog( onDismissRequest = onCancel, ){ var textValue by remember { mutableStateOf("") } Card( shape = RoundedCornerShape(8.dp)){ Column( modifier = Modifier.padding(10.dp), ) { TextField( value = textValue, onValueChange = { textValue = it }, label = { Text("Itemname") }) TextButton(onClick = { onAddButtonClick(textValue) }) { Text("Add") } } } } } @Composable private fun CartItem(itemname:String) { var amount : Int by remember { mutableStateOf(0) } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(40.dp) ){ Text( "$itemname", modifier = Modifier .weight(1f) .padding(start = 10.dp) ) IconButton(onClick = { if (amount > 0) { amount-- } }) { Icon(Icons.Filled.ArrowBack, "Decrease") } Text( "$amount", ) IconButton(onClick = { amount++ }) { Icon(Icons.Filled.ArrowForward, "Increase") } } } @Preview(showBackground = true) @Composable fun Preview() { InputDialog(onCancel = {}, onAddButtonClick = {}) }
lab3_shopping/shopping/app/src/main/java/com/example/shopping/MainActivity.kt
2774692879
package com.practicum.bluetoothbpr 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.practicum.bluetoothbpr", appContext.packageName) } }
BluetoothBPR/app/src/androidTest/java/com/practicum/bluetoothbpr/ExampleInstrumentedTest.kt
2664163813
package com.practicum.bluetoothbpr 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) } }
BluetoothBPR/app/src/test/java/com/practicum/bluetoothbpr/ExampleUnitTest.kt
3418168478
package com.practicum.bluetoothbpr.device.ui import android.app.Activity import android.app.AlertDialog import android.bluetooth.BluetoothAdapter import android.content.* import android.os.Bundle import android.os.IBinder import android.text.Spannable import android.text.SpannableStringBuilder import android.text.method.ScrollingMovementMethod import android.text.style.ForegroundColorSpan import android.view.* import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import com.practicum.bluetoothbpr.R import com.practicum.bluetoothbpr.device.TextUtil import com.practicum.bluetoothbpr.device.data.SerialService import com.practicum.bluetoothbpr.device.domain.SerialListener import java.util.* class TerminalFragment : Fragment(), ServiceConnection, SerialListener { private enum class Connected { False, Pending, True } private var deviceAddress: String? = null private var service: SerialService? = null private var receiveText: TextView? = null private var sendText: TextView? = null private var hexWatcher: TextUtil.HexWatcher? = null private var connected: com.practicum.bluetoothbpr.device.ui.TerminalFragment.Connected = com.practicum.bluetoothbpr.device.ui.TerminalFragment.Connected.False private var initialStart = true private var hexEnabled = false private var pendingNewline = false private var newline: String = TextUtil.newline_crlf /* * Lifecycle */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) retainInstance = true deviceAddress = requireArguments().getString("device") } override fun onDestroy() { if (connected != com.practicum.bluetoothbpr.device.ui.TerminalFragment.Connected.False) disconnect() requireActivity().stopService(Intent(activity, SerialService::class.java)) super.onDestroy() } override fun onStart() { super.onStart() if (service != null) service!!.attach(this) else requireActivity().startService( Intent( activity, SerialService::class.java ) ) // prevents service destroy on unbind from recreated activity caused by orientation change } override fun onStop() { if (service != null && !requireActivity().isChangingConfigurations) service!!.detach() super.onStop() } override fun onAttach(activity: Activity) { super.onAttach(activity) requireActivity().bindService( Intent(getActivity(), SerialService::class.java), this, Context.BIND_AUTO_CREATE ) } override fun onDetach() { try { requireActivity().unbindService(this) } catch (ignored: Exception) { } super.onDetach() } override fun onResume() { super.onResume() if (initialStart && service != null) { initialStart = false requireActivity().runOnUiThread { connect() } } } override fun onServiceConnected(name: ComponentName, binder: IBinder) { service = (binder as SerialService.SerialBinder).getService service!!.attach(this) if (initialStart && isResumed) { initialStart = false requireActivity().runOnUiThread { connect() } } } override fun onServiceDisconnected(name: ComponentName) { service = null } /* * UI */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { val view: View = inflater.inflate(R.layout.fragment_terminal, container, false) receiveText = view.findViewById<TextView>(R.id.receive_text) // TextView performance decreases with number of spans receiveText?.setTextColor(resources.getColor(R.color.colorRecieveText)) // set as default color to reduce number of spans receiveText?.movementMethod = ScrollingMovementMethod.getInstance() sendText = view.findViewById<TextView>(R.id.send_text) hexWatcher = TextUtil.HexWatcher(sendText ?: return null) hexWatcher?.enable(hexEnabled) sendText?.addTextChangedListener(hexWatcher) sendText?.hint = if (hexEnabled) "HEX mode" else "" val sendBtn = view.findViewById<View>(R.id.send_btn) sendBtn.setOnClickListener { v: View? -> send( sendText?.text.toString() ) } return view } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_terminal, menu) menu.findItem(R.id.hex).isChecked = hexEnabled } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId return if (id == R.id.clear) { receiveText!!.text = "" true } else if (id == R.id.newline) { val newlineNames = resources.getStringArray(R.array.newline_names) val newlineValues = resources.getStringArray(R.array.newline_values) val pos = Arrays.asList(*newlineValues).indexOf(newline) val builder = AlertDialog.Builder( activity ) builder.setTitle("Newline") builder.setSingleChoiceItems(newlineNames, pos) { dialog: DialogInterface, item1: Int -> newline = newlineValues[item1] dialog.dismiss() } builder.create().show() true } else if (id == R.id.hex) { hexEnabled = !hexEnabled sendText!!.text = "" hexWatcher?.enable(hexEnabled) sendText!!.hint = if (hexEnabled) "HEX mode" else "" item.isChecked = hexEnabled true } else { super.onOptionsItemSelected(item) } } /* * Serial + UI */ private fun connect() { try { val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() val device = bluetoothAdapter.getRemoteDevice(deviceAddress) status("connecting...") connected = com.practicum.bluetoothbpr.device.ui.TerminalFragment.Connected.Pending val socket = SerialSocket(requireActivity().applicationContext, device) service!!.connect(socket) } catch (e: Exception) { onSerialConnectError(e) } } private fun disconnect() { connected = com.practicum.ble.TerminalFragment.Connected.False service!!.disconnect() } private fun send(str: String) { if (connected != com.practicum.ble.TerminalFragment.Connected.True) { Toast.makeText(activity, "not connected", Toast.LENGTH_SHORT).show() return } try { val msg: String val data: ByteArray if (hexEnabled) { val sb = StringBuilder() TextUtil.toHexString(sb, TextUtil.fromHexString(str)) TextUtil.toHexString(sb, newline.toByteArray()) msg = sb.toString() data = TextUtil.fromHexString(msg) } else { msg = str data = (str + newline).toByteArray() } val spn = SpannableStringBuilder( """ $msg """.trimIndent() ) spn.setSpan( ForegroundColorSpan(resources.getColor(R.color.colorSendText)), 0, spn.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) receiveText!!.append(spn) service!!.write(data) } catch (e: Exception) { onSerialIoError(e) } } private fun receive(datas: ArrayDeque<ByteArray?>?) { val spn = SpannableStringBuilder() if (datas != null) { for (data in datas) { if (data != null) { if (hexEnabled) { spn.append(TextUtil.toHexString(data)).append('\n') } else { var msg = String(data) if (newline == TextUtil.newline_crlf && msg.isNotEmpty()) { // don't show CR as ^M if directly before LF msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf) // special handling if CR and LF come in separate fragments if (pendingNewline && msg[0] == '\n') { if (spn.length >= 2) { spn.delete(spn.length - 2, spn.length) } else { val edt = receiveText!!.editableText if (edt != null && edt.length >= 2) edt.delete( edt.length - 2, edt.length ) } } pendingNewline = msg[msg.length - 1] == '\r' } spn.append(TextUtil.toCaretString(msg, newline.isNotEmpty())) } } } } receiveText!!.append(spn) } private fun status(str: String) { val spn = SpannableStringBuilder( """ $str """.trimIndent() ) spn.setSpan( ForegroundColorSpan(resources.getColor(R.color.colorStatusText)), 0, spn.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) receiveText!!.append(spn) } /* * SerialListener */ override fun onSerialConnect() { status("connected") connected = com.practicum.ble.TerminalFragment.Connected.True } override fun onSerialConnectError(e: Exception?) { status("connection failed: " + e?.message) disconnect() } override fun onSerialRead(data: ByteArray?) { val datas = ArrayDeque<ByteArray?>() datas.add(data) receive(datas) } override fun onSerialRead(datas: ArrayDeque<ByteArray?>?) { receive(datas) } override fun onSerialIoError(e: Exception?) { status("connection lost: " + e?.message) disconnect() } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/TerminalFragment.kt
3419356482
package com.practicum.bluetoothbpr.device import android.text.* import android.text.style.BackgroundColorSpan import android.widget.TextView import androidx.annotation.ColorInt import java.io.ByteArrayOutputStream internal object TextUtil { @ColorInt var caretBackground = -0x99999a const val newline_crlf = "\r\n" const val newline_lf = "\n" fun fromHexString(s: CharSequence): ByteArray { val buf = ByteArrayOutputStream() var b: Byte = 0 var nibble = 0 for (element in s) { if (nibble == 2) { buf.write(b.toInt()) nibble = 0 b = 0 } val c = element.code if (c >= '0'.code && c <= '9'.code) { nibble++ b.times(16) b.plus(c - '0'.code).toByte() } if (c >= 'A'.code && c <= 'F'.code) { nibble++ b.times(16) b.plus(c - 'A'.code + 10).toByte() } if (c >= 'a'.code && c <= 'f'.code) { nibble++ b.times(16) b.plus(c - 'a'.code + 10).toByte() } } if (nibble > 0) buf.write(b.toInt()) return buf.toByteArray() } @JvmOverloads fun toHexString(buf: ByteArray?, begin: Int = 0, end: Int = buf?.size!!): String { val sb = StringBuilder(3 * (end - begin)) if (buf != null) { toHexString(sb, buf, begin, end) } return sb.toString() } @JvmOverloads fun toHexString(sb: StringBuilder, buf: ByteArray, begin: Int = 0, end: Int = buf.size) { for (pos in begin until end) { if (sb.isNotEmpty()) sb.append(' ') var c: Int = (buf[pos].toInt() and 0xff) / 16 c += if (c >= 10) 'A'.code - 10 else '0'.code sb.append(c.toChar()) c = (buf[pos].toInt() and 0xff) % 16 c += if (c >= 10) 'A'.code - 10 else '0'.code sb.append(c.toChar()) } } /** * use https://en.wikipedia.org/wiki/Caret_notation to avoid invisible control characters */ @JvmOverloads fun toCaretString(s: CharSequence, keepNewline: Boolean, length: Int = s.length): CharSequence { var found = false for (pos in 0 until length) { if (s[pos].code < 32 && (!keepNewline || s[pos] != '\n')) { found = true break } } if (!found) return s val sb = SpannableStringBuilder() for (pos in 0 until length) if (s[pos].code < 32 && (!keepNewline || s[pos] != '\n')) { sb.append('^') sb.append((s[pos].code + 64).toChar()) sb.setSpan( BackgroundColorSpan(caretBackground), sb.length - 2, sb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } else { sb.append(s[pos]) } return sb } internal class HexWatcher(private val view: TextView) : TextWatcher { private val sb = StringBuilder() private var self = false private var enabled = false fun enable(enable: Boolean) { if (enable) { view.inputType = InputType.TYPE_CLASS_TEXT + InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD } else { view.inputType = InputType.TYPE_CLASS_TEXT + InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS } enabled = enable } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { if (!enabled || self) return sb.delete(0, sb.length) var i: Int = 0 while (i < s.length) { val c = s[i] if (c in '0'..'9') sb.append(c) if (c in 'A'..'F') sb.append(c) if (c in 'a'..'f') sb.append((c.code + 'A'.code - 'a'.code).toChar()) i++ } i = 2 while (i < sb.length) { sb.insert(i, ' ') i += 3 } val s2 = sb.toString() if (s2 != s.toString()) { self = true s.replace(0, s.length, s2) self = false } } } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/TextUtil.kt
3414820411
package com.practicum.bluetoothbpr.device.data import android.annotation.SuppressLint import android.app.Activity import android.bluetooth.* import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.provider.SyncStateContract import android.util.Log import com.practicum.bluetoothbpr.R import com.practicum.bluetoothbpr.device.domain.SerialListener import java.io.IOException import java.security.InvalidParameterException import java.util.* /** * wrap BLE communication into socket like class * - connect, disconnect and write as methods, * - read + status is returned by SerialListener */ @SuppressLint("MissingPermission") class SerialSocket(context: Context, device: BluetoothDevice?) : BluetoothGattCallback() { /** * delegate device specific behaviour to inner class */ private open class DeviceDelegate { // fun connectCharacteristics(s: BluetoothGattService?): Boolean { // return true // } // // // following methods only overwritten for Telit devices // fun onDescriptorWrite(g: BluetoothGatt?, d: BluetoothGattDescriptor?, status: Int) { /*nop*/ // } // // fun onCharacteristicChanged(g: BluetoothGatt?, c: BluetoothGattCharacteristic?) { /*nop*/ // } // // fun onCharacteristicWrite( // g: BluetoothGatt?, // c: BluetoothGattCharacteristic?, // status: Int, // ) { /*nop*/ // } open fun canWrite(): Boolean { return true } open fun disconnect() { /*nop*/ } open fun onCharacteristicChanged( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic, ) { } open fun connectCharacteristics(gattService: BluetoothGattService): Boolean { TODO("Not yet implemented") } open fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int, ) { } open fun onCharacteristicWrite( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic, status: Int, ) { } } private val writeBuffer: ArrayList<ByteArray?> private val pairingIntentFilter: IntentFilter private val pairingBroadcastReceiver: BroadcastReceiver private val disconnectBroadcastReceiver: BroadcastReceiver private val context: Context private var listener: SerialListener? = null private var delegate: DeviceDelegate? = null private var device: BluetoothDevice? private var gatt: BluetoothGatt? = null private var readCharacteristic: BluetoothGattCharacteristic? = null private var writeCharacteristic: BluetoothGattCharacteristic? = null private var writePending = false private var canceled = false private var connected = false private var payloadSize = DEFAULT_MTU - 3 init { if (context is Activity) throw InvalidParameterException("expected non UI context") this.context = context this.device = device writeBuffer = ArrayList() pairingIntentFilter = IntentFilter() pairingIntentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED) pairingIntentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST) pairingBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { onPairingBroadcastReceive(context, intent) } } disconnectBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (listener != null) listener!!.onSerialIoError(IOException("background disconnect")) disconnect() // disconnect now, else would be queued until UI re-attached } } } val name: String get() = if (device!!.name != null) device!!.name else device!!.address fun disconnect() { Log.d(TAG, "disconnect") listener = null // ignore remaining data and errors device = null canceled = true synchronized(writeBuffer) { writePending = false writeBuffer.clear() } readCharacteristic = null writeCharacteristic = null if (delegate != null) delegate!!.disconnect() if (gatt != null) { Log.d(TAG, "gatt.disconnect") gatt!!.disconnect() Log.d(TAG, "gatt.close") try { gatt!!.close() } catch (ignored: Exception) { } gatt = null connected = false } try { context.unregisterReceiver(pairingBroadcastReceiver) } catch (ignored: Exception) { } try { context.unregisterReceiver(disconnectBroadcastReceiver) } catch (ignored: Exception) { } } /** * connect-success and most connect-errors are returned asynchronously to listener */ @Throws(IOException::class) fun connect(listener: SerialListener?) { if (connected || gatt != null) throw IOException("already connected") canceled = false this.listener = listener context.registerReceiver( disconnectBroadcastReceiver, IntentFilter(SyncStateContract.Constants.INTENT_ACTION_DISCONNECT) ) Log.d(TAG, "connect $device") context.registerReceiver(pairingBroadcastReceiver, pairingIntentFilter) gatt = if (Build.VERSION.SDK_INT < 23) { Log.d(TAG, "connectGatt") device!!.connectGatt(context, false, this) } else { Log.d(TAG, "connectGatt,LE") device!!.connectGatt(context, false, this, BluetoothDevice.TRANSPORT_LE) } if (gatt == null) throw IOException("connectGatt failed") // continues asynchronously in onPairingBroadcastReceive() and onConnectionStateChange() } private fun onPairingBroadcastReceive(context: Context, intent: Intent) { // for ARM Mbed, Microbit, ... use pairing from Android bluetooth settings // for HM10-clone, ... pairing is initiated here val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) if (device == null || device != this.device) return when (intent.action) { BluetoothDevice.ACTION_PAIRING_REQUEST -> { val pairingVariant = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, -1) Log.d(TAG, "pairing request $pairingVariant") onSerialConnectError(IOException(context.getString(R.string.pairing_request))) } BluetoothDevice.ACTION_BOND_STATE_CHANGED -> { val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1) val previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1) Log.d( TAG, "bond state $previousBondState->$bondState" ) } else -> Log.d(TAG, "unknown broadcast " + intent.action) } } override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { // status directly taken from gat_api.h, e.g. 133=0x85=GATT_ERROR ~= timeout if (newState == BluetoothProfile.STATE_CONNECTED) { Log.d( TAG, "connect status $status, discoverServices" ) if (!gatt.discoverServices()) onSerialConnectError(IOException("discoverServices failed")) } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { if (connected) onSerialIoError(IOException("gatt status $status")) else onSerialConnectError( IOException( "gatt status $status" ) ) } else { Log.d( TAG, "unknown connect state $newState $status" ) } // continues asynchronously in onServicesDiscovered() } override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { Log.d(TAG, "servicesDiscovered, status $status") if (canceled) return connectCharacteristics1(gatt) } private fun connectCharacteristics1(gatt: BluetoothGatt) { var sync = true writePending = false for (gattService in gatt.services) { if (gattService.uuid == BLUETOOTH_LE_CC254X_SERVICE) delegate = Cc245XDelegate() if (gattService.uuid == BLUETOOTH_LE_MICROCHIP_SERVICE) delegate = MicrochipDelegate() if (gattService.uuid == BLUETOOTH_LE_NRF_SERVICE) delegate = NrfDelegate() if (gattService.uuid == BLUETOOTH_LE_TIO_SERVICE) delegate = TelitDelegate() if (delegate != null) { sync = delegate!!.connectCharacteristics(gattService) break } } if (canceled) return if (delegate == null || readCharacteristic == null || writeCharacteristic == null) { for (gattService in gatt.services) { Log.d(TAG, "service " + gattService.uuid) for (characteristic in gattService.characteristics) Log.d( TAG, "characteristic " + characteristic.uuid ) } onSerialConnectError(IOException("no serial profile found")) return } if (sync) connectCharacteristics2(gatt) } private fun connectCharacteristics2(gatt: BluetoothGatt) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Log.d(TAG, "request max MTU") if (!gatt.requestMtu(MAX_MTU)) onSerialConnectError(IOException("request MTU failed")) // continues asynchronously in onMtuChanged } else { connectCharacteristics3(gatt) } } override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) { Log.d(TAG, "mtu size $mtu, status=$status") if (status == BluetoothGatt.GATT_SUCCESS) { payloadSize = mtu - 3 Log.d(TAG, "payload size $payloadSize") } connectCharacteristics3(gatt) } private fun connectCharacteristics3(gatt: BluetoothGatt) { val writeProperties = writeCharacteristic!!.properties if (writeProperties and BluetoothGattCharacteristic.PROPERTY_WRITE + // Microbit,HM10-clone have WRITE BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE == 0 ) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE onSerialConnectError(IOException("write characteristic not writable")) return } if (!gatt.setCharacteristicNotification(readCharacteristic, true)) { onSerialConnectError(IOException("no notification for read characteristic")) return } val readDescriptor = readCharacteristic!!.getDescriptor(BLUETOOTH_LE_CCCD) if (readDescriptor == null) { onSerialConnectError(IOException("no CCCD descriptor for read characteristic")) return } val readProperties = readCharacteristic!!.properties if (readProperties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) { Log.d(TAG, "enable read indication") readDescriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE } else if (readProperties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) { Log.d(TAG, "enable read notification") readDescriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE } else { onSerialConnectError(IOException("no indication/notification for read characteristic ($readProperties)")) return } Log.d(TAG, "writing read characteristic descriptor") if (!gatt.writeDescriptor(readDescriptor)) { onSerialConnectError(IOException("read characteristic CCCD descriptor not writable")) } // continues asynchronously in onDescriptorWrite() } override fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int, ) { delegate!!.onDescriptorWrite(gatt, descriptor, status) if (canceled) return if (descriptor.characteristic === readCharacteristic) { Log.d( TAG, "writing read characteristic descriptor finished, status=$status" ) if (status != BluetoothGatt.GATT_SUCCESS) { onSerialConnectError(IOException("write descriptor failed")) } else { // onCharacteristicChanged with incoming data can happen after writeDescriptor(ENABLE_INDICATION/NOTIFICATION) // before confirmed by this method, so receive data can be shown before device is shown as 'Connected'. onSerialConnect() connected = true Log.d(TAG, "connected") } } } /* * read */ override fun onCharacteristicChanged( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, ) { if (canceled) return delegate!!.onCharacteristicChanged(gatt, characteristic) if (canceled) return if (characteristic === readCharacteristic) { // NOPMD - test object identity val data = readCharacteristic!!.value onSerialRead(data) Log.d(TAG, "read, len=" + data.size) } } /* * write */ @Throws(IOException::class) fun write(data: ByteArray) { if (canceled || !connected || writeCharacteristic == null) throw IOException("not connected") var data0: ByteArray? synchronized(writeBuffer) { data0 = if (data.size <= payloadSize) { data } else { Arrays.copyOfRange(data, 0, payloadSize) } if (!writePending && writeBuffer.isEmpty() && delegate!!.canWrite()) { writePending = true } else { writeBuffer.add(data0) Log.d(TAG, "write queued, len=" + data0!!.size) data0 = null } if (data.size > payloadSize) { for (i in 1 until (data.size + payloadSize - 1) / payloadSize) { val from = i * payloadSize val to = Math.min(from + payloadSize, data.size) writeBuffer.add(Arrays.copyOfRange(data, from, to)) Log.d( TAG, "write queued, len=" + (to - from) ) } } } if (data0 != null) { writeCharacteristic!!.value = data0 if (!gatt!!.writeCharacteristic(writeCharacteristic)) { onSerialIoError(IOException("write failed")) } else { Log.d(TAG, "write started, len=" + data0!!.size) } } // continues asynchronously in onCharacteristicWrite() } override fun onCharacteristicWrite( gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int, ) { if (canceled || !connected || writeCharacteristic == null) return if (status != BluetoothGatt.GATT_SUCCESS) { onSerialIoError(IOException("write failed")) return } delegate!!.onCharacteristicWrite(gatt, characteristic, status) if (canceled) return if (characteristic === writeCharacteristic) { // NOPMD - test object identity Log.d(TAG, "write finished, status=$status") writeNext() } } private fun writeNext() { val data: ByteArray? synchronized(writeBuffer) { if (!writeBuffer.isEmpty() && delegate!!.canWrite()) { writePending = true data = writeBuffer.removeAt(0) } else { writePending = false data = null } } if (data != null) { writeCharacteristic!!.value = data if (!gatt!!.writeCharacteristic(writeCharacteristic)) { onSerialIoError(IOException("write failed")) } else { Log.d(TAG, "write started, len=" + data.size) } } } /** * SerialListener */ private fun onSerialConnect() { if (listener != null) listener!!.onSerialConnect() } private fun onSerialConnectError(e: Exception) { canceled = true if (listener != null) listener!!.onSerialConnectError(e) } private fun onSerialRead(data: ByteArray) { if (listener != null) listener!!.onSerialRead(data) } private fun onSerialIoError(e: Exception) { writePending = false canceled = true if (listener != null) listener!!.onSerialIoError(e) } /** * device delegates */ private inner class Cc245XDelegate : DeviceDelegate() { override fun connectCharacteristics(gattService: BluetoothGattService): Boolean { Log.d(TAG, "service cc254x uart") readCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_CC254X_CHAR_RW) writeCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_CC254X_CHAR_RW) return true } } private inner class MicrochipDelegate : DeviceDelegate() { override fun connectCharacteristics(gattService: BluetoothGattService): Boolean { Log.d(TAG, "service microchip uart") readCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_MICROCHIP_CHAR_RW) writeCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_MICROCHIP_CHAR_W) if (writeCharacteristic == null) writeCharacteristic = gattService.getCharacteristic( BLUETOOTH_LE_MICROCHIP_CHAR_RW ) return true } } private inner class NrfDelegate : DeviceDelegate() { override fun connectCharacteristics(gattService: BluetoothGattService): Boolean { Log.d(TAG, "service nrf uart") val rw2 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW2) val rw3 = gattService.getCharacteristic(BLUETOOTH_LE_NRF_CHAR_RW3) if (rw2 != null && rw3 != null) { val rw2prop = rw2.properties val rw3prop = rw3.properties val rw2write = rw2prop and BluetoothGattCharacteristic.PROPERTY_WRITE != 0 val rw3write = rw3prop and BluetoothGattCharacteristic.PROPERTY_WRITE != 0 Log.d( TAG, "characteristic properties $rw2prop/$rw3prop" ) if (rw2write && rw3write) { onSerialConnectError(IOException("multiple write characteristics ($rw2prop/$rw3prop)")) } else if (rw2write) { writeCharacteristic = rw2 readCharacteristic = rw3 } else if (rw3write) { writeCharacteristic = rw3 readCharacteristic = rw2 } else { onSerialConnectError(IOException("no write characteristic ($rw2prop/$rw3prop)")) } } return true } } private inner class TelitDelegate : DeviceDelegate() { private var readCreditsCharacteristic: BluetoothGattCharacteristic? = null private var writeCreditsCharacteristic: BluetoothGattCharacteristic? = null private var readCredits = 0 private var writeCredits = 0 override fun connectCharacteristics(gattService: BluetoothGattService): Boolean { Log.d(TAG, "service telit tio 2.0") readCredits = 0 writeCredits = 0 readCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_TIO_CHAR_RX) writeCharacteristic = gattService.getCharacteristic(BLUETOOTH_LE_TIO_CHAR_TX) readCreditsCharacteristic = gattService.getCharacteristic( BLUETOOTH_LE_TIO_CHAR_RX_CREDITS ) writeCreditsCharacteristic = gattService.getCharacteristic( BLUETOOTH_LE_TIO_CHAR_TX_CREDITS ) if (readCharacteristic == null) { onSerialConnectError(IOException("read characteristic not found")) return false } if (writeCharacteristic == null) { onSerialConnectError(IOException("write characteristic not found")) return false } if (readCreditsCharacteristic == null) { onSerialConnectError(IOException("read credits characteristic not found")) return false } if (writeCreditsCharacteristic == null) { onSerialConnectError(IOException("write credits characteristic not found")) return false } if (!gatt!!.setCharacteristicNotification(readCreditsCharacteristic, true)) { onSerialConnectError(IOException("no notification for read credits characteristic")) return false } val readCreditsDescriptor = readCreditsCharacteristic!!.getDescriptor( BLUETOOTH_LE_CCCD ) if (readCreditsDescriptor == null) { onSerialConnectError(IOException("no CCCD descriptor for read credits characteristic")) return false } readCreditsDescriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE Log.d(TAG, "writing read credits characteristic descriptor") if (!gatt!!.writeDescriptor(readCreditsDescriptor)) { onSerialConnectError(IOException("read credits characteristic CCCD descriptor not writable")) return false } Log.d(TAG, "writing read credits characteristic descriptor") return false // continues asynchronously in connectCharacteristics2 } override fun onDescriptorWrite( gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int, ) { if (descriptor.characteristic === readCreditsCharacteristic) { Log.d( TAG, "writing read credits characteristic descriptor finished, status=$status" ) if (status != BluetoothGatt.GATT_SUCCESS) { onSerialConnectError(IOException("write credits descriptor failed")) } else { connectCharacteristics2(gatt) } } if (descriptor.characteristic === readCharacteristic) { Log.d( TAG, "writing read characteristic descriptor finished, status=$status" ) if (status == BluetoothGatt.GATT_SUCCESS) { readCharacteristic!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE writeCharacteristic!!.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE grantReadCredits() // grantReadCredits includes gatt.writeCharacteristic(writeCreditsCharacteristic) // but we do not have to wait for confirmation, as it is the last write of connect phase. } } } override fun onCharacteristicChanged( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic, ) { if (characteristic === readCreditsCharacteristic) { // NOPMD - test object identity val newCredits = readCreditsCharacteristic!!.value[0].toInt() synchronized(writeBuffer) { writeCredits += newCredits } Log.d( TAG, "got write credits +$newCredits =$writeCredits" ) if (!writePending && !writeBuffer.isEmpty()) { Log.d(TAG, "resume blocked write") writeNext() } } if (characteristic === readCharacteristic) { // NOPMD - test object identity grantReadCredits() Log.d(TAG, "read, credits=$readCredits") } } override fun onCharacteristicWrite( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic, status: Int, ) { if (characteristic === writeCharacteristic) { // NOPMD - test object identity synchronized(writeBuffer) { if (writeCredits > 0) writeCredits -= 1 } Log.d( TAG, "write finished, credits=$writeCredits" ) } if (characteristic === writeCreditsCharacteristic) { // NOPMD - test object identity Log.d(TAG, "write credits finished, status=$status") } } override fun canWrite(): Boolean { if (writeCredits > 0) return true Log.d(TAG, "no write credits") return false } override fun disconnect() { readCreditsCharacteristic = null writeCreditsCharacteristic = null } private fun grantReadCredits() { val minReadCredits = 16 val maxReadCredits = 64 if (readCredits > 0) readCredits -= 1 if (readCredits <= minReadCredits) { val newCredits = maxReadCredits - readCredits readCredits += newCredits val data = byteArrayOf(newCredits.toByte()) Log.d( TAG, "grant read credits +$newCredits =$readCredits" ) writeCreditsCharacteristic!!.value = data if (!gatt!!.writeCharacteristic(writeCreditsCharacteristic)) { if (connected) onSerialIoError(IOException("write read credits failed")) else onSerialConnectError( IOException("write read credits failed") ) } } } } companion object { private val BLUETOOTH_LE_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") private val BLUETOOTH_LE_CC254X_SERVICE = UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb") private val BLUETOOTH_LE_CC254X_CHAR_RW = UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb") private val BLUETOOTH_LE_NRF_SERVICE = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e") private val BLUETOOTH_LE_NRF_CHAR_RW2 = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e") // read on microbit, write on adafruit private val BLUETOOTH_LE_NRF_CHAR_RW3 = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e") private val BLUETOOTH_LE_MICROCHIP_SERVICE = UUID.fromString("49535343-FE7D-4AE5-8FA9-9FAFD205E455") private val BLUETOOTH_LE_MICROCHIP_CHAR_RW = UUID.fromString("49535343-1E4D-4BD9-BA61-23C647249616") private val BLUETOOTH_LE_MICROCHIP_CHAR_W = UUID.fromString("49535343-8841-43F4-A8D4-ECBE34729BB3") // https://play.google.com/store/apps/details?id=com.telit.tiosample // https://www.telit.com/wp-content/uploads/2017/09/TIO_Implementation_Guide_r6.pdf private val BLUETOOTH_LE_TIO_SERVICE = UUID.fromString("0000FEFB-0000-1000-8000-00805F9B34FB") private val BLUETOOTH_LE_TIO_CHAR_TX = UUID.fromString("00000001-0000-1000-8000-008025000000") // WNR private val BLUETOOTH_LE_TIO_CHAR_RX = UUID.fromString("00000002-0000-1000-8000-008025000000") // N private val BLUETOOTH_LE_TIO_CHAR_TX_CREDITS = UUID.fromString("00000003-0000-1000-8000-008025000000") // W private val BLUETOOTH_LE_TIO_CHAR_RX_CREDITS = UUID.fromString("00000004-0000-1000-8000-008025000000") // I private const val MAX_MTU = 512 // BLE standard does not limit, some BLE 4.2 devices support 251, various source say that Android has max 512 private const val DEFAULT_MTU = 23 private const val TAG = "SerialSocket" } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/SerialSocket.kt
2987119168
import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.FragmentManager import com.practicum.bluetoothbpr.R import com.practicum.bluetoothbpr.device.ui.DevicesFragment class StartActivity : AppCompatActivity(), FragmentManager.OnBackStackChangedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_start) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) supportFragmentManager.addOnBackStackChangedListener(this) if (savedInstanceState == null) supportFragmentManager.beginTransaction() .add(R.id.fragment, DevicesFragment(), "devices").commit() else onBackStackChanged() } override fun onBackStackChanged() { supportActionBar!!.setDisplayHomeAsUpEnabled(supportFragmentManager.backStackEntryCount > 0) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/StartActivity.kt
1661501831
package com.practicum.bluetoothbpr.device.ui import android.Manifest import android.annotation.SuppressLint import android.app.AlertDialog import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothAdapter.LeScanCallback import android.bluetooth.BluetoothDevice import android.content.* import android.content.pm.PackageManager import android.location.LocationManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.provider.Settings import android.view.* import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import androidx.fragment.app.ListFragment import com.practicum.ble.BluetoothUtil import com.practicum.bluetoothbpr.R import java.util.* /** * show list of BLE devices */ class DevicesFragment : ListFragment() { private enum class ScanState { NONE, LE_SCAN, DISCOVERY, DISCOVERY_FINISHED } private var scanState = ScanState.NONE private val leScanStopHandler = Handler() private val leScanCallback: LeScanCallback private val leScanStopCallback: Runnable private val discoveryBroadcastReceiver: BroadcastReceiver private val discoveryIntentFilter: IntentFilter private var menu: Menu? = null private var bluetoothAdapter: BluetoothAdapter? = null private val listItems: ArrayList<BluetoothUtil.Device> = ArrayList<BluetoothUtil.Device>() private var listAdapter: ArrayAdapter<BluetoothUtil.Device>? = null var requestBluetoothPermissionLauncherForStartScan: ActivityResultLauncher<Array<String>> var requestLocationPermissionLauncherForStartScan: ActivityResultLauncher<String> init { leScanCallback = LeScanCallback { device: BluetoothDevice?, rssi: Int, scanRecord: ByteArray? -> if (device != null && activity != null) { requireActivity().runOnUiThread { updateScan(device) } } } discoveryBroadcastReceiver = object : BroadcastReceiver() { @SuppressLint("MissingPermission") override fun onReceive(context: Context, intent: Intent) { if (BluetoothDevice.ACTION_FOUND == intent.action) { val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) if (device!!.type != BluetoothDevice.DEVICE_TYPE_CLASSIC && activity != null) { activity!!.runOnUiThread { updateScan(device) } } } if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == intent.action) { scanState = ScanState.DISCOVERY_FINISHED // don't cancel again stopScan() } } } discoveryIntentFilter = IntentFilter() discoveryIntentFilter.addAction(BluetoothDevice.ACTION_FOUND) discoveryIntentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) leScanStopCallback = Runnable { stopScan() } // w/o explicit Runnable, a new lambda would be created on each postDelayed, which would not be found again by removeCallbacks requestBluetoothPermissionLauncherForStartScan = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()){ granted -> BluetoothUtil.onPermissionsResult(this,granted,this::startScan) } requestLocationPermissionLauncherForStartScan = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { granted: Boolean -> if (granted) { Handler(Looper.getMainLooper()).postDelayed( { startScan() }, 1 ) // run after onResume to avoid wrong empty-text } else { val builder = AlertDialog.Builder(activity) builder.setTitle(getText(R.string.location_permission_title)) builder.setMessage(getText(R.string.location_permission_denied)) builder.setPositiveButton(R.string.ok, null) builder.show() } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if (requireActivity().packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() listAdapter = object: ArrayAdapter<BluetoothUtil.Device>(requireActivity(), 0, listItems) { override fun getView(position: Int, view: View?, parent: ViewGroup): View { var view = view val device: BluetoothUtil.Device = listItems[position] if (view == null) view = requireActivity().layoutInflater.inflate(R.layout.device_list_item, parent, false) val text1 = view!!.findViewById<TextView>(R.id.text1) val text2 = view.findViewById<TextView>(R.id.text2) var deviceName: String? = device.name if (deviceName == null || deviceName.isEmpty()) deviceName = "<unnamed>" text1.text = deviceName text2.text = device.device.address return view } } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setListAdapter(null) val header: View = requireActivity().layoutInflater.inflate(R.layout.device_list_header, null, false) listView.addHeaderView(header, null, false) setEmptyText("initializing...") (listView.emptyView as TextView).textSize = 18f setListAdapter(listAdapter) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_devices, menu) this.menu = menu if (bluetoothAdapter == null) { menu.findItem(R.id.bt_settings).isEnabled = false menu.findItem(R.id.ble_scan).isEnabled = false } else if (!bluetoothAdapter!!.isEnabled) { menu.findItem(R.id.ble_scan).isEnabled = false } } override fun onResume() { super.onResume() requireActivity().registerReceiver(discoveryBroadcastReceiver, discoveryIntentFilter) if (bluetoothAdapter == null) { setEmptyText("<bluetooth LE not supported>") } else if (!bluetoothAdapter!!.isEnabled) { setEmptyText("<bluetooth is disabled>") if (menu != null) { listItems.clear() listAdapter!!.notifyDataSetChanged() menu!!.findItem(R.id.ble_scan).isEnabled = false } } else { setEmptyText("<use SCAN to refresh devices>") if (menu != null) menu!!.findItem(R.id.ble_scan).isEnabled = true } } override fun onPause() { super.onPause() stopScan() requireActivity().unregisterReceiver(discoveryBroadcastReceiver) } override fun onDestroyView() { super.onDestroyView() menu = null } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.ble_scan -> { startScan() true } R.id.ble_scan_stop -> { stopScan() true } R.id.bt_settings -> { val intent = Intent() intent.action = Settings.ACTION_BLUETOOTH_SETTINGS startActivity(intent) true } else -> { super.onOptionsItemSelected(item) } } } private fun startScan() { if (scanState != ScanState.NONE) return val nextScanState = ScanState.LE_SCAN if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (!BluetoothUtil.hasPermissions( this, requestBluetoothPermissionLauncherForStartScan ) ) return } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (requireActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { scanState = ScanState.NONE val builder = AlertDialog.Builder( activity ) builder.setTitle(R.string.location_permission_title) builder.setMessage(R.string.location_permission_grant) builder.setPositiveButton( R.string.ok ) { dialog: DialogInterface?, which: Int -> requestLocationPermissionLauncherForStartScan.launch( Manifest.permission.ACCESS_FINE_LOCATION ) } builder.show() return } val locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager var locationEnabled = false try { locationEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } catch (ignored: Exception) { } try { locationEnabled = locationEnabled or locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } catch (ignored: Exception) { } if (!locationEnabled) scanState = ScanState.DISCOVERY // Starting with Android 6.0 a bluetooth scan requires ACCESS_COARSE_LOCATION permission, but that's not all! // LESCAN also needs enabled 'location services', whereas DISCOVERY works without. // Most users think of GPS as 'location service', but it includes more, as we see here. // Instead of asking the user to enable something they consider unrelated, // we fall back to the older API that scans for bluetooth classic _and_ LE // sometimes the older API returns less results or slower } scanState = nextScanState listItems.clear() listAdapter!!.notifyDataSetChanged() setEmptyText("<scanning...>") menu!!.findItem(R.id.ble_scan).isVisible = false menu!!.findItem(R.id.ble_scan_stop).isVisible = true if (scanState == ScanState.LE_SCAN) { leScanStopHandler.postDelayed(leScanStopCallback, LE_SCAN_PERIOD) Thread({ bluetoothAdapter!!.startLeScan( null, leScanCallback ) }, "startLeScan") .start() // start async to prevent blocking UI, because startLeScan sometimes take some seconds } else { bluetoothAdapter!!.startDiscovery() } } @SuppressLint("MissingPermission") private fun updateScan(device: BluetoothDevice?) { if (scanState == ScanState.NONE) return val device2 = device?.let { BluetoothUtil.Device(it) } // slow getName() only once val pos = Collections.binarySearch(listItems, device2) if (pos < 0) { device2?.let { listItems.add(-pos - 1, it) } listAdapter!!.notifyDataSetChanged() } } @SuppressLint("MissingPermission") private fun stopScan() { if (scanState == ScanState.NONE) return setEmptyText("<no bluetooth devices found>") if (menu != null) { menu!!.findItem(R.id.ble_scan).isVisible = true menu!!.findItem(R.id.ble_scan_stop).isVisible = false } when (scanState) { ScanState.LE_SCAN -> { leScanStopHandler.removeCallbacks(leScanStopCallback) bluetoothAdapter!!.stopLeScan(leScanCallback) } ScanState.DISCOVERY -> bluetoothAdapter!!.cancelDiscovery() else -> {} } scanState = ScanState.NONE } override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) { stopScan() val device: BluetoothUtil.Device = listItems[position - 1] val args = Bundle() args.putString("device", device.device.address) val fragment: Fragment = TerminalFragment() fragment.arguments = args requireFragmentManager().beginTransaction().replace(R.id.fragment, fragment, "terminal") .addToBackStack(null).commit() } companion object { private const val LE_SCAN_PERIOD: Long = 10000 // similar to bluetoothAdapter.startDiscovery } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/DevicesFragment.kt
780384393
package com.practicum.ble import android.Manifest import android.annotation.SuppressLint import android.app.AlertDialog import android.bluetooth.BluetoothDevice import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.Settings import androidx.activity.result.ActivityResultLauncher import androidx.fragment.app.Fragment import com.practicum.bluetoothbpr.R import kotlin.reflect.KFunction0 object BluetoothUtil { /** * Android 12 permission handling */ private fun showRationaleDialog(fragment: Fragment, listener: DialogInterface.OnClickListener) { val builder = AlertDialog.Builder(fragment.activity) builder.setTitle(fragment.getString(R.string.bluetooth_permission_title)) builder.setMessage(fragment.getString(R.string.bluetooth_permission_grant)) builder.setNegativeButton("Cancel", null) builder.setPositiveButton("Continue", listener) builder.show() } private fun showSettingsDialog(fragment: Fragment) { val s = fragment.resources.getString( fragment.resources.getIdentifier( "@android:string/permgrouplab_nearby_devices", null, null ) ) val builder = AlertDialog.Builder(fragment.activity) builder.setTitle(fragment.getString(R.string.bluetooth_permission_title)) builder.setMessage( String.format( fragment.getString(R.string.bluetooth_permission_denied), s ) ) builder.setNegativeButton("Cancel", null) builder.setPositiveButton( "Settings" ) { dialog: DialogInterface?, which: Int -> fragment.startActivity( Intent( Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + "com.practicum.ble") ) ) } builder.show() } /** * CONNECT + SCAN are granted together in same permission group, so actually no need to check/request both, but one never knows */ fun hasPermissions( fragment: Fragment, requestPermissionLauncher: ActivityResultLauncher<Array<String>>, ): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return true val missingPermissions = (fragment.requireActivity() .checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED ) or (fragment.requireActivity() .checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) val showRationale = (fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_CONNECT) or fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_SCAN)) val permissions = arrayOf(Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN) return if (missingPermissions) { if (showRationale) { showRationaleDialog( fragment ) { dialog: DialogInterface?, which: Int -> requestPermissionLauncher.launch( permissions ) } } else { requestPermissionLauncher.launch(permissions) } false } else { true } } fun onPermissionsResult( fragment: Fragment, grants: Map<String, @JvmSuppressWildcards Boolean>, cb: KFunction0<Unit>, ) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return val showRationale = (fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_CONNECT) or fragment.shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH_SCAN)) val granted = grants.values.stream().reduce( true ) { a: Boolean, b: Boolean -> a && b } if (granted) { cb.call() } else if (showRationale) { showRationaleDialog( fragment ) { dialog: DialogInterface?, which: Int -> cb.call() } } else { showSettingsDialog(fragment) } } interface PermissionGrantedCallback { fun call() } /* * more efficient caching of name than BluetoothDevice which always does RPC */ internal class Device @SuppressLint("MissingPermission") constructor(var device: BluetoothDevice) : Comparable<Device?> { var name: String? init { name = device.name } override fun equals(o: Any?): Boolean { return if (o is Device) device == o.device else false } override fun compareTo(other: Device?): Int { val thisValid = name != null && !name!!.isEmpty() val otherValid = other?.name != null && !other.name!!.isEmpty() if (thisValid && otherValid) { val ret = name!!.compareTo(other?.name!!) return if (ret != 0) ret else device.address.compareTo(other.device.address) } if (thisValid) return -1 return if (otherValid) +1 else device.address.compareTo(other!!.device.address) } /** * sort by name, then address. sort named devices first */ } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/BluetoothUtil.kt
680579896
package com.practicum.bluetoothbpr.device.domain import java.util.ArrayDeque interface SerialListener { fun onSerialConnect() fun onSerialConnectError(e: Exception?) fun onSerialRead(data: ByteArray?) // socket -> service fun onSerialRead(datas: ArrayDeque<ByteArray?>?) // service -> UI thread fun onSerialIoError(e: Exception?) }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/SerialListener.kt
487970217
package com.practicum.bluetoothbpr.device.data import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Intent import android.os.* import androidx.core.app.NotificationCompat import com.practicum.bluetoothbpr.device.domain.SerialListener import java.io.IOException import java.util.* /** * create notification and queue serial data while activity is not in the foreground * use listener chain: SerialSocket -> SerialService -> UI fragment */ class SerialService : Service(), SerialListener { internal inner class SerialBinder : Binder() { val getService: SerialService get() = this@SerialService } private enum class QueueType { Connect, ConnectError, Read, IoError } private class QueueItem { var type: com.practicum.bluetoothbpr.device.data.SerialService.QueueType var datas: ArrayDeque<ByteArray?>? = null var e: Exception? = null internal constructor(type: com.practicum.ble.SerialService.QueueType) { this.type = type if (type == com.practicum.ble.SerialService.QueueType.Read) init() } internal constructor( type: com.practicum.ble.SerialService.QueueType, e: Exception?, ) { this.type = type this.e = e } internal constructor( type: com.practicum.ble.SerialService.QueueType, datas: ArrayDeque<ByteArray?>?, ) { this.type = type this.datas = datas } fun init() { datas = ArrayDeque() } fun add(data: ByteArray?) { datas!!.add(data) } } private val mainLooper: Handler private val binder: IBinder private val queue1: ArrayDeque<QueueItem> private val queue2: ArrayDeque<QueueItem> private val lastRead: QueueItem private var socket: SerialSocket? = null private var listener: SerialListener? = null private var connected = false /** * Lifecylce */ init { mainLooper = Handler(Looper.getMainLooper()) binder = SerialBinder() queue1 = ArrayDeque() queue2 = ArrayDeque() lastRead = QueueItem(com.practicum.ble.SerialService.QueueType.Read) } override fun onDestroy() { cancelNotification() disconnect() super.onDestroy() } override fun onBind(intent: Intent): IBinder? { return binder } /** * Api */ @Throws(IOException::class) fun connect(socket: SerialSocket) { socket.connect(this) this.socket = socket connected = true } fun disconnect() { connected = false // ignore data,errors while disconnecting cancelNotification() if (socket != null) { socket!!.disconnect() socket = null } } @Throws(IOException::class) fun write(data: ByteArray?) { if (!connected) throw IOException("not connected") socket!!.write(data!!) } fun attach(listener: SerialListener) { require(!(Looper.getMainLooper().thread !== Thread.currentThread())) { "not in main thread" } cancelNotification() // use synchronized() to prevent new items in queue2 // new items will not be added to queue1 because mainLooper.post and attach() run in main thread synchronized(this) { this.listener = listener } for (item in queue1) { when (item.type) { com.practicum.ble.SerialService.QueueType.Connect -> listener.onSerialConnect() com.practicum.ble.SerialService.QueueType.ConnectError -> listener.onSerialConnectError( item.e ) com.practicum.ble.SerialService.QueueType.Read -> listener.onSerialRead( item.datas ) com.practicum.ble.SerialService.QueueType.IoError -> listener.onSerialIoError( item.e ) } } for (item in queue2) { when (item.type) { com.practicum.ble.SerialService.QueueType.Connect -> listener.onSerialConnect() com.practicum.ble.SerialService.QueueType.ConnectError -> listener.onSerialConnectError( item.e ) com.practicum.ble.SerialService.QueueType.Read -> listener.onSerialRead( item.datas ) com.practicum.ble.SerialService.QueueType.IoError -> listener.onSerialIoError( item.e ) } } queue1.clear() queue2.clear() } fun detach() { if (connected) createNotification() // items already in event queue (posted before detach() to mainLooper) will end up in queue1 // items occurring later, will be moved directly to queue2 // detach() and mainLooper.post run in the main thread, so all items are caught listener = null } private fun createNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val nc = NotificationChannel( Constants.NOTIFICATION_CHANNEL, "Background service", NotificationManager.IMPORTANCE_LOW ) nc.setShowBadge(false) val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager nm.createNotificationChannel(nc) } val disconnectIntent = Intent() .setAction(Constants.INTENT_ACTION_DISCONNECT) val restartIntent = Intent() .setClassName(this, Constants.INTENT_CLASS_MAIN_ACTIVITY) .setAction(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_LAUNCHER) val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 val disconnectPendingIntent = PendingIntent.getBroadcast(this, 1, disconnectIntent, flags) val restartPendingIntent = PendingIntent.getActivity(this, 1, restartIntent, flags) val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.baseline_notifications_none_24) .setColor(resources.getColor(R.color.colorPrimary)) .setContentTitle(resources.getString(R.string.app_name)) .setContentText(if (socket != null) "Connected to " + socket!!.name else "Background Service") .setContentIntent(restartPendingIntent) .setOngoing(true) .addAction( NotificationCompat.Action( R.drawable.baseline_clear_24, "Disconnect", disconnectPendingIntent ) ) // @drawable/ic_notification created with Android Studio -> New -> Image Asset using @color/colorPrimaryDark as background color // Android < API 21 does not support vectorDrawables in notifications, so both drawables used here, are created as .png instead of .xml val notification = builder.build() startForeground(Constants.NOTIFY_MANAGER_START_FOREGROUND_SERVICE, notification) } private fun cancelNotification() { stopForeground(true) } /** * SerialListener */ override fun onSerialConnect() { if (connected) { synchronized(this) { if (listener != null) { mainLooper.post { if (listener != null) { listener!!.onSerialConnect() } else { queue1.add(QueueItem(com.practicum.ble.SerialService.QueueType.Connect)) } } } else { queue2.add(QueueItem(com.practicum.ble.SerialService.QueueType.Connect)) } } } } override fun onSerialConnectError(e: Exception?) { if (connected) { synchronized(this) { if (listener != null) { mainLooper.post { if (listener != null) { listener!!.onSerialConnectError(e) } else { queue1.add( QueueItem( com.practicum.ble.SerialService.QueueType.ConnectError, e ) ) disconnect() } } } else { queue2.add( QueueItem( com.practicum.ble.SerialService.QueueType.ConnectError, e ) ) disconnect() } } } } override fun onSerialRead(datas: ArrayDeque<ByteArray?>?) { throw UnsupportedOperationException() } /** * reduce number of UI updates by merging data chunks. * Data can arrive at hundred chunks per second, but the UI can only * perform a dozen updates if receiveText already contains much text. * * On new data inform UI thread once (1). * While not consumed (2), add more data (3). */ override fun onSerialRead(data: ByteArray?) { if (connected) { synchronized(this) { if (listener != null) { var first: Boolean synchronized(lastRead) { first = lastRead.datas!!.isEmpty() // (1) lastRead.add(data) // (3) } if (first) { mainLooper.post { var datas: ArrayDeque<ByteArray?>? synchronized(lastRead) { datas = lastRead.datas lastRead.init() // (2) } if (listener != null) { listener!!.onSerialRead(datas) } else { queue1.add( QueueItem( com.practicum.ble.SerialService.QueueType.Read, datas ) ) } } } } else { if (queue2.isEmpty() || queue2.last.type != com.practicum.ble.SerialService.QueueType.Read) queue2.add( QueueItem(com.practicum.ble.SerialService.QueueType.Read) ) queue2.last.add(data) } } } } override fun onSerialIoError(e: Exception?) { if (connected) { synchronized(this) { if (listener != null) { mainLooper.post { if (listener != null) { listener!!.onSerialIoError(e) } else { queue1.add( QueueItem( com.practicum.ble.SerialService.QueueType.IoError, e ) ) disconnect() } } } else { queue2.add( QueueItem( com.practicum.ble.SerialService.QueueType.IoError, e ) ) disconnect() } } } } }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/SerialService.kt
1583671054
package com.practicum.bluetoothbpr.device object Constants { const val INTENT_ACTION_DISCONNECT: String = "com.practicum.ble" + ".Disconnect" const val NOTIFICATION_CHANNEL: String = "com.practicum.ble" + ".Channel" const val INTENT_CLASS_MAIN_ACTIVITY: String = "com.practicum.ble" + ".MainActivity" // values have to be unique within each app const val NOTIFY_MANAGER_START_FOREGROUND_SERVICE = 1001 }
BluetoothBPR/app/src/main/java/com/practicum/bluetoothbpr/Constants.kt
3901864392
package com.stocktransaction.springcqrs import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class SpringStockTransactionCqrsApplicationTests { @Test fun contextLoads() { } }
stock-transaction-cqrs/src/test/kotlin/com/stocktransaction/springcqrs/SpringStockTransactionCqrsApplicationTests.kt
3750043928
package com.stocktransaction.springcqrs import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class SpringStockTransactionCqrsApplication fun main(args: Array<String>) { runApplication<SpringStockTransactionCqrsApplication>(*args) }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/SpringStockTransactionCqrsApplication.kt
2620035939
package com.stocktransaction.springcqrs.transport.dtos import com.stocktransaction.springcqrs.domain.core.entities.User import java.util.* data class CreateUserDTO( val id: UUID, ) fun CreateUserDTO.toDomain() = User(id)
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/transport/dtos/CreateUserDTO.kt
2916805193
package com.stocktransaction.springcqrs.transport.listeners import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.stocktransaction.springcqrs.domain.core.entities.Stock import com.stocktransaction.springcqrs.domain.services.StockService import org.springframework.kafka.annotation.KafkaListener import org.springframework.stereotype.Service import java.util.logging.Logger @Service class CreateStockListener( private val stockService: StockService ) { private val log = Logger.getLogger(CreateStockListener::class.java.name) @KafkaListener(topics = ["create-stock"], groupId = "group_id") fun createStock(message: String) { try { stockService.createStock(parseMessage(message)) } catch(e: Exception) { log.severe("Error receiving message: $message") throw e } } private fun parseMessage(message: String): Stock{ try { return jacksonObjectMapper().findAndRegisterModules().readValue(message, Stock::class.java) } catch(e: Exception) { log.severe("Error parsing message: $message") throw e } } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/transport/listeners/CreateStockListener.kt
647896460
package com.stocktransaction.springcqrs.transport.listeners import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.stocktransaction.springcqrs.domain.core.entities.Wallet import com.stocktransaction.springcqrs.domain.services.WalletService import org.springframework.kafka.annotation.KafkaListener import org.springframework.stereotype.Service import java.util.logging.Logger @Service class CreateWalletListener( private val walletService: WalletService ) { private val log = Logger.getLogger(CreateWalletListener::class.java.name) @KafkaListener(topics = ["create-wallet"], groupId = "group_id") fun createWallet(message: String) { try { walletService.createWallet(parseMessage(message)) } catch(e: Exception) { log.severe("Error creating wallet: $message") throw e } } private fun parseMessage(message: String): Wallet { try { return jacksonObjectMapper().findAndRegisterModules().readValue(message, Wallet::class.java) } catch(e: Exception) { log.severe("Error parsing message: $message") throw e } } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/transport/listeners/CreateWalletListener.kt
2340714720
package com.stocktransaction.springcqrs.transport.listeners import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.stocktransaction.springcqrs.domain.core.entities.User import com.stocktransaction.springcqrs.domain.services.UserService import org.springframework.kafka.annotation.KafkaListener import org.springframework.stereotype.Service import java.util.logging.Logger @Service class CreateUserListener( val userService: UserService ) { private val log = Logger.getLogger(CreateUserListener::class.java.name) @KafkaListener(topics = ["create-user"], groupId = "group_id") fun consume(message: String) { userService.createUser(parseMessage(message)) } private fun parseMessage(message: String): User { try { return jacksonObjectMapper().findAndRegisterModules().readValue(message, User::class.java) } catch(e: Exception) { log.severe("Error parsing message: $message") throw e } } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/transport/listeners/CreateUserListener.kt
325239917
package com.stocktransaction.springcqrs.config.services import com.stocktransaction.springcqrs.domain.services.StockService import org.axonframework.commandhandling.gateway.CommandGateway import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class StockServiceConfig( private val commandGateway: CommandGateway ) { @Bean fun stockService(): StockService { return StockService(commandGateway) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/config/services/StockServiceConfig.kt
3161728653
package com.stocktransaction.springcqrs.config.services import com.stocktransaction.springcqrs.domain.services.UserService import org.axonframework.commandhandling.gateway.CommandGateway import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class UserServiceConfig( private val commandGateway: CommandGateway ) { @Bean fun userService(): UserService { return UserService(commandGateway) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/config/services/UserServiceConfig.kt
1340360489
package com.stocktransaction.springcqrs.config.services import com.stocktransaction.springcqrs.domain.services.WalletService import org.axonframework.commandhandling.gateway.CommandGateway import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class WalletServiceConfig( private val commandGateway: CommandGateway ) { @Bean fun walletService(): WalletService { return WalletService(commandGateway) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/config/services/WalletServiceConfig.kt
12362738
package com.stocktransaction.springcqrs.domain.core.aggregates import com.stocktransaction.springcqrs.domain.core.commands.CreateStockCommand import com.stocktransaction.springcqrs.domain.core.entities.Stock import com.stocktransaction.springcqrs.domain.core.events.CreateStockEvent import com.stocktransaction.springcqrs.domain.core.valueobjects.StockCode import com.stocktransaction.springcqrs.domain.repositories.StockRepository import org.axonframework.commandhandling.CommandHandler import org.axonframework.eventsourcing.EventSourcingHandler import org.axonframework.modelling.command.AggregateIdentifier import org.axonframework.modelling.command.AggregateLifecycle import org.axonframework.spring.stereotype.Aggregate import java.util.UUID @Aggregate class StockAggregate( private val stockRepository: StockRepository ) { @AggregateIdentifier lateinit var stockId: UUID lateinit var stockCode: StockCode @CommandHandler fun handler(command: CreateStockCommand) { AggregateLifecycle.apply(CreateStockCommand(stockId, stockCode)) } @EventSourcingHandler fun on(event: CreateStockEvent) { stockRepository.save(Stock(id = event.stockId, code = event.stockCode)) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/aggregates/StockAggregate.kt
2311372621
package com.stocktransaction.springcqrs.domain.core.aggregates import com.stocktransaction.springcqrs.domain.core.commands.CreateUserCommand import com.stocktransaction.springcqrs.domain.core.entities.User import com.stocktransaction.springcqrs.domain.core.events.CreateUserEvent import com.stocktransaction.springcqrs.domain.repositories.UserRepository import org.axonframework.commandhandling.CommandHandler import org.axonframework.eventsourcing.EventSourcingHandler import org.axonframework.modelling.command.AggregateIdentifier import org.axonframework.modelling.command.AggregateLifecycle import org.axonframework.spring.stereotype.Aggregate import java.util.* @Aggregate class UserAggregate( private val userRepository: UserRepository ) { @AggregateIdentifier lateinit var userId: UUID @CommandHandler fun handleCreateUserCommand(command: CreateUserCommand){ AggregateLifecycle.apply(CreateUserEvent(userId)) } @EventSourcingHandler fun on(event: CreateUserEvent) { userRepository.save(User(id = event.userId)) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/aggregates/UserAggregate.kt
662546770
package com.stocktransaction.springcqrs.domain.core.aggregates import com.stocktransaction.springcqrs.domain.core.commands.CreateWalletCommand import com.stocktransaction.springcqrs.domain.core.entities.Wallet import com.stocktransaction.springcqrs.domain.core.events.CreateWalletEvent import com.stocktransaction.springcqrs.domain.repositories.WalletRepository import org.axonframework.commandhandling.CommandHandler import org.axonframework.eventsourcing.EventSourcingHandler import org.axonframework.modelling.command.AggregateIdentifier import org.axonframework.modelling.command.AggregateLifecycle import org.axonframework.spring.stereotype.Aggregate import java.util.UUID @Aggregate class WalletAggregate( private val walletRepository: WalletRepository ) { @AggregateIdentifier lateinit var userId: UUID @CommandHandler fun handler(command: CreateWalletCommand) { AggregateLifecycle.apply(CreateWalletEvent(userId = userId)) } @EventSourcingHandler fun on(event: CreateWalletEvent) { walletRepository.save(Wallet(id = event.id, userId = event.userId)) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/aggregates/WalletAggregate.kt
977158528
package com.stocktransaction.springcqrs.domain.core.commands import com.stocktransaction.springcqrs.domain.core.entities.User import org.axonframework.modelling.command.TargetAggregateIdentifier import java.util.UUID data class CreateUserCommand ( @TargetAggregateIdentifier val id: String, val userId: UUID ) fun User.toCreateUserCommand() = CreateUserCommand( id = UUID.randomUUID().toString(), userId = this.id )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/commands/CreateUserCommand.kt
198946439
package com.stocktransaction.springcqrs.domain.core.commands import com.stocktransaction.springcqrs.domain.core.entities.Stock import com.stocktransaction.springcqrs.domain.core.valueobjects.StockCode import org.axonframework.modelling.command.TargetAggregateIdentifier import java.util.* data class CreateStockCommand ( @TargetAggregateIdentifier val stockId: UUID, val stockCode: StockCode ) fun Stock.toCreateStockCommand() = CreateStockCommand( stockId = id, stockCode = StockCode(code.value) )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/commands/CreateStockCommand.kt
3635191552
package com.stocktransaction.springcqrs.domain.core.commands import com.stocktransaction.springcqrs.domain.core.entities.Stock import com.stocktransaction.springcqrs.domain.core.entities.Wallet import com.stocktransaction.springcqrs.domain.core.valueobjects.StockCode import org.axonframework.modelling.command.TargetAggregateIdentifier import java.util.UUID data class CreateWalletCommand ( @TargetAggregateIdentifier val userId: UUID ) fun Wallet.toCreateWalletCommand() = CreateWalletCommand( userId = userId )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/commands/CreateWalletCommand.kt
4265492652
package com.stocktransaction.springcqrs.domain.core.commands import org.axonframework.modelling.command.TargetAggregateIdentifier import java.util.UUID data class AddStockToWalletCommand ( @TargetAggregateIdentifier val walletId: UUID, val stockId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/commands/AddStockToWalletCommand.kt
2090957664
package com.stocktransaction.springcqrs.domain.core.commands import org.axonframework.modelling.command.TargetAggregateIdentifier import java.util.UUID data class CreateTransactionCommand ( @TargetAggregateIdentifier val transactionId: UUID, val buyerId: UUID, val sellerId: UUID, val stockId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/commands/CreateTransactionCommand.kt
3466959247
package com.stocktransaction.springcqrs.domain.core.events import java.util.* data class CreateTransactionEvent( val transactionId: UUID, val buyerId: UUID, val sellerId: UUID, val stockId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/events/CreateTransactionEvent.kt
482304906
package com.stocktransaction.springcqrs.domain.core.events import java.util.* data class AddStockToWalletEvent ( val walletId: UUID, val stockId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/events/AddStockToWalletEvent.kt
2962752498
package com.stocktransaction.springcqrs.domain.core.events import com.stocktransaction.springcqrs.domain.core.valueobjects.StockCode import java.util.* data class CreateStockEvent( val stockId: UUID, val stockCode: StockCode )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/events/CreateStockEvent.kt
2511515990
package com.stocktransaction.springcqrs.domain.core.events import java.util.* data class CreateWalletEvent( val id: Long? = null, val userId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/events/CreateWalletEvent.kt
707967713
package com.stocktransaction.springcqrs.domain.core.events import java.util.* data class CreateUserEvent( val userId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/events/CreateUserEvent.kt
2298570855
package com.stocktransaction.springcqrs.domain.core.entities import java.util.UUID data class Wallet( val id: Long? = null, val userId: UUID )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/entities/Wallet.kt
2038328722
package com.stocktransaction.springcqrs.domain.core.entities import java.util.* data class User( val id: UUID, )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/entities/User.kt
2723013424
package com.stocktransaction.springcqrs.domain.core.entities import com.stocktransaction.springcqrs.domain.core.valueobjects.StockCode import java.util.UUID data class Stock( val id: UUID, val code: StockCode )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/entities/Stock.kt
3452108054
package com.stocktransaction.springcqrs.domain.core.entities import com.stocktransaction.springcqrs.domain.core.valueobjects.Currency import java.util.UUID data class WalletStock( val id: Long, val walletId: UUID, val stockId: UUID, val amount: Long, val averagePrice: Currency )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/entities/WalletStock.kt
469007152
package com.stocktransaction.springcqrs.domain.core.entities import com.stocktransaction.springcqrs.domain.core.valueobjects.Currency import java.time.LocalDateTime import java.util.UUID data class Transaction( val id: Long, val externalId: UUID, val buyerId: UUID, val sellerId: UUID, val stockId: UUID, val amount: Long, val totalValue: Currency, val date: LocalDateTime )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/entities/Transaction.kt
1215255521
package com.stocktransaction.springcqrs.domain.core.valueobjects data class Currency( val value: Double )
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/valueobjects/Currency.kt
1816259875
package com.stocktransaction.springcqrs.domain.core.valueobjects import java.lang.RuntimeException data class StockCode( val value: String, ) { init { validateCode(value) } } private fun validateCode(value: String) { val matched = Regex("^[A-Z]{3}[0-1]{2}\$").matches(value) if(!matched) { throw RuntimeException("Invalid stock code") } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/core/valueobjects/StockCode.kt
3087790757
package com.stocktransaction.springcqrs.domain.repositories import com.stocktransaction.springcqrs.domain.core.entities.Stock interface StockRepository { fun save(stock: Stock) }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/repositories/StockRepository.kt
1785299792
package com.stocktransaction.springcqrs.domain.repositories import com.stocktransaction.springcqrs.domain.core.entities.User interface UserRepository { fun save(user: User) }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/repositories/UserRepository.kt
123758535
package com.stocktransaction.springcqrs.domain.repositories import com.stocktransaction.springcqrs.domain.core.entities.Wallet interface WalletRepository { fun save(wallet: Wallet) }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/repositories/WalletRepository.kt
2969007880
package com.stocktransaction.springcqrs.domain.services import com.stocktransaction.springcqrs.domain.core.commands.toCreateWalletCommand import com.stocktransaction.springcqrs.domain.core.entities.Wallet import org.axonframework.commandhandling.gateway.CommandGateway class WalletService( private val commandGateway: CommandGateway ) { fun createWallet(wallet: Wallet) { commandGateway.sendAndWait<Unit>(wallet.toCreateWalletCommand()) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/services/WalletService.kt
3806262220
package com.stocktransaction.springcqrs.domain.services import com.stocktransaction.springcqrs.domain.core.commands.toCreateStockCommand import com.stocktransaction.springcqrs.domain.core.entities.Stock import org.axonframework.commandhandling.gateway.CommandGateway class StockService( private val commandGateway: CommandGateway ) { fun createStock(stock: Stock) { val stockCommand = stock.toCreateStockCommand() commandGateway.sendAndWait<Unit>(stockCommand) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/services/StockService.kt
4041954963
package com.stocktransaction.springcqrs.domain.services import com.stocktransaction.springcqrs.domain.core.commands.toCreateUserCommand import com.stocktransaction.springcqrs.domain.core.entities.User import org.axonframework.commandhandling.gateway.CommandGateway class UserService( private val commandGateway: CommandGateway ) { fun createUser(user: User) { val command = user.toCreateUserCommand() commandGateway.sendAndWait<Unit>(command) } }
stock-transaction-cqrs/src/main/kotlin/com/stocktransaction/springcqrs/domain/services/UserService.kt
40076400
package com.w2c.kural 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.w2c.kural", appContext.packageName) } }
Kural_2023/app/src/androidTest/java/com/w2c/kural/ExampleInstrumentedTest.kt
483557808
package com.w2c.kural 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) } }
Kural_2023/app/src/test/java/com/w2c/kural/ExampleUnitTest.kt
1304715799
package com.w2c.kural.viewmodel import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.w2c.kural.R import com.w2c.kural.database.Kural import com.w2c.kural.model.Setting import com.w2c.kural.repository.MainRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.* import com.w2c.kural.utils.ATHIKARAM import com.w2c.kural.utils.IYAL import com.w2c.kural.utils.KURAL import com.w2c.kural.utils.NotificationPreference class MainActivityViewModel(private val mainRepository: MainRepository) : ViewModel() { private val kuralCache_: MutableList<Kural> = mutableListOf() val kuralCache: List<Kural> = kuralCache_ private val favClickLiveData_: MutableLiveData<Boolean> = MutableLiveData<Boolean>() val favClickLiveData: LiveData<Boolean> = favClickLiveData_ private val favUpdateTBIconLiveData_: MutableLiveData<Boolean> = MutableLiveData<Boolean>() val favUpdateTBIconLiveData: LiveData<Boolean> = favUpdateTBIconLiveData_ private val favStatusLiveData_: MutableLiveData<Array<Boolean>> = MutableLiveData<Array<Boolean>>() val favStatusLiveData: LiveData<Array<Boolean>> = favStatusLiveData_ private val notificationLiveData_: MutableLiveData<Boolean> = MutableLiveData<Boolean>() val notificationLiveData: LiveData<Boolean> = notificationLiveData_ private val notificationRefreshUILiveData_: MutableLiveData<Boolean> = MutableLiveData<Boolean>() val notificationRefreshUILiveData: LiveData<Boolean> = notificationRefreshUILiveData_ private val data: MutableLiveData<List<String>> = MutableLiveData<List<String>>() private lateinit var favoriteKural: Kural fun cacheKural(list: List<Kural>) { kuralCache_.clear() kuralCache_.addAll(list) } suspend fun getKurals( context: Context ): LiveData<List<Kural>> { return mainRepository.getKurals(context) } suspend fun getKuralsByRange( context: Context, paal: String, athikaram: String? ): LiveData<List<Kural>> { val kuralRange = mainRepository.getKuralRangeByPaal(context, paal, athikaram) val indexes = kuralRange?.split("-") var startIndex = 1 var endIndex = 1330 indexes?.let { startIndex = it[0].toInt() endIndex = it[1].toInt() } return mainRepository.getKuralsByRange(context, startIndex, endIndex) } suspend fun getHomeCardData(context: Context, paal: String): Map<String, String> { val map = mutableMapOf<String, String>() //Getting Values from repo val iyalList = mainRepository.getIyalByPaal(context, paal) val athikaramList = mainRepository.getAthikaramByPaal(context, paal, null) //Formatting Values val iyal = "${context.getString(R.string.iyals)}\n${iyalList.size}" val athikaram = "${context.getString(R.string.athikarams)}\n${athikaramList.size}" val kurals = "${context.getString(R.string.kurals)}\n${athikaramList.size * 10}" //Mapping into hashmap map[IYAL] = iyal map[ATHIKARAM] = athikaram map[KURAL] = kurals return map } suspend fun getKuralRangeByPaal(context: Context, paal: String): LiveData<List<String>> { val range = mainRepository.getKuralRangeByPaal(context, paal) range?.let { data.value = listOf(it) } return data } suspend fun getAthikaramByPaal( context: Context, paal: String, iyal: String? ): LiveData<List<String>> { val athikaram = mainRepository.getAthikaramByPaal(context, paal, iyal) data.value = athikaram return data } suspend fun getIyalByPaal(context: Context, paal: String): LiveData<List<String>> { val iyal = mainRepository.getIyalByPaal(context, paal) data.value = iyal return data } suspend fun filterKuralBySearch(searchText: String): List<Kural> { val kuralList = mutableListOf<Kural>() withContext(Dispatchers.Default) { kuralCache.forEach { kural -> val isMatched = isMatchesFound(searchText = searchText, kural = kural) if (isMatched) { kuralList.add(kural) } } } return kuralList } suspend fun getFavoriteKurals(context: Context): LiveData<List<Kural>> { return mainRepository.getFavorites(context) } suspend fun manageFavorite(context: Context, kural: Kural) { val kuralNumber = kural.number - 1 if (!kuralCache_.isEmpty() && kuralCache_.size >= kuralNumber) { kuralCache_.set(kuralNumber, kural) val statusCode = mainRepository.updateFavorite(context, kural) //(statusCode>0) refers db update status, (kural.favourite == 1) referes add/remove process val res = arrayOf(statusCode > 0, kural.favourite == 1) favStatusLiveData_.value = res } } fun onFavClick() { favClickLiveData_.value = true } fun updateFavToolBarIcon(visible: Boolean) { favUpdateTBIconLiveData_.value = visible } suspend fun getKuralDetail(context: Context, number: Int): LiveData<Kural> { return mainRepository.getKuralDetail(context, number) } fun observeNotificationChanges() { notificationLiveData_.value = true } fun updateNotificationStatus(context: Context): Boolean { val prefs = NotificationPreference.getInstance(context) prefs.isDailyNotifyValue = !prefs.isDailyNotifyValue return prefs.isDailyNotifyValue } fun getSettingsData(context: Context): List<Setting> { return mainRepository.getSettingsData(context) } fun notificationUpdateUI() { notificationRefreshUILiveData_.value = true } fun isMatchesFound(searchText: String, kural: Kural?): Boolean { return matchTranslation(searchText, kural) || matchTamilTranslation( searchText, kural ) || matchMk(searchText, kural) || matchMv(searchText, kural) || matchSp( searchText, kural ) || matchExplanation(searchText, kural) || matchCouplet(searchText, kural) || matchKuralNo( searchText, kural ) } private fun matchKuralNo(searchText: String, kural: Kural?): Boolean { return kural?.number.toString() == searchText } private fun matchCouplet(searchText: String, kural: Kural?): Boolean { return kural?.couplet?.contains(searchText) ?: false } private fun matchExplanation(searchText: String, kural: Kural?): Boolean { return kural?.explanation?.contains(searchText) ?: false } private fun matchSp(searchText: String, kural: Kural?): Boolean { return kural?.sp?.lowercase(Locale.getDefault())?.contains(searchText) ?: false } private fun matchMv(searchText: String, kural: Kural?): Boolean { return kural?.mv?.lowercase(Locale.getDefault())?.contains(searchText) ?: false } private fun matchMk(searchText: String, kural: Kural?): Boolean { return kural?.mk?.lowercase(Locale.getDefault())?.contains(searchText) ?: false } private fun matchTamilTranslation(searchText: String, kural: Kural?): Boolean { return kural?.tamilTranslation?.lowercase(Locale.getDefault())?.contains(searchText) ?: false } private fun matchTranslation(searchText: String, kural: Kural?): Boolean { return kural?.translation?.lowercase(Locale.getDefault())?.contains(searchText) ?: false } }
Kural_2023/app/src/main/java/com/w2c/kural/viewmodel/MainActivityViewModel.kt
3710078373
package com.w2c.kural.viewmodel import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.w2c.kural.repository.MainRepository @Suppress("UNCHECKED_CAST") class MainVMFactory(private val context: Context, private val repository: MainRepository) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { return MainActivityViewModel(repository) as T } }
Kural_2023/app/src/main/java/com/w2c/kural/viewmodel/MainVMFactory.kt
1743718446
package com.w2c.kural.datasource import android.content.Context import com.w2c.kural.database.Kural interface DataSource { suspend fun getKuralList(context: Context): List<Kural> suspend fun getFavourites(context: Context): List<Kural> suspend fun getKural(context: Context, number: Int): Kural? suspend fun cacheKural(context: Context, kuralList: List<Kural>) }
Kural_2023/app/src/main/java/com/w2c/kural/datasource/DataSource.kt
2449156025
package com.w2c.kural.datasource import android.content.Context import com.w2c.kural.database.Kural import com.w2c.kural.retrofit.RetrofitClient class RemoteDataSource : DataSource { override suspend fun getKuralList(context: Context): List<Kural> { try { return RetrofitClient.instance.getKuralApi().getKural().kural } catch (e: Exception) { throw Exception(e) } } override suspend fun getFavourites(context: Context): List<Kural> { //Since we don't have API to maintain favourite in server, //we are leaving this function as Empty. return emptyList() } override suspend fun getKural(context: Context, number: Int): Kural? { //Since we don't have API to get kural from server, //we are leaving this function as Empty. return null } override suspend fun cacheKural(context: Context, kuralList: List<Kural>) { //Since we don't have API to get kural from server, //we are leaving this function as Empty. } }
Kural_2023/app/src/main/java/com/w2c/kural/datasource/RemoteDataSource.kt
3574395653
package com.w2c.kural.datasource import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.w2c.kural.R import com.w2c.kural.database.DatabaseController import com.w2c.kural.database.Kural import com.w2c.kural.datasource.DataSource import com.w2c.kural.model.Setting import com.w2c.kural.retrofit.KuralResponse import java.io.FileNotFoundException import java.util.ArrayList class LocalDataSource : DataSource { override suspend fun getKuralList(context: Context): List<Kural> { return DatabaseController.getInstance(context).kuralDAO.allKural } override suspend fun getFavourites(context: Context): List<Kural> { return DatabaseController.getInstance(context).kuralDAO.favKuralList } override suspend fun getKural(context: Context, number: Int): Kural? { return DatabaseController.getInstance(context).kuralDAO.getKural(number) } override suspend fun cacheKural(context: Context, kuralList: List<Kural>) { for (k in kuralList) { DatabaseController.getInstance(context).kuralDAO.insertKuralData(k) } } fun clearKural(context: Context) { DatabaseController.getInstance(context).kuralDAO.deleteData() } suspend fun fetchKuralsFromAssets(context: Context): List<Kural> { try { val kuralJson = context.assets.open("thirukkural.json").reader().use { it.readText() } return Gson().fromJson<KuralResponse>( kuralJson, object : TypeToken<KuralResponse>() {}.type ).kural } catch (fnfException: FileNotFoundException) { return emptyList() } } suspend fun loadPaalFromAssets(context: Context): String { return context.assets.open("details.json").bufferedReader().use { it.readText() } } suspend fun getKuralsByRange(context: Context, startIndex: Int, endIndex: Int): List<Kural> { return DatabaseController.getInstance(context).kuralDAO.getKuralByRange( startIndex, endIndex ) } suspend fun updateFavorite(context: Context, kural: Kural): Int { return DatabaseController.getInstance(context) .kuralDAO .updateKuralData(kural) } fun getSettingsData(context: Context): List<Setting> = buildList{ val dailyNotify = Setting( context.getString(R.string.daily_one_kural), listOf(R.drawable.ic_bell_enable, R.drawable.ic_bell_disable) ) add(dailyNotify) val feedBack = Setting( context.getString(R.string.feedback), listOf(R.drawable.ic_email) ) add(feedBack) val rateUs = Setting( context.getString(R.string.rate_us), listOf(R.drawable.ic_rate) ) add(rateUs) val shareApp = Setting( context.getString(R.string.share_app), listOf(R.drawable.ic_share) ) add(shareApp) } }
Kural_2023/app/src/main/java/com/w2c/kural/datasource/LocalDataSource.kt
2582923187
package com.w2c.kural.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.w2c.kural.utils.DB_VERSION @Database(entities = [Kural::class], version = 1, exportSchema = false) abstract class DatabaseController : RoomDatabase() { abstract val kuralDAO: KuralDAO companion object { private lateinit var mDBController: DatabaseController @Synchronized fun getInstance(context: Context): DatabaseController { if (!Companion::mDBController.isInitialized) { mDBController = Room.databaseBuilder( context.applicationContext, DatabaseController::class.java, "KuralDB" ).build() } return mDBController } } }
Kural_2023/app/src/main/java/com/w2c/kural/database/DatabaseController.kt
1575095647
package com.w2c.kural.database interface KuralCallback { fun update(kural: Kural?) fun updateList(kural: List<Kural?>?) }
Kural_2023/app/src/main/java/com/w2c/kural/database/KuralCallback.kt
1864273188
package com.w2c.kural.database import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Update @Dao interface KuralDAO { @Insert fun insertKuralData(kural: Kural) @Query("delete from Kural") fun deleteData() @Update fun updateKuralData(kural: Kural): Int @get:Query("select * from Kural") val allKural: List<Kural> @Query("select * from Kural where number=:number") fun getKural(number: Int): Kural? @Query("select * from Kural where number between :startIndex and :endIndex") fun getKuralByRange(startIndex: Int, endIndex: Int): List<Kural> @get:Query("select * from Kural where favourite=1") val favKuralList: List<Kural> @get:Query("select * from Kural where line1=line1") val kuralWord: List<Kural> }
Kural_2023/app/src/main/java/com/w2c/kural/database/KuralDAO.kt
3283583261
package com.w2c.kural.database import android.text.TextUtils import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import java.io.Serializable @Entity data class Kural( @PrimaryKey @SerializedName("Number") val number: Int, @SerializedName("Line1") val line1: String, @SerializedName("Line2") val line2: String, val mv: String, val sp: String, val mk: String, val explanation: String, val couplet: String, val transliteration1: String, val transliteration2: String, var favourite: Int = 0 ) : Serializable { val translation: String get() = transliteration1 + transliteration2 val tamilTranslation: String get() = if (TextUtils.isEmpty(line1) && TextUtils.isEmpty(line2)) { "" } else if (TextUtils.isEmpty(line1)) { line2 } else if (TextUtils.isEmpty(line2)) { line1 } else { "$line1\n$line2" } }
Kural_2023/app/src/main/java/com/w2c/kural/database/Kural.kt
488178836
package com.w2c.kural.repository import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.w2c.kural.database.Kural import com.w2c.kural.datasource.LocalDataSource import com.w2c.kural.datasource.RemoteDataSource import com.w2c.kural.model.Setting import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONArray import org.json.JSONObject class MainRepository constructor( private val localDataSource: LocalDataSource, private val remoteDataSource: RemoteDataSource ) { private val kuralListLiveData = MutableLiveData<List<Kural>>() private val kuralListByRangeLiveData = MutableLiveData<List<Kural>>() private val favoriteKuralListLiveData = MutableLiveData<List<Kural>>() private val kuralLiveData = MutableLiveData<Kural>() suspend fun getKurals(context: Context): LiveData<List<Kural>> { withContext(Dispatchers.IO) { var kuralList = localDataSource.getKuralList(context) if (kuralList.isEmpty()) { kuralList = fetchKural(context) localDataSource.clearKural(context) localDataSource.cacheKural(context, kuralList) } kuralListLiveData.postValue(kuralList) } return kuralListLiveData } suspend fun getKuralsByRange( context: Context, startIndex: Int, endIndex: Int ): LiveData<List<Kural>> { withContext(Dispatchers.IO) { var kuralList = localDataSource.getKuralsByRange(context, startIndex, endIndex) if (kuralList.isEmpty()) { val kurals = fetchKural(context) localDataSource.clearKural(context) localDataSource.cacheKural(context, kurals) kuralList = localDataSource.getKuralsByRange(context, startIndex, endIndex) } kuralListByRangeLiveData.postValue(kuralList) } return kuralListByRangeLiveData } suspend fun getKuralDetail(context: Context, number: Int): LiveData<Kural> { withContext(Dispatchers.IO) { localDataSource.getKural(context = context, number = number)?.let { kuralLiveData.postValue(it) } } return kuralLiveData } private suspend fun fetchKural(context: Context): List<Kural> { return try { remoteDataSource.getKuralList(context) } catch (e: Exception) { localDataSource.fetchKuralsFromAssets(context) } } suspend fun getPaals(context: Context): List<String> { val paalList = mutableListOf<String>() val paalArray = getBaseDetails(context) for (i in 0..paalArray.length() - 1) { val paal: JSONObject = paalArray.getJSONObject(i) paalList.add(paal.get("name").toString()) } return paalList } suspend fun getBaseDetails(context: Context): JSONArray { val detailJson = localDataSource.loadPaalFromAssets(context) val detailsArray: JSONArray = JSONArray(detailJson) val detailsObj: JSONObject = detailsArray.getJSONObject(0) val paalObj: JSONObject = detailsObj.getJSONObject("section") return paalObj.getJSONArray("detail") } suspend fun getIyalByPaal(context: Context, paal: String): List<String> { return withContext(Dispatchers.IO) { var chaptersGroupDetails: JSONArray? = getChapterGroupDetails(context, paal) val iyals = mutableListOf<String>() chaptersGroupDetails?.let { for (j in 0..it.length() - 1) { val iyal = it.getJSONObject(j) val iyalName = iyal.get("name").toString() iyals.add(iyalName) } } iyals } } private suspend fun getChapterGroupDetails(context: Context, paal: String): JSONArray? { var chaptersGroupDetails: JSONArray? = null val paalArray = getBaseDetails(context) for (i in 0..paalArray.length() - 1) { val p: JSONObject = paalArray.getJSONObject(i) if (paal.equals(p.getString("name"))) { val chapterGroup: JSONObject = p.getJSONObject("chapterGroup") chaptersGroupDetails = chapterGroup.getJSONArray("detail") break } } return chaptersGroupDetails } suspend fun getAthikaramByPaal( context: Context, paal: String, iyalName: String? ): List<String> { return withContext(Dispatchers.IO) { var chaptersGroupDetails: JSONArray? = getChapterGroupDetails(context, paal) val athikaram = mutableListOf<String>() chaptersGroupDetails?.let { for (j in 0..it.length() - 1) { val iyal = it.getJSONObject(j) val chapters = iyal.getJSONObject("chapters") val name = iyal.getString("name") val detail = chapters.getJSONArray("detail") if (iyalName != null) { if (iyalName.equals(name)) { for (k in 0..detail.length() - 1) { val n = detail.getJSONObject(k).getString("name").toString() athikaram.add(n) } break } } else { for (k in 0..detail.length() - 1) { val nm = detail.getJSONObject(k).getString("name").toString() athikaram.add(nm) } } } } athikaram } } suspend fun getKuralRangeByPaal( context: Context, paal: String, athikaram: String? = null ): String? { return withContext(Dispatchers.IO) { val chaptersGroupDetails: JSONArray? = getChapterGroupDetails(context, paal) return@withContext chaptersGroupDetails?.let { return@withContext if (athikaram != null) { filterKuralByAthikaram( athikaram = athikaram, chaptersGroupDetails = it ) } else { filterKuralByRange(it) } } } } suspend fun getFavorites(context: Context): LiveData<List<Kural>> { withContext(Dispatchers.IO) { val favourites = localDataSource.getFavourites(context) favoriteKuralListLiveData.postValue(favourites) } return favoriteKuralListLiveData } suspend fun updateFavorite(context: Context, kural: Kural): Int { return withContext(Dispatchers.IO) { val statusCode = localDataSource.updateFavorite(context, kural) if (statusCode > 0) { getFavorites(context) } statusCode } } private fun filterKuralByAthikaram( athikaram: String?, chaptersGroupDetails: JSONArray ): String { for (i in 0..chaptersGroupDetails.length() - 1) { val iyalObj = chaptersGroupDetails.getJSONObject(i) val chapters = iyalObj.getJSONObject("chapters") val chapterDetail = chapters.getJSONArray("detail") for (j in 0..chapterDetail.length() - 1) { val athikaramName = chapterDetail.getJSONObject(j).getString("name") if (athikaramName.equals(athikaram)) { val start = chapterDetail.getJSONObject(j).getInt("start") val end = chapterDetail.getJSONObject(j).getInt("end") return "$start-$end" } } } return "" } private fun filterKuralByRange(chaptersGroupDetails: JSONArray): String { val chapterStart = chaptersGroupDetails.getJSONObject(0).getJSONObject("chapters") val chapterArrayStart = chapterStart.getJSONArray("detail") val startIndex = chapterArrayStart.getJSONObject(0).getInt("start") val chaptersEnd = chaptersGroupDetails.getJSONObject(chaptersGroupDetails.length().minus(1)) .getJSONObject("chapters") val chapterArrayEnd = chaptersEnd.getJSONArray("detail") val endIndex = chapterArrayEnd.getJSONObject(chapterArrayEnd.length() - 1).getInt("end") return "$startIndex-$endIndex" } fun getSettingsData(context: Context): List<Setting> { return localDataSource.getSettingsData(context) } }
Kural_2023/app/src/main/java/com/w2c/kural/repository/MainRepository.kt
598515997
package com.w2c.kural.notificationwork import android.app.* import android.content.* import android.graphics.BitmapFactory import android.os.Build import android.os.Bundle import androidx.core.app.NotificationCompat import androidx.navigation.NavDeepLinkBuilder import com.w2c.kural.R import com.w2c.kural.database.DatabaseController import com.w2c.kural.database.Kural import com.w2c.kural.utils.NUMBER import com.w2c.kural.view.fragment.KuralDetailsArgs import java.util.* import java.util.concurrent.Executors object MyNotificationManager { fun displayNotification(context: Context) { val randomKuralNumber = Random().nextInt(1330) Executors.newSingleThreadExecutor().execute { val kural: Kural? = DatabaseController.getInstance(context).kuralDAO .getKural(randomKuralNumber) kural?.let { showNotification(kural, context) } } } private fun showNotification(kural: Kural, context: Context) { val channelId = "111" val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationChannel: NotificationChannel if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = NotificationChannel( channelId, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(notificationChannel) } val kuralNo = String.format(context.getString(R.string.kural_no), kural.number) val notification = NotificationCompat.Builder(context, channelId).apply { setContentTitle(context.getString(R.string.daily_one_kural)) setContentText("$kuralNo\n${kural.line1}") setStyle( NotificationCompat.BigTextStyle().bigText("$kuralNo\n${kural.tamilTranslation}") ) setSmallIcon(R.drawable.ic_notification) setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE) setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) color = context.getColor(androidx.core.R.color.notification_icon_bg_color) setTicker(context.getString(R.string.new_notification_from_kural)) setAutoCancel(true) setDefaults(Notification.DEFAULT_SOUND) setContentIntent(getPendingIntent(context, kural.number)) } notificationManager.notify(111, notification.build()) } private fun getPendingIntent(context: Context, number: Int): PendingIntent { val bundle = Bundle().apply { putInt(NUMBER, number) } return NavDeepLinkBuilder(context) .setGraph(R.navigation.my_navigation) .addDestination(R.id.kuralDetails) .setArguments(bundle) .createPendingIntent() } }
Kural_2023/app/src/main/java/com/w2c/kural/notificationwork/MyNotificationManager.kt
3510910820
package com.w2c.kural.notificationwork import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters class NotificationWork(private val context: Context, workerParams: WorkerParameters) : Worker( context, workerParams ) { override fun doWork(): Result { MyNotificationManager.displayNotification(context) return Result.success() } }
Kural_2023/app/src/main/java/com/w2c/kural/notificationwork/NotificationWork.kt
3593546359
package com.w2c.kural import android.app.Application class MyApplication : Application() { }
Kural_2023/app/src/main/java/com/w2c/kural/MyApplication.kt
507362772
package com.w2c.kural.utils import android.util.Log import android.view.View import android.view.ViewGroup import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale fun View.visible() { this.visibility = View.VISIBLE } fun View.hide() { this.visibility = View.GONE } fun ViewGroup.visible() { this.visibility = View.VISIBLE } fun ViewGroup.hide() { this.visibility = View.GONE } //Formatted date 15-07-2021 09:07 PM val todayDate: String get() { val currentDate = Date() val simpleDateFormat = SimpleDateFormat( "dd-MM-yyyy hh:mm a", Locale.getDefault() ) val formattedDate = simpleDateFormat.format(currentDate) Log.d("Formatted date", formattedDate) //Formatted date 15-07-2021 09:07 PM return formattedDate } fun getDifferentMillsToNextDay(): Long { val currentTime = Calendar.getInstance().time val now = Calendar.getInstance(Locale.getDefault()) now.time = currentTime return getTargetTime().timeInMillis - now.timeInMillis } private fun getTargetTime(): Calendar { val calender = Calendar.getInstance(Locale.getDefault()) calender.time = Date() calender.set(Calendar.HOUR_OF_DAY, 3) calender.set(Calendar.MINUTE, 0) calender.set(Calendar.SECOND, 0) calender.add(Calendar.DAY_OF_MONTH, 1) return calender }
Kural_2023/app/src/main/java/com/w2c/kural/utils/Utils.kt
1707880833
package com.w2c.kural.utils interface OnItemClickListener { fun onItemClick(position: Int) fun onManageFavorite(position: Int) }
Kural_2023/app/src/main/java/com/w2c/kural/utils/OnItemClickListener.kt
701521423
package com.w2c.kural.utils enum class ScreenTypes { IYAL, ATHIKARAM, KURALH, KURALF }
Kural_2023/app/src/main/java/com/w2c/kural/utils/ScreenTypes.kt
2152076124
package com.w2c.kural.utils interface AthikaramClickListener { fun onItemClick(position: Int) }
Kural_2023/app/src/main/java/com/w2c/kural/utils/AthikaramClickListener.kt
632135391
package com.w2c.kural.utils enum class AdapterActions { ITEM_CLICK, MANAGE_FAVORITE }
Kural_2023/app/src/main/java/com/w2c/kural/utils/AdapterActions.kt
2505858293
package com.w2c.kural.utils import android.Manifest /*SETTINGS PROPERTIES*/ val MAIL_TO = "mailto:" val SUPPORT_MAIL_ID = "[email protected]" val APP_FEEDBACK = "Thirukkural App Feedback" val APP_NOT_FOUND = "No mail application available in this device, please install mail application and try again.." val MARKET_PATH = "market://details?id=" val STORE_PATH = "http://play.google.com/store/apps/details?id" val PLAIN_TEXT = "text/plain" val SHARE_VIA = "Share via" val WORK_NAME = "kural-work" val PACKAGE = "package" /*DB PROPERTIES*/ val DB_VERSION = 1 /*NETWORK PROPERTIES*/ val TO_SEC = 4L val BASE_URL = "https://firebasestorage.googleapis.com/v0/b/thirukkural-5f267.appspot.com/o/" /*BUNDLE PROPERTIES*/ val ATHIKARAM = "athikaram" val IYAL = "iyal" val PAAL = "paal" val KURAL = "kural" val NUMBER = "number" /*PERMISSION PROPERTIES*/ val NOTIFICATION_REQ_CODE = 1010 val POST_NOTIFICATIONS = Manifest.permission.POST_NOTIFICATIONS
Kural_2023/app/src/main/java/com/w2c/kural/utils/Constants.kt
2415126617
package com.w2c.kural.utils import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences class NotificationPreference private constructor(context: Context) { @set:SuppressLint("ApplySharedPref") var isDailyNotifyValue: Boolean get() = notification.getBoolean("switch", false) set(dailyNotifyValue) { val editor = notification.edit() editor.putBoolean("switch", dailyNotifyValue) editor.commit() } companion object { private lateinit var notification: SharedPreferences private lateinit var myPreference: NotificationPreference fun getInstance(context: Context): NotificationPreference { if (!Companion::myPreference.isInitialized) { myPreference = NotificationPreference(context) } return myPreference } } init { notification = context.getSharedPreferences("KURAL_NOTIFICATION", Context.MODE_PRIVATE) } }
Kural_2023/app/src/main/java/com/w2c/kural/utils/NotificationPreference.kt
460147204
package com.w2c.kural.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.w2c.kural.databinding.ListItemChapterBinding import com.w2c.kural.model.Chapter import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.AthikaramClickListener class AthikaramAdapter( private val tag: String, private val list: List<String>, private val callback: (pos: Int, action: AdapterActions) -> Unit ) : RecyclerView.Adapter<AthikaramAdapter.AthikaramViewHolder>() { class AthikaramViewHolder( val binding: ListItemChapterBinding, val callback: (pos: Int, action: AdapterActions) -> Unit ) : RecyclerView.ViewHolder(binding.root) { init { binding.root.setOnClickListener { callback(layoutPosition, AdapterActions.ITEM_CLICK) } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): AthikaramViewHolder { val binding = ListItemChapterBinding.inflate(LayoutInflater.from(parent.context), parent, false) return AthikaramViewHolder(binding, callback) } override fun onBindViewHolder(holder: AthikaramAdapter.AthikaramViewHolder, position: Int) { val chapter = Chapter("$tag-${position + 1}", list[position]) holder.binding.chapter = chapter } override fun getItemCount(): Int { return list.size } }
Kural_2023/app/src/main/java/com/w2c/kural/adapter/AthikaramAdapter.kt
3765912899
package com.w2c.kural.adapter import android.annotation.SuppressLint import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.MotionEvent import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.w2c.kural.R import com.w2c.kural.adapter.KuralAdapter.KuralViewHolder import com.w2c.kural.database.DatabaseController import com.w2c.kural.database.Kural import com.w2c.kural.databinding.ListItemKuralBinding import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.OnItemClickListener import com.zerobranch.layout.SwipeLayout import java.util.concurrent.Executors class KuralAdapter( private val kuralList: List<Kural>, private val callback: (pos: Int, action: AdapterActions) -> Unit ) : RecyclerView.Adapter<KuralViewHolder>() { private var isFromFavourite = false fun setFromFavourite() { isFromFavourite = true } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KuralViewHolder { val listBinding = ListItemKuralBinding.inflate(LayoutInflater.from(parent.context), parent, false) return KuralViewHolder(listBinding, callback) } override fun onBindViewHolder(holder: KuralViewHolder, position: Int) { val kural = kuralList[position] holder.kuralListBinding.kural = kural } override fun getItemCount(): Int { return kuralList.size } class KuralViewHolder(val kuralListBinding: ListItemKuralBinding, val callback: (pos: Int, action: AdapterActions) -> Unit) : RecyclerView.ViewHolder(kuralListBinding.root) { init { kuralListBinding.constraintLayout.setOnClickListener { callback(layoutPosition, AdapterActions.ITEM_CLICK) } kuralListBinding.swipeItem.setOnClickListener { callback(layoutPosition, AdapterActions.MANAGE_FAVORITE) } } } }
Kural_2023/app/src/main/java/com/w2c/kural/adapter/KuralAdapter.kt
3787998936
package com.w2c.kural.adapter import android.annotation.SuppressLint import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import com.w2c.kural.adapter.SettingsAdapter.SettingsViewHolder import com.w2c.kural.databinding.ListItemSettingsBinding import com.w2c.kural.model.Setting import com.w2c.kural.notificationwork.NotificationWork import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.NotificationPreference import com.w2c.kural.utils.OnItemClickListener import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit class SettingsAdapter(private val callback: (pos: Int, action: AdapterActions) -> Unit, private val mList: List<Setting>) : RecyclerView.Adapter<SettingsViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder { val settings = ListItemSettingsBinding.inflate(LayoutInflater.from(parent.context), parent, false) return SettingsViewHolder(settings, callback) } override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) { val item = mList[position] if (position == 0) { holder.settingsBinding.switch1.visibility = View.VISIBLE holder.settingsBinding.tvSettings.visibility = View.GONE val notify = NotificationPreference.getInstance(holder.itemView.context) .isDailyNotifyValue holder.settingsBinding.switch1.isChecked = notify holder.settingsBinding.ivSettings.setImageResource(if (notify) item.images.first() else item.images[1]) } else { holder.settingsBinding.tvSettings.visibility = View.VISIBLE holder.settingsBinding.switch1.visibility = View.GONE holder.settingsBinding.tvSettings.text = item.description holder.settingsBinding.ivSettings.setImageResource(item.images.first()) } } override fun getItemCount(): Int { return mList.size } class SettingsViewHolder( val settingsBinding: ListItemSettingsBinding, val callback: (pos: Int, action: AdapterActions) -> Unit ) : RecyclerView.ViewHolder( settingsBinding.root ) { init { settingsBinding.root.setOnClickListener { callback(adapterPosition, AdapterActions.ITEM_CLICK) } } } }
Kural_2023/app/src/main/java/com/w2c/kural/adapter/SettingsAdapter.kt
1420953725
package com.w2c.kural.retrofit import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import com.w2c.kural.utils.TO_SEC import com.w2c.kural.utils.BASE_URL class RetrofitClient private constructor() { private val mRetrofitInstance: Retrofit by lazy { val okHttpClient = OkHttpClient() .newBuilder() .connectTimeout(TO_SEC, TimeUnit.SECONDS) .readTimeout(TO_SEC, TimeUnit.SECONDS) .build() Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()).build() } fun getKuralApi(): KuralApi { return mRetrofitInstance.create(KuralApi::class.java) } companion object { private lateinit var INSTANCE: RetrofitClient @get:Synchronized val instance: RetrofitClient get() { if (!Companion::INSTANCE.isInitialized) { INSTANCE = RetrofitClient() } return INSTANCE } } }
Kural_2023/app/src/main/java/com/w2c/kural/retrofit/RetrofitClient.kt
896642219
package com.w2c.kural.retrofit import retrofit2.http.GET import retrofit2.http.Query interface KuralApi { @GET(KURAL_URL) suspend fun getKural( @Query("alt") alt: String = "media", @Query("token") token: String = "9c8ad44f-a816-427f-8b25-21aabbefa9ae" ): KuralResponse companion object { const val KURAL_URL = "thirukkural.json" } }
Kural_2023/app/src/main/java/com/w2c/kural/retrofit/KuralApi.kt
1647002023
package com.w2c.kural.retrofit import com.w2c.kural.database.Kural data class KuralResponse(var kural: List<Kural>)
Kural_2023/app/src/main/java/com/w2c/kural/retrofit/KuralResponse.kt
1256890679
package com.w2c.kural.model data class Chapter(val title: String, val description: String)
Kural_2023/app/src/main/java/com/w2c/kural/model/Chapter.kt
1147370841
package com.w2c.kural.model data class Setting(val description: String, val images: List<Int>)
Kural_2023/app/src/main/java/com/w2c/kural/model/Setting.kt
2683438882
package com.w2c.kural.view.activity import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.view.LayoutInflater import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import androidx.work.BackoffPolicy import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequest import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import com.google.android.material.bottomnavigation.BottomNavigationView import com.w2c.kural.R import com.w2c.kural.databinding.ActivityMainBinding import com.w2c.kural.datasource.LocalDataSource import com.w2c.kural.datasource.RemoteDataSource import com.w2c.kural.notificationwork.NotificationWork import com.w2c.kural.repository.MainRepository import com.w2c.kural.utils.ATHIKARAM import com.w2c.kural.utils.IYAL import com.w2c.kural.utils.NOTIFICATION_REQ_CODE import com.w2c.kural.utils.NotificationPreference import com.w2c.kural.utils.PAAL import com.w2c.kural.utils.POST_NOTIFICATIONS import com.w2c.kural.utils.ScreenTypes import com.w2c.kural.utils.WORK_NAME import com.w2c.kural.utils.PACKAGE import com.w2c.kural.utils.getDifferentMillsToNextDay import com.w2c.kural.utils.hide import com.w2c.kural.utils.visible import com.w2c.kural.viewmodel.MainActivityViewModel import com.w2c.kural.viewmodel.MainVMFactory import kotlinx.coroutines.launch import java.util.concurrent.TimeUnit class MainActivity : AppCompatActivity() { private lateinit var controller: NavController private lateinit var bottomNavigationBar: BottomNavigationView private lateinit var binding: ActivityMainBinding private var firstTime = true private val topLevelDestinations = setOf( R.id.paalFragment, R.id.home, R.id.favourite, R.id.setting, R.id.progressDialogFragment ) private var favorite = false private var isInSettings = false private lateinit var viewModel: MainActivityViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(LayoutInflater.from(this)) setContentView(binding.root) preLoadKural() initView() setUpFavoriteObserver() setUpNotificationObserver() } override fun onResume() { super.onResume() verifyPermission() } private fun initView() { val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment controller = navHostFragment.navController bottomNavigationBar = findViewById(R.id.bottomNav) controller.addOnDestinationChangedListener { _, destination, args -> //Mange Title val title: String? = getTitleFromDestination(destination.label, args) binding.title.text = title ?: "" val showTitle = topLevelDestinations.contains(destination.id) && args?.get("screenType") != ScreenTypes.KURALH //Manage BottomBar and Back Button Visibility manageBottomBarAndBackBtn(showTitle) //Manage Favorite Icon in Detail Screen if (destination.id == R.id.kuralDetails) binding.ivFav.visible() else binding.ivFav.hide() } binding.bottomNav.setupWithNavController(controller) } private fun manageBottomBarAndBackBtn(show: Boolean) { if (show) { binding.ivBack.hide() bottomNavigationBar.visible() } else { binding.ivBack.visible() bottomNavigationBar.hide() } binding.ivBack.setOnClickListener { controller.popBackStack() } } private fun getTitleFromDestination(label: CharSequence?, args: Bundle?): String? { val athikaram = args?.getString(ATHIKARAM) val iyal = args?.getString(IYAL) val paal = args?.getString(PAAL) return if (!athikaram.isNullOrEmpty()) athikaram else if (!iyal.isNullOrEmpty()) iyal else if (!paal.isNullOrEmpty()) paal else label?.toString() } private fun preLoadKural() { val repo = MainRepository(LocalDataSource(), RemoteDataSource()) viewModel = ViewModelProvider( this, MainVMFactory(context = this, repository = repo) )[MainActivityViewModel::class.java] lifecycleScope.launch { viewModel.getKurals(this@MainActivity).observe(this@MainActivity) { if (firstTime) { firstTime = false viewModel.cacheKural(it) } } } } private fun setUpFavoriteObserver() { binding.ivFav.setOnClickListener { favorite = !favorite updateFavIcon() viewModel.onFavClick() } viewModel.favUpdateTBIconLiveData.observe(this) { favorite = it updateFavIcon() } viewModel.favStatusLiveData.observe(this) { //it[0] => denotes, status(true=>success/false=>failure) //it[1] => denotes, action(true=>add/false=>remove) val message = if (it[0]) { getString(if (it[1]) R.string.added_to_favorites else R.string.remove_from_favorites) } else { getString(if (it[1]) R.string.unable_to_add else R.string.unable_to_remove) } Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show() } } private fun updateFavIcon() { val resource = if (favorite) R.drawable.ic_remove_favorite else R.drawable.ic_add_favorite binding.ivFav.setImageResource(resource) binding.ivFav.setColorFilter( ContextCompat.getColor(this, R.color.primary), android.graphics.PorterDuff.Mode.SRC_IN ) } private fun setUpNotificationObserver() { viewModel.notificationLiveData.observe(this) { checkNotificationPermission() } } private fun checkNotificationPermission() { if (Build.VERSION.SDK_INT < 33) { scheduleNotificationWork() return } when { ContextCompat.checkSelfPermission( this@MainActivity, POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED -> { scheduleNotificationWork() } shouldShowRequestPermissionRationale(POST_NOTIFICATIONS) -> { controller.navigate(R.id.notificationEducationFragment) } else -> { ActivityCompat.requestPermissions( this@MainActivity, arrayOf(POST_NOTIFICATIONS), NOTIFICATION_REQ_CODE ) } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == NOTIFICATION_REQ_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText( applicationContext, getString(R.string.notification_granted_info), Toast.LENGTH_SHORT ).show() scheduleNotificationWork() } else if (shouldShowRequestPermissionRationale(POST_NOTIFICATIONS)) { controller.navigate(R.id.notificationEducationFragment) } else if (!shouldShowRequestPermissionRationale(POST_NOTIFICATIONS)) { showPermissionDialog() } else { ActivityCompat.requestPermissions( this@MainActivity, arrayOf(POST_NOTIFICATIONS), NOTIFICATION_REQ_CODE ) } } } private fun showPermissionDialog(notify: Boolean = false) { val alertDialog = AlertDialog.Builder(this).setTitle(getString(R.string.permission_required)) .setCancelable(false).setMessage(getString(R.string.permission_required_desc)) .setPositiveButton( getString(R.string.go_to_settings) ) { dialogInterface: DialogInterface, _: Int -> navigateToSettings() dialogInterface.dismiss() } if (!notify) { alertDialog.setNegativeButton( getString(R.string.not_now), ) { dialogInterface: DialogInterface, _: Int -> dialogInterface.dismiss() } } alertDialog.show() } private fun navigateToSettings() { isInSettings = true val intent = Intent() intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS val uri = Uri.fromParts( PACKAGE, packageName, null ) intent.data = uri startActivity(intent) } private fun scheduleNotificationWork() { val notify = viewModel.updateNotificationStatus(this) if (notify) { val workRequest: PeriodicWorkRequest = PeriodicWorkRequestBuilder<NotificationWork>(1, TimeUnit.DAYS) .setInitialDelay(getDifferentMillsToNextDay(), TimeUnit.MILLISECONDS) .setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.HOURS) .build() WorkManager.getInstance(this) .enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, workRequest) } else { WorkManager.getInstance(this).cancelUniqueWork(WORK_NAME) } updateSettingsUI(notify) } private fun verifyPermission() { //If ==> When the notification on in app setting but //it turned off in mobile setting, forcing user to turn on permission in settings. //Else ==> Updating UI when user currently in app settings and turning on the //notification permission from mobile settings val granted = ContextCompat.checkSelfPermission( this, POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED if (NotificationPreference.getInstance(this).isDailyNotifyValue && !granted ) { showPermissionDialog(true) } else if (isInSettings && granted) { scheduleNotificationWork() } } private fun updateSettingsUI(notify: Boolean) { viewModel.notificationUpdateUI() Toast.makeText( applicationContext, getString(if (notify) R.string.notification_tuned_on else R.string.notification_tuned_off), Toast.LENGTH_SHORT ).show() } }
Kural_2023/app/src/main/java/com/w2c/kural/view/activity/MainActivity.kt
2140489746
package com.w2c.kural.view.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.app.ActivityCompat import androidx.fragment.app.DialogFragment import androidx.navigation.fragment.findNavController import com.w2c.kural.databinding.FragmentNotificationEducationBinding import com.w2c.kural.utils.NOTIFICATION_REQ_CODE import com.w2c.kural.utils.POST_NOTIFICATIONS class NoticeFragment : DialogFragment() { private var binding_: FragmentNotificationEducationBinding? = null private val binding get() = binding_!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding_ = FragmentNotificationEducationBinding.inflate(inflater) initView() return binding.root } fun initView() { binding.ivClose.setOnClickListener { findNavController().popBackStack() } binding.btnOk.setOnClickListener { findNavController().popBackStack() ActivityCompat.requestPermissions( requireActivity(), arrayOf(POST_NOTIFICATIONS), NOTIFICATION_REQ_CODE ) } } override fun onDestroyView() { super.onDestroyView() binding.unbind() } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/NoticeFragment.kt
2762203942
package com.w2c.kural.view.fragment import android.content.ActivityNotFoundException import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import com.w2c.kural.adapter.SettingsAdapter import android.view.View import android.widget.Toast import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.MobileAds import com.w2c.kural.databinding.FragmentSettingsBinding import com.w2c.kural.utils.OnItemClickListener import com.w2c.kural.utils.todayDate import java.util.ArrayList import com.w2c.kural.utils.* import com.w2c.kural.R import com.w2c.kural.model.Setting import com.w2c.kural.viewmodel.MainActivityViewModel class Settings : Fragment() { private var settingsBinding_: FragmentSettingsBinding? = null private val settingsBinding get() = settingsBinding_!! private lateinit var adapter: SettingsAdapter private lateinit var viewModel: MainActivityViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { settingsBinding_ = FragmentSettingsBinding.inflate(inflater) setUpAd() loadSettingsData() observeUIUpdate() return settingsBinding.root } private fun setUpAd() { MobileAds.initialize(requireActivity()) val adRequest = AdRequest.Builder().build() settingsBinding.adView.loadAd(adRequest) } private fun loadSettingsData() { viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] val data = viewModel.getSettingsData(requireActivity()) settingsBinding.rvSettings.layoutManager = LinearLayoutManager(requireActivity()) adapter = SettingsAdapter(getCallBack, data) settingsBinding.rvSettings.adapter = adapter } private val getCallBack = { pos: Int, action: AdapterActions -> onItemClick(pos) } private fun observeUIUpdate() { viewModel.notificationRefreshUILiveData.observe(viewLifecycleOwner) { adapter.notifyItemChanged(0) } } private fun onItemClick(position: Int) { when (position) { 0 -> { viewModel.observeNotificationChanges() } 1 -> { navigateToMailIntent() } 2 -> { navigateToRateAppIntent() } 3 -> { navigateToShareAppIntent() } } } private fun navigateToMailIntent() { val selectorIntent = Intent(Intent.ACTION_SENDTO) selectorIntent.data = Uri.parse(MAIL_TO) val emailIntent = Intent(Intent.ACTION_SEND) emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(SUPPORT_MAIL_ID)) emailIntent.putExtra(Intent.EXTRA_SUBJECT, "$APP_FEEDBACK : $todayDate") emailIntent.putExtra(Intent.EXTRA_TEXT, "") emailIntent.selector = selectorIntent try { startActivity(emailIntent) } catch (e: Exception) { Toast.makeText( requireActivity(), APP_NOT_FOUND, Toast.LENGTH_SHORT ).show() } } private fun navigateToRateAppIntent() { val rateAppIntent = Intent(Intent.ACTION_VIEW) try { rateAppIntent.data = Uri.parse(MARKET_PATH + requireActivity().packageName) startActivity(rateAppIntent) } catch (e: ActivityNotFoundException) { rateAppIntent.data = Uri.parse( STORE_PATH + requireActivity().packageName ) startActivity(rateAppIntent) } } private fun navigateToShareAppIntent() { val shareAppIntent = Intent(Intent.ACTION_SEND) val url = "$STORE_PATH=" + requireActivity().packageName shareAppIntent.putExtra(Intent.EXTRA_TEXT, url) shareAppIntent.type = PLAIN_TEXT startActivity(Intent.createChooser(shareAppIntent, SHARE_VIA)) } override fun onDestroyView() { settingsBinding.rvSettings.adapter = null super.onDestroyView() removeAdView() settingsBinding_ = null } private fun removeAdView() { val adView = settingsBinding.adView if (adView.parent != null) { (adView.parent as ViewGroup).removeView(adView) } adView.destroy() } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/Settings.kt
3453435669
package com.w2c.kural.view.fragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.w2c.kural.databinding.FragmentProgressDialogBinding class ProgressDialogFragment : DialogFragment() { private var binding_: FragmentProgressDialogBinding? = null private val binding get() = binding_!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { isCancelable = false binding_ = FragmentProgressDialogBinding.inflate(inflater) return binding.root } override fun onDestroyView() { super.onDestroyView() binding_ = null } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/ProgressDialogFragment.kt
82376634
package com.w2c.kural.view.fragment import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.w2c.kural.R import com.w2c.kural.adapter.AthikaramAdapter import com.w2c.kural.databinding.FragmentAthikaramListBinding import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.AthikaramClickListener import com.w2c.kural.utils.ScreenTypes import com.w2c.kural.view.activity.MainActivity import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class AthikaramList : Fragment(), AthikaramClickListener { private var binding_: FragmentAthikaramListBinding? = null private val binding get() = binding_!! private lateinit var viewmodel: MainActivityViewModel private lateinit var list: List<String> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding_ = FragmentAthikaramListBinding.inflate(inflater) viewmodel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] loadData() return binding.root } private fun loadData() { val args: AthikaramListArgs by navArgs() loadAthikaram(args.paal, args.iyal, getString(R.string.athikaram)) } private fun loadAthikaram(paal: String, iyal: String?, title: String) { lifecycleScope.launch(Dispatchers.Main + getExceptionHandler()) { viewmodel.getAthikaramByPaal(requireActivity(), paal, iyal).observe(viewLifecycleOwner) { it?.let { list = it val adapter = AthikaramAdapter(title, it, getCallBack) binding.rvChapter.adapter = adapter } } } } private val getCallBack = { pos: Int, _: AdapterActions -> onItemClick(pos) } private fun getExceptionHandler(): CoroutineExceptionHandler { val handler = CoroutineExceptionHandler { _, exception -> lifecycleScope.launch(Dispatchers.Main) { Toast.makeText(requireActivity(), exception.message, Toast.LENGTH_SHORT).show() } } return handler } override fun onItemClick(position: Int) { if (!::list.isInitialized) { throw IllegalArgumentException("List cannot be empty or null") } val item = list[position] val args: AthikaramListArgs by navArgs() val kuralList = AthikaramListDirections.actionAthikaramListToHome( screenType = ScreenTypes.KURALH, athikaram = item, paal = args.paal, iyal = args.iyal ) findNavController().navigate(kuralList) } override fun onDestroyView() { binding.rvChapter.adapter = null super.onDestroyView() binding_=null } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/AthikaramList.kt
851882726
package com.w2c.kural.view.fragment import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.w2c.kural.adapter.KuralAdapter import com.w2c.kural.database.Kural import com.w2c.kural.databinding.KuralListBinding import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.ScreenTypes import com.w2c.kural.utils.hide import com.w2c.kural.utils.visible import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.* import com.w2c.kural.R class KuralList : Fragment() { private var binding_: KuralListBinding? = null private val binding get() = binding_!! private var kuralAdapter: KuralAdapter? = null private var mKuralList: MutableList<Kural> = mutableListOf() private val mKuralListOriginal: MutableList<Kural> = mutableListOf() private lateinit var viewModel: MainActivityViewModel private var handler = Handler() private lateinit var runnable: Runnable override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { initView() getKuralList() return binding.root } override fun onResume() { super.onResume() manageUI() } private fun manageUI() { if (isFromHomeCard()) { binding.edtSearch.hide() binding.ivSearch.hide() } else { binding.edtSearch.visible() binding.ivSearch.visible() } } private fun initView() { binding_ = KuralListBinding.inflate(LayoutInflater.from(requireActivity())) binding.rvKuralList.layoutManager = LinearLayoutManager(requireActivity()) viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] if (!isFromHomeCard()) { setUpListeners() } } private fun setUpListeners() { binding.edtSearch.tag = false binding.edtSearch.setOnFocusChangeListener { v, _ -> v.tag = true } binding.edtSearch.addTextChangedListener { val tag = binding.edtSearch.tag as Boolean val key = it.toString().lowercase().trimStart().trimEnd() if (tag || key.isNotEmpty()) { manageCancelView(key) runnable = Runnable { searchKural(key) } handler.postDelayed(runnable, 500) } } binding.ivCancel.setOnClickListener { binding.edtSearch.setText("") mKuralList.addAll(mKuralListOriginal) kuralAdapter?.notifyDataSetChanged() binding.tvNotFound.hide() } } private fun manageCancelView(key: String) { if (key.isNotEmpty()) { binding.ivCancel.visible() } else { binding.ivCancel.hide() } } private fun searchKural(searchKey: String) { lifecycleScope.launch(Dispatchers.Main) { val filteredKurals = viewModel.filterKuralBySearch(searchKey) mKuralList.clear() if (filteredKurals.isNotEmpty()) { mKuralList.addAll(filteredKurals) binding.tvNotFound.hide() } else { binding.tvNotFound.visible() } kuralAdapter?.notifyDataSetChanged() } } private fun getKuralList() { lifecycleScope.launch(getExceptionHandler()) { getKural() } } private fun getExceptionHandler(): CoroutineExceptionHandler { val handler = CoroutineExceptionHandler { _, exception -> lifecycleScope.launch(Dispatchers.Main) { hideProgress() Toast.makeText(requireActivity(), exception.message, Toast.LENGTH_SHORT).show() } } return handler } private suspend fun getKural() { val data = viewModel.kuralCache if (isFromHomeCard()) { fetchKuralsByRange(getNavArgs().paal!!, getNavArgs().athikaram) } else if (data.isNotEmpty()) { setKuralList(data) } else { fetchKurals() } } private fun isFromHomeCard(): Boolean { return getNavArgs().screenType == ScreenTypes.KURALH } private fun getNavArgs(): KuralListArgs { val kuralArgs: KuralListArgs by navArgs() return kuralArgs } private suspend fun fetchKuralsByRange(paal: String, athikaram: String?) { viewModel.getKuralsByRange(requireActivity(), paal, athikaram) .observe(viewLifecycleOwner) { data: List<Kural> -> setKuralList(data) hideProgress() } } private suspend fun fetchKurals() { showProgress() viewModel.getKurals(requireActivity()).observe(viewLifecycleOwner) { data: List<Kural> -> setKuralList(data) hideProgress() } } private fun setKuralList(data: List<Kural>) { mKuralListOriginal.clear() mKuralListOriginal.addAll(data) mKuralList.clear() mKuralList.addAll(data) kuralAdapter = KuralAdapter(mKuralList, getCallBack) binding.rvKuralList.adapter = kuralAdapter } private val getCallBack = { pos: Int, action: AdapterActions -> if (action == AdapterActions.ITEM_CLICK) onItemClick(pos) else onManageFavorite(pos) } private fun onItemClick(position: Int) { val controller = findNavController() val kuralNumber = mKuralList[position].number val kuralDetailDirection = KuralListDirections.actionHomeToKuralDetails(kuralNumber) //Illegal Arguments Crash fix //Navigation destination cannot be found from the current destination if (controller.currentDestination?.id != kuralDetailDirection.actionId) { controller.navigate(kuralDetailDirection) } } private fun onManageFavorite(position: Int) { lifecycleScope.launch(Dispatchers.Main) { val kural = mKuralList[position].apply { favourite = if (favourite == 0) 1 else 0 } kuralAdapter?.notifyItemChanged(position, kural) viewModel.manageFavorite(requireActivity(), kural) } } override fun onDestroyView() { binding.rvKuralList.adapter = null super.onDestroyView() if (::runnable.isInitialized && handler.hasCallbacks(runnable)) { handler.removeCallbacks(runnable) } binding_ = null } private fun showProgress() { findNavController().navigate(KuralListDirections.actionHomeToProgressDialogFragment()) } private fun hideProgress() { if (findNavController().currentDestination!!.id == R.id.progressDialogFragment) { findNavController().popBackStack() } } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/KuralList.kt
3887905822
package com.w2c.kural.view.fragment import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.MobileAds import com.w2c.kural.database.DatabaseController import com.w2c.kural.database.Kural import com.w2c.kural.utils.hide import com.w2c.kural.utils.visible import com.w2c.kural.view.activity.MainActivity import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.concurrent.Executors import com.w2c.kural.databinding.FragmentKuralDetailsBinding class KuralDetails : Fragment() { private var kuralBinding_: FragmentKuralDetailsBinding? = null private val kuralBinding get() = kuralBinding_!! private lateinit var viewModel: MainActivityViewModel private lateinit var kural: Kural override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { kuralBinding_ = FragmentKuralDetailsBinding.inflate(LayoutInflater.from(requireActivity())) kuralBinding.parentLayout.hide() viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] setUpAd() updateUI() setUpFavoriteClickObserver() return kuralBinding.root } private fun setUpAd() { MobileAds.initialize(requireActivity()) val adRequest = AdRequest.Builder().build() kuralBinding.adView.loadAd(adRequest) } private fun updateUI() { val args: KuralDetailsArgs by navArgs<KuralDetailsArgs>() lifecycleScope.launch(Dispatchers.Main) { viewModel.getKuralDetail(requireActivity(), args.number) .observe(viewLifecycleOwner) { it -> kural = it kuralBinding.kural = kural viewModel.updateFavToolBarIcon(kural.favourite == 1) kuralBinding.parentLayout.visible() } } } private fun setUpFavoriteClickObserver() { viewModel.favClickLiveData.observe(viewLifecycleOwner) { lifecycleScope.launch(Dispatchers.Main) { if (::kural.isInitialized) { kural.apply { favourite = if (favourite == 0) 1 else 0 } viewModel.manageFavorite(requireActivity(), kural) } } } } override fun onDestroyView() { super.onDestroyView() removeAdView() kuralBinding_ = null } private fun removeAdView() { val adView = kuralBinding.adView if (adView.parent != null) { (adView.parent as ViewGroup).removeView(adView) } adView.destroy() } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/KuralDetails.kt
1863892572
package com.w2c.kural.view.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.w2c.kural.adapter.KuralAdapter import com.w2c.kural.database.Kural import com.w2c.kural.databinding.FragmentFavouriteBinding import com.w2c.kural.utils.OnItemClickListener import com.w2c.kural.utils.hide import com.w2c.kural.utils.visible import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import com.w2c.kural.R import com.w2c.kural.utils.AdapterActions class Favourites : Fragment() { private var binding_: FragmentFavouriteBinding? = null private val binding get() = binding_!! private lateinit var viewModel: MainActivityViewModel private var favAdapter: KuralAdapter? = null private var favourites: MutableList<Kural> = mutableListOf() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this binding_ = FragmentFavouriteBinding.inflate(inflater) viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] fetchFavorites() return binding.root } private fun fetchFavorites() { setupAdapter() lifecycleScope.launch(Dispatchers.Main) { viewModel.getFavoriteKurals(requireActivity()).observe(viewLifecycleOwner) { if (favourites.isNotEmpty()) favourites.clear() favourites.addAll(it) favAdapter?.notifyDataSetChanged() manageKuralEmptyView(favourites.isEmpty()) } } } private fun manageKuralEmptyView(empty: Boolean) { if (empty) { binding.tvNoFavorites.visible() binding.rvFavourite.hide() } else { binding.rvFavourite.visible() binding.tvNoFavorites.hide() } } private fun setupAdapter() { binding.rvFavourite.layoutManager = LinearLayoutManager(requireActivity()) favAdapter = KuralAdapter(favourites, getCallBack) favAdapter?.setFromFavourite() binding.rvFavourite.adapter = favAdapter } private val getCallBack = { pos: Int, action: AdapterActions -> if(action==AdapterActions.ITEM_CLICK) onItemClick(pos) else onManageFavorite(pos) } private fun onItemClick(position: Int) { val kuralNumber = favourites[position].number val kuralDetailDirection = FavouritesDirections.actionFavouriteToKuralDetails(kuralNumber) findNavController().navigate(kuralDetailDirection) } private fun onManageFavorite(position: Int) { lifecycleScope.launch(Dispatchers.Main) { val kural = favourites[position].apply { favourite = 0 } favAdapter?.notifyItemChanged(position, kural) viewModel.manageFavorite(requireActivity(), kural) } } override fun onDestroyView() { binding.rvFavourite.adapter = null super.onDestroyView() binding_ = null } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/Favourites.kt
2498914942
package com.w2c.kural.view.fragment import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdView import com.google.android.gms.ads.MobileAds import com.w2c.kural.R import com.w2c.kural.databinding.FragmentPaalBinding import com.w2c.kural.utils.ScreenTypes import com.w2c.kural.view.activity.MainActivity import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.supervisorScope import com.w2c.kural.utils.ATHIKARAM import com.w2c.kural.utils.IYAL import com.w2c.kural.utils.KURAL class PaalList : Fragment() { private var binding_: FragmentPaalBinding? = null private val binding get() = binding_!! private lateinit var mainActivityViewModel: MainActivityViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding_ = FragmentPaalBinding.inflate(LayoutInflater.from(requireActivity())) mainActivityViewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] setUpAd() setUpListeners() loadData() return binding.root } private fun setUpAd() { MobileAds.initialize(requireActivity()) val adRequest = AdRequest.Builder().build() binding.adView.loadAd(adRequest) } private fun setUpListeners() { binding.incLayArathuppaal.tvIyal.setOnClickListener { navigateToIyal(getString(R.string.arathuppaal)) } binding.incLayArathuppaal.tvAthikaram.setOnClickListener { navigateToAthikaram(getString(R.string.arathuppaal)) } binding.incLayArathuppaal.tvKurals.setOnClickListener { navigateToKuralList(getString(R.string.arathuppaal)) } binding.incLayPorutpaal.tvIyal.setOnClickListener { navigateToIyal(getString(R.string.porutpaal)) } binding.incLayPorutpaal.tvAthikaram.setOnClickListener { navigateToAthikaram(getString(R.string.porutpaal)) } binding.incLayPorutpaal.tvKurals.setOnClickListener { navigateToKuralList(getString(R.string.porutpaal)) } binding.incLayKamathuppaal.tvIyal.setOnClickListener { navigateToIyal(getString(R.string.kamathuppaal)) } binding.incLayKamathuppaal.tvAthikaram.setOnClickListener { navigateToAthikaram(getString(R.string.kamathuppaal)) } binding.incLayKamathuppaal.tvKurals.setOnClickListener { navigateToKuralList(getString(R.string.kamathuppaal)) } } private fun loadData() { val scope = viewLifecycleOwner.lifecycleScope scope.launch { supervisorScope { val arathuppaalAsync = scope.async { mainActivityViewModel.getHomeCardData( requireActivity(), getString(R.string.arathuppaal) ) } val porutpaalAsync = scope.async { mainActivityViewModel.getHomeCardData( requireActivity(), getString(R.string.porutpaal) ) } val kamathuppaalAsync = scope.async { mainActivityViewModel.getHomeCardData( requireActivity(), getString(R.string.kamathuppaal) ) } setUpValues( arathuppaalAsync.await(), porutpaalAsync.await(), kamathuppaalAsync.await() ) } } } private fun setUpValues( arathuppaal: Map<String, String>, porutpaal: Map<String, String>, kamathuppaal: Map<String, String> ) { binding.incLayArathuppaal.tvIyal.text = arathuppaal[IYAL] binding.incLayArathuppaal.tvAthikaram.text = arathuppaal[ATHIKARAM] binding.incLayArathuppaal.tvKurals.text = arathuppaal[KURAL] binding.incLayPorutpaal.tvIyal.text = porutpaal[IYAL] binding.incLayPorutpaal.tvAthikaram.text = porutpaal[ATHIKARAM] binding.incLayPorutpaal.tvKurals.text = porutpaal[KURAL] binding.incLayKamathuppaal.tvIyal.text = kamathuppaal[IYAL] binding.incLayKamathuppaal.tvAthikaram.text = kamathuppaal[ATHIKARAM] binding.incLayKamathuppaal.tvKurals.text = kamathuppaal[KURAL] } private fun navigateToAthikaram(paal: String) { val iyalDirection = PaalListDirections.actionPaalFragmentToAthikaramList( paal = paal, iyal = null ) findNavController().navigate(iyalDirection) } private fun navigateToIyal(paal: String) { val iyalDirection = PaalListDirections.actionPaalFragmentToIyalList(paal = paal) findNavController().navigate(iyalDirection) } private fun navigateToKuralList(paal: String) { val kuralListDirection = PaalListDirections.actionPaalFragmentToHome( screenType = ScreenTypes.KURALH, paal = paal, athikaram = null, iyal = null ) findNavController().navigate(kuralListDirection) } override fun onDestroyView() { super.onDestroyView() removeAdView() binding_ = null } private fun removeAdView() { val adView = binding.adView if (adView.parent != null) { (adView.parent as ViewGroup).removeView(adView) } adView.destroy() } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/PaalList.kt
806925739
package com.w2c.kural.view.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.w2c.kural.R import com.w2c.kural.adapter.AthikaramAdapter import com.w2c.kural.databinding.FragmentIyalListBinding import com.w2c.kural.utils.AdapterActions import com.w2c.kural.utils.AthikaramClickListener import com.w2c.kural.utils.ScreenTypes import com.w2c.kural.view.activity.MainActivity import com.w2c.kural.viewmodel.MainActivityViewModel import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class IyalList : Fragment(), AthikaramClickListener { private var binding_: FragmentIyalListBinding? = null private val binding get() = binding_!! private lateinit var viewmodel: MainActivityViewModel private lateinit var list: List<String> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding_ = FragmentIyalListBinding.inflate(inflater) viewmodel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java] loadData() return binding.root } private fun loadData() { val args: AthikaramListArgs by navArgs() loadIyal(args.paal, getString(R.string.iyal)) } private fun loadIyal(paal: String, title: String) { lifecycleScope.launch(Dispatchers.Main + getExceptionHandler()) { viewmodel.getIyalByPaal(requireActivity(), paal).observe(viewLifecycleOwner) { it?.let { list = it val adapter = AthikaramAdapter(title, list, getCallBack) binding.rvIyal.adapter = adapter } } } } private val getCallBack = { pos: Int, _: AdapterActions -> onItemClick(pos) } private fun getExceptionHandler(): CoroutineExceptionHandler { val handler = CoroutineExceptionHandler { _, exception -> lifecycleScope.launch(Dispatchers.Main) { Toast.makeText(requireActivity(), exception.message, Toast.LENGTH_SHORT).show() } } return handler } override fun onItemClick(position: Int) { val item = list[position] val args: AthikaramListArgs by navArgs() val kuralList = IyalListDirections.actionIyalListToAthikaramList( paal = args.paal, iyal = item ) findNavController().navigate(kuralList) } override fun onDestroyView() { binding.rvIyal.adapter = null super.onDestroyView() binding_=null } }
Kural_2023/app/src/main/java/com/w2c/kural/view/fragment/IyalList.kt
2987887998
package com.matrix.android_104_android 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.matrix.android_104_android", appContext.packageName) } }
Simple_LoginApp/app/src/androidTest/java/com/matrix/android_104_android/ExampleInstrumentedTest.kt
2947001833
package com.matrix.android_104_android 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) } }
Simple_LoginApp/app/src/test/java/com/matrix/android_104_android/ExampleUnitTest.kt
2341177560
package com.matrix.android_104_android.ui import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.matrix.android_104_android.R import com.matrix.android_104_android.databinding.FragmentLoginBinding import com.matrix.android_104_android.db.RoomDb import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class LoginFragment : Fragment() { private lateinit var binding: FragmentLoginBinding private var db: RoomDb? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLoginBinding.inflate(inflater) db = RoomDb.accessDB(requireContext()) adaptLayout() login() setNavigation() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) checkSharedPreferences() } private fun checkSharedPreferences() { val sharedPreferences = activity?.getSharedPreferences("UserRegistration", Context.MODE_PRIVATE) if (sharedPreferences!!.contains("username")) { findNavController().navigate(R.id.action_loginFragment_to_homeFragment) } } private fun adaptLayout() { binding.txtHeader.text = "Login" binding.btn.text = "Login" binding.txtNav.text = "Have not an account ? Register" } private fun setNavigation() { binding.txtNav.setOnClickListener { findNavController().navigate(R.id.action_loginFragment_to_registerFragment) } } private fun login() { binding.btn.setOnClickListener { CoroutineScope(Dispatchers.Main).launch { val username = binding.edtUsername.text.toString() val password = binding.edtPassword.text.toString() val checkLogin = db?.userDao()?.checkLogin(username, password) if (checkLogin != 0) { val preference = activity?.getSharedPreferences("UserRegistration", Context.MODE_PRIVATE) with(preference?.edit()) { this?.putString("password", password) this?.putString("username", username) this?.commit() } findNavController().navigate(R.id.action_loginFragment_to_homeFragment) }else{ Snackbar.make(requireView(),"Wrong username or password",Snackbar.LENGTH_SHORT).show() } } } } }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/ui/LoginFragment.kt
2528309510
package com.matrix.android_104_android.ui import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.matrix.android_104_android.R import com.matrix.android_104_android.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private lateinit var binding: FragmentHomeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(inflater) binding.txtName.text = activity?.getSharedPreferences("UserRegistration", Context.MODE_PRIVATE)?.getString("username","N/A") logOut() return binding.root } private fun logOut(){ binding.btn.setOnClickListener { val sharedPreferences = activity?.getSharedPreferences("UserRegistration", Context.MODE_PRIVATE) val editor = sharedPreferences!!.edit() editor.remove("password") editor.remove("username") val commit = editor.commit() if(commit){ findNavController().navigate(R.id.action_homeFragment_to_loginFragment) }else { Snackbar.make(requireView(),"There was an error while log out",Snackbar.LENGTH_SHORT).show() } } } }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/ui/HomeFragment.kt
2427348810
package com.matrix.android_104_android.ui import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.matrix.android_104_android.R import com.matrix.android_104_android.databinding.FragmentLoginBinding import com.matrix.android_104_android.db.RoomDb import com.matrix.android_104_android.db.UserEntity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class RegisterFragment : Fragment() { private var db: RoomDb? = null private lateinit var binding: FragmentLoginBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLoginBinding.inflate(inflater) db = RoomDb.accessDB(requireContext()) adaptLayout() setNavigation() register() return binding.root } private fun adaptLayout() { binding.txtHeader.text = "Register" binding.btn.text = "Register" binding.txtNav.text = "Already have an account? Login" } private fun setNavigation() { binding.txtNav.setOnClickListener { findNavController().popBackStack() } } private fun register() { binding.btn.setOnClickListener { CoroutineScope(Dispatchers.Main).launch { val insert = db?.userDao()?.insert(UserEntity(userName = binding.edtUsername.text.toString(), password = binding.edtPassword.text.toString())) if(insert!=-1L){ Snackbar.make(requireView(),"Successfully registered ",Snackbar.LENGTH_SHORT).show() findNavController().popBackStack() } } } } }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/ui/RegisterFragment.kt
3905638696
package com.matrix.android_104_android import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/MainActivity.kt
1789705342
package com.matrix.android_104_android.db import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface UserDao { @Insert suspend fun insert(userEntity: UserEntity):Long @Query("Select Count(*) from users where userName==:username AND password==:password") suspend fun checkLogin(username:String, password:String):Int }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/db/UserDao.kt
2308992938
package com.matrix.android_104_android.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [UserEntity::class], version = 1) abstract class RoomDb : RoomDatabase() { abstract fun userDao(): UserDao companion object { private var INSTANCE: RoomDb? = null fun accessDB(context: Context): RoomDb? { if (INSTANCE == null) { synchronized(RoomDb::class) { INSTANCE = Room.databaseBuilder( context.applicationContext, RoomDb::class.java, "Registration" ).build() } } return INSTANCE } } }
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/db/RoomDb.kt
3126307809
package com.matrix.android_104_android.db import androidx.room.Entity import androidx.room.PrimaryKey @Entity("Users") data class UserEntity ( @PrimaryKey(autoGenerate = true) val id : Int =0, val userName : String, val password : String )
Simple_LoginApp/app/src/main/java/com/matrix/android_104_android/db/UserEntity.kt
1016129330