content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
import platform.UIKit.UIDevice
class IOSPlatform: Platform {
override val name: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
actual fun getPlatform(): Platform = IOSPlatform() | ComposeMultiplatformExample/composeApp/src/iosMain/kotlin/Platform.ios.kt | 110407275 |
import dev.icerock.moko.mvvm.viewmodel.ViewModel
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class BirdsUiState(
val images: List<BirdImage> = emptyList(),
val selectedCategory: String? = null
) {
val categories: Set<String> = images.map { it.category }.toSet()
val selectedImages: List<BirdImage> = images.filter { it.category == selectedCategory }
}
class BirdViewModel: ViewModel() {
private val _uiState: MutableStateFlow<BirdsUiState> = MutableStateFlow(BirdsUiState(emptyList()))
val uiState: StateFlow<BirdsUiState> = _uiState.asStateFlow()
private val httpClient: HttpClient = HttpClient() {
install(ContentNegotiation) {
json()
}
}
fun updateImages() {
viewModelScope.launch {
val images: List<BirdImage> = getImages()
_uiState.update {
it.copy(images = images)
}
}
}
fun selectCategory(category: String) {
_uiState.update { state: BirdsUiState ->
if (state.selectedCategory == category) {
state.copy(selectedCategory = null)
} else {
state.copy(selectedCategory = category)
}
}
}
override fun onCleared() {
httpClient.close()
}
private suspend fun getImages(): List<BirdImage> {
return httpClient.get("https://sebi.io/demo-image-api/pictures.json").body<List<BirdImage>>()
}
} | ComposeMultiplatformExample/composeApp/src/commonMain/kotlin/BirdViewModel.kt | 1861866646 |
import kotlinx.serialization.Serializable
@Serializable
data class BirdImage(
val category: String,
val path: String,
val author: String
) | ComposeMultiplatformExample/composeApp/src/commonMain/kotlin/BirdImage.kt | 3924094129 |
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import dev.icerock.moko.mvvm.compose.getViewModel
import dev.icerock.moko.mvvm.compose.viewModelFactory
import io.kamel.image.KamelImage
import io.kamel.image.asyncPainterResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
fun App() {
MaterialTheme {
val birdViewModel: BirdViewModel = getViewModel(Unit, viewModelFactory { BirdViewModel() })
val uiState by birdViewModel.uiState.collectAsState()
LaunchedEffect(birdViewModel) {
birdViewModel.updateImages()
}
BirdsPage(uiState, onSelectCategory = { birdViewModel.selectCategory(it) })
}
}
@Composable
fun BirdsPage(uiState: BirdsUiState, onSelectCategory: (String) -> Unit) {
Column {
Row {
for (category in uiState.categories) {
Button(
onClick = { onSelectCategory(category) },
modifier = Modifier.aspectRatio(1.0f).weight(1.0f)
) {
Text(category)
}
}
}
AnimatedVisibility(visible = uiState.selectedImages.isNotEmpty()) {
LazyVerticalGrid(
columns = GridCells.Adaptive(180.dp)
) {
items(uiState.selectedImages) { image ->
BirdImageCell(image)
}
}
}
}
}
@Composable
fun BirdImageCell(image: BirdImage) {
KamelImage(
resource = asyncPainterResource("https://sebastianaigner.github.io/demo-image-api/${image.path}"),
contentDescription = "${image.category} by ${image.author}",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(1.0f),
)
} | ComposeMultiplatformExample/composeApp/src/commonMain/kotlin/App.kt | 2843592844 |
interface Platform {
val name: String
}
expect fun getPlatform(): Platform | ComposeMultiplatformExample/composeApp/src/commonMain/kotlin/Platform.kt | 960794953 |
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
} | ComposeMultiplatformExample/composeApp/src/commonMain/kotlin/Greeting.kt | 2562376394 |
class JVMPlatform: Platform {
override val name: String = "Java ${System.getProperty("java.version")}"
}
actual fun getPlatform(): Platform = JVMPlatform() | ComposeMultiplatformExample/composeApp/src/desktopMain/kotlin/Platform.jvm.kt | 1652497929 |
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
fun main() = application {
Window(onCloseRequest = ::exitApplication, title = "KotlinProject") {
App()
}
}
@Preview
@Composable
fun AppDesktopPreview() {
App()
} | ComposeMultiplatformExample/composeApp/src/desktopMain/kotlin/main.kt | 658814640 |
package org.example.project
import App
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App()
}
}
}
@Preview
@Composable
fun AppAndroidPreview() {
App()
} | ComposeMultiplatformExample/composeApp/src/androidMain/kotlin/org/example/project/MainActivity.kt | 401857393 |
import android.os.Build
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform() | ComposeMultiplatformExample/composeApp/src/androidMain/kotlin/Platform.android.kt | 3472575554 |
package com.example.mylibrary1
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.mylibrary1.test", appContext.packageName)
}
} | example2/mylibrary1/src/androidTest/java/com/example/mylibrary1/ExampleInstrumentedTest.kt | 1191222971 |
package com.example.mylibrary1
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)
}
} | example2/mylibrary1/src/test/java/com/example/mylibrary1/ExampleUnitTest.kt | 2030652353 |
package com.example.moduleexample
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.moduleexample", appContext.packageName)
}
} | example2/app/src/androidTest/java/com/example/moduleexample/ExampleInstrumentedTest.kt | 2051826241 |
package com.example.moduleexample
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)
}
} | example2/app/src/test/java/com/example/moduleexample/ExampleUnitTest.kt | 1607016033 |
package com.example.moduleexample.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) | example2/app/src/main/java/com/example/moduleexample/ui/theme/Color.kt | 3060084978 |
package com.example.moduleexample.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 ModuleExampleTheme(
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
)
} | example2/app/src/main/java/com/example/moduleexample/ui/theme/Theme.kt | 3323003608 |
package com.example.moduleexample.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
)
*/
) | example2/app/src/main/java/com/example/moduleexample/ui/theme/Type.kt | 4118434246 |
package com.example.moduleexample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.moduleexample.ui.theme.ModuleExampleTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ModuleExampleTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ModuleExampleTheme {
Greeting("Android")
}
} | example2/app/src/main/java/com/example/moduleexample/MainActivity.kt | 3155878222 |
package com.example.hw_35
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.hw_35", appContext.packageName)
}
} | hw_3.5/app/src/androidTest/java/com/example/hw_35/ExampleInstrumentedTest.kt | 2853235509 |
package com.example.hw_35
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)
}
} | hw_3.5/app/src/test/java/com/example/hw_35/ExampleUnitTest.kt | 2612865910 |
package com.example.hw_35
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)
supportFragmentManager.beginTransaction().add(R.id.container,MainFragment()).commit()
}
} | hw_3.5/app/src/main/java/com/example/hw_35/MainActivity.kt | 3958569826 |
package com.example.hw_35
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.hw_35.databinding.FragmentMainBinding
import com.example.hw_35.databinding.FragmentTextBinding
class TextFragment : Fragment() {
private lateinit var binding: FragmentTextBinding
var result=arguments?.getString("text")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding=FragmentTextBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.text.text=result.toString()
}
} | hw_3.5/app/src/main/java/com/example/hw_35/TextFragment.kt | 3019316881 |
package com.example.hw_35
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.hw_35.databinding.FragmentMainBinding
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
private var count = 0
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.btnNum.setOnClickListener { view ->
if (count < 10 && binding.btnNum.text != "-1") {
count++
binding.tvNum.text = count.toString()
} else if (count == 10 || count < 10 && count>0) {
binding.btnNum.text="-1"
count--
binding.tvNum.text=count.toString()
}else if (count==0){
val textFragment=TextFragment()
var bundle=Bundle()
parentFragmentManager.beginTransaction().replace(R.id.container,textFragment).commit()
bundle.putString("text",count.toString())
textFragment.arguments=bundle
}
}
}
} | hw_3.5/app/src/main/java/com/example/hw_35/MainFragment.kt | 4098324557 |
package com.example.cs310_kotlin_final
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.cs310_kotlin_final", appContext.packageName)
}
} | cs310_kotlin_final/app/src/androidTest/java/com/example/cs310_kotlin_final/ExampleInstrumentedTest.kt | 3424298416 |
package com.example.cs310_kotlin_final
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)
}
} | cs310_kotlin_final/app/src/test/java/com/example/cs310_kotlin_final/ExampleUnitTest.kt | 3031864349 |
package com.example.cs310_kotlin_final
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.cs310_kotlin_final.MainActivity.Companion.itemAdapter
class MainActivity : AppCompatActivity(), ItemAdapter.ItemClickListener{
companion object {
val Workouts = mutableListOf<Workout>()
lateinit var itemAdapter: ItemAdapter
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var recyclerView: RecyclerView = findViewById(R.id.recyclerViewMainWorkout)
itemAdapter = ItemAdapter(Workouts, this)
recyclerView.adapter = itemAdapter
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.mainactivity_menu, menu)
return true;
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.addItem -> {
//Toast.makeText(this, "add", Toast.LENGTH_LONG).show()
val intent = Intent(this, CreateWorkout::class.java)
startActivity(intent)
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onItemClick(position: Int) {
//Toast.makeText(this, position.toString(), Toast.LENGTH_LONG).show()
val intent = Intent(this, WorkoutDetail::class.java)
intent.putExtra("POSITION", position)
startActivity(intent)
}
} | cs310_kotlin_final/app/src/main/java/com/example/cs310_kotlin_final/MainActivity.kt | 4201979367 |
package com.example.cs310_kotlin_final
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class CreateWorkout: AppCompatActivity() {
lateinit var editTextName: EditText
lateinit var editTextReps: EditText
lateinit var radioGroupComplete: RadioGroup
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.create_workout_layout)
editTextName = findViewById(R.id.editTextWorkoutName)
editTextReps = findViewById(R.id.editTextNumberReps)
radioGroupComplete = findViewById(R.id.radioGroupDone)
var addButton: Button = findViewById(R.id.buttonAdd)
addButton.setOnClickListener{
val name = editTextName.text.toString()
val reps = editTextReps.text.toString()
if(name != "" && reps != "" && reps.toInt() > 0){
var completed: String = ""
when(radioGroupComplete.checkedRadioButtonId){
R.id.radioButtonComplete -> completed = "Completed"
R.id.radioButtonIncomplete -> completed = "Incomplete"
}
val newWorkout = Workout(name, reps.toInt(), completed)
MainActivity.Workouts.add(newWorkout)
MainActivity.itemAdapter.notifyDataSetChanged()
finish()
}else{
val toast = Toast.makeText(this, "please fill in name and reps", Toast.LENGTH_LONG).show()
}
}
}
}
| cs310_kotlin_final/app/src/main/java/com/example/cs310_kotlin_final/CreateWorkout.kt | 3883541912 |
package com.example.cs310_kotlin_final
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class WorkoutDetail:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.workout_detail_layout)
var textViewName:EditText = findViewById(R.id.editTextDetailName)
var textViewReps:EditText = findViewById(R.id.editTextDetailReps)
var radioButtonComplete:RadioButton = findViewById(R.id.radioButtonDetComplete)
var radioButtonIncomplete:RadioButton = findViewById(R.id.radioButtonDetIncomplete)
var radioGroup:RadioGroup = findViewById(R.id.radioGroupDetail)
var buttonUpdate:Button = findViewById(R.id.buttonDetUpdate)
var buttonDelete:Button = findViewById(R.id.buttonDetDelete)
val intent: Intent = intent
val position = intent.getIntExtra("POSITION", 0)
var workout:Workout = MainActivity.Workouts.get(position)
//Toast.makeText(this, workout.toString(), Toast.LENGTH_LONG).show()
textViewName.setText(workout.name)
textViewReps.setText(workout.reps.toString())
if(workout.complete == "Completed"){
radioButtonComplete.isChecked = true
}else if(workout.complete == "Incomplete"){
radioButtonIncomplete.isChecked = true
}
buttonDelete.setOnClickListener {
MainActivity.Workouts.removeAt(position)
MainActivity.itemAdapter.notifyDataSetChanged()
finish()
}
buttonUpdate.setOnClickListener {
var completed: String = ""
if(textViewName.text.toString() != "" && textViewReps.text.toString() != "") {
when (radioGroup.checkedRadioButtonId) {
R.id.radioButtonDetComplete -> completed = "Completed"
R.id.radioButtonDetIncomplete -> completed = "Incomplete"
}
var newWorkout: Workout = Workout(
textViewName.text.toString(),
textViewReps.text.toString().toInt(),
completed
)
MainActivity.Workouts.set(position, newWorkout)
MainActivity.itemAdapter.notifyDataSetChanged()
finish()
}else{
Toast.makeText(this, "please fill in name and reps", Toast.LENGTH_LONG).show()
}
}
}
} | cs310_kotlin_final/app/src/main/java/com/example/cs310_kotlin_final/WorkoutDetail.kt | 2867949043 |
package com.example.cs310_kotlin_final
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.AdapterView.OnItemClickListener
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ItemAdapter(val data: MutableList<Workout>, val itemClickListener: ItemClickListener):RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
interface ItemClickListener{
fun onItemClick(position:Int)
}
inner class ItemViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
val textViewName: TextView = itemView.findViewById(R.id.textViewExcersiseName)
val textViewReps: TextView = itemView.findViewById(R.id.textViewExcerciseReps)
val textViewDone: TextView = itemView.findViewById(R.id.textViewDone)
init{
itemView.setOnClickListener {
if(adapterPosition >= 0){
itemClickListener.onItemClick(adapterPosition)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val listItemView = LayoutInflater.from(parent.context).inflate(R.layout.workout_layout, parent, false)
return ItemViewHolder(listItemView)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.textViewDone.text = data[position].complete
holder.textViewReps.text = data[position].reps.toString()
holder.textViewName.text = data[position].name
if(data[position].complete == "Completed"){
holder.textViewDone.setBackgroundColor(Color.GREEN)
holder.textViewDone.setTextColor(Color.BLACK)
}else if(data[position].complete == "Incomplete"){
holder.textViewDone.setBackgroundColor(Color.DKGRAY)
holder.textViewDone.setTextColor(Color.WHITE)
}
}
} | cs310_kotlin_final/app/src/main/java/com/example/cs310_kotlin_final/ItemAdapter.kt | 2126965149 |
package com.example.cs310_kotlin_final
import java.util.Date
data class Workout (val name:String, val reps:Int, val complete:String){
} | cs310_kotlin_final/app/src/main/java/com/example/cs310_kotlin_final/Workout.kt | 2236274426 |
package com.example.button
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.button", appContext.packageName)
}
} | botonesLog/app/src/androidTest/java/com/example/button/ExampleInstrumentedTest.kt | 3814179623 |
package com.example.button
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)
}
} | botonesLog/app/src/test/java/com/example/button/ExampleUnitTest.kt | 2858122487 |
package com.example.button
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Aquí configuramos un Listener en algún evento,
// por ejemplo, cuando se hace clic en un botón
val button = findViewById<Button>(R.id.my_button)
button.setOnClickListener {
val intent = Intent(this, ButtonActivity::class.java)
startActivity(intent)
}
}
}
| botonesLog/app/src/main/java/com/example/button/MainActivity.kt | 1592294495 |
package com.example.button
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.button.databinding.ActivityButtonBinding
import android.util.Log
class ButtonActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var binding: ActivityButtonBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityButtonBinding.inflate(layoutInflater)
setContentView(binding.root)
// Configurar listeners para los botones
binding.holaMundoButton.setOnClickListener(this)
binding.containedButton.setOnClickListener(this)
binding.textButton.setOnClickListener(this)
binding.button1.setOnClickListener(this)
binding.button2.setOnClickListener(this)
binding.button3.setOnClickListener(this)
binding.customButton.setOnClickListener(this)
// Imprimir mensaje en Logcat al iniciar la actividad
Log.d("ButtonActivity", "onCreate en uso")
}
override fun onClick(view: View) {
// Acciones para cada botón
}
override fun onStart() {
super.onStart()
// Imprimir mensaje en Logcat al iniciar la actividad
Log.d("ButtonActivity", "onStart en uso ")
}
override fun onResume() {
super.onResume()
// Imprimir mensaje en Logcat al resumir la actividad
Log.d("ButtonActivity", "onResume en uso")
}
override fun onPause() {
super.onPause()
// Imprimir mensaje en Logcat al pausar la actividad
Log.d("ButtonActivity", "onPause en uso")
}
override fun onStop() {
super.onStop()
// Imprimir mensaje en Logcat al detener la actividad
Log.d("ButtonActivity", "onStop en uso")
}
override fun onDestroy() {
super.onDestroy()
// Imprimir mensaje en Logcat al destruir la actividad
Log.d("ButtonActivity", "onDestroy en uso")
}
override fun onRestart() {
super.onRestart()
// Imprimir mensaje en Logcat al reiniciar la actividad
Log.d("ButtonActivity", "onRestart en uso")
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
}
| botonesLog/app/src/main/java/com/example/button/ButtonActivity.kt | 3888991197 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | UsmanSaikh/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
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)
}
} | UsmanSaikh/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication.ui.history
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HistoryViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "No History available. Contribute Polls and See Your Journey Here."
}
val text: LiveData<String> = _text
} | UsmanSaikh/app/src/main/java/com/example/myapplication/ui/history/HistoryViewModel.kt | 3486900042 |
package com.example.myapplication.ui.history
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.adapter.PollGroupAdapter
import com.example.myapplication.database.PollDatabase
import com.example.myapplication.database.Repository
import com.example.myapplication.databinding.FragmentHistoryBinding
class HistoryPollFragment : Fragment() {
private var _binding: FragmentHistoryBinding? = null
private lateinit var pollGroupAdapter: PollGroupAdapter
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val historyViewModel =
ViewModelProvider(this).get(HistoryViewModel::class.java)
_binding = FragmentHistoryBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHistory
historyViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
GetData()
return root
}
private fun GetData() {
val database by lazy { PollDatabase.getDatabase(requireActivity()) }
val repository by lazy { Repository(database.expanseDao()) }
repository.pollListHistory.observe(viewLifecycleOwner) { list ->
list.let {
pollGroupAdapter = PollGroupAdapter(it, false)
binding.rvHistoryList.adapter = pollGroupAdapter
if (it.size != 0) {
binding.textHistory.visibility = View.GONE
} else {
binding.textHistory.visibility = View.VISIBLE
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/ui/history/HistoryPollFragment.kt | 806370450 |
package com.example.myapplication.ui.poll
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class CurrentPollModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "The Poling Grounds Await Your Questions"
}
val text: LiveData<String> = _text
} | UsmanSaikh/app/src/main/java/com/example/myapplication/ui/poll/CurrentPollModel.kt | 616036718 |
package com.example.myapplication.ui.poll
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.MyApplication
import com.example.myapplication.adapter.CurrentPollListAdapter
import com.example.myapplication.adapter.PollGroupAdapter
import com.example.myapplication.database.DatabaseViewModel
import com.example.myapplication.database.PollDatabase
import com.example.myapplication.database.Repository
import com.example.myapplication.databinding.FragmentCurrentPollBinding
class CurrentPollFragment : Fragment() {
private var _binding: FragmentCurrentPollBinding? = null
private val binding get() = _binding!!
private lateinit var pollGroupAdapter: PollGroupAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val currentPollModel =
ViewModelProvider(this).get(CurrentPollModel::class.java)
_binding = FragmentCurrentPollBinding.inflate(inflater, container, false)
val root: View = binding.root
val textView: TextView = binding.textHome
currentPollModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
getData()
return root
}
private fun getData() {
val database by lazy { PollDatabase.getDatabase(requireActivity()) }
val repository by lazy { Repository(database.expanseDao()) }
repository.pollList.observe(viewLifecycleOwner) { list ->
list.let {
pollGroupAdapter = PollGroupAdapter(it, true)
binding.rvPollList.adapter = pollGroupAdapter
Log.e("Data", "getData: " + it.size )
if (it.size != 0) {
binding.textHome.visibility = View.GONE
} else {
binding.textHome.visibility = View.VISIBLE
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/ui/poll/CurrentPollFragment.kt | 751323214 |
package com.example.myapplication.database
import androidx.annotation.Keep
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import java.util.Date
@Keep
@Entity(tableName = "poll_table")
class Entry(
@PrimaryKey(autoGenerate = true) val id: Int,
@ColumnInfo(name = "question") val question: String,
@ColumnInfo(name = "option") val option: ArrayList<String>,
@ColumnInfo(name = "ishistory") val ishistory: Boolean,
@ColumnInfo(name = "answer") val answer: Int,
)
| UsmanSaikh/app/src/main/java/com/example/myapplication/database/tables.kt | 1437792391 |
package com.example.myapplication.database
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Date
class DatabaseViewModel(private val repository: Repository) : ViewModel() {
suspend fun insert(entry: Entry) {
repository.insert(entry)
}
fun isExist(s: String): Boolean {
return repository.isExist(s)
}
class DatabaseViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DatabaseViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return DatabaseViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/database/DatabaseViewModel.kt | 882059392 |
package com.example.myapplication.database
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface PollDao {
@Insert
suspend fun insert(entry: Entry)
@Update
suspend fun update(entry: Entry)
// TODO for History
@Query("SELECT * FROM poll_table WHERE ishistory = 'true'")
fun getHistoryData(): List<Entry>
@Query("SELECT * FROM poll_table WHERE ishistory = :flagValue")
fun getItemsByFlag(flagValue: Boolean):LiveData<List<Entry>>
@Query("SELECT * FROM poll_table WHERE question = :s")
fun isExist(s: String): Boolean
} | UsmanSaikh/app/src/main/java/com/example/myapplication/database/PollDao.kt | 1015210278 |
package com.example.myapplication.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
@Database(entities = [Entry::class], version = 1)
@TypeConverters(Converter::class)
public abstract class PollDatabase : RoomDatabase() {
abstract fun expanseDao(): PollDao
companion object {
private var INSTANCE: PollDatabase? = null
fun getDatabase(context: Context): PollDatabase {
if (INSTANCE == null) {
synchronized(this) {
INSTANCE = Room.databaseBuilder(context,
PollDatabase::class.java,
"poll_database"
)
.allowMainThreadQueries()
.build()
}
}
return INSTANCE!!
}
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/database/PollDatabase.kt | 1330145734 |
package com.example.myapplication.database
import android.util.Log
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
class Repository(private val pollDao: PollDao) {
val pollList: LiveData<List<Entry>> = pollDao.getItemsByFlag(false)
val pollListHistory: LiveData<List<Entry>> = pollDao.getItemsByFlag(true)
fun isExist(s: String): Boolean {
return pollDao.isExist(s)
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun insert(entry: Entry) {
pollDao.insert(entry)
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun upDate(entry: Entry) {
pollDao.update(entry)
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/database/Repository.kt | 677787421 |
package com.example.myapplication.database
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.Date
class Converter {
@TypeConverter
fun fromString(value: String?): ArrayList<String> {
val listType = object : TypeToken<ArrayList<String>>() {}.type
return Gson().fromJson(value, listType)
}
@TypeConverter
fun fromArrayList(list: ArrayList<String>): String {
return Gson().toJson(list)
}
}
| UsmanSaikh/app/src/main/java/com/example/myapplication/database/Converter.kt | 2622049859 |
package com.example.myapplication
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider.NewInstanceFactory.Companion.instance
import com.example.myapplication.database.PollDatabase
import com.example.myapplication.database.Repository
class MyApplication : Application() {
private val database by lazy { PollDatabase.getDatabase(this.applicationContext) }
val repository by lazy { Repository(database.expanseDao()) }
override fun onCreate() {
super.onCreate()
instance = this
Log.d("MyApplication", "Application is initialized")
}
companion object {
lateinit var instance: MyApplication
fun getAppContext(): Context {
return instance.applicationContext
}
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/MyApplication.kt | 1865980130 |
package com.example.myapplication
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.example.myapplication.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_current_poll, R.id.navigation_history
)
)
navView.setupWithNavController(navController)
initViews()
}
private fun initViews() {
val create_poll: CardView = binding.createPoll
create_poll.setOnClickListener(View.OnClickListener {
val intent = Intent(this, CreatePollActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
})
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/MainActivity.kt | 2771931692 |
package com.example.myapplication
interface MyAdapterListener {
fun onItemClicked(position: Int)
fun onEditTextValueChanged(position: Int, value: String)
} | UsmanSaikh/app/src/main/java/com/example/myapplication/MyAdapterListener.kt | 680550270 |
package com.example.myapplication
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.adapter.CurrentPollListAdapter
import com.example.myapplication.adapter.DragablePollListAdapter
import com.example.myapplication.adapter.NormalPollListAdapter
import com.example.myapplication.database.DatabaseViewModel
import com.example.myapplication.database.Entry
import com.example.myapplication.databinding.ActivityCreatePollBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class CreatePollActivity : AppCompatActivity(), MyAdapterListener {
private lateinit var binding: ActivityCreatePollBinding
private val pollViewModel: DatabaseViewModel by viewModels {
DatabaseViewModel.DatabaseViewModelFactory((application as MyApplication).repository)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCreatePollBinding.inflate(layoutInflater)
setContentView(binding.root)
initClicks()
val itemList = HashMap<Int, String>(5)
val adapter = DragablePollListAdapter(this,itemList){
if (it < 5) {
binding.tvAddOption.background =
ContextCompat.getDrawable(this, R.drawable.add_option_bg)
binding.tvOption.text = "You can add " + (5 - itemList.size) + " more options"
}
}.also {
binding.listview.adapter = it
it.enableDragAndDrop(binding.listview)
}
binding.tvOption.text = "You can add " + 5 + " more options"
binding.tvAddOption.setOnClickListener {
if (itemList.size < 5) {
if (itemList.isEmpty()) {
itemList.put(0, "")
} else {
val position = itemList.size
itemList.put(position, "")
}
binding.tvOption.text = "You can add " + (5 - itemList.size) + " more options"
if (itemList.size >= 5) {
binding.tvAddOption.background =
ContextCompat.getDrawable(this, R.drawable.add_nonselected_option_bg)
}
binding.listview.adapter?.notifyItemInserted(itemList.size)
}
}
binding.tvCreate.setOnClickListener {
if (!binding.etQuestion.text.equals("")) {
if (itemList.size >= 2) {
var functionExecuted = false
for (i in 0 until itemList.size) {
if (!itemList.get(i).equals("")) {
if (!functionExecuted) {
val entry = Entry(
0,
binding.etQuestion.text.toString(),
ArrayList(adapter.itemList.values),
false,
0
)
CoroutineScope(Dispatchers.IO).launch {
if (!pollViewModel.isExist(entry.question)) {
pollViewModel.insert(entry)
runOnUiThread(Runnable {
Toast.makeText(
this@CreatePollActivity,
"Poll Created",
Toast.LENGTH_SHORT
).show()
})
finish()
} else {
runOnUiThread(Runnable {
Toast.makeText(
this@CreatePollActivity,
"this Question is Already Exist ",
Toast.LENGTH_SHORT
).show()
})
}
}
functionExecuted = true
}
}
else{
runOnUiThread(Runnable {
Toast.makeText(
this,
"Please Enter Valid Question at least two option ",
Toast.LENGTH_SHORT
).show()
})
}
}
} else {
runOnUiThread(Runnable {
Toast.makeText(
this,
"Please Enter Valid Question at least two option ",
Toast.LENGTH_SHORT
).show()
})
}
} else {
runOnUiThread(Runnable {
Toast.makeText(
this,
"Please Enter Valid Question at least two option ",
Toast.LENGTH_SHORT
).show()
})
}
}
}
private fun initClicks() {
binding.ivBack.setOnClickListener { view ->
onBackPressed()
}
}
override fun onItemClicked(position: Int) {
binding.tvAddOption.performClick()
}
override fun onEditTextValueChanged(position: Int, value: String) {
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/CreatePollActivity.kt | 2011856831 |
package com.example.myapplication.adapter
import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.MyAdapterListener
import com.example.myapplication.R
class NormalPollListAdapter(
private val listener: MyAdapterListener,
var itemList: HashMap<Int, String>,
val callBack: (position: Int) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return BlogViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_item_layout, parent, false)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, @SuppressLint("RecyclerView") position: Int) {
when (holder) {
is BlogViewHolder -> {
holder.bind(itemList, position)
holder.cancelButton.setOnClickListener {
if (itemList.size > position) {
itemList.remove(position)
notifyItemRemoved(position)
callBack.invoke(position)
}
}
if (position == 5) {
holder.textItem.imeOptions = EditorInfo.IME_ACTION_DONE;
} else {
holder.textItem.imeOptions = EditorInfo.IME_ACTION_NEXT;
}
holder.textItem.setOnEditorActionListener { _, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_NEXT || (event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
Log.e("EditText_TAG", "bind: " + "setOnEditorActionListener")
listener.onItemClicked(position)
return@setOnEditorActionListener true
}
false
}
holder.textItem.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
// Log.d("textItem", "textItem: " + s.toString())
// itemList.add(position, s.toString())
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Log.d("textItem", "position : $position || textItem: " + s)
if (itemList.size > 0) {
// itemList.remove(position)
// itemList.put(position,s.toString())
// if (!s.isNullOrBlank()) {
val isValueDuplicate = itemList.any { it.value == s.toString() && it.key != position }
if (isValueDuplicate) {
// Show error message or handle the duplicate value as needed
// For example, you can set an error message on the EditText
holder.textItem.error = "already exists"
} else {
// Update the itemList with the entered value
itemList[position] = s.toString()
// }
}
}
// optionList[position] = s.toString()
// notifyDataSetChanged()
}
})
}
}
}
override fun getItemCount(): Int {
return itemList.size
}
private class BlogViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textItem: EditText = itemView.findViewById(R.id.editView)
val cancelButton: ImageView = itemView.findViewById(R.id.cancelButton)
fun bind(itemList: HashMap<Int, String>, position: Int) {
textItem.requestFocus()
textItem.setText(itemList[position])
textItem.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_NEXT) {
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
}
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/adapter/NormalPollListAdapter.kt | 607905801 |
package com.example.myapplication.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.MyAdapterListener
import com.example.myapplication.MyApplication
import com.example.myapplication.R
class DragablePollListAdapter(
private val listener: MyAdapterListener,
var itemList: HashMap<Int, String>,
val callBack: (position: Int) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return DragablePollListAdapter.BlogViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_item_layout, parent, false)
)
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
@SuppressLint("RecyclerView") position: Int
) {
when (holder) {
is DragablePollListAdapter.BlogViewHolder -> {
holder.bind(itemList, position)
holder.cancelButton.setOnClickListener {
if (itemList.size > position) {
itemList.remove(position)
notifyItemRemoved(position)
callBack.invoke(position)
}
}
if (position == 5) {
holder.textItem.imeOptions = EditorInfo.IME_ACTION_DONE;
} else {
holder.textItem.imeOptions = EditorInfo.IME_ACTION_NEXT;
}
holder.textItem.setOnEditorActionListener { _, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_NEXT || (event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
listener.onItemClicked(position)
return@setOnEditorActionListener true
}
false
}
holder.textItem.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence?,
start: Int,
before: Int,
count: Int
) {
if (itemList.size > 0) {
val isValueDuplicate =
itemList.any { it.value == s.toString() && it.key != position }
if (isValueDuplicate) {
holder.textItem.error = "already exists"
} else {
itemList[position] = s.toString()
}
}
}
})
}
}
}
override fun getItemCount(): Int {
return itemList.size
}
private class BlogViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textItem: EditText = itemView.findViewById(R.id.editView)
val cancelButton: ImageView = itemView.findViewById(R.id.cancelButton)
fun bind(itemList: HashMap<Int, String>, position: Int) {
textItem.requestFocus()
textItem.setText(itemList[position])
textItem.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_NEXT) {
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
}
}
fun enableDragAndDrop(recyclerView: RecyclerView) {
val itemTouchHelper = ItemTouchHelper(DragItemTouchHelperCallback(this))
itemTouchHelper.attachToRecyclerView(recyclerView)
}
class DragItemTouchHelperCallback(private val adapter: DragablePollListAdapter) :
ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled(): Boolean {
return true
}
override fun isItemViewSwipeEnabled(): Boolean {
return false
}
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
return makeMovementFlags(dragFlags, 0)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
vibratePhone()
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
}
private fun vibratePhone() {
val vibrator =
MyApplication.instance?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(
VibrationEffect.createOneShot(
200,
VibrationEffect.DEFAULT_AMPLITUDE
)
)
} else {
vibrator.vibrate(200)
}
}
}
fun onItemMove(fromPosition: Int, toPosition: Int) {
if (fromPosition != toPosition) {
val fromEntry = itemList.entries.elementAt(fromPosition)
val toEntry = itemList.entries.elementAt(toPosition)
itemList.remove(fromEntry.key)
itemList.remove(toEntry.key)
itemList[toEntry.key] = fromEntry.value
itemList[fromEntry.key] = toEntry.value
notifyItemMoved(fromPosition, toPosition)
}
}
}
| UsmanSaikh/app/src/main/java/com/example/myapplication/adapter/DragablePollListAdapter.kt | 2070612896 |
package com.example.myapplication.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R
import com.example.myapplication.database.Entry
import com.example.myapplication.model.PollOption
class PollGroupAdapter(private val pollGroups: List<Entry>,var b: Boolean) : RecyclerView.Adapter<PollGroupAdapter.ViewHolder>() {
lateinit var radioButton :RadioButton
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_poll_group, parent, false)
radioButton = RadioButton(parent.context)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val pollGroup = pollGroups[position]
holder.bind(pollGroup)
}
override fun getItemCount(): Int {
return pollGroups.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(pollGroup: Entry) {
itemView.findViewById<TextView>(R.id.groupName).text = pollGroup.question
var ChiledList: ArrayList<PollOption> = ArrayList()
if (!b)
{
for (i in 0 until pollGroup.option.size) {
if (pollGroup.answer == i) {
ChiledList.add(PollOption(pollGroup.option[i],true))
} else {
ChiledList.add(PollOption(pollGroup.option[i],false))
}
}
}
else{
for (i in 0 until pollGroup.option.size) {
ChiledList.add(PollOption(pollGroup.option[i],false))
}
}
val pollAdapter = CurrentPollListAdapter(ChiledList,pollGroup,b)
itemView.findViewById<RecyclerView>(R.id.innerRecyclerView).apply {
layoutManager = LinearLayoutManager(itemView.context)
adapter = pollAdapter
}
}
}
}
| UsmanSaikh/app/src/main/java/com/example/myapplication/adapter/PollGroupAdapter.kt | 1741820450 |
package com.example.myapplication.adapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.RadioButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.MyApplication
import com.example.myapplication.R
import com.example.myapplication.database.Entry
import com.example.myapplication.database.PollDatabase
import com.example.myapplication.database.Repository
import com.example.myapplication.model.PollOption
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class CurrentPollListAdapter(
private val options: List<PollOption>,
val pollGroup: Entry,
val b: Boolean
) :
RecyclerView.Adapter<CurrentPollListAdapter.ViewHolder>() {
var selectedOption: Int = RecyclerView.NO_POSITION
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.current_poll_list_item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {
val option = options[position]
holder.radioButton.text = option.optionText
holder.radioButton.isChecked = selectedOption == position
if (b) {
holder.radioButton.setOnClickListener {
selectedOption = position
val itemList = ArrayList<String>()
for (i in 0 until options.size) {
options.get(i).selected = false
itemList.add(options.get(i).optionText)
}
options.get(position).selected = true
notifyItemChanged(selectedOption)
val applicationContext: Context = MyApplication.getAppContext()
val database by lazy { PollDatabase.getDatabase(applicationContext) }
val repository by lazy { Repository(database.expanseDao()) }
val entry = Entry(pollGroup.id, pollGroup.question, itemList, true, selectedOption)
CoroutineScope(Dispatchers.IO).launch {
repository.upDate(entry)
}
}
if (option.selected) {
holder.radioButton.isChecked = true
animateBackgroundColor(holder.linearLayout)
holder.tvPersent.text = "100%"
} else {
holder.radioButton.isChecked = false
animateBackgroundColorNormal(holder.linearLayout)
holder.tvPersent.text = "0%"
}
} else {
if (option.selected) {
holder.radioButton.isChecked = true
animateBackgroundColor(holder.linearLayout)
holder.tvPersent.text = "100%"
} else {
holder.radioButton.isChecked = false
animateBackgroundColorNormal(holder.linearLayout)
holder.linearLayout.visibility = View.GONE
holder.radioButton.isClickable = false
holder.tvPersent.text = "0%"
holder.radioButton.buttonDrawable = null
}
}
}
private fun animateBackgroundColor(view: View) {
val colorFrom = android.graphics.Color.parseColor("#E8DEF8")
val colorTo = android.graphics.Color.parseColor("#FF6200EE")
val backgroundColorAnimator =
ObjectAnimator.ofArgb(view, "backgroundColor", colorFrom, colorTo)
backgroundColorAnimator.duration = 100
backgroundColorAnimator.interpolator = AccelerateInterpolator()
val animatorSet = AnimatorSet()
animatorSet.play(backgroundColorAnimator)
animatorSet.start()
}
private fun animateBackgroundColorNormal(view: View) {
val colorFrom = android.graphics.Color.parseColor("#E8DEF8")
val colorTo = android.graphics.Color.parseColor("#FF6200EE")
val backgroundColorAnimator =
ObjectAnimator.ofArgb(view, "backgroundColor", colorTo, colorFrom)
backgroundColorAnimator.duration = 500
backgroundColorAnimator.interpolator = AccelerateInterpolator()
val animatorSet = AnimatorSet()
animatorSet.play(backgroundColorAnimator)
animatorSet.start()
}
override fun getItemCount(): Int {
return options.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var radioButton: RadioButton
lateinit var linearLayout: LinearLayout
lateinit var tvPersent: TextView
fun bind(option: PollOption, position: Int) {
itemView.setOnClickListener {
selectedOption = adapterPosition
notifyDataSetChanged()
}
}
init {
radioButton = itemView.findViewById(R.id.radioButton)
linearLayout = itemView.findViewById<LinearLayout>(R.id.linear_layout)
tvPersent = itemView.findViewById<TextView>(R.id.tvPersent)
}
}
} | UsmanSaikh/app/src/main/java/com/example/myapplication/adapter/CurrentPollListAdapter.kt | 351657243 |
package com.example.myapplication.model
data class PollOption(val optionText: String, var selected :Boolean)
| UsmanSaikh/app/src/main/java/com/example/myapplication/model/PollOption.kt | 3439921092 |
package com.example.pressbrakecalculator
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.pressbrakecalculator", appContext.packageName)
}
} | press-brake-calculator/app/src/androidTest/java/com/example/pressbrakecalculator/ExampleInstrumentedTest.kt | 750571857 |
package com.example.pressbrakecalculator
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)
}
} | press-brake-calculator/app/src/test/java/com/example/pressbrakecalculator/ExampleUnitTest.kt | 1015498759 |
package com.example.pressbrakecalculator.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) | press-brake-calculator/app/src/main/java/com/example/pressbrakecalculator/ui/theme/Color.kt | 2397214531 |
package com.example.pressbrakecalculator.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 PressBrakeCalculatorTheme(
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
)
} | press-brake-calculator/app/src/main/java/com/example/pressbrakecalculator/ui/theme/Theme.kt | 3260971564 |
package com.example.pressbrakecalculator.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
)
*/
) | press-brake-calculator/app/src/main/java/com/example/pressbrakecalculator/ui/theme/Type.kt | 802691705 |
package com.example.pressbrakecalculator
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.pressbrakecalculator.ui.theme.PressBrakeCalculatorTheme
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import kotlin.math.*
const val FILE_NAME = "bending_data.txt"
const val BASE_DEGREES = 90
// Map of gauge as an int to ArrayList of (degree, BND) Pairs
val dataMap = HashMap<Int, ArrayList<Pair<Float, Float>>>()
val bestSlopes = HashMap<Int, Float>()
// The base degree and bend value to use for each gauge, typically a pair of 90 degrees bend
val baseBendValues = HashMap<Int, Pair<Float, Float>>()
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PressBrakeCalculatorTheme {
initializeMapFromFile(filesDir)
BendCalculatorApp(filesDir)
}
}
}
}
@Preview
@Composable
fun BendCalculatorApp(filesDir : File) {
InputFields(filesDir,
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center)
)
}
fun isNumber(input: String): Boolean {
if (input == "" || input == ".") {
return false
}
val integerChars = '0'..'9'
var decimalQuantity = 0
return input.all { it in integerChars || it == '.' && decimalQuantity++ < 1 }
}
// Rounds given bend point to 3 decimal places at most and returns it
fun roundBendPoint(bendPoint : Float) : String {
return String.format("%.3f", bendPoint)
}
fun roundBendPoint(bendPoint : String) : String {
return String.format("%.3f", bendPoint)
}
// Calculate and return the estimated BND point value that will result in the given degrees for the given gauge.
// Output has undefined behaviour if the best fit slope has not yet been calculated.
fun calculateBendPoint(gauge : Int, degrees : Float) : Float {
val base = baseBendValues[gauge]
val degreeDifference = degrees - base!!.first
return (base.second + (bestSlopes[gauge]!! * degreeDifference))
}
@Composable
fun InputFields(filesDir : File, modifier: Modifier = Modifier) {
Column (
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
var bendText by remember { mutableStateOf("") }
var gaugeText by remember { mutableStateOf("") }
var degreesText by remember { mutableStateOf("") }
fun updateBendPoint() {
if (!isNumber(gaugeText) || !isNumber(degreesText)) {
return
}
if (!bestSlopes.containsKey(gaugeText.toInt())) {
return
}
bendText = roundBendPoint(calculateBendPoint(gaugeText.toInt(), degreesText.toFloat()))
}
TextField(
value = bendText,
onValueChange = { bendText = it },
label = { Text("BND Point") },
modifier = Modifier.padding(12.dp),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
)
TextField(
value = gaugeText,
onValueChange = { gaugeText = it; updateBendPoint() },
label = { Text("Gauge") },
modifier = Modifier.padding(12.dp),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
)
TextField(
value = degreesText,
onValueChange = { degreesText = it; updateBendPoint() },
label = { Text("Degrees") },
modifier = Modifier.padding(12.dp),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
)
Button(onClick = {
logValues(
filesDir,
bendText,
gaugeText,
degreesText
)
}) {
Text(stringResource(R.string.log_values))
}
}
}
fun logValues(filesDir : File, bendText: String, gaugeText: String, degreesText: String) {
if (!isNumber(bendText) || !isNumber(gaugeText) || !isNumber(degreesText)) {
return
}
val file : File = File(filesDir, FILE_NAME)
val pw = PrintWriter(FileOutputStream(file, true))
pw.println("$gaugeText,$degreesText,$bendText")
pw.close()
Log.d("logValues", "logged gauge $gaugeText, degrees $degreesText, BND point $bendText")
addToDataMap(gaugeText.toInt(), degreesText.toFloat(), bendText.toFloat())
calculateBestSlope(gaugeText.toInt())
}
fun addToDataMap(gauge : Int, degrees: Float, bendPoint: Float) {
if (!dataMap.containsKey(gauge)) {
// Create new map entry and give it new data point
dataMap[gauge] = arrayListOf(Pair(degrees, bendPoint))
} else {
// Add new data point to existing map entry
dataMap[gauge] = ArrayList(dataMap.getValue(gauge) + Pair(degrees, bendPoint))
}
tryUpdateBaseBendValues(gauge, degrees, bendPoint)
}
// Populate the dataMap by reading data from the file
fun initializeMapFromFile(filesDir : File) {
val file : File = File(filesDir, FILE_NAME)
if (!file.exists()) {
return
}
val contents = file.readText()
val data = contents.split("\n").toTypedArray()
// Process each data point
for (line in data) {
if (line.isEmpty()) {
continue
}
val splitLine = line.split(",").toTypedArray()
val gauge: Int = splitLine[0].toInt()
val x: Float = splitLine[1].toFloat()
val y: Float = splitLine[2].toFloat()
addToDataMap(gauge, x, y)
}
Log.d("dataMap updated", "current dataMap: $dataMap")
calculateBestSlopes()
}
// Update a gauge's base bend value if it's close to 90 degrees
fun tryUpdateBaseBendValues(gauge : Int, degrees: Float, bendPoint : Float) {
if (!baseBendValues.containsKey(gauge) ||
abs(BASE_DEGREES - degrees) < abs(BASE_DEGREES - baseBendValues[gauge]!!.first)) {
baseBendValues[gauge] = Pair(degrees, bendPoint)
}
}
// Calculate the best slopes for each gauge that has a key in the dataMap
fun calculateBestSlopes() {
for ((key, value) in dataMap) {
calculateBestSlope(key)
}
}
// Calculate the best slope for the given gauge
fun calculateBestSlope(gauge : Int) {
if (!dataMap.containsKey(gauge) || dataMap[gauge]!!.size <= 1) {
Log.d("calculateBestSlope", "failed to calculate best slope for gauge $gauge due to insufficient data (<= 1)")
return
}
var n = 0
var sigmaX : Float = 0f
var sigmaXSquared : Float = 0f
var sigmaY : Float = 0f
var sigmaXY : Float = 0f
// Process each data point
for (pair in dataMap[gauge]!!) {
n++
val x : Float = pair.first
val y : Float = pair.second
sigmaX += x
sigmaXSquared += x * x
sigmaY += y
sigmaXY += x * y
}
val bestSlope = (n * sigmaXY - sigmaX * sigmaY) / (n * sigmaXSquared - sigmaX * sigmaX)
// Ignore bad slopes that would result for example if all the data points have the same x
if (!bestSlope.isNaN() && !bestSlope.isInfinite()) {
bestSlopes[gauge] = bestSlope
}
}
| press-brake-calculator/app/src/main/java/com/example/pressbrakecalculator/MainActivity.kt | 2684980275 |
package com.milomobile.exampletrailinglambda
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.milomobile.exampletrailinglambda", appContext.packageName)
}
} | ExampleTrailingLambda/app/src/androidTest/java/com/milomobile/exampletrailinglambda/ExampleInstrumentedTest.kt | 2446789098 |
package com.milomobile.exampletrailinglambda
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)
}
} | ExampleTrailingLambda/app/src/test/java/com/milomobile/exampletrailinglambda/ExampleUnitTest.kt | 2666871715 |
package com.milomobile.exampletrailinglambda.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) | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/ui/theme/Color.kt | 3421012006 |
package com.milomobile.exampletrailinglambda.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 ExampleTrailingLambdaTheme(
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
)
} | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/ui/theme/Theme.kt | 3256199047 |
package com.milomobile.exampletrailinglambda.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
)
*/
) | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/ui/theme/Type.kt | 3335830240 |
package com.milomobile.exampletrailinglambda
fun thirdParam(a: Int, b: Int) : Unit {
}
fun runMath(first: Int, second: Int, mathAction: (a: Int, b: Int) -> Unit) {
mathAction(first, second)
}
fun example() {
runMath(1, 3) { first: Int, second: Int ->
first * second
}
} | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/ExampleLambda.kt | 3249518158 |
package com.milomobile.exampletrailinglambda
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.milomobile.exampletrailinglambda.ui.theme.ExampleTrailingLambdaTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ExampleTrailingLambdaTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ExampleTrailingLambdaTheme {
Greeting("Android")
}
} | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/MainActivity.kt | 1756285612 |
package com.milomobile.exampletrailinglambda
class dummy {
} | ExampleTrailingLambda/app/src/main/java/com/milomobile/exampletrailinglambda/dummy.kt | 4050691723 |
package com.andrew.compose
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.andrew.compose", appContext.packageName)
}
} | ComposeLearning/app/src/androidTest/java/com/andrew/compose/ExampleInstrumentedTest.kt | 2335648100 |
package com.andrew.compose
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)
}
} | ComposeLearning/app/src/test/java/com/andrew/compose/ExampleUnitTest.kt | 265670118 |
package com.andrew.compose.ui
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor() : ViewModel() {
val inputText = mutableStateOf("")
val names = MutableLiveData(mutableListOf<String>())
private val _selectedPageIndex = mutableIntStateOf(0)
val selectedPageIndex = _selectedPageIndex
fun addName(name: String) {
names.value?.add(name)
inputText.value = ""
}
fun changeInputText(newText: String) {
inputText.value = newText
}
fun changeSelectedPage(index: Int) {
_selectedPageIndex.value = index
}
} | ComposeLearning/app/src/main/java/com/andrew/compose/ui/MainViewModel.kt | 4141702622 |
package com.andrew.compose.ui.modify
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
@Composable
fun ModifyStudentScreen(
navController: NavController,
studentId: Int
) {
Text(text = "Modify student: $studentId")
} | ComposeLearning/app/src/main/java/com/andrew/compose/ui/modify/ModifyStudentScreen.kt | 105638176 |
package com.andrew.compose.ui.profile
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@Composable
fun ProfileScreen() {
Text(text = "Profile screen")
} | ComposeLearning/app/src/main/java/com/andrew/compose/ui/profile/ProfileScreen.kt | 3878132646 |
package com.andrew.compose.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) | ComposeLearning/app/src/main/java/com/andrew/compose/ui/theme/Color.kt | 670817068 |
package com.andrew.compose.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 ComposeTheme(
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
)
} | ComposeLearning/app/src/main/java/com/andrew/compose/ui/theme/Theme.kt | 1173785002 |
package com.andrew.compose.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
)
*/
) | ComposeLearning/app/src/main/java/com/andrew/compose/ui/theme/Type.kt | 1093556526 |
package com.andrew.compose.ui.name
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
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.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.andrew.compose.ui.MainViewModel
@Composable
fun NameListPage(viewModel: MainViewModel) {
val inputName by remember {
viewModel.inputText
}
val names = remember {
viewModel.names.value ?: emptyList()
}
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = "Welcome to Compose",
color = Color.Black,
fontSize = 20.sp,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold,
// style = TextStyle(
// color = Color.Blue,
// fontSize = 80.sp,
// fontWeight = FontWeight.Thin
// )
modifier = Modifier
.padding(20.dp)
.background(Color.Green)
.padding(20.dp)
)
// OutlinedTextField(
// value = "",
// onValueChange = {
// // do something here
// },
// placeholder = {
// Text(text = "Enter a name")
// },
// colors = TextFieldDefaults.colors(
// cursorColor = Color.Blue,
// focusedContainerColor = Color.Red
// ),
// modifier = Modifier
// .fillMaxWidth()
// .padding(horizontal = 20.dp),
// )
TextField(
value = inputName,
onValueChange = {
viewModel.changeInputText(it)
},
placeholder = {
Text(text = "Enter a name")
},
colors = TextFieldDefaults.colors(
cursorColor = Color.Blue,
focusedContainerColor = Color.Red
),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
)
Spacer(modifier = Modifier.height(20.dp))
Button(
onClick = {
viewModel.addName(inputName)
},
modifier = Modifier.align(Alignment.CenterHorizontally),
colors = ButtonDefaults.buttonColors(
contentColor = Color.White,
containerColor = Color.DarkGray
),
contentPadding = PaddingValues(horizontal = 40.dp),
) {
Text(text = "Add a name")
}
LazyColumn {
items(names) {
Text(text = it)
}
}
}
} | ComposeLearning/app/src/main/java/com/andrew/compose/ui/name/NameListPage.kt | 411588583 |
package com.andrew.compose.ui.main
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.andrew.compose.BottomNavigationItem
import com.andrew.compose.Page1
import com.andrew.compose.Page2
import com.andrew.compose.R
import com.andrew.compose.ui.MainViewModel
import com.andrew.compose.ui.name.NameListPage
import kotlinx.coroutines.launch
val items = listOf(
BottomNavigationItem(
title = "Home",
selectedIcon = Icons.Filled.Home,
unselectedIcon = Icons.Outlined.Home,
),
BottomNavigationItem(
title = "Reservation",
selectedIcon = Icons.Filled.ShoppingCart,
unselectedIcon = Icons.Outlined.ShoppingCart
),
BottomNavigationItem(
title = "Profile",
selectedIcon = Icons.Filled.Person,
unselectedIcon = Icons.Outlined.Person,
)
)
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MainScreen(
navController: NavController,
viewModel: MainViewModel = hiltViewModel()
) {
val navigationState = rememberDrawerState(initialValue = DrawerValue.Closed)
val selectedItemIndex by rememberSaveable {
viewModel.selectedPageIndex
}
val pagerState = rememberPagerState(pageCount = {
3
})
val scope = rememberCoroutineScope()
ModalNavigationDrawer(
drawerContent = {
ModalDrawerSheet {
Spacer(modifier = Modifier.height(26.dp))
Image(
painter = painterResource(id = R.drawable.ic_launcher_foreground),
contentDescription = "",
modifier = Modifier
.size(150.dp)
.fillMaxWidth()
.align(Alignment.CenterHorizontally)
)
Spacer(modifier = Modifier.height(26.dp))
items.forEachIndexed { index, drawerItem ->
NavigationDrawerItem(label = {
Text(text = drawerItem.title)
}, selected = index == selectedItemIndex, onClick = {
scope.launch {
viewModel.changeSelectedPage(index)
pagerState.scrollToPage(selectedItemIndex)
navigationState.close()
}
}, icon = {
Icon(
imageVector = if (index == selectedItemIndex) {
drawerItem.selectedIcon
} else drawerItem.unselectedIcon,
contentDescription = drawerItem.title
)
}, modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
)
}
}
},
drawerState = navigationState,
) {
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary,
),
title = {
Text("Compose App", modifier = Modifier.padding(horizontal = 20.dp))
},
navigationIcon = {
IconButton(onClick = {
scope.launch {
navigationState.open()
}
}) {
Icon(Icons.Default.Menu, contentDescription = "Menu")
}
},
actions = {
IconButton(onClick = {
navController.navigate("profile_screen")
}) {
Icon(
imageVector = Icons.Filled.Settings,
contentDescription = "Localized description"
)
}
}
)
},
bottomBar = {
NavigationBar {
items.forEachIndexed { index, item ->
NavigationBarItem(
selected = selectedItemIndex == index,
onClick = {
scope.launch {
viewModel.changeSelectedPage(index)
pagerState.scrollToPage(index)
}
},
label = {
Text(text = item.title)
},
icon = {
Icon(
imageVector =
if (selectedItemIndex == index)
item.selectedIcon
else item.unselectedIcon,
contentDescription = item.title
)
}
)
}
}
},
floatingActionButton = {
ExtendedFloatingActionButton(
text = { Text("Add") },
icon = { Icon(Icons.Filled.Add, contentDescription = "") },
onClick = {
}
)
}
) { paddings ->
Box(modifier = Modifier.padding(paddings)) {
HorizontalPager(state = pagerState) { page ->
when (page) {
0 -> NameListPage(viewModel = viewModel)
1 -> Page1()
2 -> Page2()
else -> throw IllegalArgumentException("Unknown page index: $page")
}
}
}
}
}
}
| ComposeLearning/app/src/main/java/com/andrew/compose/ui/main/MainScreen.kt | 2555013120 |
package com.andrew.compose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.andrew.compose.ui.main.MainScreen
import com.andrew.compose.ui.modify.ModifyStudentScreen
import com.andrew.compose.ui.profile.ProfileScreen
import com.andrew.compose.ui.theme.ComposeTheme
import dagger.hilt.android.AndroidEntryPoint
data class BottomNavigationItem(
val title: String,
val selectedIcon: ImageVector,
val unselectedIcon: ImageVector,
)
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "main_screen") {
composable("main_screen") {
MainScreen(navController)
}
composable("profile_screen") {
ProfileScreen()
}
composable("modify_student_screen/{studentId}", arguments = listOf(
navArgument("studentId") {
type = NavType.IntType
}
)) {
val studentId = remember {
it.arguments?.getInt("studentId") ?: -1
}
ModifyStudentScreen(
navController = navController,
studentId = studentId
)
}
}
}
}
}
}
}
@Composable
fun Page1() {
Text(text = "Page 1")
}
@Composable
fun Page2() {
Text(text = "Page 2")
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ComposeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen(rememberNavController())
}
}
} | ComposeLearning/app/src/main/java/com/andrew/compose/MainActivity.kt | 4192621209 |
package com.andrew.compose.di
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
} | ComposeLearning/app/src/main/java/com/andrew/compose/di/AppModule.kt | 3511375680 |
package com.andrew.compose.core
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ComposeApplication: Application() {
} | ComposeLearning/app/src/main/java/com/andrew/compose/core/ComposeApplication.kt | 2580538807 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged.ui.theme
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
private val LightColorScheme = lightColorScheme(
primary = Yellow,
secondary = MintGreen,
tertiary = Coral,
secondaryContainer = Yellow,
surface = White
)
private val shapes: Shapes
@Composable
get() = MaterialTheme.shapes.copy(
large = CircleShape
)
@Composable
fun JetLaggedTheme(
content: @Composable () -> Unit,
) {
MaterialTheme(
colorScheme = LightColorScheme,
typography = Typography,
shapes = shapes,
content = content
)
}
| JetLagged/app/src/main/java/com/example/jetlagged/ui/theme/Theme.kt | 3180050508 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import com.example.jetlagged.ui.theme.JetLaggedTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
JetLaggedTheme {
HomeScreenDrawer()
}
}
}
}
| JetLagged/app/src/main/java/com/example/jetlagged/MainActivity.kt | 2149448182 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetlagged.ui.theme.SmallHeadingStyle
import com.example.jetlagged.ui.theme.Yellow
import com.example.jetlagged.ui.theme.YellowVariant
import java.time.DayOfWeek
import java.time.format.TextStyle
import java.util.Locale
@Preview(showBackground = true)
@Preview(device = Devices.FOLDABLE, showBackground = true)
@Composable
fun JetLaggedScreen(
modifier: Modifier = Modifier,
onDrawerClicked: () -> Unit = {}
) {
Column(
modifier = modifier
.background(Color.White)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Column(modifier = Modifier.yellowBackground()) {
JetLaggedHeader(
onDrawerClicked = onDrawerClicked,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(32.dp))
JetLaggedSleepSummary(modifier = Modifier.padding(start = 16.dp, end = 16.dp))
}
Spacer(modifier = Modifier.height(16.dp))
var selectedTab by remember { mutableStateOf(SleepTab.Week) }
JetLaggedHeaderTabs(
onTabSelected = { selectedTab = it },
selectedTab = selectedTab,
)
Spacer(modifier = Modifier.height(16.dp))
val sleepState by remember {
mutableStateOf(sleepData)
}
JetLaggedTimeGraph(sleepState)
}
}
@Composable
private fun JetLaggedTimeGraph(sleepGraphData: SleepGraphData) {
val scrollState = rememberScrollState()
val hours = (sleepGraphData.earliestStartHour..23) + (0..sleepGraphData.latestEndHour)
TimeGraph(
modifier = Modifier
.horizontalScroll(scrollState)
.wrapContentSize(),
dayItemsCount = sleepGraphData.sleepDayData.size,
hoursHeader = {
HoursHeader(hours)
},
dayLabel = { index ->
val data = sleepGraphData.sleepDayData[index]
DayLabel(data.startDate.dayOfWeek)
},
bar = { index ->
val data = sleepGraphData.sleepDayData[index]
// We have access to Modifier.timeGraphBar() as we are now in TimeGraphScope
SleepBar(
sleepData = data,
modifier = Modifier.padding(bottom = 8.dp)
.timeGraphBar(
start = data.firstSleepStart,
end = data.lastSleepEnd,
hours = hours,
)
)
}
)
}
@Composable
private fun DayLabel(dayOfWeek: DayOfWeek) {
Text(
dayOfWeek.getDisplayName(
TextStyle.SHORT, Locale.getDefault()
),
Modifier
.height(24.dp)
.padding(start = 8.dp, end = 24.dp),
style = SmallHeadingStyle,
textAlign = TextAlign.Center
)
}
@Composable
private fun HoursHeader(hours: List<Int>) {
Row(
Modifier
.padding(bottom = 16.dp)
.drawBehind {
val brush = Brush.linearGradient(listOf(YellowVariant, Yellow))
drawRoundRect(
brush,
cornerRadius = CornerRadius(10.dp.toPx(), 10.dp.toPx()),
)
}
) {
hours.forEach {
Text(
text = "$it",
textAlign = TextAlign.Center,
modifier = Modifier
.width(50.dp)
.padding(vertical = 4.dp),
style = SmallHeadingStyle
)
}
}
}
| JetLagged/app/src/main/java/com/example/jetlagged/JetLaggedScreen.kt | 2047191887 |
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bedtime
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Leaderboard
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import kotlinx.coroutines.launch
@Composable
fun HomeScreenDrawer() {
Surface(
modifier = Modifier.fillMaxSize()
) {
var drawerState by remember {
mutableStateOf(DrawerState.Closed)
}
var screenState by remember {
mutableStateOf(Screen.Home)
}
val translationX = remember {
Animatable(0f)
}
val drawerWidth = with(LocalDensity.current) {
DrawerWidth.toPx()
}
translationX.updateBounds(0f, drawerWidth)
val coroutineScope = rememberCoroutineScope()
fun toggleDrawerState() {
coroutineScope.launch {
if (drawerState == DrawerState.Open) {
translationX.animateTo(0f)
} else {
translationX.animateTo(drawerWidth)
}
drawerState = if (drawerState == DrawerState.Open) {
DrawerState.Closed
} else {
DrawerState.Open
}
}
}
HomeScreenDrawerContents(
selectedScreen = screenState,
onScreenSelected = { screen ->
screenState = screen
}
)
val draggableState = rememberDraggableState(onDelta = { dragAmount ->
coroutineScope.launch {
translationX.snapTo(translationX.value + dragAmount)
}
})
val decay = rememberSplineBasedDecay<Float>()
ScreenContents(
selectedScreen = screenState,
onDrawerClicked = ::toggleDrawerState,
modifier = Modifier
.graphicsLayer {
this.translationX = translationX.value
val scale = lerp(1f, 0.8f, translationX.value / drawerWidth)
this.scaleX = scale
this.scaleY = scale
val roundedCorners = lerp(0f, 32.dp.toPx(), translationX.value / drawerWidth)
this.shape = RoundedCornerShape(roundedCorners)
this.clip = true
this.shadowElevation = 32f
}
// This example is showing how to use draggable with custom logic on stop to snap to the edges
// You can also use `anchoredDraggable()` to set up anchors and not need to worry about more calculations.
.draggable(
draggableState, Orientation.Horizontal,
onDragStopped = { velocity ->
val targetOffsetX = decay.calculateTargetValue(
translationX.value,
velocity
)
coroutineScope.launch {
val actualTargetX = if (targetOffsetX > drawerWidth * 0.5) {
drawerWidth
} else {
0f
}
// checking if the difference between the target and actual is + or -
val targetDifference = (actualTargetX - targetOffsetX)
val canReachTargetWithDecay =
(
targetOffsetX > actualTargetX && velocity > 0f &&
targetDifference > 0f
) ||
(
targetOffsetX < actualTargetX && velocity < 0 &&
targetDifference < 0f
)
if (canReachTargetWithDecay) {
translationX.animateDecay(
initialVelocity = velocity,
animationSpec = decay
)
} else {
translationX.animateTo(actualTargetX, initialVelocity = velocity)
}
drawerState = if (actualTargetX == drawerWidth) {
DrawerState.Open
} else {
DrawerState.Closed
}
}
}
)
)
}
}
@Composable
private fun ScreenContents(
selectedScreen: Screen,
onDrawerClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Box(modifier) {
when (selectedScreen) {
Screen.Home ->
JetLaggedScreen(
modifier = Modifier,
onDrawerClicked = onDrawerClicked
)
Screen.SleepDetails ->
Surface(
modifier = Modifier.fillMaxSize()
) {
}
Screen.Leaderboard ->
Surface(
modifier = Modifier.fillMaxSize()
) {
}
Screen.Settings ->
Surface(
modifier = Modifier.fillMaxSize()
) {
}
}
}
}
private enum class DrawerState {
Open,
Closed
}
@Composable
private fun HomeScreenDrawerContents(
selectedScreen: Screen,
onScreenSelected: (Screen) -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
Screen.values().forEach {
NavigationDrawerItem(
label = {
Text(it.text)
},
icon = {
Icon(imageVector = it.icon, contentDescription = it.text)
},
colors =
NavigationDrawerItemDefaults.colors(unselectedContainerColor = Color.White),
selected = selectedScreen == it,
onClick = {
onScreenSelected(it)
},
)
}
}
}
private val DrawerWidth = 300.dp
private enum class Screen(val text: String, val icon: ImageVector) {
Home("Home", Icons.Default.Home),
SleepDetails("Sleep", Icons.Default.Bedtime),
Leaderboard("Leaderboard", Icons.Default.Leaderboard),
Settings("Settings", Icons.Default.Settings),
}
| JetLagged/app/src/main/java/com/example/jetlagged/JetLaggedDrawer.kt | 372024743 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetlagged.ui.theme.HeadingStyle
import com.example.jetlagged.ui.theme.SmallHeadingStyle
import com.example.jetlagged.ui.theme.TitleBarStyle
@Preview
@Composable
fun JetLaggedHeader(
onDrawerClicked: () -> Unit = {},
modifier: Modifier = Modifier
) {
Box(
modifier.height(150.dp)
) {
Row(modifier = Modifier.windowInsetsPadding(insets = WindowInsets.systemBars)) {
IconButton(
onClick = onDrawerClicked,
) {
Icon(
Icons.Default.Menu,
contentDescription = stringResource(R.string.not_implemented)
)
}
Text(
stringResource(R.string.jetlagged_app_heading),
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
style = TitleBarStyle,
textAlign = TextAlign.Start
)
}
}
}
@Preview
@Composable
fun JetLaggedSleepSummary(modifier: Modifier = Modifier) {
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Column {
Text(
stringResource(R.string.average_time_in_bed_heading),
style = SmallHeadingStyle
)
Text(
stringResource(R.string.placeholder_text_ave_time),
style = HeadingStyle
)
}
Spacer(modifier = Modifier.width(16.dp))
Column {
Text(
stringResource(R.string.average_sleep_time_heading),
style = SmallHeadingStyle
)
Text(
stringResource(R.string.placeholder_text_ave_time_2),
style = HeadingStyle,
)
}
}
Spacer(modifier = Modifier.height(32.dp))
}
| JetLagged/app/src/main/java/com/example/jetlagged/JetLaggedHeader.kt | 4117899480 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetlagged
import android.graphics.Color
import android.graphics.RuntimeShader
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.animation.core.withInfiniteAnimationFrameMillis
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.ShaderBrush
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.node.DrawModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import com.example.jetlagged.ui.theme.White
import com.example.jetlagged.ui.theme.Yellow
import com.example.jetlagged.ui.theme.YellowVariant
import kotlinx.coroutines.launch
import org.intellij.lang.annotations.Language
private data object YellowBackgroundElement : ModifierNodeElement<YellowBackgroundNode>() {
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun create() = YellowBackgroundNode()
override fun update(node: YellowBackgroundNode) {
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private class YellowBackgroundNode : DrawModifierNode, Modifier.Node() {
private val shader = RuntimeShader(SHADER)
private val shaderBrush = ShaderBrush(shader)
private val time = mutableFloatStateOf(0f)
init {
shader.setColorUniform(
"color",
Color.valueOf(Yellow.red, Yellow.green, Yellow.blue, Yellow.alpha)
)
}
override fun ContentDrawScope.draw() {
shader.setFloatUniform("resolution", size.width, size.height)
shader.setFloatUniform("time", time.floatValue)
drawRect(shaderBrush)
drawContent()
}
override fun onAttach() {
coroutineScope.launch {
while (true) {
withInfiniteAnimationFrameMillis {
time.floatValue = it / 1000f
}
}
}
}
}
fun Modifier.yellowBackground(): Modifier =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.then(YellowBackgroundElement)
} else {
drawWithCache {
val gradientBrush = Brush.verticalGradient(listOf(Yellow, YellowVariant, White))
onDrawBehind {
drawRect(gradientBrush)
}
}
}
@Language("AGSL")
val SHADER = """
uniform float2 resolution;
uniform float time;
layout(color) uniform half4 color;
float calculateColorMultiplier(float yCoord, float factor) {
return step(yCoord, 1.0 + factor * 2.0) - step(yCoord, factor - 0.1);
}
float4 main(in float2 fragCoord) {
// Config values
const float speedMultiplier = 1.5;
const float waveDensity = 1.0;
const float loops = 8.0;
const float energy = 0.6;
// Calculated values
float2 uv = fragCoord / resolution.xy;
float3 rgbColor = color.rgb;
float timeOffset = time * speedMultiplier;
float hAdjustment = uv.x * 4.3;
float3 loopColor = vec3(1.0 - rgbColor.r, 1.0 - rgbColor.g, 1.0 - rgbColor.b) / loops;
for (float i = 1.0; i <= loops; i += 1.0) {
float loopFactor = i * 0.1;
float sinInput = (timeOffset + hAdjustment) * energy;
float curve = sin(sinInput) * (1.0 - loopFactor) * 0.05;
float colorMultiplier = calculateColorMultiplier(uv.y, loopFactor);
rgbColor += loopColor * colorMultiplier;
// Offset for next loop
uv.y += curve;
}
return float4(rgbColor, 1.0);
}
""".trimIndent()
| JetLagged/app/src/main/java/com/example/jetlagged/Background.kt | 3899894403 |
/*
* Copyright $YEAR The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
| JetLagged/spotless/copyright.kt | 2813624007 |
package com.R.movsenseapplication
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.R.movsenseapplication", appContext.packageName)
}
} | RND-MoveSense/app/src/androidTest/java/com/R/movsenseapplication/ExampleInstrumentedTest.kt | 1000546390 |
package com.R.movsenseapplication
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)
}
} | RND-MoveSense/app/src/test/java/com/R/movsenseapplication/ExampleUnitTest.kt | 3867843539 |
import com.polidea.rxandroidble2.RxBleDevice
import com.polidea.rxandroidble2.scan.ScanResult
class MyScanResult2(scanResult: ScanResult) {
var rssi: Int = 0
var macAddress: String = ""
var name: String = ""
var connectedSerial: String? = null
init {
macAddress = scanResult.bleDevice.macAddress
rssi = scanResult.rssi
name = scanResult.bleDevice.name!!
}
fun isConnected(): Boolean {
return connectedSerial != null
}
fun markConnected(serial: String) {
connectedSerial = serial
}
fun markDisconnected() {
connectedSerial = null
}
override fun equals(other: Any?): Boolean {
if (other is MyScanResult2 && other.macAddress == this.macAddress) {
return true
} else if (other is RxBleDevice && other.macAddress == this.macAddress) {
return true
} else {
return false
}
}
override fun toString(): String {
return (if (isConnected()) "*** " else "") + macAddress + " - " + name + " [" + rssi + "]" + (if (isConnected()) " ***" else "")
}
}
| RND-MoveSense/app/src/main/java/MyScanResult2.kt | 3647296097 |
package com.R.movsenseapplication.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) | RND-MoveSense/app/src/main/java/com/R/movsenseapplication/ui/theme/Color.kt | 26424098 |
package com.R.movsenseapplication.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 MovsenseApplicationTheme(
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
)
} | RND-MoveSense/app/src/main/java/com/R/movsenseapplication/ui/theme/Theme.kt | 1028502005 |
package com.R.movsenseapplication.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
)
*/
) | RND-MoveSense/app/src/main/java/com/R/movsenseapplication/ui/theme/Type.kt | 917886218 |
//package com.R.movsenseapplication
//
//import android.app.AlertDialog
//import android.content.pm.PackageManager
//import android.os.Bundle
//import android.os.Handler
//import android.os.Looper
//import android.util.Log
//import android.view.View
//import android.widget.AdapterView
//import android.widget.ArrayAdapter
//import android.widget.Button
//import android.widget.ListView
//import androidx.activity.ComponentActivity
//import androidx.core.app.ActivityCompat
//import androidx.core.content.ContextCompat
//import com.movesense.mds.Mds
//import com.movesense.mds.MdsConnectionListener
//import com.movesense.mds.MdsException
//import com.polidea.rxandroidble3.RxBleClient
//import com.polidea.rxandroidble3.RxBleConnection
//import com.polidea.rxandroidble3.RxBleDevice
//import com.polidea.rxandroidble3.exceptions.BleException
//import com.polidea.rxandroidble3.scan.ScanSettings
//import io.reactivex.exceptions.UndeliverableException
//import io.reactivex.rxjava3.core.Observable
//import io.reactivex.rxjava3.disposables.Disposable
//import io.reactivex.rxjava3.plugins.RxJavaPlugins
//import io.reactivex.rxjava3.schedulers.Schedulers
//import java.util.concurrent.TimeUnit
//
//
//class MainActivity : ComponentActivity() {
// private var mMds: Mds? = null
//
// private lateinit var mScanSubscription: Disposable
// private lateinit var mScanResultListView: ListView
// private lateinit var mScanResArrayList: ArrayList<MyScanResult>
// private lateinit var mScanResArrayAdapter: ArrayAdapter<MyScanResult>
// private lateinit var rxBleClient: RxBleClient
// private lateinit var buttonScan: Button
// private lateinit var buttonScanStop: Button
// private val LOCATION_PERMISSION_REQUEST_CODE = 100
// private val BLUETOOTH_PERMISSION_REQUEST_CODE = 101
//
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
// initMds()
// mScanResultListView = findViewById(R.id.listScanResult)
// buttonScan = findViewById(R.id.buttonScan)
// buttonScanStop = findViewById(R.id.buttonScanStop)
// mScanResArrayList = ArrayList()
// mScanResArrayAdapter =
// ArrayAdapter(this, android.R.layout.simple_list_item_1, mScanResArrayList)
// mScanResultListView.adapter = mScanResArrayAdapter
// mScanResultListView.setOnItemClickListener { parent, view, position, id ->
// onItemClick(
// parent,
// view,
// position,
// id
// )
// }
// mScanResultListView.setOnItemLongClickListener { parent, view, position, id ->
// onItemLongClick(
// parent,
// view,
// position,
// id
// )
// }
//
// buttonScan.setOnClickListener {
// findViewById<View>(R.id.buttonScan).visibility = View.GONE
// findViewById<View>(R.id.buttonScanStop).visibility = View.VISIBLE
// onScanClicked()
// }
// buttonScanStop.setOnClickListener {
// findViewById<View>(R.id.buttonScan).visibility = View.VISIBLE
// findViewById<View>(R.id.buttonScanStop).visibility = View.GONE
// onScanStopClicked()
//
//// testConnect()
// }
// if (ContextCompat.checkSelfPermission(
// this,
// android.Manifest.permission.ACCESS_FINE_LOCATION
// )
// != PackageManager.PERMISSION_GRANTED
// ) {
// ActivityCompat.requestPermissions(
// this,
// arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
// LOCATION_PERMISSION_REQUEST_CODE
// )
// }
//
// // Check and request Bluetooth permissions
// if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH)
// != PackageManager.PERMISSION_GRANTED ||
// ContextCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_ADMIN)
// != PackageManager.PERMISSION_GRANTED
// ) {
// ActivityCompat.requestPermissions(
// this,
// arrayOf(
// android.Manifest.permission.BLUETOOTH,
// android.Manifest.permission.BLUETOOTH_ADMIN,
// android.Manifest.permission.NEARBY_WIFI_DEVICES
// ),
// BLUETOOTH_PERMISSION_REQUEST_CODE
// )
// }
//
// }
//
// override fun onRequestPermissionsResult(
// requestCode: Int,
// permissions: Array<out String>,
// grantResults: IntArray
// ) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// when (requestCode) {
// LOCATION_PERMISSION_REQUEST_CODE -> {
// if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// // Location permission granted
// } else {
// // Location permission denied
// }
// }
//
// BLUETOOTH_PERMISSION_REQUEST_CODE -> {
// if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
// // Bluetooth permissions granted
// } else {
// // Bluetooth permissions denied
// }
// }
// }
// }
//
// private fun initMds() {
// mMds = Mds.builder().build(this)
// }
//
//
// fun onScanClicked() {
// mScanResArrayList.clear()
// mScanResArrayAdapter.notifyDataSetChanged()
// rxBleClient = RxBleClient.create(this)
// mScanSubscription = rxBleClient.scanBleDevices(
// ScanSettings.Builder()
//// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
//// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
// .build() // add filters if needed
// )
// .subscribe(
// { scanResult ->
// Log.d(
// "LOG_TAG",
// "mac: ${scanResult.bleDevice.macAddress}" + "name: ${scanResult.bleDevice.name}"
// )
// scanResult.bleDevice?.let { bleDevice ->
// Log.d(
// "LOG_TAG",
// "mac: ${scanResult.bleDevice.macAddress}" + "name: ${scanResult.bleDevice.name}" + "name2: ${bleDevice.name}"
// )
// if (bleDevice.name != null && bleDevice.name!!.contains("Movesense")) {
// val msr = MyScanResult(scanResult)
// if (mScanResArrayList.contains(msr))
// mScanResArrayList[mScanResArrayList.indexOf(msr)] = msr
// else
// mScanResArrayList.add(0, msr)
// //mScanResArrayList.add(0, scanResult)
//
//// mScanResArrayList.add(0, msr)
// mScanResArrayAdapter.notifyDataSetChanged()
// onScanStopClicked()
// }
// }
// }, { throwable ->
// Log.e("LOG_TAG", "scan error: $throwable")
// onScanStopClicked()
// })
//
// }
//
// fun onScanStopClicked() {
// try {
// mScanSubscription.dispose()
// } catch (ex: Exception) {
//
// }
//
// }
//
// private fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
//
// }
//
// private fun testConnect() {
// val device = rxBleClient.getBleDevice("0C:8C:DC:41:E2:2B")
// mScanSubscription = device
// .establishConnection(false)
// .subscribeOn(Schedulers.io())
// .observeOn(Schedulers.io())
// .subscribe(
// { conn ->
// Log.v("TAG", "BLE connected")
// },
// { throwable -> Log.e("TAG", "BLE connection failed", throwable) },
// {
// Log.v("TAG", "BLE completed")
// }
// )
// }
//
// /*Own implementation using RxAndroidBle-library for easy scanning of BLE devices file*/
// private fun onItemLongClick(
// parent: AdapterView<*>,
// view: View,
// position: Int,
// id: Long
// ): Boolean {
// mScanResultListView.setOnItemLongClickListener { parent, view, position, id ->
// if (position < 0 || position >= mScanResArrayList.size)
// return@setOnItemLongClickListener false
// val device = mScanResArrayList[position]
// val bleDevice = device.macAddress.bleDevice.macAddress
// if (!device.isConnected) {
// val device = rxBleClient.getBleDevice(bleDevice)
// mScanSubscription = device
// .establishConnection(false)
// .subscribeOn(Schedulers.io())
// .observeOn(Schedulers.io())
// .subscribe(
// { conn ->
// Log.v("TAG", "BLE connected")
// Handler(Looper.getMainLooper()).post {
// MyToast.showLongToast(this, "BLE connected!")
// }
// },
// { throwable ->
// Log.e("TAG", "BLE connection failed", throwable)
// Handler(Looper.getMainLooper()).post {
// MyToast.showLongToast(this, "BLE connection failed!,Already connected")
// mMds!!.disconnect(bleDevice)
// MyToast.showLongToast(this, "Disconnecting from BLE device")
// mScanResArrayList.clear()
// mScanResArrayAdapter.notifyDataSetChanged()
// buttonScan.visibility = View.VISIBLE
// mScanSubscription.dispose()
// buttonScanStop.visibility = View.GONE
// }
// },
// {
// Log.v("TAG", "BLE completed")
// Handler(Looper.getMainLooper()).post {
// MyToast.showLongToast(this, "BLE completed")
// }
// }
// )
//
// } else {
// Log.i("LOG_TAG", "Disconnecting from BLE device: ${device.macAddress}")
// mMds!!.disconnect(bleDevice)
// }
// true
// }
// return true
// }
//
//
// /*Doucument wise implementation*/
//
//
// private fun onItemLongClick1(
// parent: AdapterView<*>,
// view: View,
// position: Int,
// id: Long
// ): Boolean {
// mScanResultListView.setOnItemLongClickListener { parent, view, position, id ->
// if (position < 0 || position >= mScanResArrayList.size)
// return@setOnItemLongClickListener false
// val device = mScanResArrayList[position]
// val bleDevice = device.macAddress.bleDevice.macAddress
// if (!device.isConnected) {
// val device = rxBleClient.getBleDevice(bleDevice)
// Log.i("LOG_TAG", "Connecting to BLE device: ${device}")
// try {
// mMds!!.connect(bleDevice, object : MdsConnectionListener {
// override fun onConnect(s: String) {
// Log.d("LOG_TAG", "onConnect: $s")
// }
//
// override fun onConnectionComplete(macAddress: String, serial: String) {
// for (sr in mScanResArrayList) {
// if (sr.macAddress.equals(macAddress)) {
// sr.markConnected(serial)
// break
// }
// }
// runOnUiThread {
// mScanResArrayAdapter.notifyDataSetChanged()
// }
// }
//
// override fun onError(e: MdsException) {
// Log.e("LOG_TAG", "onError: $e")
// showConnectionError(e)
// }
//
// override fun onDisconnect(bleAddress: String) {
// Log.d("LOG_TAG", "onDisconnect: $bleAddress")
// for (sr in mScanResArrayList) {
// if (bleAddress == sr.macAddress.toString())
// sr.markDisconnected()
// }
// runOnUiThread {
// mScanResArrayAdapter.notifyDataSetChanged()
// }
// }
// })
// }catch (ex:Exception){
// Log.d("LOG_TAG", "onConnect--1: $ex")
// }
//
// } else {
// Log.i("LOG_TAG", "Disconnecting from BLE device: ${device.macAddress}")
// mMds!!.disconnect(bleDevice)
// }
// true
// }
// return true
// }
//
//
// private fun showConnectionError(e: MdsException) {
// val builder = AlertDialog.Builder(this)
// .setTitle("Connection Error:")
// .setMessage(e.message)
//
// builder.create().show()
// }
//
//}
//
//
| RND-MoveSense/app/src/main/java/com/R/movsenseapplication/MainActivity.kt | 53761446 |
package com.R.movsenseapplication
import MyScanResult2
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.movesense.mds.Mds
import com.movesense.mds.MdsConnectionListener
import com.movesense.mds.MdsException
import com.movesense.mds.MdsNotificationListener
import com.movesense.mds.MdsSubscription
import com.polidea.rxandroidble2.RxBleClient
import com.polidea.rxandroidble2.RxBleDevice
import com.polidea.rxandroidble2.scan.ScanSettings
import io.reactivex.disposables.Disposable
class MainActivity2 : AppCompatActivity(), AdapterView.OnItemLongClickListener,
AdapterView.OnItemClickListener {
private var mMds: Mds? = null
// UI
private var mScanResultListView: ListView? = null
private val mScanResArrayList = ArrayList<MyScanResult2>()
private var mScanResArrayAdapter: ArrayAdapter<MyScanResult2>? = null
private var mdsSubscription: MdsSubscription? = null
private var subscribedDeviceSerial: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
// Init Scan UI
mScanResultListView = findViewById<View>(R.id.listScanResult) as ListView?
mScanResArrayAdapter = ArrayAdapter<MyScanResult2>(
this,
android.R.layout.simple_list_item_1, mScanResArrayList
)
mScanResultListView!!.adapter = mScanResArrayAdapter
mScanResultListView!!.setOnItemLongClickListener(this)
mScanResultListView!!.setOnItemClickListener(this)
// Make sure we have all the permissions this app needs
requestNeededPermissions()
// Initialize Movesense MDS library
initMds()
}
private val bleClient: RxBleClient?
private get() {
// Init RxAndroidBle (Ble helper library) if not yet initialized
if (mBleClient == null) {
mBleClient = RxBleClient.create(this)
}
return mBleClient
}
private fun initMds() {
mMds = Mds.builder().build(this)
}
fun requestNeededPermissions() {
var requiredPermissions: Array<String?>
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
!= PackageManager.PERMISSION_GRANTED
) {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(
this, arrayOf<String>(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT
),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
}
var mScanSubscription: Disposable? = null
fun onScanClicked(view: View?) {
findViewById<View>(R.id.buttonScan).setVisibility(View.GONE)
findViewById<View>(R.id.buttonScanStop).setVisibility(View.VISIBLE)
// Start with empty list
mScanResArrayList.clear()
mScanResArrayAdapter!!.notifyDataSetChanged()
mScanSubscription = bleClient!!.scanBleDevices(
ScanSettings.Builder()// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build() // add filters if needed
)
.subscribe(
{ scanResult ->
Log.d(LOG_TAG, "scanResult: $scanResult")
// Process scan result here. filter movesense devices.
if (scanResult.getBleDevice() != null && scanResult.getBleDevice()
.getName() != null &&
scanResult.getBleDevice().getName()!!.startsWith("Movesense")
) {
// replace if exists already, add otherwise
val msr = MyScanResult2(scanResult)
if (mScanResArrayList.contains(msr)) mScanResArrayList[mScanResArrayList.indexOf(
msr
)] = msr else mScanResArrayList.add(0, msr)
mScanResArrayAdapter!!.notifyDataSetChanged()
}
}
) { throwable ->
Log.e(LOG_TAG, "scan error: $throwable")
// Handle an error here.
// Re-enable scan buttons, just like with ScanStop
onScanStopClicked(null)
}
}
fun onScanStopClicked(view: View?) {
if (mScanSubscription != null) {
mScanSubscription!!.dispose()
mScanSubscription = null
}
findViewById<View>(R.id.buttonScan).setVisibility(View.VISIBLE)
findViewById<View>(R.id.buttonScanStop).setVisibility(View.GONE)
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
if (position < 0 || position >= mScanResArrayList.size) return
val device = mScanResArrayList[position]
if (!device.isConnected()) {
// Stop scanning
onScanStopClicked(null)
// And connect to the device
connectBLEDevice(device)
} else {
// Device is connected, trigger showing /Info
subscribeToSensor(device.connectedSerial!!)
}
}
private fun subscribeToSensor(connectedSerial: String) {
// Clean up existing subscription (if there is one)
if (mdsSubscription != null) {
unsubscribe()
}
// Build JSON doc that describes what resource and device to subscribe
// Here we subscribe to 13 hertz accelerometer data
val sb = StringBuilder()
val strContract =
sb.append("{\"Uri\": \"").append(connectedSerial).append(URI_MEAS_ACC_13).append("\"}")
.toString()
Log.d(LOG_TAG, strContract)
val sensorUI: View = findViewById<View>(R.id.sensorUI)
subscribedDeviceSerial = connectedSerial
mdsSubscription = Mds.builder().build(this).subscribe(
URI_EVENTLISTENER,
strContract, object : MdsNotificationListener {
override fun onNotification(data: String) {
Log.d(LOG_TAG, "onNotification(): $data")
// If UI not enabled, do it now
if (sensorUI.visibility == View.GONE) sensorUI.visibility = View.VISIBLE
val accResponse: AccDataResponse2 =
Gson().fromJson(data, AccDataResponse2::class.java)
if (accResponse != null && accResponse.body.array.size > 0) {
val accStr = java.lang.String.format(
"%.02f, %.02f, %.02f",
accResponse.body.array.get(0).x,
accResponse.body.array.get(0).y,
accResponse.body.array.get(0).z
)
(findViewById<View>(R.id.sensorMsg) as TextView).text = accStr
}
}
override fun onError(error: MdsException) {
Log.e(LOG_TAG, "subscription onError(): ", error)
unsubscribe()
}
})
}
override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
if (position < 0 || position >= mScanResArrayList.size)
return false
val device = mScanResArrayList[position]
Log.d(LOG_TAG, "onItemLongClick, ${device.connectedSerial} vs $subscribedDeviceSerial")
if (device.connectedSerial == subscribedDeviceSerial)
unsubscribe()
Log.i(LOG_TAG, "Disconnecting from BLE device: ${device.macAddress}")
mMds!!.disconnect(device.macAddress)
return true
}
private fun connectBLEDevice(device: MyScanResult2) {
val bleDevice: RxBleDevice = bleClient!!.getBleDevice(device.macAddress)
Log.i(LOG_TAG, "Connecting to BLE device: " + bleDevice.getMacAddress())
mMds!!.connect(bleDevice.getMacAddress(), object : MdsConnectionListener {
override fun onConnect(s: String) {
Log.d(LOG_TAG, "onConnect:$s")
}
override fun onConnectionComplete(macAddress: String, serial: String) {
for (sr in mScanResArrayList) {
if (sr.macAddress.equals(macAddress)) {
sr.markConnected(serial)
break
}
}
mScanResArrayAdapter!!.notifyDataSetChanged()
}
override fun onError(e: MdsException) {
Log.e(LOG_TAG, "onError:$e")
showConnectionError(e)
}
override fun onDisconnect(bleAddress: String) {
Log.d(LOG_TAG, "onDisconnect: $bleAddress")
for (sr in mScanResArrayList) {
if (bleAddress == sr.macAddress) {
if (sr.connectedSerial != null && sr.connectedSerial == subscribedDeviceSerial) unsubscribe()
sr.markDisconnected()
}
}
mScanResArrayAdapter!!.notifyDataSetChanged()
}
})
}
private fun showConnectionError(e: MdsException) {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
.setTitle("Connection Error:")
.setMessage(e.message)
builder.create().show()
}
private fun unsubscribe() {
if (mdsSubscription != null) {
mdsSubscription!!.unsubscribe()
mdsSubscription = null
}
subscribedDeviceSerial = null
// If UI not invisible, do it now
val sensorUI: View = findViewById<View>(R.id.sensorUI)
if (sensorUI.visibility != View.GONE) sensorUI.visibility = View.GONE
}
fun onUnsubscribeClicked(view: View?) {
unsubscribe()
}
companion object {
private val LOG_TAG = MainActivity2::class.java.simpleName
private const val MY_PERMISSIONS_REQUEST_LOCATION = 1
const val URI_CONNECTEDDEVICES = "suunto://MDS/ConnectedDevices"
const val URI_EVENTLISTENER = "suunto://MDS/EventListener"
const val SCHEME_PREFIX = "suunto://"
// BleClient singleton
private var mBleClient: RxBleClient? = null
// Sensor subscription
private const val URI_MEAS_ACC_13 = "/Meas/Acc/13"
}
} | RND-MoveSense/app/src/main/java/com/R/movsenseapplication/MainActivity2.kt | 2265983412 |
package com.R.movsenseapplication
//import com.polidea.rxandroidble3.scan.ScanResult
//data class MyScanResult(var macAddress: ScanResult, var connectedSerial: String= "", var isConnected: Boolean = false) {
// fun markDisconnected() {
// isConnected = false
// }
// fun markConnected(serial: String) {
// connectedSerial = serial
// isConnected = true
// }
//}
| RND-MoveSense/app/src/main/java/com/R/movsenseapplication/MyScanResult.kt | 3712359308 |
package com.R.movsenseapplication
/**
* Created by lipponep on 22.11.2017.
*/
import com.google.gson.annotations.SerializedName
class AccDataResponse2(@field:SerializedName("Body") val body: Body) {
class Body(
@field:SerializedName("Timestamp") val timestamp: Long, @field:SerializedName(
"ArrayAcc"
) val array: kotlin.Array<Array>, @field:SerializedName(
"Headers"
) val header: Headers
)
class Array(
@field:SerializedName("x") val x: Double, @field:SerializedName(
"y"
) val y: Double, @field:SerializedName("z") val z: Double
)
class Headers(@field:SerializedName("Param0") val param0: Int)
} | RND-MoveSense/app/src/main/java/com/R/movsenseapplication/AccDataResponse2.kt | 461663754 |
package com.R.movsenseapplication
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.movesense.mds.Mds
import com.movesense.mds.MdsConnectionListener
import com.movesense.mds.MdsException
import com.movesense.mds.MdsResponseListener
//import com.polidea.rxandroidble2.RxBleClient
//import com.polidea.rxandroidble2.scan.ScanResult
//import com.polidea.rxandroidble2.scan.ScanSettings
//import io.reactivex.disposables.Disposable
class ActivityMovsense : AppCompatActivity() {
private lateinit var mMds: Mds
// private lateinit var mScanSubscription: Disposable
private lateinit var mScanResultListView: ListView
// private val mScanResArrayList: ArrayList<MyScanResult> = ArrayList()
// private lateinit var mScanResArrayAdapter: ArrayAdapter<MyScanResult>
// private lateinit var bleClient: RxBleClient
private val LOG_TAG = "ActivityMovsense"
val SCHEME_PREFIX = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mMds = Mds.builder().build(this)
// bleClient = RxBleClient.create(this)
// mScanResultListView = findViewById(R.id.listScanResult)
// mScanResArrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, mScanResArrayList)
// mScanResultListView.adapter = mScanResArrayAdapter
// mScanResultListView.setOnItemLongClickListener(this)
// mScanResultListView.setOnItemClickListener(this)
}
// Define a dummy getBleClient method
/* private fun getBleClient(): RxBleClient {
// Return your RxBleClient instance or handle the creation of it
return bleClient
}
fun onScanClicked(view: View) {
findViewById<View>(R.id.buttonScan).visibility = View.GONE
findViewById<View>(R.id.buttonScanStop).visibility = View.VISIBLE
// Start with empty list
mScanResArrayList.clear()
mScanResArrayAdapter.notifyDataSetChanged()
mScanSubscription = getBleClient().scanBleDevices(
ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build()
// add filters if needed
)
.subscribe(
{ scanResult ->
Log.d(LOG_TAG, "scanResult: $scanResult")
// Process scan result here. filter movesense devices.
if (scanResult.bleDevice != null &&
scanResult.bleDevice.name != null &&
scanResult.bleDevice.name!!.startsWith("Movesense")
) {
// Replace if exists already, add otherwise
val msr = MyScanResult(scanResult)
if (mScanResArrayList.contains(msr))
mScanResArrayList[mScanResArrayList.indexOf(msr)] = msr
else
mScanResArrayList.add(0, msr)
runOnUiThread {
mScanResArrayAdapter.notifyDataSetChanged()
}
}
},
{ throwable ->
Log.e(LOG_TAG, "scan error: $throwable")
// Handle an error here.
// Re-enable scan buttons, just like with ScanStop
onScanStopClicked(view)
}
)
}
private fun MyScanResult(macAddress: ScanResult?): MyScanResult {
TODO("Not yet implemented")
}
fun onScanStopClicked(view: View) {
mScanSubscription.dispose()
findViewById<View>(R.id.buttonScan).visibility = View.VISIBLE
findViewById<View>(R.id.buttonScanStop).visibility = View.GONE
}
override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
if (position < 0 || position >= mScanResArrayList.size)
return false
val device = mScanResArrayList[position]
if (!device.isConnected) {
val bleDevice = getBleClient().getBleDevice(device.macAddress.toString())
Log.i(LOG_TAG, "Connecting to BLE device: " + bleDevice.macAddress)
mMds.connect(bleDevice.macAddress, object : MdsConnectionListener {
override fun onConnect(s: String) {
Log.d(LOG_TAG, "onConnect:$s")
}
override fun onConnectionComplete(macAddress: String, serial: String) {
for (sr in mScanResArrayList) {
if (sr.macAddress.equals(macAddress)) {
sr.markConnected(serial)
break
}
}
runOnUiThread {
mScanResArrayAdapter.notifyDataSetChanged()
}
}
override fun onError(e: MdsException) {
Log.e(LOG_TAG, "onError:$e")
showConnectionError(e)
}
override fun onDisconnect(bleAddress: String) {
Log.d(LOG_TAG, "onDisconnect: $bleAddress")
for (sr in mScanResArrayList) {
if (bleAddress.equals(sr.macAddress))
sr.markDisconnected()
}
runOnUiThread {
mScanResArrayAdapter.notifyDataSetChanged()
}
}
})
} else {
Log.i(LOG_TAG, "Disconnecting from BLE device: ${device.macAddress}")
mMds.disconnect(device.macAddress.toString())
}
return true
}
*//* override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (position < 0 || position >= mScanResArrayList.size)
return
val device = mScanResArrayList[position]
if (!device.isConnected) {
return
}
val uri = "$SCHEME_PREFIX${device.connectedSerial}/Info"
mMds.get(uri, null, object : MdsResponseListener {
override fun onSuccess(s: String) {
Log.i(LOG_TAG, "Device ${device.connectedSerial} /info request successful: $s")
// Display info in alert dialog
AlertDialog.Builder(this@ActivityMovsense)
.setTitle("Device info:")
.setMessage(s)
.show()
}
override fun onError(e: MdsException) {
Log.e(LOG_TAG, "Device ${device.connectedSerial} /info returned error: $e")
}
})
}*//*
private fun showConnectionError(e: MdsException) {
AlertDialog.Builder(this)
.setTitle("Connection Error:")
.setMessage(e.message)
.create()
.show()
}*/
}
| RND-MoveSense/app/src/main/java/com/R/movsenseapplication/ActivityMovsense.kt | 3386798594 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.