path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
jiwonminsu/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 | 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)
}
} |
jiwonminsu/app/src/main/java/com/example/myapplication/ui/theme/Color.kt | 2513741509 | package com.example.myapplication.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) |
jiwonminsu/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt | 196007232 | package com.example.myapplication.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 MyApplicationTheme(
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
)
} |
jiwonminsu/app/src/main/java/com/example/myapplication/ui/theme/Type.kt | 3481532690 | package com.example.myapplication.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
)
*/
) |
jiwonminsu/app/src/main/java/com/example/myapplication/MainActivity.kt | 3231288311 | package com.example.myapplication
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.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Android")
}
}
}
}
}
// git test
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
Greeting("Android")
}
} |
MikesInventoryList/app/src/androidTest/java/com/angrypenguin/mikesinventorysystem/ExampleInstrumentedTest.kt | 4147614012 | package com.angrypenguin.mikesinventorysystem
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.angrypenguin.mikesinventorysystem", appContext.packageName)
}
} |
MikesInventoryList/app/src/test/java/com/angrypenguin/mikesinventorysystem/contacts/InventoryClassTests.kt | 1812740749 | package com.angrypenguin.mikesinventorysystem.contacts
import android.database.sqlite.SQLiteDatabase
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertTrue
import org.junit.Test
//class InventoryTableTest {
//
// private val db = mockk<SQLiteDatabase>(relaxed = true)
// private val table = InventoryTable()
//
// @Test
// fun `creates table if it doesn't exist`() {
// table.createTable(db)
//
// verify(db).execSQL(contains("CREATE TABLE IF NOT EXISTS"))
// }
//
// @Test
// fun `table exist check works`() {
// table.createTable(db)
//
// val exists = table.doesTableExist(db)
//
// assertTrue(exists)
// }
//
// @Test
// fun `can search inventory by partial match`() {
// // Populate some test data
//
// val results = table.searchInventory(db, "office")
//
// assertTrue(results.isNotEmpty())
// assertTrue(results[0].location.contains("office"))
// }
//
// @Test
// fun `can insert new item`() {
// val guid = "test_guid"
// val item = InventoryItem(guid = guid, ...)
//
// table.insertItem(db, item)
//
// verify(db).insert(TABLE_NAME, null, hasValue(guid))
// }
//
// @Test
// fun `can update existing item`() {
// // Insert
// val item = InventoryItem(...)
// table.insertItem(db, item)
//
// // Update
// item.qty = 15
// table.updateItem(db, item)
//
// verify(db).update(eq(TABLE_NAME), hasValue(15), any(), any())
// }
//} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/ui/theme/Color.kt | 738418412 | package com.angrypenguin.mikesinventorysystem.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) |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/ui/theme/Theme.kt | 2830503979 | package com.angrypenguin.mikesinventorysystem.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 MikesInventorySystemTheme(
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
)
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/ui/theme/Type.kt | 4192849162 | package com.angrypenguin.mikesinventorysystem.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
)
*/
) |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/MainActivity.kt | 509938589 | package com.angrypenguin.mikesinventorysystem
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.angrypenguin.mikesinventorysystem.components.screens.HomeScreen
import com.angrypenguin.mikesinventorysystem.contracts.DBHelper
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import com.angrypenguin.mikesinventorysystem.ui.theme.MikesInventorySystemTheme
import java.io.File
import java.io.PrintWriter
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!InventoryTable.doesTableExist(db!!)) {
InventoryTable.createTable(db!!)
}
setContent {
MikesInventorySystemTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
HomeScreen(this, ::exportFile);
}
}
}
}
private fun exportFile() {
var items = InventoryTable.getInventory(db!!)
// Get downloads path
val downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
// Create file in downloads folder
val file = File(downloadsPath, "mikeInventorySystem.txt")
// Write text to file
val writer = PrintWriter(file)
for (item in items) {
writer.println(item.toCSVRecord())
}
writer.close()
}
private val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
// Handle the returned uri
if (uri != null) {
val path = uri.path // file path
// Do something with the file
}
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/BaseActivity.kt | 493832665 | package com.angrypenguin.mikesinventorysystem
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import androidx.activity.ComponentActivity
import com.angrypenguin.mikesinventorysystem.contracts.DBHelper
open class BaseActivity : ComponentActivity() {
var db: SQLiteDatabase? = null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val dbHelper = DBHelper(this)
db = dbHelper!!.writableDatabase
}
override fun onDestroy() {
super.onDestroy()
db?.close()
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/contracts/IntentoryContract.kt | 3465622113 | package com.angrypenguin.mikesinventorysystem.contracts
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import java.util.Date
class InventoryTable {
companion object {
const val TABLE_NAME = "INVENTORY"
const val COLUMN_NAME_GUID = "GUID"
const val COLUMN_NAME_BARCODE = "BARCODE"
const val COLUMN_NAME_NAME = "NAME"
const val COLUMN_NAME_QTY = "QTY"
const val COLUMN_NAME_LOCATION = "LOCATION"
const val COLUMN_NAME_DATE = "DATE"
fun createTable(db: SQLiteDatabase) {
val createTableSql = """
CREATE TABLE IF NOT EXISTS $TABLE_NAME (
$COLUMN_NAME_GUID TEXT PRIMARY KEY,
$COLUMN_NAME_BARCODE TEXT,
$COLUMN_NAME_NAME TEXT,
$COLUMN_NAME_QTY INTEGER,
$COLUMN_NAME_LOCATION TEXT,
$COLUMN_NAME_DATE DATETIME
)
""".trimIndent()
db.execSQL(createTableSql)
}
fun doesTableExist(db: SQLiteDatabase): Boolean {
val cursor = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name='$TABLE_NAME'",
null
)
val exists = cursor.count > 0
cursor.close()
return exists
}
fun getItem(db: SQLiteDatabase, guid: String): InventoryItem? {
lateinit var item: InventoryItem
val cursor = db.query(
TABLE_NAME,
null,
"${COLUMN_NAME_GUID} = ?",
arrayOf(guid),
null,
null,
null
)
if (cursor.moveToFirst()) {
item = get_item_from_cursor(cursor)
} else {
return null;
}
cursor.close();
return item;
}
fun searchInventory(db: SQLiteDatabase, query: String): List<InventoryItem> {
val selection = """
$COLUMN_NAME_BARCODE LIKE ?
OR $COLUMN_NAME_NAME LIKE ?
OR $COLUMN_NAME_LOCATION LIKE ?
"""
val selectionArgs = arrayOf(
"%$query%",
"%$query%",
"%$query%"
)
var cursor = db.query(
TABLE_NAME,
null,
selection,
selectionArgs,
null,
null,
null
)
val items = mutableListOf<InventoryItem>()
while (cursor.moveToNext()) {
val item = get_item_from_cursor(cursor)
items.add(item)
}
cursor.close()
return items
}
fun getInventory(db: SQLiteDatabase): List<InventoryItem> {
var cursor = db.query(
TABLE_NAME,
null,
null,
null,
null,
null,
null
)
val items = mutableListOf<InventoryItem>()
while (cursor.moveToNext()) {
val item = get_item_from_cursor(cursor)
items.add(item)
}
cursor.close()
return items
}
fun insertItem(db: SQLiteDatabase, item: InventoryItem) {
val values = ContentValues().apply {
put(COLUMN_NAME_GUID, item.guid)
put(COLUMN_NAME_BARCODE, item.barcode)
put(COLUMN_NAME_NAME, item.name)
put(COLUMN_NAME_QTY, item.qty)
put(COLUMN_NAME_LOCATION, item.location)
put(COLUMN_NAME_DATE, item.date.time)
}
db.insert(TABLE_NAME, null, values)
}
fun updateItem(db: SQLiteDatabase, item: InventoryItem) {
val values = ContentValues().apply {
put(COLUMN_NAME_BARCODE, item.barcode)
put(COLUMN_NAME_NAME, item.name)
put(COLUMN_NAME_QTY, item.qty)
put(COLUMN_NAME_LOCATION, item.location)
put(COLUMN_NAME_DATE, item.date.time)
}
db.update(TABLE_NAME, values, "$COLUMN_NAME_GUID = ?", arrayOf(item.guid))
}
fun deleteItem(db: SQLiteDatabase, item: InventoryItem) {
db.delete(TABLE_NAME, "$COLUMN_NAME_GUID = ?", arrayOf(item.guid))
}
private fun get_item_from_cursor(cursor: Cursor) : InventoryItem {
return InventoryItem(
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME_GUID)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME_BARCODE)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME_NAME)),
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_NAME_QTY)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME_LOCATION)),
Date(cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_NAME_DATE)))
)
}
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/contracts/MyDBHelper.kt | 1448238636 | package com.angrypenguin.mikesinventorysystem.contracts
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
const val DB_NAME = "MikesInventorySystem"
const val DB_VERSION = 1
class DBHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
override fun onCreate(db: SQLiteDatabase) {}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/AddNewItemActivity.kt | 303237493 | package com.angrypenguin.mikesinventorysystem
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.angrypenguin.mikesinventorysystem.components.screens.AddNewItem
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.models.InventoryItemModel
import com.angrypenguin.mikesinventorysystem.ui.theme.MikesInventorySystemTheme
class AddNewItemActivity : BaseActivity() {
private val viewModel: InventoryItemModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var guid = intent.getStringExtra("guid")
var from_search = intent.getBooleanExtra("from_search", false)
if (guid != null) {
viewModel.setGuid(guid)
var item = InventoryTable.getItem(db!!, guid!!)
if (item != null) {
viewModel.barcode.value = item.barcode
viewModel.name.value = item.name
viewModel.location.value = item.location
viewModel.date.value = item.date
viewModel.qty.value = item.qty
}
}
setContent {
MikesInventorySystemTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
AddNewItem(this, guid, from_search, viewModel)
}
}
}
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/models/InventoryListModel.kt | 2295577974 | package com.angrypenguin.mikesinventorysystem.models
import android.database.sqlite.SQLiteDatabase
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
class InventoryListModel : ViewModel() {
var list = MutableLiveData<MutableList<InventoryItem>>(mutableListOf())
var input = "";
fun updateList(db: SQLiteDatabase, input: String) {
this.input = input
list.value = InventoryTable.searchInventory(db, input).toMutableList()
}
fun updateList(db:SQLiteDatabase) {
list.value = InventoryTable.searchInventory(db, input).toMutableList()
}
fun deleteItem(db: SQLiteDatabase, item: InventoryItem) {
InventoryTable.deleteItem(db, item)
updateList(db)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/models/InventoryItemModel.kt | 1236621065 | package com.angrypenguin.mikesinventorysystem.models
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import java.util.Date
class InventoryItemModel : ViewModel() {
private var guid: String? = null;
var barcode = MutableLiveData("")
var name = MutableLiveData("")
var qty = MutableLiveData(1)
var location = MutableLiveData("")
var date = MutableLiveData(Date())
fun setGuid(guid: String) {
this.guid = guid;
}
fun getInventoryItem(): InventoryItem {
if (guid != null) {
return InventoryItem(
guid!!,
barcode.value!!,
name.value!!,
qty.value!!,
location.value!!,
date.value!!
)
}
return InventoryItem(
barcode.value!!,
name.value!!,
qty.value!!,
location.value!!,
date.value!!
)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/SearchActivity.kt | 2784392400 | package com.angrypenguin.mikesinventorysystem
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import com.angrypenguin.mikesinventorysystem.components.screens.SearchScreen
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import com.angrypenguin.mikesinventorysystem.models.InventoryItemModel
import com.angrypenguin.mikesinventorysystem.models.InventoryListModel
import com.angrypenguin.mikesinventorysystem.ui.theme.MikesInventorySystemTheme
class SearchActivity : BaseActivity() {
private val viewModel: InventoryListModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var searchBar = intent.getBooleanExtra("SEARCH_BAR", true)
setContent {
MikesInventorySystemTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
SearchScreen(db!!, viewModel, ::deleteItem, searchBar)
}
}
}
}
override fun onResume() {
super.onResume()
viewModel.updateList(db!!)
}
private fun deleteItem(item: InventoryItem) {
viewModel.deleteItem(db!!, item)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/components/screens/HomeScreen.kt | 2398942848 | package com.angrypenguin.mikesinventorysystem.components.screens
import android.content.Context
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.angrypenguin.mikesinventorysystem.AddNewItemActivity
import com.angrypenguin.mikesinventorysystem.SearchActivity
@Composable
fun HomeScreen(context: Context, exportFile: () -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = {
val intent = Intent(context, AddNewItemActivity::class.java)
context.startActivity(intent)
},
content = {
Text (text = "Add New Items")
},
modifier = Modifier
.fillMaxWidth(1F)
.align(Alignment.CenterHorizontally)
.padding(8.dp)
)
Button(
onClick = {
val intent = Intent(context, SearchActivity::class.java)
context.startActivity(intent)
},
content = {
Text (text = "Search")
},
modifier = Modifier
.fillMaxWidth(1F)
.align(Alignment.CenterHorizontally)
.padding(8.dp)
)
Button(
onClick = {
val intent = Intent(context, SearchActivity::class.java)
intent.putExtra("SEARCH_BAR", false)
context.startActivity(intent)
},
content = {
Text (text = "View All")
},
modifier = Modifier
.fillMaxWidth(1F)
.align(Alignment.CenterHorizontally)
.padding(8.dp)
)
Button(
onClick = {
exportFile()
},
content = {
Text (text = "Export")
},
modifier = Modifier
.fillMaxWidth(1F)
.align(Alignment.CenterHorizontally)
.padding(8.dp)
)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/components/screens/SearchScreen.kt | 790400947 | package com.angrypenguin.mikesinventorysystem.components.screens
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.graphics.drawable.Icon
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.angrypenguin.mikesinventorysystem.AddNewItemActivity
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import com.angrypenguin.mikesinventorysystem.models.InventoryListModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(db: SQLiteDatabase,
viewModel: InventoryListModel,
deleteItem: (item: InventoryItem) -> Unit,
searchBar: Boolean) {
var context = LocalContext.current
var input by remember { mutableStateOf("") }
val items by viewModel.list.observeAsState()
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
if (searchBar) {
Row() {
OutlinedTextField(
label = {
Text(
text = "Search"
)
},
value = input,
onValueChange = {
input = it
viewModel.updateList(db, input)
}
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(15.dp)
.clickable {
val intent = Intent(context, AddNewItemActivity::class.java)
intent.putExtra("from_search", true)
context.startActivity(intent)
}
) {
Icon(
Icons.Default.Add,
contentDescription = "Add New Item",
modifier = Modifier
.background(Color.LightGray, RoundedCornerShape(8.dp))
.padding(10.dp)
)
}
}
}
ListInventoryScreen(items = items!!, deleteItem)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/components/screens/AddNewItem.kt | 176532236 | package com.angrypenguin.mikesinventorysystem.components.screens
import android.content.Context
import android.content.Intent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
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.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.angrypenguin.mikesinventorysystem.AddNewItemActivity
import com.angrypenguin.mikesinventorysystem.BaseActivity
import com.angrypenguin.mikesinventorysystem.contracts.InventoryTable
import com.angrypenguin.mikesinventorysystem.models.InventoryItemModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddNewItem(context: Context, guid: String?, from_search: Boolean, viewModel: InventoryItemModel) {
var activity = LocalContext.current as BaseActivity
val barcode by viewModel.barcode.observeAsState("")
val name by viewModel.name.observeAsState("")
var qtyString by remember { mutableStateOf("")}
val location by viewModel.location.observeAsState("")
val date by viewModel.date.observeAsState(initial = Date())
val formatter = SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH)
var dateString by remember { mutableStateOf(formatter.format(date)) }
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
label = {
Text (
text = "Barcode"
)
},
value = barcode,
onValueChange = {
viewModel.barcode.value = it
}
)
OutlinedTextField(
label = {
Text (
text = "Name"
)
},
value = name,
onValueChange = {
viewModel.name.value = it
}
)
OutlinedTextField(
label = {
Text (
text = "Quantity"
)
},
value = qtyString,
onValueChange = {
qtyString = it
try {
viewModel.qty.value = it.toInt()
} catch (e: Exception){
//do nothing
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
label = {
Text (
text = "Location"
)
},
value = location,
onValueChange = {
viewModel.location.value = it
}
)
OutlinedTextField(
value = dateString,
label = {
Text (
text = "Date"
)
},
onValueChange = {
try {
dateString = it
viewModel.date.value = formatter.parse(dateString)
} catch (e: Exception) {
}
}
)
Button(
onClick = {
activity?.db?.let {
var item = viewModel.getInventoryItem()
if (guid == null) {
InventoryTable.insertItem(it,item)
if (!from_search) {
val intent = Intent(context, AddNewItemActivity::class.java)
context.startActivity(intent)
}
} else {
InventoryTable.updateItem(it, item)
}
}
activity?.finish();
},
content = {
Text (text = "Save")
},
modifier = Modifier
.fillMaxWidth(1F)
.align(Alignment.CenterHorizontally)
.padding(8.dp)
)
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/components/screens/ListInventoryScreen.kt | 264058255 | package com.angrypenguin.mikesinventorysystem.components.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.angrypenguin.mikesinventorysystem.components.listitems.InventoryListItem
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
@Composable
fun ListInventoryScreen(items: List<InventoryItem>, deleteItem: (item: InventoryItem) -> Unit) {
Column(
modifier = Modifier.padding(10.dp)
) {
Text(
text = "Inventory List:",
style = TextStyle(
fontSize = 18.sp
)
)
LazyColumn() {
items(items = items) { item ->
InventoryListItem(item = item, deleteItem)
}
}
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/components/listitems/InventoryListItem.kt | 4248096691 | package com.angrypenguin.mikesinventorysystem.components.listitems
import android.content.Intent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.angrypenguin.mikesinventorysystem.AddNewItemActivity
import com.angrypenguin.mikesinventorysystem.data.InventoryItem
import java.text.SimpleDateFormat
import java.util.Locale
@Composable
fun InventoryListItem(item: InventoryItem, deleteItem: (item: InventoryItem) -> Unit) {
val context = LocalContext.current
Column(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp)
.border(BorderStroke(1.5.dp, Color.Black), RoundedCornerShape(10.dp))
.padding(10.dp)
.clickable {
val intent = Intent(context, AddNewItemActivity::class.java)
intent.putExtra("guid", item.guid);
context.startActivity(intent)
},
) {
Row() {
Text(
text = item.name,
modifier = Modifier.weight(1f)
)
Text(
text = "Qty: ${item.qty}"
)
}
Row() {
Box(
Modifier.weight(1f)
) {
Text(
text = item.location
)
}
Text(
text = item.barcode
)
}
Row() {
Box(
Modifier.weight(1f)
) {
val formatter = SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH)
Text(
text = formatter.format(item.date)
)
}
Box(
Modifier.weight(1f)
) {
Icon(
Icons.Default.Delete,
contentDescription = "Delete Item",
modifier = Modifier
.background(Color.LightGray, RoundedCornerShape(8.dp))
.padding(10.dp)
.clickable{
deleteItem(item)
}
)
}
}
}
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/data/State.kt | 2479503127 | package com.angrypenguin.mikesinventorysystem.data
enum class State {
HomeScreen,
AddNewItem,
} |
MikesInventoryList/app/src/main/java/com/angrypenguin/mikesinventorysystem/data/InventoryItem.kt | 4130651348 | package com.angrypenguin.mikesinventorysystem.data
import java.util.Date
import java.util.UUID
class InventoryItem {
var guid: String = UUID.randomUUID().toString()
var barcode: String = ""
var name: String = ""
var qty: Int = 1
var location: String = ""
var date: Date = Date()
constructor()
constructor(
barcode: String,
name: String,
qty: Int = 1,
location: String = "",
date: Date = Date()
) {
this.barcode = barcode
this.name = name
this.qty = qty
this.location = location
this.date = date
}
constructor(
guid: String,
barcode: String,
name: String,
qty: Int = 1,
location: String = "",
date: Date = Date()
) {
this.guid = guid
this.barcode = barcode
this.name = name
this.qty = qty
this.location = location
this.date = date
}
fun toCSVRecord() : String {
return "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\""
.format(
guid,
barcode,
name,
qty,
location,
date
)
}
} |
e-commerce-android-app-with-Kotlin/app/src/androidTest/java/com/example/firebasegroupapp1/ExampleInstrumentedTest.kt | 27666528 | package com.example.firebasegroupapp1
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.firebasegroupapp1", appContext.packageName)
}
} |
e-commerce-android-app-with-Kotlin/app/src/test/java/com/example/firebasegroupapp1/ExampleUnitTest.kt | 3789899055 | package com.example.firebasegroupapp1
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)
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/Product.kt | 499895552 | package com.example.firebasegroupapp1
data class Product (
var name: String = "",
var price: Double = 0.0,
var image: String = "",
var description: String = ""
) |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/ProductActivity.kt | 2684098120 | package com.example.firebasegroupapp1
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.android.material.appbar.MaterialToolbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class ProductActivity : AppCompatActivity() {
private lateinit var adapter: ProductAdapter
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_product)
val topAppBar: MaterialToolbar = findViewById(R.id.top_app_bar)
setSupportActionBar(topAppBar)
supportActionBar?.title = "Products"
auth = FirebaseAuth.getInstance()
val query = FirebaseDatabase.getInstance().reference.child("Products")
val options = FirebaseRecyclerOptions.Builder<Product>().setQuery(query, Product::class.java).build()
adapter = ProductAdapter(options)
val productsRecyclerView: RecyclerView = findViewById(R.id.productsRecyclerView)
productsRecyclerView.adapter = adapter
val layoutManager = if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
GridLayoutManager(this, 3)
} else {
GridLayoutManager(this, 2)
}
productsRecyclerView.layoutManager = layoutManager
val logoutButton: ImageView = findViewById(R.id.logoutButton)
logoutButton.setOnClickListener {
FirebaseAuth.getInstance().signOut()
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_products -> {
true
}
R.id.action_orders -> {
startActivity(Intent(this, OrderActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/OrderAdapter.kt | 299996320 | package com.example.firebasegroupapp1
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.firebase.ui.database.FirebaseRecyclerAdapter
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.firebase.storage.FirebaseStorage
class OrderAdapter(options: FirebaseRecyclerOptions<Order>)
: FirebaseRecyclerAdapter<Order, OrderAdapter.OrderViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder {
val inflater = LayoutInflater.from(parent.context)
return OrderViewHolder(inflater, parent)
}
override fun onBindViewHolder(holder: OrderViewHolder, position: Int, model: Order) {
holder.fullNameTextView.text = model.fullName
holder.productNameTextView.text = model.productName
holder.quantityTextView.text = model.quantity.toString()
holder.totalPriceTextView.text = "$" + model.totalPrice.toString()
holder.addressTextView.text = model.address
val theImage: String = model.productImage
if (theImage.indexOf("gs://") >-1) {
val storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(theImage)
Glide.with(holder.productImageView.context)
.load(storageReference)
.into(holder.productImageView)
} else {
Glide.with(holder.productImageView.context)
.load(theImage)
.into(holder.productImageView)
}
}
class OrderViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
RecyclerView.ViewHolder(inflater.inflate(R.layout.order_item, parent, false)) {
val fullNameTextView: TextView = itemView.findViewById(R.id.fullNameTextView)
val productNameTextView: TextView = itemView.findViewById(R.id.productNameTextView)
val quantityTextView: TextView = itemView.findViewById(R.id.quantityTextView)
val totalPriceTextView: TextView = itemView.findViewById(R.id.totalPriceTextView)
val addressTextView: TextView = itemView.findViewById(R.id.addressTextView)
val productImageView: ImageView = itemView.findViewById(R.id.productImageView)
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/MainActivity.kt | 3222537099 | package com.example.firebasegroupapp1
import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import com.example.firebasegroupapp1.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.FirebaseUiUserCollisionException
import com.firebase.ui.auth.FirebaseAuthUIActivityResultContract
import com.firebase.ui.auth.data.model.FirebaseAuthUIAuthenticationResult
import com.google.firebase.auth.FirebaseUser
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser
if (currentUser == null) {
createSignInIntent()
} else {
loadUIDesign(currentUser)
}
}
private fun createSignInIntent() {
val providers = arrayListOf(AuthUI.IdpConfig.EmailBuilder().build())
val signInIntent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.build()
signInLauncher.launch(signInIntent)
}
private val signInLauncher = registerForActivityResult(FirebaseAuthUIActivityResultContract()) { result ->
this.onSignInResult(result)
}
private fun onSignInResult(result: FirebaseAuthUIAuthenticationResult) {
if (result.resultCode == RESULT_OK) {
val user = FirebaseAuth.getInstance().currentUser
user?.let { loadUIDesign(it) }
} else {
createSignInIntent()
}
}
private fun loadUIDesign(user: FirebaseUser) {
setContentView(R.layout.activity_main)
val fullName = user.displayName
val fullNameTextView = findViewById<TextView>(R.id.fullNameTextView)
fullNameTextView.text = fullName
val shopButton: Button = findViewById(R.id.shop_button)
shopButton.setOnClickListener {
startActivity(Intent(this, ProductActivity::class.java))
}
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/ProductDetailActivity.kt | 2420022923 | package com.example.firebasegroupapp1
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.bumptech.glide.Glide
import android.view.MenuItem
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.auth.FirebaseAuth
class ProductDetailActivity : AppCompatActivity() {
private var quantity: Int = 1
private lateinit var txtQuantity: TextView
private lateinit var topAppBar: Toolbar
var productImage : String? = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_product_detail)
topAppBar = findViewById(R.id.top_app_bar)
setSupportActionBar(topAppBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "Product Detail"
val productName = intent.getStringExtra("productName")
val productPrice = intent.getDoubleExtra("productPrice", 0.0)
productImage = intent.getStringExtra("productImage")
val productDescription = intent.getStringExtra("productDescription")
val txtProductName: TextView = findViewById(R.id.txtProductName)
val txtProductPrice: TextView = findViewById(R.id.txtProductPrice)
val txtProductDescription: TextView = findViewById(R.id.txtProductDescription)
val productImageView: ImageView = findViewById(R.id.productImageView)
var totalPrice = roundToTwoDecimalPlaces(productPrice)
txtProductName.text = " $productName"
txtProductPrice.text = "Price: $$totalPrice"
txtProductDescription.text = "$productDescription"
txtQuantity = findViewById(R.id.txtQuantity)
txtQuantity.text = quantity.toString()
val theImage: String = productImage ?: ""
if (theImage.indexOf("gs://") > -1) {
val storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(theImage)
Glide.with(this)
.load(storageReference)
.into(productImageView)
} else {
Glide.with(this)
.load(theImage)
.into(productImageView)
}
val btnPlus: Button = findViewById(R.id.btnPlus)
val btnMinus: Button = findViewById(R.id.btnMinus)
btnPlus.setOnClickListener {
incrementQuantity()
}
btnMinus.setOnClickListener {
decrementQuantity()
}
val btnCheckout: Button = findViewById(R.id.btnCheckout)
btnCheckout.setOnClickListener {
checkout(productName, quantity, productPrice, productImage)
}
}
fun roundToTwoDecimalPlaces(number: Double): Double {
return "%.2f".format(number).toDouble()
}
private fun incrementQuantity() {
if (quantity < 10) {
quantity++
updateQuantityTextView()
} else {
showToast("Maximum quantity reached")
}
}
private fun decrementQuantity() {
if (quantity > 1) {
quantity--
updateQuantityTextView()
} else {
showToast("Minimum quantity reached")
}
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
private fun updateQuantityTextView() {
txtQuantity.text = quantity.toString()
}
private fun checkout(productName: String?, quantity: Int, productPrice: Double, productImage: String?) {
val totalPrice = roundToTwoDecimalPlaces(quantity * productPrice)
val intent = Intent(this, CheckoutActivity::class.java).apply {
putExtra("productName", productName)
putExtra("quantity", quantity)
putExtra("totalPrice", totalPrice)
putExtra("productImage", productImage)
putExtra("fullName", FirebaseAuth.getInstance().currentUser?.displayName)
}
startActivity(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
super.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/OrderActivity.kt | 2484427034 | package com.example.firebasegroupapp1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.view.Menu
import android.widget.Toast
import android.widget.ImageView
import android.widget.TextView
import android.view.MenuItem
import android.content.res.Configuration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.appbar.MaterialToolbar
import com.google.firebase.database.FirebaseDatabase
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
class OrderActivity : AppCompatActivity() {
private lateinit var adapter: OrderAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_order)
val topAppBar: MaterialToolbar = findViewById(R.id.top_app_bar)
setSupportActionBar(topAppBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "Orders"
val currentUser = FirebaseAuth.getInstance().currentUser
val uid = currentUser?.uid ?: ""
val query = FirebaseDatabase.getInstance().reference.child("Orders").child(uid)
val options = FirebaseRecyclerOptions.Builder<Order>().setQuery(query, Order::class.java).build()
adapter = OrderAdapter(options)
val ordersRecyclerView: RecyclerView = findViewById(R.id.ordersRecyclerView)
val layoutManager = if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
GridLayoutManager(this, 2)
} else {
LinearLayoutManager(this)
}
ordersRecyclerView.layoutManager = layoutManager
ordersRecyclerView.adapter = adapter
val removeAllButton: Button = findViewById(R.id.removeAllButton)
removeAllButton.setOnClickListener {
removeOrdersFromDatabase(uid)
}
}
private fun removeOrdersFromDatabase(uid: String) {
val ordersRef = FirebaseDatabase.getInstance().reference.child("Orders").child(uid)
ordersRef.removeValue().addOnCompleteListener { task ->
if (task.isSuccessful) {
adapter.notifyDataSetChanged()
Toast.makeText(this, "All orders removed successfully", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Failed to remove orders", Toast.LENGTH_SHORT).show()
}
}
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_products -> {
startActivity(Intent(this, ProductActivity::class.java))
true
}
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/CheckoutActivity.kt | 3912609961 | package com.example.firebasegroupapp1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class CheckoutActivity : AppCompatActivity() {
private lateinit var topAppBar: Toolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_checkout)
topAppBar = findViewById(R.id.topAppBar)
setSupportActionBar(topAppBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = "Checkout"
val productName = intent.getStringExtra("productName")
val quantity = intent.getIntExtra("quantity", 0)
val totalPrice = intent.getDoubleExtra("totalPrice", 0.0)
val totalPriceFormatted = roundToTwoDecimalPlaces(totalPrice)
val txtProductName: TextView = findViewById(R.id.txtProductName)
val txtQuantity: TextView = findViewById(R.id.txtQuantity)
val txtTotalPrice: TextView = findViewById(R.id.txtTotalPrice)
txtProductName.text = "Product Name: $productName"
txtQuantity.text = "Quantity: $quantity"
txtTotalPrice.text = "Total Price: $$totalPriceFormatted"
val currentUser = FirebaseAuth.getInstance().currentUser
val fullName = currentUser?.displayName
val email = currentUser?.email
val etFullName: EditText = findViewById(R.id.etFullName)
etFullName.setText(fullName)
val btnPlaceOrder: Button = findViewById(R.id.btnPlaceOrder)
val etPhoneNumber: EditText = findViewById(R.id.etPhoneNumber)
val etAddress: EditText = findViewById(R.id.etAddress)
val etCity: EditText = findViewById(R.id.etCity)
val etProvince: EditText = findViewById(R.id.etProvince)
val etPostalCode: EditText = findViewById(R.id.etPostalCode)
val etCardHolderName: EditText = findViewById(R.id.etCardHolderName)
val etCardNumber: EditText = findViewById(R.id.etCardNumber)
val etSecurityCode: EditText = findViewById(R.id.etSecurityCode)
val etValidUntil: EditText = findViewById(R.id.etValidUntil)
btnPlaceOrder.setOnClickListener {
val phoneNumber = etPhoneNumber.text.toString()
val address = etAddress.text.toString()
val city = etCity.text.toString()
val province = etProvince.text.toString()
val postalCode = etPostalCode.text.toString()
val cardHolderName = etCardHolderName.text.toString()
val cardNumber = etCardNumber.text.toString()
val securityCode = etSecurityCode.text.toString()
val validUntil = etValidUntil.text.toString()
val validationErrors = mutableListOf<Pair<EditText, String>>()
val nameRegex = Regex("^[a-zA-Z ]+\$")
val phoneRegex = Regex("^[0-9]{10}\$")
val cityRegex = Regex("^[a-zA-Z.,\\- ]+\$")
val provinceRegex = Regex("^[a-zA-Z]+\$")
val postalCodeRegex = Regex("^[a-zA-Z0-9]{6}\$")
val cardNumberRegex = Regex("^[0-9]{16}\$")
val securityCodeRegex = Regex("^[0-9]{3}\$")
val validUntilRegex = Regex("^[0-9]{4}\$")
if (!phoneNumber.matches(phoneRegex)) {
validationErrors.add(Pair(etPhoneNumber, "Invalid phone number"))
}
if (address.isBlank()) {
validationErrors.add(Pair(etAddress, "Address cannot be empty"))
}
if (!city.matches(cityRegex)) {
validationErrors.add(Pair(etCity, "Invalid city"))
}
if (!province.matches(provinceRegex)) {
validationErrors.add(Pair(etProvince, "Invalid province"))
}
if (!postalCode.matches(postalCodeRegex)) {
validationErrors.add(Pair(etPostalCode, "Invalid postal code"))
}
if (!cardHolderName.matches(nameRegex)) {
validationErrors.add(Pair(etCardHolderName, "Invalid card holder name"))
}
if (!cardNumber.matches(cardNumberRegex)) {
validationErrors.add(Pair(etCardNumber, "Invalid card number"))
}
if (!securityCode.matches(securityCodeRegex)) {
validationErrors.add(Pair(etSecurityCode, "Invalid security code"))
}
if (!validUntil.matches(validUntilRegex)) {
validationErrors.add(Pair(etValidUntil, "Invalid valid until"))
}
validationErrors.forEach { (editText, errorMessage) ->
editText.error = errorMessage
}
if (validationErrors.isNotEmpty()) {
return@setOnClickListener
}
val order = Order(
fullName = fullName,
email = email,
quantity = quantity,
productName = productName,
phoneNumber = phoneNumber,
totalPrice = totalPrice,
address = address,
city = city,
province = province,
postalCode = postalCode,
cardHolderName = cardHolderName,
cardNumber = cardNumber,
securityCode = securityCode,
validUntil = validUntil,
productImage = intent.getStringExtra("productImage") ?: ""
)
saveOrder(order)
}
}
private fun saveOrder(order: Order) {
val currentUser = FirebaseAuth.getInstance().currentUser
val uid = currentUser?.uid
if (uid != null) {
val roundedTotalPrice = roundToTwoDecimalPlaces(order.totalPrice)
order.totalPrice = roundedTotalPrice
FirebaseDatabase.getInstance().reference.child("Orders/$uid").push().setValue(order).addOnSuccessListener {
Toast.makeText(this, "Order placed successfully!", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, OrderActivity::class.java))
finish()
}
.addOnFailureListener {
Toast.makeText(this, "Failed to place order: ${it.message}", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "User not authenticated", Toast.LENGTH_SHORT).show()
}
}
fun roundToTwoDecimalPlaces(number: Double): Double {
return "%.2f".format(number).toDouble()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
super.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/ProductAdapter.kt | 4048909337 | package com.example.firebasegroupapp1
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.firebase.ui.database.FirebaseRecyclerAdapter
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
class ProductAdapter(options: FirebaseRecyclerOptions<Product>)
: FirebaseRecyclerAdapter<Product, ProductAdapter.ProductViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ProductViewHolder(inflater, parent)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int, model: Product) {
holder.productNameTextView.text = model.name
holder.productPriceTextView.text = "$" + model.price.toString()
val theImage: String = model.image
if (theImage.indexOf("gs://") >-1) {
val storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(theImage)
Glide.with(holder.productImageView.context)
.load(storageReference)
.into(holder.productImageView)
} else {
Glide.with(holder.productImageView.context)
.load(theImage)
.into(holder.productImageView)
}
holder.itemView.setOnClickListener {
val intent = Intent(holder.itemView.context, ProductDetailActivity::class.java).apply {
putExtra("productName", model.name)
putExtra("productPrice", model.price)
putExtra("productImage", model.image)
putExtra("productDescription", model.description)
}
holder.itemView.context.startActivity(intent)
}
}
class ProductViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
RecyclerView.ViewHolder(inflater.inflate(R.layout.item_product, parent, false)) {
val productNameTextView: TextView = itemView.findViewById(R.id.productNameTextView)
val productPriceTextView: TextView = itemView.findViewById(R.id.productPriceTextView)
val productImageView: ImageView = itemView.findViewById(R.id.productImageView)
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/MyAppGlideModule.kt | 2646647544 | package com.example.firebasegroupapp1
import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
import com.firebase.ui.storage.images.FirebaseImageLoader
import com.google.firebase.storage.StorageReference
import java.io.InputStream
@GlideModule
class MyAppGlideModule: AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
//super.registerComponents(context, glide, registry)
registry.append(
StorageReference::class.java,
InputStream::class.java,
FirebaseImageLoader.Factory()
)
}
} |
e-commerce-android-app-with-Kotlin/app/src/main/java/com/example/firebasegroupapp1/Order.kt | 4279151207 | package com.example.firebasegroupapp1
data class Order(
var fullName: String? = null,
var email: String? = null,
var productName: String? = null,
var quantity: Int = 0,
var totalPrice: Double = 0.0,
var address: String = "",
var city: String = "",
var province: String = "",
var postalCode: String = "",
var cardHolderName: String = "",
var cardNumber: String = "",
var securityCode: String = "",
var validUntil: String = "",
var phoneNumber: String = "",
var productImage: String = ""
) |
nastart_android_app/app/src/androidTest/java/com/example/nastartapplication/ExampleInstrumentedTest.kt | 2899044486 | package com.example.nastartapplication
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.nastartapplication", appContext.packageName)
}
} |
nastart_android_app/app/src/test/java/com/example/nastartapplication/ExampleUnitTest.kt | 2344948806 | package com.example.nastartapplication
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)
}
} |
nastart_android_app/app/src/main/java/com/example/nastartapplication/ui/theme/Color.kt | 2694527405 | package com.example.nastartapplication.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) |
nastart_android_app/app/src/main/java/com/example/nastartapplication/ui/theme/Theme.kt | 2892000704 | package com.example.nastartapplication.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 NastartApplicationTheme(
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
)
} |
nastart_android_app/app/src/main/java/com/example/nastartapplication/ui/theme/Type.kt | 4059735394 | package com.example.nastartapplication.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.nastartapplication.R
val themeFontFamily = FontFamily(
Font(R.font.inter, FontWeight.Light),
Font(R.font.inter, FontWeight.Normal),
Font(R.font.inter, FontWeight.Bold)
)
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = themeFontFamily,
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
)
*/
) |
nastart_android_app/app/src/main/java/com/example/nastartapplication/WebSocketClient.kt | 74493499 | package com.example.nastartapplication
import Order
import io.ktor.client.HttpClient
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.http.HttpMethod
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.delay
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
class WebSocketClient(private val onOrderReceived: (Order) -> Unit) {
private val client = HttpClient {
install(WebSockets)
}
suspend fun connect() {
while (true) {
try {
client.webSocket(method = HttpMethod.Get, host = "c501-171-33-254-209.ngrok-free.app", path = "/ws?client=abcde") {
incoming.consumeEach { frame ->
if (frame is Frame.Text) {
val orders: List<Order> = Json.decodeFromString(frame.readText())
orders.forEach { onOrderReceived(it) }
}
}
}
break
} catch (e: Exception) {
delay(100)
}
}
}
} |
nastart_android_app/app/src/main/java/com/example/nastartapplication/MainActivity.kt | 3397506441 | package com.example.nastartapplication
import Order
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.RowScope
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.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.nastartapplication.ui.theme.NastartApplicationTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
private val Context.dataStore by preferencesDataStore("settings")
@Serializable
data class AuthResponse(
@SerialName("isAuth")
val isAuth: Boolean
)
class MainActivity : ComponentActivity() {
private val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startService(Intent(this, WebSocketService::class.java))
val authKey = stringPreferencesKey("auth")
setContent {
val authFlow: Flow<String?> = dataStore.data.map { preferences ->
preferences[authKey]
}
val coroutineScope = rememberCoroutineScope()
val authState by authFlow.collectAsState(initial = false)
NastartApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val isAuthorized = remember { mutableStateOf(false) }
Column {
Header(isAuthorized)
if (!isAuthorized.value) {
LoginForm(onLoginClick = { token ->
coroutineScope.launch {
checkAuthToken(token, onResult = { isValid ->
if (isValid) {
coroutineScope.launch {
storeAuthKey(token)
}
}
}, isAuthorized = isAuthorized)
}
}, isAuthorized = isAuthorized)
} else {
MainScreen()
}
}
}
}
}
}
private suspend fun storeAuthKey(token: String) {
dataStore.edit { preferences ->
preferences[stringPreferencesKey("auth")] = token
}
}
private suspend fun checkAuthToken(token: String, onResult: (Boolean) -> Unit, isAuthorized: MutableState<Boolean>) {
withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("https://c501-171-33-254-209.ngrok-free.app/auth?token=$token")
.build()
client.newCall(request).execute().use { response ->
val body = response.body?.string()
val authResponse = body?.let { Json.decodeFromString<AuthResponse>(it) }
withContext(Dispatchers.Main) {
val isValid = authResponse?.isAuth ?: false
onResult(isValid)
if (isValid) {
isAuthorized.value = true
}
}
}
}
}
}
@Composable
fun MainScreen() {
var currentOrder by remember { mutableStateOf<Order?>(null) }
var isMainViewActive by remember { mutableStateOf(true) }
val orders = remember { mutableStateListOf<Order>() }
LaunchedEffect(Unit) {
val webSocketClient = WebSocketClient { order: Order ->
orders.add(order)
}
webSocketClient.connect()
}
ActiveCompletedSwitcher { isMainViewActive = !isMainViewActive; currentOrder = null }
if (currentOrder == null) {
MainView(orders, onOrderClick = { order ->
currentOrder = order
isMainViewActive = false
})
} else {
OrderView(currentOrder!!) {
currentOrder = null
isMainViewActive = true
}
}
}
@Composable
fun MainView(orders: MutableList<Order>, onOrderClick: (Order) -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
for (order in orders) {
BuildOrderButton(order, onOrderClick)
}
}
}
@Composable
fun OrderView(order: Order, onBackClick: () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = 12.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.width(360.dp)
.height(480.dp)
.clip(RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp))
.border(
2.dp,
Color.Black.copy(alpha = 0.3f),
RoundedCornerShape(topStart = 15.dp, topEnd = 15.dp)
)
) {
Text(
text = order.invoice.createdTime,
fontSize = 18.sp,
modifier = Modifier
.align(Alignment.TopCenter)
.padding(top = 4.dp)
)
val nameColumn = .60f // 60%
val quantityColumn = .15f // 15%
val priceColumn = .25f // 25%
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(
top = 34.dp,
start = 12.dp,
end = 12.dp
),
userScrollEnabled = true) {
item {
Row(
Modifier
.background(colorResource(id = R.color.secondary))) {
TableCell(text = "Наименование", weight = nameColumn)
TableCell(text = "x", weight = quantityColumn)
TableCell(text = "Сумма", weight = priceColumn)
}
}
for (product in order.invoice.products) {
item {
Row {
Row(Modifier.fillMaxWidth()) {
TableCell(text = product.title, weight = nameColumn)
TableCell(text = product.quantity.toString(), weight = quantityColumn)
TableCell(text = (product.price * product.quantity).toString(), weight = priceColumn)
}
}
}
}
item {
Row(
Modifier
.background(colorResource(id = R.color.secondary))) {
TableCell(text = "Итого", weight = 0.6f)
TableCell(text = order.invoice.price.toString() + " руб.", weight = 0.4f)
}
Row(Modifier.padding(bottom = 34.dp)) {}
}
}
val context = LocalContext.current
val webView = remember {
WebView(context).apply {
webViewClient = WebViewClient()
settings.javaScriptEnabled = true
loadDataWithBaseURL(
null,
"""
<!DOCTYPE html>
<html>
<head>
<title>Быстрый старт. Размещение интерактивной карты на странице</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://api-maps.yandex.ru/2.1/?apikey=bb3bf806-ea2f-4b74-87a7-d81b10882d76&lang=ru_RU"></script>
<script>
ymaps.ready(init);
function init() {
var myMap = new ymaps.Map("map", {
center: ${order.delivery.coords},
zoom: 14
});
var myPlacemark = new ymaps.Placemark(${order.delivery.coords}, {}, {
iconLayout: 'default#image',
iconImageHref: 'https://cdn4.iconfinder.com/data/icons/small-n-flat/24/map-marker-512.png',
iconImageSize: [30, 42],
iconImageOffset: [-3, -42]
});
myMap.geoObjects.add(myPlacemark);
}
</script>
</head>
<body>
<div id="map" style="width: 500px; height: 250px"></div>
</body>
</html>
""",
"text/html",
"UTF-8",
null
)
}
}
AndroidView({ webView },
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(top = 10.dp)
.align(Alignment.BottomCenter)) { webView ->
// Update WebView in here if necessary
}
}
Button(
onClick = {},
modifier = Modifier
.width(360.dp)
.height(80.dp)
.shadow(
elevation = 4.dp,
spotColor = Color.Black,
shape = RoundedCornerShape(bottomStart = 15.dp, bottomEnd = 15.dp)
),
colors = ButtonDefaults.buttonColors(
containerColor = colorResource(id = R.color.primary),
contentColor = colorResource(id = R.color.main_black)
),
shape = RoundedCornerShape(bottomStart = 15.dp, bottomEnd = 15.dp),
) {
Text(
text = "Отправить в доставку"
)
}
}
}
@Composable
fun RowScope.TableCell(
text: String,
weight: Float
) {
Text(
text = text,
Modifier
.border(1.dp, Color.Black.copy(alpha = 0.1f))
.weight(weight)
.padding(4.dp)
)
}
@Composable
fun BuildOrderButton(order: Order, onOrderClick: (Order) -> Unit) {
Button(
onClick = { onOrderClick(order) },
modifier = Modifier
.padding(
top = 12.dp,
bottom = 12.dp
)
.width(360.dp)
.height(160.dp)
.border(1.dp, Color.Black.copy(alpha = 0.1f), RoundedCornerShape(15.dp))
.shadow(
elevation = 8.dp,
spotColor = Color.Black,
shape = RoundedCornerShape(15.dp)
),
shape = RoundedCornerShape(15.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color.White,
contentColor = colorResource(id = R.color.main_black)
)
) {
Box(
modifier = Modifier.fillMaxSize()
) {
Text(
text = order.invoice.createdTime,
fontSize = 18.sp,
modifier = Modifier.align(Alignment.TopCenter)
)
Row {
Column {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.padding(top = 25.dp)
) {
Image(
painter = painterResource(id = R.drawable.avataaars),
contentDescription = "Client avatar",
modifier = Modifier
.width(70.dp)
.align(Alignment.CenterVertically)
)
}
Row(
modifier = Modifier
.align(Alignment.CenterHorizontally)
) {
Text(
text = order.customer.name,
fontSize = 20.sp,
)
}
}
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
for (product in order.invoice.products) {
Row(
modifier = Modifier
.align(Alignment.CenterHorizontally)
) {
Text(text = product.title + " x " + product.quantity)
}
}
}
}
Text(
text = "Итог: " + order.invoice.price + " руб.",
modifier = Modifier
.align(Alignment.BottomCenter))
}
}
}
@Composable
fun Header(isAuthorized: MutableState<Boolean>) {
var showDialog by remember { mutableStateOf(false) }
val context = LocalContext.current
val dataStore = context.dataStore
val authKeyPreferencesKey = stringPreferencesKey("auth")
val authFlow: Flow<String?> = dataStore.data.map { preferences ->
preferences[authKeyPreferencesKey]
}
val authKey by authFlow.collectAsState(initial = false)
if (showDialog) {
AlertDialog(
onDismissRequest = { showDialog = false },
title = { Text(text = "Ваш токен:\n$authKey") },
confirmButton = {
Button(onClick = {
CoroutineScope(Dispatchers.IO).launch {
dataStore.edit { preferences ->
preferences.remove(authKeyPreferencesKey)
}
}
showDialog = false
isAuthorized.value = false // Добавьте эту строку
}) {
Text("Выйти")
}
},
dismissButton = {
Button(onClick = { showDialog = false }) {
Text("Отмена")
}
}
)
}
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.nastart_logo),
contentDescription = "App logo",
modifier = Modifier
.width(340.dp)
.padding(start = 50.dp, end = 50.dp, top = 10.dp),
contentScale = ContentScale.FillWidth
)
Button(onClick = { showDialog = true }) {
Text("⚙️") // Простой символ для кнопки
}
}
}
@Composable
fun ActiveCompletedSwitcher(onSwitch: () -> Unit) {
var activeWindowToggled by remember { mutableStateOf(true) }
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row {
Button(
onClick = { if (!activeWindowToggled) { activeWindowToggled = true}; onSwitch() },
modifier = Modifier.width(180.dp),
shape = RoundedCornerShape(topStart = 15.dp, bottomStart = 15.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (activeWindowToggled) colorResource(id = R.color.primary) else colorResource(id = R.color.secondary),
contentColor = colorResource(id = R.color.main_black)
)
) {
Text(
text = stringResource(id = R.string.active_window_label),
fontSize = 18.sp
)
}
Button(
onClick = { if (activeWindowToggled) { activeWindowToggled = false}; onSwitch() },
modifier = Modifier.width(180.dp),
shape = RoundedCornerShape(topEnd = 15.dp, bottomEnd = 15.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (!activeWindowToggled) colorResource(id = R.color.primary) else colorResource(id = R.color.secondary),
contentColor = colorResource(id = R.color.main_black)
)
) {
Text(
text = stringResource(id = R.string.completed_window_label),
fontSize = 18.sp
)
}
}
}
}
@Composable
fun LoginForm(onLoginClick: (String) -> Unit, isAuthorized: MutableState<Boolean>) {
var text by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(id = R.string.welcome_message),
modifier = Modifier.padding(bottom = 50.dp),
fontSize = 30.sp,
)
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = {
Text(
text = stringResource(id = R.string.token_field_label)
)
}
)
FilledTonalButton(
onClick = {
onLoginClick(text)
},
modifier = Modifier.padding(top = 50.dp),
) {
Text(
text = stringResource(id = R.string.login_button_text),
fontSize = 20.sp
)
}
}
}
|
nastart_android_app/app/src/main/java/com/example/nastartapplication/WebSocketService.kt | 311492155 | package com.example.nastartapplication
import Order
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.os.Process
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class WebSocketService : Service() {
private val channelId = "WebSocketServiceChannel"
private val notificationId = 1
override fun onBind(intent: Intent): IBinder? {
return null
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate() {
super.onCreate()
createNotificationChannel()
val webSocketClient = WebSocketClient { order: Order ->
sendNotification(order)
}
GlobalScope.launch(Dispatchers.IO) {
webSocketClient.connect()
}
// Create an Intent for the activity you want to start
val notificationIntent = Intent(this, MainActivity::class.java)
// Create the PendingIntent
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE)
// Create a notification
val notification: Notification = Notification.Builder(this, channelId)
.setContentTitle("WebSocket Service")
.setContentText("The WebSocket service is running...")
.setSmallIcon(R.drawable.avataaars)
.setContentIntent(pendingIntent)
.build()
// Start the service in the foreground
startForeground(notificationId, notification)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "WebSocket Notifications"
val descriptionText = "Notifications for new orders"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
private fun sendNotification(order: Order) {
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.avataaars)
.setContentTitle("New Order")
.setContentText("You have a new order from ${order.customer.name}")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(this)) {
try {
if (checkPermission(Manifest.permission.VIBRATE, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
notify(notificationId, builder.build())
}
} catch (e: SecurityException) {
// Handle the SecurityException
}
}
}
} |
nastart_android_app/app/src/main/java/com/example/nastartapplication/LoginForm.kt | 116937145 | //package com.example.nastartapplication
//
//import android.os.Bundle
//import androidx.activity.ComponentActivity
//import androidx.activity.compose.setContent
//import androidx.compose.foundation.Image
//import androidx.compose.foundation.layout.Arrangement
//import androidx.compose.foundation.layout.Column
//import androidx.compose.foundation.layout.fillMaxSize
//import androidx.compose.foundation.layout.fillMaxWidth
//import androidx.compose.foundation.layout.padding
//import androidx.compose.material3.FilledTonalButton
//import androidx.compose.material3.MaterialTheme
//import androidx.compose.material3.OutlinedTextField
//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.setValue
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.layout.ContentScale
//import androidx.compose.ui.res.painterResource
//import androidx.compose.ui.res.stringResource
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import com.example.nastartapplication.ui.theme.NastartApplicationTheme
//
//class LoginForm : ComponentActivity() {
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContent {
// NastartApplicationTheme {
// // A surface container using the 'background' color from the theme
// Surface(
// modifier = Modifier.fillMaxSize(),
// color = MaterialTheme.colorScheme.background
// ) {
// Login()
// }
// }
// }
// }
//}
//
//@Composable
//fun Login() {
// /*
// * Welcome composition, here user have to enter the authentication token
// *
// */
//
// var text by remember { mutableStateOf("") }
//
// Column(
// modifier = Modifier.fillMaxWidth(),
// horizontalAlignment = Alignment.CenterHorizontally) {
// Image(
// painter = painterResource(id = R.drawable.nastart_logo),
// contentDescription = "App logo",
// modifier = Modifier
// .fillMaxWidth()
// .padding(50.dp),
// contentScale = ContentScale.FillWidth)
// }
// Column(
// modifier = Modifier.fillMaxSize(),
// verticalArrangement = Arrangement.Center,
// horizontalAlignment = Alignment.CenterHorizontally) {
//
// Text(
// text = stringResource(id = R.string.welcome_message),
// modifier = Modifier.padding(bottom = 50.dp),
// fontSize = 30.sp,
// )
//
//
// OutlinedTextField(
// value = text,
// onValueChange = {text = it},
// label = {
// Text(
// text = stringResource(id = R.string.token_field_label)
// )
// })
//
// FilledTonalButton(
// onClick = { /*TODO*/ },
// modifier = Modifier.padding(top = 50.dp),
// ) {
// Text(
// text = stringResource(id = R.string.login_button_text),
// fontSize = 20.sp
// )
// }
//
// }
//}
|
nastart_android_app/app/src/main/java/com/example/nastartapplication/Order.kt | 3428854567 | import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Integration(
val login: String,
val password: String
)
@Serializable
data class Shop(
@SerialName("tg_group_id") val tgGroupId: String,
val coords: List<Double>,
val id: String,
val secret: String,
val title: String,
@SerialName("contact_phone") val contactPhone: String,
@SerialName("contact_name") val contactName: String,
val address: String
)
@Serializable
data class Customer(
val name: String,
@SerialName("contact_phone") val contactPhone: String
)
@Serializable
data class Product(
val title: String,
val quantity: Int,
val price: Int
)
@Serializable
data class Invoice(
@SerialName("wc_id") val wcId: Int,
val products: List<Product>,
val price: Int,
@SerialName("payment_type") val paymentType: String,
@SerialName("created_time") val createdTime: String,
val timezone: String,
@SerialName("customer_note") val customerNote: String
)
@Serializable
data class Delivery(
val type: String,
val price: Int,
val address: String,
val coords: List<Double>,
val token: String,
val geocoder: String,
val commission: Int
)
@Serializable
data class Order(
val shop: Shop,
val customer: Customer,
val invoice: Invoice,
val delivery: Delivery
) |
Naval-battle-Game/src/Main.kt | 804705646 | import kotlin.math.sqrt
import java.io.File
import java.io.PrintWriter
var numLinhas = -1
var numColunas = -1
var tabuleiroHumano: Array<Array<Char?>> = emptyArray()
var tabuleiroComputador: Array<Array<Char?>> = emptyArray()
var tabuleiroPalpitesDoHumano: Array<Array<Char?>> = emptyArray()
var tabuleiroPalpitesDoComputador: Array<Array<Char?>> = emptyArray()
fun tamanhoTabuleiroValido(numLinhas : Int, numColunas : Int) : Boolean
{
when
{
numLinhas == numColunas && (numLinhas == 4 || numLinhas == 5 || numLinhas == 7 || numLinhas == 8 || numLinhas == 10)-> return true
}
return false
}
fun criaLegendaHorizontal(numColunas: Int) : String
{
var count = 0
var horizontal = ""
while(count <= numColunas - 2)
{
horizontal += (65 + count).toChar() + " | "
count++
}
horizontal += (65 + count).toChar()
return horizontal
}
fun criaTerreno(numLinhas: Int,numColunas: Int) : String
{
var count1 = 1
var vertical = "|"
var count = 0
var tabuleiro = "| " + criaLegendaHorizontal(numColunas) + " |"
while (count1 <= numLinhas)
{
while (count <=numColunas - 1)
{
vertical += " |"
count++
}
tabuleiro += "\n$vertical $count1"
count1++
}
return "\n$tabuleiro\n"
}
fun menuDefinirTabuleiro()
{
var linhas : Int? = 0
var colunas : Int? = 0
println("""
|
|> > Batalha Naval < <
|
|Defina o tamanho do tabuleiro:
""".trimMargin())
do {
println("Quantas linhas?")
linhas = readln().toIntOrNull()
when (linhas) {
null -> println("!!! Número de linhas invalidas, tente novamente")
-1 -> menuPrincipal()
}
}
while (linhas == null)
if (linhas != -1) {
do {
println("Quantas colunas?")
colunas = readln().toIntOrNull()
when (colunas) {
null -> println("!!! Número de linhas invalidas, tente novamente")
-1 -> menuPrincipal()
}
} while (colunas == null)
if (tamanhoTabuleiroValido(linhas, colunas)) {
numColunas = colunas!!
numLinhas = linhas!!
tabuleiroHumano = criaTabuleiroVazio(linhas,colunas)
for (l in obtemMapa(tabuleiroHumano,true)) {
println(l)
}
menuDefinirNavios()
}
}
}
fun processaCoordenadas(coordenadas : String, linhas : Int , colunas : Int) : Pair<Int,Int>?{
var count = 0
var numeros = ""
var count2 = 0
var count3 = 1
when{
coordenadas == "" || coordenadas.length < 3 -> return null
}
while (coordenadas[count] != ','){
count++
if (coordenadas.length - 1 <= count){
return null
}
}
while (count2 != count){
if (coordenadas[count2].isDigit()) {
numeros += coordenadas[count2]
count2++
}
else{
return null
}
}
count++
while (coordenadas[count] != (count3 + 64).toChar())
{
count3++
}
return when{
count != coordenadas.length - 1 -> null
numeros.toInt() in 1..linhas && count3 in (1..colunas) -> return Pair(numeros.toInt(),count3)
else -> null
}
}
fun menuDefinirNavios() {
val numNaviosTipo = calculaNumNavios(tabuleiroHumano.size,tabuleiroHumano[0].size)
var dimensao = 0
var nome = ""
for (i in 0 until numNaviosTipo.size) {
when(i)
{
0 -> { dimensao = 1
nome = "submarino"}
1 -> { dimensao = 2
nome = "contra-torpedeiro"}
2 -> { dimensao = 3
nome = "navio-tanque"}
3 -> { dimensao = 4
nome = "porta-avioes"}
}
if (numNaviosTipo[i]>0){
for (j in 1..numNaviosTipo[i]){
println("Insira as coordenadas de um $nome:\nCoordenadas? (ex: 6,G)")
var coordenadas = readln()
if (coordenadas == "-1") {
return main()
}
var coordenadasNavio = processaCoordenadas(coordenadas, numLinhas, numColunas)
if (dimensao == 1){
while (coordenadasNavio == null || coordenadas == "" ||
!insereNavioSimples(tabuleiroHumano,coordenadasNavio.first,coordenadasNavio.second,dimensao)) {
println("!!! Posicionamento invalido, tente novamente\nInsira as coordenadas de um $nome:\nCoordenadas? (ex: 6,G)")
coordenadas = readln()
if (coordenadas == "-1") {
return main()
}
coordenadasNavio = processaCoordenadas(coordenadas, numLinhas, numColunas)
}
}else{
println("Insira a orientacao do navio:\nOrientacao? (N, S, E, O)")
var orientacao = readln()
if (orientacao == "-1"){
return main()
}
while (coordenadasNavio == null || coordenadas == "" ||
!insereNavio(tabuleiroHumano,coordenadasNavio.first,coordenadasNavio.second,orientacao,dimensao)) {
println("!!! Posicionamento invalido, tente novamente\nInsira as coordenadas de um $nome:\nCoordenadas? (ex: 6,G)")
coordenadas = readln()
if (coordenadas == "-1") {
return main()
}
coordenadasNavio = processaCoordenadas(coordenadas, numLinhas, numColunas)
println("Insira a orientacao do navio:\nOrientacao? (N, S, E, O)")
orientacao = readln()
if (orientacao == "-1"){
return main()
}
}
}
val tabueleiro = obtemMapa(tabuleiroHumano,true)
for (linha in 0 until tabueleiro.size){
println(tabueleiro[linha])
}
}
}
}
tabuleiroPalpitesDoHumano = criaTabuleiroVazio(numLinhas, numColunas)
tabuleiroComputador()
}
fun tabuleiroComputador()
{
tabuleiroPalpitesDoComputador = criaTabuleiroVazio(numLinhas,numColunas)
tabuleiroComputador = criaTabuleiroVazio(numLinhas,numColunas)
println("Pretende ver o mapa gerado para o Computador? (S/N)")
val resposta = readln()
when (resposta) {
"S" ->{ preencheTabuleiroComputador(tabuleiroComputador,calculaNumNavios(numLinhas,numColunas))
for (l in obtemMapa(tabuleiroComputador,true))
{
println(l)
}
return menuPrincipal()
}
"N" -> menuPrincipal()
else -> print("!!! Opcao invalida, tente novamente")
}
}
fun menuPrincipal(){
var escolha: Int? = 0
println("""
|
|> > Batalha Naval < <
|
|1 - Definir Tabuleiro e Navios
|2 - Jogar
|3 - Gravar
|4 - Ler
|0 - Sair
|
""".trimMargin())
do {
escolha = readln().toIntOrNull()
when{
escolha == 1 -> menuDefinirTabuleiro()
escolha == 2 -> menuJogar()
escolha == 3 -> { println("Introduza o nome do ficheiro (ex: jogo.txt)")
val ficheiro = readln()
gravarJogo(ficheiro,tabuleiroHumano,tabuleiroPalpitesDoHumano,tabuleiroComputador,tabuleiroPalpitesDoComputador)
println("Tabuleiro ${tabuleiroHumano.size}x${tabuleiroHumano.size} gravado com sucesso")
return menuPrincipal()
}
escolha == 4 -> {
println("Introduza o nome do ficheiro (ex: jogo.txt)")
val ficheiro = readln()
tabuleiroHumano = lerJogo(ficheiro,1)
tabuleiroPalpitesDoHumano = lerJogo(ficheiro,2)
tabuleiroComputador = lerJogo(ficheiro,3)
tabuleiroPalpitesDoComputador = lerJogo(ficheiro,4)
println("Tabuleiro ${numLinhas}x${numColunas} lido com sucesso")
for (l in obtemMapa(tabuleiroHumano,true))
{
println(l)
}
return menuPrincipal()
}
escolha != 0 -> println("!!! Opcao invalida, tente novamente")
}
} while (escolha !in 0..4)
}
fun calculaNumNavios(numLinhas: Int, numColunas: Int) : Array<Int>
{
var dimensao = emptyArray<Int>()
if(numLinhas == numColunas) {
dimensao = when (numLinhas)
{
4 -> arrayOf(2,0,0,0)
5 -> arrayOf(1,1,1,0)
7 -> arrayOf(2,1,1,1)
8 -> arrayOf(2,2,1,1)
10 -> arrayOf(3,2,1,1)
else -> dimensao
}
}
return dimensao
}
fun criaTabuleiroVazio(numLinhas: Int,numColunas: Int) : Array<Array<Char?>>
{
return Array(numLinhas){Array(numColunas){ null }}
}
fun coordenadaContida(tabuleiro: Array<Array<Char?>>, numLinhas: Int, numColunas: Int): Boolean
{
when
{
tabuleiro.size >= numLinhas && tabuleiro.size >= numColunas && numLinhas >= 1 && numColunas >= 1 -> return true
}
return false
}
fun limparCoordenadasVazias(coordenadas: Array<Pair<Int, Int>>): Array<Pair<Int,Int>>
{
var count = 0
var count2 = 0
for (num1 in 0..coordenadas.size - 1) {
when {
coordenadas[num1] == Pair(0, 0) -> {
count++
}
}
}
val retorno = Array<Pair<Int,Int>>(coordenadas.size - count){Pair(0,0)}
for (num1 in 0..coordenadas.size - 1) {
when {
coordenadas[num1] != Pair(0, 0) -> {
retorno[count2] = coordenadas[num1]
count2++
}
}
}
return retorno
}
fun juntarCoordenadas(coordenadas1: Array<Pair<Int, Int>>, coordenadas2: Array<Pair<Int, Int>>): Array<Pair<Int, Int>> {
return coordenadas1 + coordenadas2
}
fun gerarCoordenadasNavio(tabuleiro: Array<Array<Char?>>, numLinhas: Int, numColunas: Int,orientacao: String, dimensao: Int): Array<Pair<Int, Int>> {
if (dimensao > 0) {
val retorno = Array<Pair<Int, Int>>(dimensao) { Pair(0, 0) }
for (count in 0..dimensao - 1) {
when (orientacao) {
"E" ->
when {
coordenadaContida(tabuleiro, numLinhas, numColunas + count) ->
retorno[count] = Pair(numLinhas, numColunas + count)
else -> return emptyArray()
}
"O" ->
when {
coordenadaContida(tabuleiro, numLinhas, numColunas - count) ->
retorno[count] = Pair(numLinhas, numColunas - count)
else -> return emptyArray()
}
"N" ->
when {
coordenadaContida(tabuleiro, numLinhas - count, numColunas) ->
retorno[count] = Pair(numLinhas - count, numColunas)
else -> return emptyArray()
}
"S" ->
when {
coordenadaContida(tabuleiro, numLinhas + count, numColunas) ->
retorno[count] = Pair(numLinhas + count, numColunas)
else -> return emptyArray()
}
}
}
return retorno
}
return emptyArray()
}
fun gerarCoordenadasFronteira(tabuleiro: Array<Array<Char?>>, numLinhas: Int,
numColunas: Int, orientacao: String, dimensao: Int ): Array<Pair<Int, Int>>
{
var resultado = emptyArray<Pair<Int,Int>>()
for (count in -1 ..1) {
for (count1 in -1..dimensao) {
val coordenada = when (orientacao) {
"E" -> Pair(numLinhas + count, numColunas + count1)
"O" -> Pair(numLinhas + count, numColunas - count1)
"S" -> Pair(numLinhas + count1, numColunas + count)
"N" -> Pair(numLinhas - count1, numColunas + count)
else -> null
}
if (coordenada != null && coordenadaContida(tabuleiro, coordenada.first, coordenada.second)) {
resultado = juntarCoordenadas(resultado, arrayOf(coordenada))
}
}
}
val navio = gerarCoordenadasNavio(tabuleiro,numLinhas,numColunas,orientacao,dimensao)
if (navio.size > 0) {
for (count in 0..navio.size - 1) {
for (count1 in 0..resultado.size - 1) {
when {
resultado[count1] == navio[count] -> resultado[count1] = Pair(0, 0)
}
}
}
val borracha = limparCoordenadasVazias(resultado)
return borracha
}
return emptyArray()
}
fun estaLivre(tabuleiro: Array<Array<Char?>>, coordenadas: Array<Pair<Int, Int>>): Boolean
{
for (coords in 0.. coordenadas.size - 1) {
for (linha in 0..tabuleiro.size -1) {
for (coluna in 0..tabuleiro.size -1) {
when
{
!coordenadaContida(tabuleiro,coordenadas[coords].first,coordenadas[coords].second) -> return false
coordenadas[coords] == Pair(1+linha,1+coluna) -> when{tabuleiro[linha][coluna] != null -> return false}
}
}
}
}
return true
}
fun insereNavioSimples(tabuleiro: Array<Array<Char?>>, numLinhas: Int, numColunas: Int, dimensao: Int): Boolean {
val navio = juntarCoordenadas(gerarCoordenadasNavio(tabuleiro, numLinhas, numColunas, "E", dimensao),
gerarCoordenadasFronteira(tabuleiro, numLinhas, numColunas, "E", dimensao))
if (navio.size > 0) {
when {
estaLivre(tabuleiro, navio) -> {
for (count in 0..dimensao - 1) {
tabuleiro[numLinhas - 1][numColunas + count - 1] = (dimensao + 48).toChar()
}
return true
}
}
}
return false
}
fun insereNavio(tabuleiro: Array<Array<Char?>>, numLinhas: Int, numColunas: Int, orientacao: String,
dimensao: Int ): Boolean
{
val navio = juntarCoordenadas(gerarCoordenadasNavio(tabuleiro, numLinhas, numColunas, orientacao, dimensao),
gerarCoordenadasFronteira(tabuleiro, numLinhas, numColunas, orientacao, dimensao))
if (navio.size > 0)
{
when
{
estaLivre(tabuleiro,navio) == true ->
{
for (count in 0..dimensao-1) {
when(orientacao)
{
"E" -> tabuleiro[numLinhas - 1][numColunas + count - 1] = (dimensao + 48).toChar()
"O" -> tabuleiro[numLinhas - 1][numColunas - count - 1] = (dimensao + 48).toChar()
"S" -> tabuleiro[numLinhas + count - 1][numColunas - 1] = (dimensao + 48).toChar()
"N" -> tabuleiro[numLinhas - count - 1][numColunas - 1] = (dimensao + 48).toChar()
}
}
return true
}
}
return false
}
return false
}
fun preencheTabuleiroComputador(tabuleiro: Array<Array<Char?>>, numNavios: Array<Int>) {
for (dimensao in 4 downTo 1) {
for (i in 0 until numNavios[dimensao - 1]) {
var sucesso = false
while (!sucesso) {
val numLinhas = (1..tabuleiro.size).random()
val numColunas = (1..tabuleiro[numLinhas - 1].size).random()
val orientacao = when ((0..3).random()) {
0 -> "E"
1 -> "O"
2 -> "S"
else -> "N"
}
sucesso = coordenadaContida(tabuleiro, numLinhas, numColunas) &&
insereNavio(tabuleiro, numLinhas, numColunas, orientacao, dimensao)
}
}
}
}
fun navioCompleto(tabuleiro: Array<Array<Char?>>, numLinhas: Int, numColunas: Int): Boolean {
var completo = 1
val tamanho = arrayOf('1','2','3','4')
var dimensao = 0
var count = 1
when{
tabuleiro[numLinhas -1][numColunas -1] == '4' -> dimensao = 4
tabuleiro[numLinhas -1][numColunas -1] == '3' -> dimensao = 3
tabuleiro[numLinhas -1][numColunas -1] == '2' -> dimensao = 2
tabuleiro[numLinhas -1][numColunas -1] == '1' -> return true
else -> return false
}
while (count != dimensao){
when {numLinhas + count in 1..tabuleiro.size -> if(tabuleiro[numLinhas + count -1][numColunas -1] == tamanho[dimensao - 1]) { completo++}}
when {numLinhas - count in 1..tabuleiro.size -> if(tabuleiro[numLinhas - count -1][numColunas -1] == tamanho[dimensao - 1]) { completo++}}
when {numColunas + count in 1..tabuleiro.size -> if(tabuleiro[numLinhas -1][numColunas + count -1] == tamanho[dimensao - 1]) { completo++}}
when {numColunas - count in 1..tabuleiro.size -> if(tabuleiro[numLinhas -1][numColunas - count -1] == tamanho[dimensao - 1]) { completo++}}
count++
}
if(completo == dimensao){
return true
}
else{
return false
}
}
fun obtemMapa(tabuleiro: Array<Array<Char?>>, verifica: Boolean): Array<String> {
val tamanhoMapa = tabuleiro.size + 1
var mapa = Array(tamanhoMapa) { "" }
var numLinhas = 0
mapa[numLinhas++] = "| " + criaLegendaHorizontal(tabuleiro.size) + " |"
for (numLinha in 0 until tabuleiro.size) {
var linha = "|"
for (numColunas in 0 until tabuleiro[numLinha].size) {
val conteudo = if(verifica){tabuleiro[numLinha][numColunas]?: '~'}
else {
val navioCompleto = navioCompleto(tabuleiro, numLinha + 1, numColunas + 1)
when(tabuleiro[numLinha][numColunas]) {
'4' -> if(!navioCompleto) '\u2084' else '4'
'3' -> if(!navioCompleto) '\u2083' else '3'
'2' -> if(!navioCompleto) '\u2082' else '2'
else -> tabuleiro[numLinha][numColunas] ?: '?'
}
}
linha += " $conteudo |"
}
mapa[numLinhas++] = "$linha ${numLinha + 1}"
}
return mapa
}
fun lancarTiro(tabuleiro: Array<Array<Char?>>, tabuleiroPalpites: Array<Array<Char?>>, coordenadas: Pair<Int, Int>): String {
when (tabuleiro[coordenadas.first - 1][coordenadas.second - 1]) {
'1' -> {
tabuleiroPalpites[coordenadas.first - 1][coordenadas.second - 1] = '1'
return "Tiro num submarino."
}
'2' -> {
tabuleiroPalpites[coordenadas.first - 1][coordenadas.second - 1] = '2'
return "Tiro num contra-torpedeiro."
}
'3' -> {
tabuleiroPalpites[coordenadas.first - 1][coordenadas.second - 1] = '3'
return "Tiro num navio-tanque."
}
'4' -> {
tabuleiroPalpites[coordenadas.first - 1][coordenadas.second - 1] = '4'
return "Tiro num porta-avioes."
}
else -> {
tabuleiroPalpites[coordenadas.first - 1][coordenadas.second - 1] = 'X'
return "Agua."}
}
}
fun geraTiroComputador(tabuleiro: Array<Array<Char?>>): Pair<Int, Int> {
var numLinhas: Int
var numColunas: Int
do {
numLinhas = (1..tabuleiro.size).random()
numColunas = (1..tabuleiro.size).random()
} while (tabuleiro[numLinhas - 1][numColunas - 1] != null)
lancarTiro(tabuleiro, criaTabuleiroVazio(tabuleiro.size, tabuleiro.size), Pair(numLinhas, numColunas))
return Pair(numLinhas, numColunas)
}
fun contarNaviosDeDimensao(tabuleiro: Array<Array<Char?>>, dimensao: Int): Int {
var submarino = 0
var contraTorpedeiro = 0
var navioTanque = 0
var portaAvioes = 0
for (numLinha in 0 until tabuleiro.size) {
for (numColuna in 0 until tabuleiro.size) {
if (navioCompleto(tabuleiro, numLinha + 1, numColuna + 1)) {
when (tabuleiro[numLinha][numColuna]) {
'4' -> if (dimensao == 4) portaAvioes++
'3' -> if (dimensao == 3) navioTanque++
'2' -> if (dimensao == 2) contraTorpedeiro++
'1' -> if (dimensao == 1) submarino++
}
}
}
}
return when (dimensao) {
4 -> portaAvioes / 4
3 -> navioTanque / 3
2 -> contraTorpedeiro / 2
1 -> submarino
else -> 0
}
}
fun venceu(tabuleiro: Array<Array<Char?>>): Boolean {
for (dimensao in 1..4) {
if (contarNaviosDeDimensao(tabuleiro, dimensao) != calculaNumNavios(tabuleiro.size, tabuleiro.size)[dimensao - 1]) {
return false
}
}
return true
}
fun lerJogo(nomeDoFicheiro: String, tipoDeTabuleiro: Int): Array<Array<Char?>> {
val ficheiro = File(nomeDoFicheiro).readLines()
numLinhas = ficheiro[0][0].digitToInt()
numColunas = ficheiro[0][2].digitToInt()
val linhaMin = 3 * tipoDeTabuleiro + 1 + numLinhas * (tipoDeTabuleiro - 1)
var linha = linhaMin
val tabuleiro = criaTabuleiroVazio(numLinhas, numColunas)
while (linha in (3 * tipoDeTabuleiro + 1 + numLinhas * (tipoDeTabuleiro - 1) until 3 * tipoDeTabuleiro + 1 + numLinhas * tipoDeTabuleiro)) {
var coluna = 0
var count = 0
while (count < numColunas && coluna < ficheiro[linha].length) {
when (ficheiro[linha][coluna]) {
',' -> count++
in '1'..'4', 'X' -> tabuleiro[linha - linhaMin][count] = ficheiro[linha][coluna]
}
coluna++
}
linha++
}
return tabuleiro
}
fun gravarJogo(
nomeDoFicheiro: String,
tabuleiroRealHumano: Array<Array<Char?>>,
tabuleiroPalpitesHumano: Array<Array<Char?>>,
tabuleiroRealComputador: Array<Array<Char?>>,
tabuleiroPalpitesComputador: Array<Array<Char?>>
) {
val filePrinter = File(nomeDoFicheiro).printWriter()
filePrinter.println("${tabuleiroRealHumano.size},${tabuleiroRealHumano.size}\n")
estruturaTabuleiro(filePrinter, "Jogador\nReal", tabuleiroRealHumano)
estruturaTabuleiro(filePrinter, "\nJogador\nPalpites", tabuleiroPalpitesHumano)
estruturaTabuleiro(filePrinter, "\nComputador\nReal", tabuleiroRealComputador)
estruturaTabuleiro(filePrinter, "\nComputador\nPalpites", tabuleiroPalpitesComputador)
filePrinter.close()
}
fun estruturaTabuleiro(filePrinter: PrintWriter, titulo: String, tabuleiro: Array<Array<Char?>>) {
filePrinter.println(titulo)
for (linha in 0 until tabuleiro.size) {
for (coluna in 0 until tabuleiro[linha].size) {
filePrinter.print("${tabuleiro[linha][coluna] ?: ""}")
if (coluna < tabuleiro[linha].size - 1) {
filePrinter.print(",")
}
}
filePrinter.println()
}
}
fun menuJogar() {
when {
numLinhas == -1 -> {
println("!!! Tem que primeiro definir o tabuleiro do jogo, tente novamente")
return menuPrincipal() } }
val tiroComputador = geraTiroComputador(tabuleiroPalpitesDoHumano)
while (!venceu(tabuleiroPalpitesDoComputador) || !venceu(tabuleiroPalpitesDoHumano)) {
for (l in obtemMapa(tabuleiroPalpitesDoHumano, false)) { println(l) }
println("""Indique a posição que pretende atingir
|Coordenadas? (ex: 6,G)
""".trimMargin())
var coordenadasNavio: Pair<Int, Int>? = null
while (coordenadasNavio == null) {
val input = readln()
if (input == "?") {
val naviosFaltando = calculaNaviosFaltaAfundar(tabuleiroPalpitesDoHumano)
var naviosFaltandoString = ""
for (i in 0..3) {
val count = naviosFaltando[i]
val nome = when (i) {
0 -> "porta-avioes(s)"
1 -> "navio-tanque(s)"
2 -> "contra-torpedeiro(s)"
3 -> "submarino(s)"
else -> ""
}
if (count > 0) { naviosFaltandoString = if (naviosFaltandoString.length == 0) { "$count $nome" }
else { "$naviosFaltandoString; $count $nome" } } }
if (naviosFaltandoString.length > 0) { println("Falta afundar: $naviosFaltandoString") }
println("""Indique a posição que pretende atingir
|Coordenadas? (ex: 6,G)""".trimMargin()) }
if (input == "-1") { return menuPrincipal() }
if(input == "" ) { println("Coordenadas invalidas! tente novamente") }
coordenadasNavio= processaCoordenadas(input, numLinhas, numColunas)
if (coordenadasNavio != null) { lancarTiro(tabuleiroComputador, tabuleiroPalpitesDoHumano, coordenadasNavio) }
lancarTiro(tabuleiroHumano, tabuleiroPalpitesDoComputador, tiroComputador) }
if (navioCompleto(tabuleiroPalpitesDoHumano, coordenadasNavio.first, coordenadasNavio.second) ) {
println(">>> HUMANO >>>${lancarTiro(tabuleiroComputador, tabuleiroPalpitesDoHumano, coordenadasNavio)} Navio ao fundo!") }
else { println(">>> HUMANO >>>${lancarTiro(tabuleiroComputador, tabuleiroPalpitesDoHumano, coordenadasNavio)}") }
if(!venceu(tabuleiroPalpitesDoHumano)) { println("Computador lancou tiro para a posicao $tiroComputador")
if (navioCompleto(tabuleiroPalpitesDoComputador, tiroComputador.first, tiroComputador.second)) {
println(">>> COMPUTADOR >>>${lancarTiro(tabuleiroHumano, tabuleiroPalpitesDoComputador, tiroComputador)} Navio ao fundo!")
}
else { println(">>> COMPUTADOR >>>${lancarTiro(tabuleiroHumano, tabuleiroPalpitesDoComputador, tiroComputador)}") } }
obtemMapa(tabuleiroPalpitesDoComputador, false)
obtemMapa(tabuleiroPalpitesDoHumano, false)
when {
venceu(tabuleiroPalpitesDoHumano) -> {
println("PARABENS! Venceu o jogo!")
println("Prima enter para voltar ao menu principal")
readln()
return menuPrincipal() }
venceu(tabuleiroPalpitesDoComputador) -> {
println("OPS! O computador venceu o jogo!")
println("Prima enter para voltar ao menu principal")
readln()
return menuPrincipal() }
else -> {
println("Prima enter para continuar")
readln() }
}
}
}
fun calculaEstatisticas(tabuleiroPalpites: Array<Array<Char?>>): Array<Int> {
val retorno = arrayOf(0, 0, 0)
for (numLinha in 0 until tabuleiroPalpites.size) {
for (numColuna in 0 until tabuleiroPalpites[numLinha].size) {
if (tabuleiroPalpites[numLinha][numColuna] != null) {
val navioCompleto = navioCompleto(tabuleiroPalpites, numLinha + 1, numColuna + 1)
retorno[0]++
when (tabuleiroPalpites[numLinha][numColuna]) {
'1' -> {
retorno[1]++
retorno[2]++
}
in '2'..'4' -> {
if (navioCompleto) {
retorno[1]++
if (tabuleiroPalpites[numLinha][numColuna] == '4' && retorno[2] < 4) { retorno[2]++ }
else if (tabuleiroPalpites[numLinha][numColuna] == '3' && retorno[2] < 3) { retorno[2]++ }
else if (tabuleiroPalpites[numLinha][numColuna] == '2' && retorno[2] < 2) { retorno[2]++ }
}
else if (!navioCompleto) { retorno[1]++ }
}
}
}
}
}
return retorno
}
fun calculaNaviosFaltaAfundar(tabuleiroPalpites: Array<Array<Char?>>): Array<Int> {
val retorno = arrayOf(0, 0, 0, 0)
for (dimensao in 1..4) {
val numNavios = calculaNumNavios(tabuleiroPalpites.size, tabuleiroPalpites[0].size)[dimensao - 1]
val count = numNavios - contarNaviosDeDimensao(tabuleiroPalpites, dimensao)
when (dimensao) {
1 -> retorno[3] = count
2 -> retorno[2] = count
3 -> retorno[1] = count
4 -> retorno[0] = count
}
}
return retorno
}
fun main() {
menuPrincipal()
}
|
voice-recognition-sample/app/src/androidTest/java/com/almer/voicerecognitionsample/ExampleInstrumentedTest.kt | 2707428583 | package com.almer.voicerecognitionsample
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.almer.voicerecognitionsample", appContext.packageName)
}
} |
voice-recognition-sample/app/src/test/java/com/almer/voicerecognitionsample/ExampleUnitTest.kt | 2459751208 | package com.almer.voicerecognitionsample
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)
}
} |
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/ui/theme/Color.kt | 258227938 | package com.almer.voicerecognitionsample.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) |
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/ui/theme/Theme.kt | 1152698708 | package com.almer.voicerecognitionsample.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 VoiceRecognitionSampleTheme(
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
)
} |
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/ui/theme/Type.kt | 53566372 | package com.almer.voicerecognitionsample.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
)
*/
) |
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/MainActivity.kt | 1790831209 | package com.almer.voicerecognitionsample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.almer.voicerecognitionsample.ui.theme.VoiceRecognitionSampleTheme
import org.koin.androidx.compose.get
import org.koin.compose.koinInject
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
VoiceRecognitionSampleTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen()
}
}
}
}
}
// TODO: Make this FUN
@Composable
fun MainScreen(viewModel: VoiceCommandsViewModel = koinInject()) {
val state = viewModel.state.collectAsState().value
Column {
Text("Voice recognition is ongoing: ${state.isVoiceRecognitionOngoing}")
Button(onClick = viewModel::registerCommands) {
Text("Register commands")
}
}
}
|
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/di/Modules.kt | 2989535595 | package com.almer.voicerecognitionsample.di
import com.almer.voicerecognitionsample.VoiceCommandsViewModel
import org.koin.dsl.module
val appModule = module {
single { VoiceCommandsViewModel(get()) }
} |
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/VoiceCommandsViewModel.kt | 139680173 | package com.almer.voicerecognitionsample
import android.content.Context
import android.widget.Toast
import com.almer.voice.recognition.bridge.SpeechListener
import com.almer.voice.recognition.bridge.VoiceCommand
import com.almer.voice.recognition.bridge.registerVoiceCommands
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class VoiceCommandsViewModel(private val context: Context): SpeechListener(context) {
private val _state = MutableStateFlow(VoiceCommandsState())
val state = _state.asStateFlow()
//TODO: Make this "FUN"
fun registerCommands(){
context.registerVoiceCommands(listOf(VoiceCommand("Hello")))
}
init {
registerCommands()
}
override fun onVoiceRecognitionStarted() {
updateState { copy(isVoiceRecognitionOngoing = true) }
}
override fun onVoiceRecognitionStopped() {
updateState { copy(isVoiceRecognitionOngoing = false) }
}
override fun onSpeechEvent(
detectedSpeech: String,
extraParameters: VoiceCommand.CallbackParams
) {
Toast.makeText(
context,
"You said $detectedSpeech ${extraParameters.freeSpeech}",
Toast.LENGTH_SHORT
).show()
}
private fun updateState(reducer: VoiceCommandsState.() -> VoiceCommandsState) {
_state.update(reducer)
}
}
data class VoiceCommandsState(val isVoiceRecognitionOngoing: Boolean = true)
|
voice-recognition-sample/app/src/main/java/com/almer/voicerecognitionsample/MainApp.kt | 2297672327 | package com.almer.voicerecognitionsample
import android.app.Application
import com.almer.voicerecognitionsample.di.appModule
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class MainApp: Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MainApp)
modules(appModule)
}
}
} |
Compass_Connector/app/src/androidTest/java/com/example/compassconnect/ExampleInstrumentedTest.kt | 1014645408 | package com.example.compassconnect
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.compassconnect", appContext.packageName)
}
} |
Compass_Connector/app/src/test/java/com/example/compassconnect/ExampleUnitTest.kt | 440928631 | package com.example.compassconnect
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)
}
} |
Compass_Connector/app/src/main/java/com/example/compassconnect/MainActivity.kt | 4116514911 | package com.example.compassconnect
import android.app.usage.UsageEvents.Event
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
class MainActivity : AppCompatActivity(),SensorEventListener {
var sensor: Sensor?=null
var currentDegree= 0f //to keep track how the compass is rotating
var sensorManager:SensorManager?=null
lateinit var compassImage:ImageView
lateinit var rotateTV:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sensorManager= getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensor=sensorManager!!.getDefaultSensor(Sensor.TYPE_ORIENTATION)
compassImage=findViewById(R.id.imageView2)
rotateTV=findViewById(R.id.textView)
}
override fun onSensorChanged(p0: SensorEvent?) {
var degree= Math.round(p0!!.values[0])
rotateTV.text=degree.toString() + "degrees"
var rotationAnimation= RotateAnimation(currentDegree, (-degree).toFloat(),Animation.RELATIVE_TO_SELF,
0.5f,Animation.RELATIVE_TO_SELF,0.5f)
rotationAnimation.duration=210
rotationAnimation.fillAfter=true
compassImage.startAnimation(rotationAnimation)
currentDegree= (-degree).toFloat()
}
override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
}
override fun onResume() {
super.onResume()
sensorManager!!.registerListener(this,sensor,SensorManager.SENSOR_DELAY_GAME)
}
override fun onPause() {
super.onPause()
sensorManager!!.unregisterListener(this)
}
}
|
itemName2/buildSrc/src/main/kotlin/SetupTask.kt | 2240665127 | import org.eclipse.jgit.api.Git
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.io.IOException
/**
* GitHub アカウントを使って プロジェクトをセットアップする
*/
open class SetupTask : DefaultTask() {
@TaskAction
fun action() {
val projectDir = project.projectDir
val repository = try {
FileRepositoryBuilder.create(projectDir.resolve(".git"))
} catch (ex: IOException) {
error("リポジトリが見つかりませんでした")
}
val git = Git(repository)
val remoteList = git.remoteList().call()
val uri = remoteList.flatMap { it.urIs }.firstOrNull { it.host == "github.com" } ?: error("GitHub のプッシュ先が見つかりませんでした")
val rawAccount = "/?([^/]*)/?".toRegex().find(uri.path)?.groupValues?.get(1) ?: error("アカウント名が見つかりませんでした (${uri.path})")
val account = rawAccount.replace('-', '_')
val groupId = "com.github.$account"
val srcDir = projectDir.resolve("src/main/kotlin/com/github/$account").apply(File::mkdirs)
srcDir.resolve("Main.kt").writeText(
"""
package $groupId
import org.bukkit.plugin.java.JavaPlugin
class Main : JavaPlugin()
""".trimIndent()
)
val buildScript = projectDir.resolve("build.gradle.kts")
buildScript.writeText(buildScript.readText().replace("@group@", groupId))
projectDir.resolve("README.md").writeText(
"""
# ${project.name}
## plugin.yml
ビルド時に自動生成されます。[build.gradle.kts](build.gradle.kts) の以下の箇所で設定できます。
書き方は https://github.com/Minecrell/plugin-yml の Bukkit kotlin-dsl を見てください。
```kotlin
configure<BukkitPluginDescription> {
// 内容
}
```
## タスク
### プラグインのビルド `build`
`build/libs` フォルダに `.jar` を生成します。
### テストサーバーの起動 `buildAndLaunchServer`
`:25565` でテストサーバーを起動します。
""".trimIndent()
)
}
}
|
itemName2/src/main/kotlin/com/github/Ringoame196/Player.kt | 33361544 | package com.github.Ringoame196
import net.md_5.bungee.api.ChatColor
import org.bukkit.Sound
import org.bukkit.entity.Player
class Player(val player: Player) {
fun sendErrorMessage(message: String) {
player.sendMessage("${ChatColor.RED}[エラー] $message")
player.playSound(player, Sound.BLOCK_NOTE_BLOCK_BELL, 1f, 1f)
}
}
|
itemName2/src/main/kotlin/com/github/Ringoame196/ItemManager.kt | 994840060 | package com.github.Ringoame196
import net.md_5.bungee.api.ChatColor
import org.bukkit.Sound
import org.bukkit.entity.Player
import org.bukkit.inventory.meta.ItemMeta
class ItemManager {
val reset = "!reset"
fun acquisitionDefaultName(player: Player, typeList: Array<out String>): MutableList<String>? {
val playerItem = player.inventory.itemInMainHand
val meta = playerItem.itemMeta ?: return mutableListOf()
return when (typeList[0]) {
"display" -> mutableListOf(meta.displayName)
"lore" -> meta.lore ?: mutableListOf()
"customModelData" -> try { mutableListOf(meta.customModelData.toString()) } catch (e: Exception) { mutableListOf() }
else -> mutableListOf("${ChatColor.RED}引数が間違っています")
}
}
fun setDisplay(meta: ItemMeta, displayName: String?) {
meta.setDisplayName(changeColorCode(displayName ?: ""))
if (displayName == reset) {
meta.setDisplayName(null)
}
}
fun setLore(meta: ItemMeta, oldLore: Array<out String>) {
val newLore = mutableListOf<String>()
for (i in 1 until oldLore.size) {
newLore.add(changeColorCode(oldLore[i]))
}
meta.lore = newLore
if (oldLore[1] == reset) {
meta.lore = null
}
}
fun setCustomModelData(meta: ItemMeta, customModule: Int?) {
meta.setCustomModelData(customModule)
}
private fun changeColorCode(text: String): String {
return text.replace("&", "§")
}
fun itemSetting(player: Player, meta: ItemMeta, menu: String, inputText: String) {
val menuMap = mapOf(
"display" to "アイテム名",
"lore" to "説明",
"customModelData" to "カスタムモデルデータ"
)
val action = if (inputText == "!reset") { "${ChatColor.RED}リセット" } else { "変更" }
player.inventory.itemInMainHand.setItemMeta(meta)
player.playSound(player, Sound.BLOCK_ANVIL_USE, 1f, 1f)
player.sendMessage("${ChatColor.YELLOW}[itemName] ${menuMap[menu]}情報を${action}しました")
}
}
|
itemName2/src/main/kotlin/com/github/Ringoame196/Main.kt | 2650190155 | package com.github.Ringoame196
import com.github.Ringoame196.Commands.ItemName
import org.bukkit.plugin.java.JavaPlugin
class Main : JavaPlugin() {
override fun onEnable() {
super.onEnable()
getCommand("itemName")!!.setExecutor(ItemName())
}
override fun onDisable() {
super.onDisable()
}
}
|
itemName2/src/main/kotlin/com/github/Ringoame196/Commands/ItemName.kt | 2256301140 | package com.github.Ringoame196.Commands
import com.github.Ringoame196.ItemManager
import org.bukkit.Material
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.command.TabCompleter
import org.bukkit.entity.Player
class ItemName : CommandExecutor, TabCompleter {
private val itemManager = ItemManager()
override fun onCommand(player: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (player !is Player) {
return false
}
val playerClass = com.github.Ringoame196.Player(player)
val playerItem = player.inventory.itemInMainHand
if (playerItem.type == Material.AIR) {
playerClass.sendErrorMessage("空気以外を持ってください")
return false
}
val meta = playerItem.itemMeta ?: return false
if (args.isEmpty() || args.size < 2) {
return false
}
val menu = args[0]
val inputText = args[1]
val processMap = mutableMapOf(
"display" to { itemManager.setDisplay(meta, inputText) },
"lore" to { itemManager.setLore(meta, args) },
"customModelData" to {
try {
val customModelData = inputText.toInt()
itemManager.setCustomModelData(meta, customModelData)
} catch (e: NumberFormatException) {
itemManager.setCustomModelData(meta, null)
}
}
)
processMap[menu]?.invoke()
itemManager.itemSetting(player, meta, menu, inputText)
return true
}
override fun onTabComplete(player: CommandSender, command: Command, label: String, args: Array<out String>): MutableList<String> {
if (player !is Player) { return mutableListOf() }
return when (args.size) {
1 -> mutableListOf("display", "lore", "customModelData")
in 2..Int.MAX_VALUE -> (itemManager.acquisitionDefaultName(player, args)?.plus(itemManager.reset))?.toMutableList() ?: mutableListOf()
else -> mutableListOf()
}
}
}
|
Education/app/src/main/java/com/example/education/MainViewModel.kt | 754159777 | package com.example.education
import android.content.Context
import android.util.Log
import com.example.education.base.BaseViewModel
import com.example.education.bean.SchoolBean
import com.example.education.bean.SchoolBeanDao
import com.example.education.bean.StudentBean
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.InputStream
/**
* @author fengerzhang
* @date 2023/12/6 09:28
*/
class MainViewModel : BaseViewModel() {
companion object {
private const val TAG = "MainViewModel"
}
// 获取DAO实例
private val session: SchoolBeanDao = App.daoSession.schoolBeanDao
/**
* 读取学生表Excel数据,获取全部学生信息
*
* @return List<StudentBean></StudentBean> */
fun readExcel(context: Context): List<StudentBean> {
val studentList: MutableList<StudentBean> = ArrayList()
val input: InputStream = context.assets.open("test_excel.xlsx")
// 获取表格对象
val sheet: Sheet = XSSFWorkbook(input).getSheetAt(0)
// 循环读取表格数据
for (row in sheet) {
// 首行(即表头)不读取,后面可以校验表头
if (row.rowNum == 0) {
continue
}
// 读取当前行中单元格数据,索引从0开始
val name = row.getCell(0).stringCellValue
val id = row.getCell(1).numericCellValue.toLong()
val gender = row.getCell(2).stringCellValue == "男"
val grade = row.getCell(3).numericCellValue.toInt()
val classID = row.getCell(4).numericCellValue.toInt()
studentList.add(row.rowNum - 1, StudentBean(name, id, gender, grade, classID, 1))
}
// 关闭数据流
input.close()
return studentList
}
/**
* 删除全部学校数据
*/
fun deleteSchool() {
session.deleteAll()
Log.d(TAG, "当前学校数据已被清空,学校数据为${session.loadAll().size}")
}
/**
* 新增学校数据
*/
fun insertSchool() {
session.insert(SchoolBean("第${session.loadAll().size + 1}中学"))
}
/**
* 删除全部学校数据
*/
fun querySchool() {
val schoolList = session.loadAll()
var string = ""
for (item in schoolList) {
string += "和${item.schoolId}"
}
Log.d("学校数量", "当前学校数据有${schoolList.size}条,分别是$string")
}
} |
Education/app/src/main/java/com/example/education/ui/theme/Shape.kt | 2803858998 | package com.example.education.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ShapeDefaults
import androidx.compose.ui.unit.dp
//val Shapes = androidx.compose.material3.ShapeDefaults(
// small = RoundedCornerShape(4.dp),
// medium = RoundedCornerShape(4.dp),
// large = RoundedCornerShape(0.dp)
//) |
Education/app/src/main/java/com/example/education/ui/theme/Color.kt | 3382548824 | package com.example.education.ui.theme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Green500 = Color(0xFF1EB980)
val DarkBlue900 = Color(0xFF26282F)
// Rally is always dark themed.
val ColorPalette = darkColorScheme(
primary = Green500,
surface = DarkBlue900,
onSurface = Color.White,
background = DarkBlue900,
onBackground = Color.White
)
@Composable
fun ColorScheme.compositedOnSurface(alpha: Float): Color {
return onSurface.copy(alpha = alpha).compositeOver(surface)
} |
Education/app/src/main/java/com/example/education/ui/theme/Theme.kt | 2275804702 | package com.example.education.ui.theme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Typography
import androidx.compose.runtime.Composable
@Composable
fun EducationTheme(content: @Composable () -> Unit) {
MaterialTheme(colorScheme = ColorPalette, typography = Typography, content = content)
}
object MineTheme {
val colors: ColorScheme
@Composable get() = MaterialTheme.colorScheme
val typography: Typography
@Composable get() = MaterialTheme.typography
val shapes: Shapes
@Composable get() = MaterialTheme.shapes
val elevations: Elevations
@Composable get() = LocalElevations.current
} |
Education/app/src/main/java/com/example/education/ui/theme/Type.kt | 2507748309 | package com.example.education.ui.theme
import androidx.compose.material3.Typography
// Set of Material typography styles to start with
val Typography = Typography(
) |
Education/app/src/main/java/com/example/education/ui/theme/Elevations.kt | 186408104 | package com.example.education.ui.theme
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* @author fengerzhang
* @date 2021/12/14 15:03
*/
@Immutable
data class Elevations(val card: Dp = 0.dp)
internal val LocalElevations = staticCompositionLocalOf { Elevations() }
|
Education/app/src/main/java/com/example/education/App.kt | 949329162 | package com.example.education
import android.app.Application
import com.example.education.bean.DaoMaster
import com.example.education.bean.DaoSession
/**
* @author fengerzhang
* @date 2023/12/5 12:19
*/
class App: Application() {
companion object {
lateinit var daoSession: DaoSession
}
override fun onCreate() {
super.onCreate()
initGreenDao()
}
/**
* 初始化GreenDao,直接在Application中进行初始化操作
*/
private fun initGreenDao() {
/**
* 连接数据库并创建会话
*
* TODO 待修改数据库名字
*/
val devOpenHelper: DaoMaster.DevOpenHelper = DaoMaster.DevOpenHelper(this, "aserbao.db")
val db = devOpenHelper.writableDatabase
// 2、创建数据库连接
val daoMaster = DaoMaster(db)
// 3、创建数据库会话
daoSession = daoMaster.newSession()
}
} |
Education/app/src/main/java/com/example/education/MainActivity.kt | 2605734522 | package com.example.education
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.education.ui.theme.EducationTheme
import com.example.education.ui.theme.MineTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val mainViewModel: MainViewModel = viewModel()
EducationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
// 测试greendao功能
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(
onClick = { mainViewModel.querySchool() },
modifier = Modifier
.padding(5.dp)
.background(
color = MineTheme.colors.background,
shape = RoundedCornerShape(5.dp)
)
) {
Text(text = "查询学校数据")
}
Button(
onClick = { mainViewModel.insertSchool() },
modifier = Modifier
.padding(5.dp)
.background(
color = MineTheme.colors.background,
shape = RoundedCornerShape(5.dp)
)
) {
Text(text = "增加学校数据")
}
Button(
onClick = { mainViewModel.deleteSchool() },
modifier = Modifier
.padding(5.dp)
.background(
color = MineTheme.colors.background,
shape = RoundedCornerShape(5.dp)
)
) {
Text(text = "清除所有学校数据")
}
}
}
}
}
}
} |
Education/app/src/main/java/com/example/education/base/BaseViewModel.kt | 2254318890 | package com.example.education.base
import androidx.lifecycle.ViewModel
/**
* @author fengerzhang
* @date 2023/12/6 09:28
*/
open class BaseViewModel : ViewModel() {
} |
myassignment_st10442381/app/src/androidTest/java/com/example/myassignment/ExampleInstrumentedTest.kt | 3133898427 | package com.example.myassignment
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.myassignment", appContext.packageName)
}
} |
myassignment_st10442381/app/src/androidTest/java/com/example/myassignment/UnitTesting.kt | 4268032106 | import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.myassignment.MainActivity
import org.hamcrest.CoreMatchers.containsString
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class UnitTesting {
@Test
fun testAgeMatching() {
// Launch the MainActivity
ActivityScenario.launch(MainActivity::class.java)
// Input an age
onView(withId(R.id.numberAge)).perform(typeText("30"), closeSoftKeyboard())
// Click the button to find matching historical figures
onView(withId(R.id.btn1)).perform(click())
// Check if the matched historical figure information is displayed
onView(withId(R.id.information))
.check(matches(withText(containsString("Eazy-E"))))
}
@Test
fun testClearButton() {
// Launch the MainActivity
ActivityScenario.launch(MainActivity::class.java)
// Input an age
onView(withId(R.id.numberAge)).perform(typeText("40"), closeSoftKeyboard())
// Click the button to find matching historical figures
onView(withId(R.id.btn1)).perform(click())
// Check if the matched historical figure information is displayed
onView(withId(R.id.information))
.check(matches(withText(containsString("paul walker"))))
// Click the clear button
onView(withId(R.id.btn2)).perform(click())
// Check if the age input field is cleared
onView(withId(R.id.numberAge)).check(matches(withText("")))
// Check if the information field is empty
onView(withId(R.id.information)).check(matches(withText("")))
}
@Test
fun testInvalidAge() {
// Launch the MainActivity
ActivityScenario.launch(MainActivity::class.java)
// Input an invalid age
onView(withId(R.id.numberAge)).perform(typeText("10"), closeSoftKeyboard())
// Click the button to find matching historical figures
onView(withId(R.id.btn1)).perform(click())
// Check if the error message is displayed
onView(withId(R.id.information))
.check(matches(withText("No Figure has been found from the input of your age.")))
}
}
|
myassignment_st10442381/app/src/test/java/com/example/myassignment/ExampleUnitTest.kt | 3233357919 | package com.example.myassignment
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)
}
} |
myassignment_st10442381/app/src/main/java/com/example/myassignment/MainActivity.kt | 2181584287 | package com.example.myassignment
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
enum class HistoricalFigures(val age: Int, val description: String) {
Figure_1(20, "Cameron Boyce was a talented American actor and dancer known for his roles in Disney Channel productions"),
Figure_2(25, "Shawn Mendes , gained recognition on YouTube and Vine through his affiliation with the popular Vine group."),
Figure_3(30, "Eazy-E he is an influential West Coast rapper and producer who is known for being a part of the late 80's rap group" ),
Figure_4(35, "Anne Boleyn died at the age of 35, she was a English royalty who served as the Queen of England from 1533 to 1536"),
Figure_5(40,"paul walker Died at 40 Actor who won the 2001 Hollywood Breakthrough Award for New Male Style maker for his performance in The Fast and the Furious."),
Figure_6(45, "ian Somerhalder became Known to television drama audiences for playing the heartthrob Damon Salvatore. "),
Figure_7(50, " michael jackson died at 50 The King of Pop who became the most successful singer in American history for releasing award-winning hits."),
Figure_8(55, "Celine Dion is a pop and artist known for singing the theme from Titanic etc. "),
Figure_9(60, "michelle obama Former First Lady of the United States of America who married Barack Obama, the 44th President of the United States of America, in 1992"),
Figure_10(65, "Walt Disney is an Animator, voice actor, producer and entertainer who founded The Walt Disney Company and created the iconic character Mickey Mouse"),
Figure_11(70, "oprah winfrey Television host and producer who was named the most influential woman in the world by TIME magazine and hosted The Oprah Winfrey Show."),
Figure_12(75, "King Carles III Became King of the United Kingdom in September 2022, following the death of his mother"),
Figure_13(80, " Wallace Shawn is a comedic actor and writer best known for his roles in My Dinner with Andre and The Princess Bride."),
Figure_14(85,"James Madison died at the age 85, who was the fourth president of America and the father of the constitution,who notably authored America's Bill of Rights"),
Figure_15(90,"Winston Churchill died at the age of 90, he was the British Prime Minister during World War II who encouraged bravery and endurance."),
Figure_16(95, "Nelson Mandela died at the age of 95, he radically changed the conditions of the apartheid state of South Africa, He also became south Africa's first black president"),
Figure_17(100, "Gloria Stuart died at the age 100, she became an actress in the 1930s and later played Rose in the film Titanic"),
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn1 = findViewById<Button>(R.id.btn1)
val btn2 = findViewById<Button>(R.id.btn2)
val numberAge = findViewById<EditText>(R.id.numberAge)
val information = findViewById<TextView>(R.id.information)
btn1?.setOnClickListener {
val birthYear = numberAge.text.toString().toInt()
if(birthYear != null && birthYear in 20..100) {
val figuresAge = HistoricalFigures.values().map { it.age }
val descriptions = when (birthYear)
{
in figuresAge -> {
val description = HistoricalFigures.values().find { it.age == birthYear}
listOf(" $birthYear:${description?.description ?: "description"}")
}
in figuresAge.map { it - 1} ->{
val description = HistoricalFigures.values().find { it.age == birthYear + 1}
listOf("your age is one year before Historical Figure which is " +
"${description?.description ?: "figure"}")
}
in figuresAge.map { it + 1} -> {
val description = HistoricalFigures.values().find { it.age == birthYear - 1}
listOf("your age is one year after Historical Figure which is " +
"${description?.description ?: "figure"}")
}
in figuresAge.map { it + 2} ->{
val description = HistoricalFigures.values().find { it.age == birthYear - 2}
listOf("your age is two years after Historical Figure which is " +
"${description?.description ?: "figure"}")
}
in figuresAge.map { it - 2} ->{
val description = HistoricalFigures.values().find { it.age == birthYear + 2}
listOf("your age is two years before Historical Figure which is " +
"${description?.description ?: "figure"}")
}
else -> listOf(" No historical Figures found for $birthYear.")
}
information.text = descriptions.joinToString( "\n")
} else {
information.text = "No Figure has been found from the input of your age."
}
}
btn2?.setOnClickListener {
numberAge.text.clear()
information.text = ""
}
}
}
|
Room_LocalDatabase/app/src/androidTest/java/com/example/room/ExampleInstrumentedTest.kt | 1518437082 | package com.example.room
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.room", appContext.packageName)
}
} |
Room_LocalDatabase/app/src/test/java/com/example/room/ExampleUnitTest.kt | 2233529401 | package com.example.room
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)
}
} |
Room_LocalDatabase/app/src/main/java/com/example/room/viewmodel/ContactState.kt | 2244288410 | package com.example.room.viewmodel
import com.example.room.model.Contact
import com.example.room.model.SortType
data class ContactState(
val contacts: List<Contact> = emptyList(),
val firstName: String = "",
val lastName: String = "",
val phoneNumber: String = "",
val isAddingContact: Boolean = false,
val sortType: SortType = SortType.FIRST_NAME
)
|
Room_LocalDatabase/app/src/main/java/com/example/room/viewmodel/ContactViewModel.kt | 2113688084 | package com.example.room.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.room.data.ContactDao
import com.example.room.model.Contact
import com.example.room.model.SortType
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@OptIn(ExperimentalCoroutinesApi::class)
class ContactViewModel(private val dao: ContactDao) : ViewModel() {
private val _sortType = MutableStateFlow(SortType.FIRST_NAME)
private val _contacts = _sortType
.flatMapLatest {sortType ->
when(sortType){
SortType.FIRST_NAME -> dao.getContactsOrderedByFirstName()
SortType.LAST_NAME -> dao.getContactsOrderedByLastName()
SortType.PHONE_NUMBER -> dao.getContactsOrderedByPhoneNumber()
}
}
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())
private val _state = MutableStateFlow(ContactState())
val state = combine(_state,_sortType,_contacts){ state,sortType,contacts ->
state.copy(
contacts = contacts,
sortType = sortType,
)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), ContactState())
fun onEvent(event: ContactEvent){
when(event){
is ContactEvent.DeleteContact -> {
viewModelScope.launch {
dao.deleteContact(event.contact)
}
}
ContactEvent.HideDialog -> {
_state.update { it.copy(
isAddingContact = false
)
}
}
ContactEvent.SaveContact -> {
val firstName = state.value.firstName
val lastName = state.value.lastName
val phoneNumber = state.value.phoneNumber
if (firstName.isBlank() || lastName.isBlank() || phoneNumber.isBlank()){
return
}
val contact = Contact(
firstName = firstName,
lastName = lastName,
phoneNumber = phoneNumber
)
viewModelScope.launch {
dao.upsertContact(contact)
}
_state.update { it.copy(
isAddingContact = false,
firstName = "",
lastName = "",
phoneNumber = ""
)
}
}
is ContactEvent.SetFirstName -> {
_state.update {it.copy(
firstName = event.firstName
)
}
}
is ContactEvent.SetLastName -> {
_state.update {it.copy(
lastName = event.lastName
)
}
}
is ContactEvent.SetPhoneNumber -> {
_state.update {it.copy(
phoneNumber = event.phoneNumber
)
}
}
ContactEvent.ShowDialog -> {
_state.update {it.copy(
isAddingContact = true
)
}
}
is ContactEvent.SortContacts -> {
_sortType.value = event.sortType
}
}
}
} |
Room_LocalDatabase/app/src/main/java/com/example/room/viewmodel/ContactEvent.kt | 506483709 | package com.example.room.viewmodel
import com.example.room.model.Contact
import com.example.room.model.SortType
sealed interface ContactEvent {
//Event with State
object SaveContact : ContactEvent
object ShowDialog : ContactEvent
object HideDialog : ContactEvent
//Event with Database
data class SetFirstName(val firstName: String) : ContactEvent
data class SetLastName(val lastName: String) : ContactEvent
data class SetPhoneNumber(val phoneNumber: String) : ContactEvent
data class SortContacts(val sortType : SortType) : ContactEvent
data class DeleteContact(val contact: Contact) : ContactEvent
} |
Room_LocalDatabase/app/src/main/java/com/example/room/ui/screens/ContactScreen.kt | 2979997111 | package com.example.room.ui.screens
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.example.room.model.SortType
import com.example.room.ui.widgets.AddContactDialog
import com.example.room.viewmodel.ContactEvent
import com.example.room.viewmodel.ContactState
@Composable
fun ContactScreen(
state: ContactState,
onEvent: (ContactEvent) -> Unit
){
Scaffold(
floatingActionButton = {
FloatingActionButton(onClick = {
onEvent(ContactEvent.ShowDialog)
}) {
Icon(imageVector = Icons.Default.Add, contentDescription ="Add")
}
}
){ padding ->
if (state.isAddingContact){
AddContactDialog(state = state, onEvent = onEvent)
}
LazyColumn(
contentPadding = padding,
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
){
item{
Row(modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState()),
verticalAlignment = Alignment.CenterVertically
){
SortType.entries.forEach { sortType ->
Row(modifier = Modifier.clickable {
onEvent(ContactEvent.SortContacts(sortType = sortType))
}, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center){
RadioButton(selected = state.sortType == sortType, onClick = {
onEvent(ContactEvent.SortContacts(sortType))
})
Text(text = sortType.name)
}
}
}
}
items(state.contacts){ contact ->
Row(modifier = Modifier.fillMaxWidth()){
Column(modifier = Modifier.weight(1f)){
Text(text = "${contact.firstName} ${contact.lastName}", fontSize = 20.sp)
Text(text = contact.phoneNumber, fontSize = 12.sp)
}
IconButton(onClick = { onEvent(ContactEvent.DeleteContact(contact = contact)) }) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete Account")
}
}
}
}
}
} |
Room_LocalDatabase/app/src/main/java/com/example/room/ui/theme/Color.kt | 2493359795 | package com.example.room.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) |
Room_LocalDatabase/app/src/main/java/com/example/room/ui/theme/Theme.kt | 1106103487 | package com.example.room.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 RoomLocalDatabaseTheme(
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
)
} |
Room_LocalDatabase/app/src/main/java/com/example/room/ui/theme/Type.kt | 1754787796 | package com.example.room.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
)
*/
) |
Room_LocalDatabase/app/src/main/java/com/example/room/ui/widgets/AddContactDialog.kt | 921653084 | package com.example.room.ui.widgets
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.example.room.viewmodel.ContactEvent
import com.example.room.viewmodel.ContactState
@Composable
fun AddContactDialog(
state: ContactState,
onEvent: (ContactEvent) -> Unit,
modifier: Modifier = Modifier
){
AlertDialog(
modifier = Modifier,
onDismissRequest = {
onEvent(ContactEvent.HideDialog)
},
confirmButton = {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd){
Button(onClick = { onEvent(ContactEvent.SaveContact) }) {
Text(text = "Save Contact")
}
}
},
title = {
Text(text = "Add Contact")
},
text = {
Column {
TextField(value = state.firstName, onValueChange = {
onEvent(ContactEvent.SetFirstName(it))
}, placeholder = {
Text(text = "First Name")
})
TextField(value = state.lastName, onValueChange = {
onEvent(ContactEvent.SetLastName(it))
}, placeholder = {
Text(text = "Last Name")
})
TextField(value = state.phoneNumber, onValueChange = {
onEvent(ContactEvent.SetPhoneNumber(it))
}, placeholder = {
Text(text = "Phone Number")
})
}
},
)
} |
Room_LocalDatabase/app/src/main/java/com/example/room/MainActivity.kt | 3360819705 | package com.example.room
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.room.Room
import com.example.room.data.ContactDatabase
import com.example.room.ui.screens.ContactScreen
import com.example.room.ui.theme.RoomLocalDatabaseTheme
import com.example.room.viewmodel.ContactViewModel
class MainActivity : ComponentActivity() {
private val db by lazy {
Room.databaseBuilder(
applicationContext,
ContactDatabase::class.java,
"contacts.db"
).build()
}
private val viewModel by viewModels<ContactViewModel>(
factoryProducer = {
object : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ContactViewModel(db.dao) as T
}
}
},
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RoomLocalDatabaseTheme {
val state by viewModel.state.collectAsState()
ContactScreen(state = state, onEvent = viewModel::onEvent)
}
}
}
}
|
Room_LocalDatabase/app/src/main/java/com/example/room/model/SortType.kt | 2960621502 | package com.example.room.model
enum class SortType {
FIRST_NAME,
LAST_NAME,
PHONE_NUMBER
} |
Room_LocalDatabase/app/src/main/java/com/example/room/model/Contact.kt | 759489465 | package com.example.room.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Contact(
val firstName:String,
val lastName:String,
val phoneNumber:String,
@PrimaryKey(autoGenerate = true)
val id:Int? = 0,
)
|
Room_LocalDatabase/app/src/main/java/com/example/room/data/ContactDatabase.kt | 3229366508 | package com.example.room.data
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.room.model.Contact
@Database(
entities = [Contact::class],
version = 1
)
abstract class ContactDatabase : RoomDatabase() {
abstract val dao: ContactDao
} |
Room_LocalDatabase/app/src/main/java/com/example/room/data/ContactDao.kt | 2182226505 | package com.example.room.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Upsert
import com.example.room.model.Contact
@Dao
interface ContactDao{
@Upsert
suspend fun upsertContact(contact: Contact)
@Delete
suspend fun deleteContact(contact: Contact)
@Query("SELECT * FROM contact ORDER BY firstName ASC")
fun getContactsOrderedByFirstName(): kotlinx.coroutines.flow.Flow<List<Contact>>
@Query("SELECT * FROM contact ORDER BY lastName ASC")
fun getContactsOrderedByLastName(): kotlinx.coroutines.flow.Flow<List<Contact>>
@Query("SELECT * FROM contact ORDER BY phoneNumber ASC")
fun getContactsOrderedByPhoneNumber(): kotlinx.coroutines.flow.Flow<List<Contact>>
}
|
api_warehouse/WarehouseManagerApp/app/src/androidTest/java/com/example/warehousemanagerapp/ExampleInstrumentedTest.kt | 635350898 | package com.example.warehousemanagerapp
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.warehousemanagerapp", appContext.packageName)
}
} |
api_warehouse/WarehouseManagerApp/app/src/test/java/com/example/warehousemanagerapp/ExampleUnitTest.kt | 2026528456 | package com.example.warehousemanagerapp
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)
}
} |
api_warehouse/WarehouseManagerApp/app/src/main/java/com/example/warehousemanagerapp/ui/theme/Color.kt | 1709170081 | package com.example.warehousemanagerapp.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)
// github color picker
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)
val md_theme_light_primary = Color(0xFF474CD4)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFE1E0FF)
val md_theme_light_onPrimaryContainer = Color(0xFF04006D)
val md_theme_light_secondary = Color(0xFF5C5D72)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFE2E0F9)
val md_theme_light_onSecondaryContainer = Color(0xFF191A2C)
val md_theme_light_tertiary = Color(0xFF79536A)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFD8ED)
val md_theme_light_onTertiaryContainer = Color(0xFF2E1125)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF1C1B1F)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF1C1B1F)
val md_theme_light_surfaceVariant = Color(0xFFE4E1EC)
val md_theme_light_onSurfaceVariant = Color(0xFF46464F)
val md_theme_light_outline = Color(0xFF777680)
val md_theme_light_inverseOnSurface = Color(0xFFF3EFF4)
val md_theme_light_inverseSurface = Color(0xFF313034)
val md_theme_light_inversePrimary = Color(0xFFC0C1FF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF474CD4)
val md_theme_light_outlineVariant = Color(0xFFC7C5D0)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFC0C1FF)
val md_theme_dark_onPrimary = Color(0xFF0C04A8)
val md_theme_dark_primaryContainer = Color(0xFF2D2FBC)
val md_theme_dark_onPrimaryContainer = Color(0xFFE1E0FF)
val md_theme_dark_secondary = Color(0xFFC5C4DD)
val md_theme_dark_onSecondary = Color(0xFF2E2F42)
val md_theme_dark_secondaryContainer = Color(0xFF454559)
val md_theme_dark_onSecondaryContainer = Color(0xFFE2E0F9)
val md_theme_dark_tertiary = Color(0xFFE8B9D4)
val md_theme_dark_onTertiary = Color(0xFF46263B)
val md_theme_dark_tertiaryContainer = Color(0xFF5F3C52)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFD8ED)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1C1B1F)
val md_theme_dark_onBackground = Color(0xFFE5E1E6)
val md_theme_dark_surface = Color(0xFF1C1B1F)
val md_theme_dark_onSurface = Color(0xFFE5E1E6)
val md_theme_dark_surfaceVariant = Color(0xFF46464F)
val md_theme_dark_onSurfaceVariant = Color(0xFFC7C5D0)
val md_theme_dark_outline = Color(0xFF918F9A)
val md_theme_dark_inverseOnSurface = Color(0xFF1C1B1F)
val md_theme_dark_inverseSurface = Color(0xFFE5E1E6)
val md_theme_dark_inversePrimary = Color(0xFF474CD4)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFC0C1FF)
val md_theme_dark_outlineVariant = Color(0xFF46464F)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF7177FF)
val CustomColor1 = Color(0xFF9E6C3C)
val light_CustomColor1 = Color(0xFF8D4F00)
val light_onCustomColor1 = Color(0xFFFFFFFF)
val light_CustomColor1Container = Color(0xFFFFDCC0)
val light_onCustomColor1Container = Color(0xFF2D1600)
val dark_CustomColor1 = Color(0xFFFFB875)
val dark_onCustomColor1 = Color(0xFF4B2800)
val dark_CustomColor1Container = Color(0xFF6B3B00)
val dark_onCustomColor1Container = Color(0xFFFFDCC0) |
api_warehouse/WarehouseManagerApp/app/src/main/java/com/example/warehousemanagerapp/ui/theme/Theme.kt | 3688654047 | package com.example.warehousemanagerapp.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.ViewCompat
private val DarkColorScheme = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
private val LightColorScheme = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
/* 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 WarehouseManagerAppTheme(
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 {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
api_warehouse/WarehouseManagerApp/app/src/main/java/com/example/warehousemanagerapp/ui/theme/Type.kt | 3223542279 | package com.example.warehousemanagerapp.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
)
*/
) |
api_warehouse/WarehouseManagerApp/app/src/main/java/com/example/warehousemanagerapp/MainActivity.kt | 226902293 | package com.example.warehousemanagerapp
import android.content.Intent
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.Scaffold
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 androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.Navigation
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.warehousemanagerapp.ui.theme.WarehouseManagerAppTheme
import com.example.warehousemanagerapp.view.loginWarehouse.LogScreenViewModel
import com.example.warehousemanagerapp.view.loginWarehouse.warehouseNav.NavigationBarItem
import com.example.warehousemanagerapp.view.loginWarehouse.warehouseNav.WarehouseActivity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val context = applicationContext
setContent {
WarehouseManagerAppTheme {
val logScreenViewModel: LogScreenViewModel = viewModel()
// A surface container using the 'background' color from the theme
Navigation(logScreenViewModel, context)
}
}
}
}
//
//@Composable
//fun Greeting(name: String) {
// Text(text = "Hello $name!")
//}
//
//@Preview(showBackground = true)
//@Composable
//fun DefaultPreview() {
// WarehouseManagerAppTheme {
// Greeting("Android")
// }
//} |
api_warehouse/WarehouseManagerApp/app/src/main/java/com/example/warehousemanagerapp/util/Consts.kt | 43246756 | package com.example.warehousemanagerapp.util
object JsonConst {
const val WAREHOUSE_ID = "id"
const val NAME = "name"
const val PASSWORD = "password"
const val ADDRESS = "address"
const val COLOR = "color"
const val IMAGE = "image"
const val ADDRESS_ID = "id"
const val STREET_NAME = "street_name"
const val HOUSE_NUMBER = "house_number"
const val LOCAL_NUMBER = "local_number"
const val PLACE = "place"
const val CODE = "code"
const val OWNER_NAME = "name"
const val EMAIL = "email"
const val OWNER = "owner"
const val OWNER_ID = "id"
const val CONTRACTORS = "contractors"
const val CONTRACTOR_ID = "id"
const val CONTRACTOR_NAME = "name"
const val CONTRACTOR_ADDRESS = "address"
const val RECIPIENT = "recipient"
const val SUPPLIER = "supplier"
const val NIP = "nip"
const val COMMODITIES = "commodities"
const val COMMODITIES_ID = "id"
const val COMMODITIES_NAME = "name"
const val COUNTER = "counter"
const val TEMP_COUNTER = "temp_counter"
const val DESCRIPTION = "description"
const val EXPIRATION_DATE = "expiration_date"
const val UNIT = "unit"
const val ORDERS = "orders"
const val ORDER_ID = "id"
const val SUBMIT_TIME = "submit_time"
const val ACCEPT_TIME = "accept_time"
const val COMPLETED_TIME = "completed_time"
const val ORDER_STATUS = "order_status"
const val CONTRACTOR = "contractor"
const val COMMODITIES_LIST = "commodities_list"
const val STORE_ACTIONS = "store_actions"
const val STORE_ACTION_DATE = "date"
const val STORE_ACTION_ID = "id"
const val DOC_NUMBER = "doc_number"
const val COMMODITY_ID = "commodity"
const val QUANTITY = "quantity"
const val TYPE = "type" //Receipt or Release
} |
Subsets and Splits