path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
klox/klox/src/main/kotlin/interpreter/Environment.kt
1474512797
package interpreter import parser.Token class Environment( val enclosing: Environment? = null ) { private val values = HashMap<String, Any?>() fun define(name: String, value: Any?) { values[name] = value } fun ancestor(distance: Int): Environment { var environment: Environment = this for (i in 0..<distance) { environment = environment.enclosing!! } return environment } fun get(name: Token): Any? { if (values.containsKey(name.lexeme)) { return values[name.lexeme] } if (enclosing != null) { return enclosing.get(name) } throw Interpreter.RuntimeError(name, "Undefined variable '${name.lexeme}'.") } fun getAt(distance: Int, name: String): Any? { return ancestor(distance).values[name] } fun assign(name: Token, value: Any?) { if (values.containsKey(name.lexeme)) { values[name.lexeme] = value return } if (enclosing != null) { enclosing.assign(name, value) return } throw Interpreter.RuntimeError(name, "Undefined variable '${name.lexeme}'.") } fun assignAt(distance: Int, name: Token, value: Any?) { ancestor(distance).values[name.lexeme] = value } }
klox/klox/src/main/kotlin/interpreter/Interpreter.kt
3099179048
package interpreter import LoxCallable import LoxClass import LoxFunction import LoxInstance import OutputHandler import parser.Token import parser.TokenType.* import ast.Expr import ast.Stmt class Interpreter : Expr.Visitor<Any?>, Stmt.Visitor<Unit> { val globals = Environment() private var environment = globals private val locals: MutableMap<Expr, Int> = HashMap() init { globals.define("clock", object: LoxCallable { override fun arity(): Int { return 0 } override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? { return System.currentTimeMillis() / 1000.0 } override fun toString(): String { return "<native fn>" } }) } fun interpret(statements: List<Stmt?>) { try { statements.forEach(this::execute) } catch (error: RuntimeError) { OutputHandler.runtimeError(error) } } fun executeBlock( statements: List<Stmt?>, environment: Environment ) { val previous = this.environment try { this.environment = environment statements.forEach(this::execute) } finally { this.environment = previous } } fun resolve(expr: Expr, depth: Int) { locals[expr] = depth } override fun visitAssignExpr(expr: Expr.Assign): Any? { val value = evaluate(expr.value) val distance = locals[expr] if (distance != null) { environment.assignAt(distance, expr.name, value) } else { globals.assign(expr.name, value) } return value } override fun visitBinaryExpr(expr: Expr.Binary): Any? { val left = evaluate(expr.left) val right = evaluate(expr.right) val asNumbers = fun (predicate: (Double, Double) -> Any?): Any? { checkNumberOperands(expr.operator, left, right) return predicate(left as Double, right as Double) } return when (expr.operator.type) { BANG_EQUAL -> !isEqual(left, right) EQUAL_EQUAL -> isEqual(left, right) GREATER -> asNumbers { a, b -> a > b } GREATER_EQUAL -> asNumbers { a, b -> a >= b } LESS -> asNumbers { a, b -> a < b } LESS_EQUAL -> asNumbers { a, b -> a <= b } MINUS -> asNumbers { a, b -> a - b } SLASH -> asNumbers { a, b -> a / b } STAR -> asNumbers { a, b -> a * b } PLUS -> { when { left is Double && right is Double -> left + right left is String && right is String -> left + right else -> null // unreachable } } else -> null // unreachable } } override fun visitCallExpr(expr: Expr.Call): Any? { val callee = evaluate(expr.callee) val arguments = expr.arguments.map { evaluate(it) } return when (callee) { is LoxCallable -> { if (arguments.size != callee.arity()) { throw RuntimeError(expr.paren, "Expected ${callee.arity()} arguments but got ${arguments.size}.") } callee.call(this, arguments) } else -> throw RuntimeError(expr.paren, "Can only call functions and classes.") } } override fun visitGetExpr(expr: Expr.Get): Any? { val instance: Any? = evaluate(expr.instance) if (instance is LoxInstance) { return instance.get(expr.name) } throw RuntimeError(expr.name, "Only instances have properties") } override fun visitGroupingExpr(expr: Expr.Grouping): Any? { return evaluate(expr.expression) } override fun visitLiteralExpr(expr: Expr.Literal): Any? { return expr.value } override fun visitLogicalExpr(expr: Expr.Logical): Any? { val left = evaluate(expr.left) if (expr.operator.type == OR) { if (isTruthy(left)) { return left } } else { if (!isTruthy(left)) { return left } } return evaluate(expr.right) } override fun visitSetExpr(expr: Expr.Set): Any? { val instance = evaluate(expr.instance) if (instance !is LoxInstance) { throw RuntimeError(expr.name, "Only instances have fields.") } val value = evaluate(expr.value) instance.set(expr.name, value) return value } override fun visitUnaryExpr(expr: Expr.Unary): Any? { val right = evaluate(expr.right) return when (expr.operator.type) { BANG -> !isTruthy(right) MINUS -> { checkNumberOperand(expr.operator, right) -(right as Double) } else -> null } } override fun visitVariableExpr(expr: Expr.Variable): Any? { return lookUpVariable(expr.name, expr) } private fun lookUpVariable(name: Token, expr: Expr): Any? { val distance = locals[expr] return distance?.let { environment.getAt(distance, name.lexeme) } ?: globals.get(name) } private fun evaluate(expr: Expr): Any? { return expr.accept(this) } private fun execute(stmt: Stmt?) { stmt?.accept(this) } override fun visitBlockStmt(stmt: Stmt.Block) { executeBlock(stmt.statements, Environment(environment)) } override fun visitClassStmt(stmt: Stmt.Class) { environment.define(stmt.name.lexeme, null) val klass = LoxClass(stmt.name.lexeme) environment.assign(stmt.name, klass) } override fun visitExpressionStmt(stmt: Stmt.Expression) { evaluate(stmt.expression) } override fun visitFunctionStmt(stmt: Stmt.Function) { val function = LoxFunction(stmt, environment) environment.define(stmt.name.lexeme, function) } override fun visitIfStmt(stmt: Stmt.If) { if (isTruthy(evaluate(stmt.condition))) { execute(stmt.thenBranch) } else if (stmt.elseBranch != null) { execute(stmt.elseBranch) } } override fun visitPrintStmt(stmt: Stmt.Print) { val value = evaluate(stmt.expression) println(stringify(value)) } override fun visitReturnStmt(stmt: Stmt.Return) { val value = stmt.value?.let(this::evaluate) // I agree with the book that while using an exception for control flow // is bad form. The alternative in a recursive interpreter like this // would be hard to implmenent, confusing to read and follow, and hard // to reason about. Some of the features of the exception are disabled to // try and lower the overhead of this. throw Return(value) } override fun visitVarStmt(stmt: Stmt.Var) { val value: Any? = stmt.initializer?.let(this::evaluate) environment.define(stmt.name.lexeme, value) } override fun visitWhileStmt(stmt: Stmt.While) { while (isTruthy(evaluate(stmt.condition))) { execute(stmt.body) } } private fun isTruthy(value: Any?): Boolean { return when(value) { is Boolean -> value null -> false else -> true } } private fun isEqual(a: Any?, b: Any?): Boolean { if (a == null && b == null) { return true } if (a == null) { return false } return a == b } private fun stringify(value: Any?): String { if (value == null) { return "nil" } if (value is Double) { var text = value.toString() if (text.endsWith(".0")) { text = text.substring(0, text.length - 2) } return text } return value.toString() } private fun checkNumberOperand(operator: Token, operand: Any?) { if (operand is Double) { return } throw RuntimeError(operator, "Operand must be a number.") } private fun checkNumberOperands(operator: Token, left: Any?, right: Any?) { if (left is Double && right is Double) { return } throw RuntimeError(operator, "Operands must both be numbers.") } class RuntimeError(val token: Token, message: String): RuntimeException(message) class Return(val value: Any?): RuntimeException(null, null, false, false) }
klox/klox/src/main/kotlin/interpreter/LoxCallable.kt
186389425
import ast.Stmt import interpreter.Environment import interpreter.Interpreter import parser.Token interface LoxCallable { fun arity(): Int fun call(interpreter: Interpreter, arguments: List<Any?>): Any? } class LoxFunction( private val declaration: Stmt.Function, private val closure: Environment, ) : LoxCallable { override fun arity(): Int { return declaration.params.size } override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? { val environment = Environment(closure) declaration.params.forEachIndexed { index, param -> environment.define(param.lexeme, arguments[index]) } try { interpreter.executeBlock(declaration.body, environment) } catch (returnThrowable: Interpreter.Return) { return returnThrowable.value } return null } override fun toString(): String { return "<fn ${declaration.name.lexeme}>" } } class LoxClass( val name: String ): LoxCallable { override fun arity(): Int { return 0 } override fun call(interpreter: Interpreter, arguments: List<Any?>): Any? { return LoxInstance(this) } override fun toString(): String { return name } } class LoxInstance( private val klass: LoxClass, private val fields: MutableMap<String, Any?> = HashMap() ) { fun get(name: Token): Any? { if (!fields.containsKey(name.lexeme)) { throw Interpreter.RuntimeError(name, "Undefined property '${name.lexeme}'.") } return fields[name.lexeme] } fun set(name: Token, value: Any?) { fields[name.lexeme] = value } override fun toString(): String { return "${klass.name} instance" } }
klox/klox/src/main/kotlin/Resolver.kt
1586051446
import ast.Expr import ast.Stmt import interpreter.Interpreter import parser.Token import java.util.* class Resolver( private val interpreter: Interpreter ): Expr.Visitor<Unit>, Stmt.Visitor<Unit> { private enum class FunctionType { NONE, FUNCTION } private val scopes = Stack<MutableMap<String, Boolean>>() private var currentFunction = FunctionType.NONE override fun visitAssignExpr(expr: Expr.Assign) { resolve(expr.value) resolveLocal(expr, expr.name) } override fun visitBinaryExpr(expr: Expr.Binary) { resolve(expr.left) resolve(expr.right) } override fun visitCallExpr(expr: Expr.Call) { resolve(expr.callee) expr.arguments.forEach(::resolve) } override fun visitGetExpr(expr: Expr.Get) { resolve(expr.instance) } override fun visitGroupingExpr(expr: Expr.Grouping) { resolve(expr.expression) } override fun visitLiteralExpr(expr: Expr.Literal) { // no-op } override fun visitLogicalExpr(expr: Expr.Logical) { resolve(expr.left) resolve(expr.right) } override fun visitSetExpr(expr: Expr.Set) { resolve(expr.value) resolve(expr.instance) } override fun visitUnaryExpr(expr: Expr.Unary) { resolve(expr.right) } override fun visitVariableExpr(expr: Expr.Variable) { if (scopes.isNotEmpty() && scopes.peek()[expr.name.lexeme] == false) { OutputHandler.error(expr.name, "Can't read local variable in its own initializer.") } resolveLocal(expr, expr.name) } override fun visitBlockStmt(stmt: Stmt.Block) { beginScope() resolve(stmt.statements) endScope() } override fun visitClassStmt(stmt: Stmt.Class) { declare(stmt.name) define(stmt.name) } override fun visitExpressionStmt(stmt: Stmt.Expression) { resolve(stmt.expression) } override fun visitFunctionStmt(stmt: Stmt.Function) { declare(stmt.name) define(stmt.name) resolveFunction(stmt, FunctionType.FUNCTION) } override fun visitIfStmt(stmt: Stmt.If) { resolve(stmt.condition) resolve(stmt.thenBranch) stmt.elseBranch?.let(::resolve) } override fun visitPrintStmt(stmt: Stmt.Print) { resolve(stmt.expression) } override fun visitReturnStmt(stmt: Stmt.Return) { if (currentFunction == FunctionType.NONE) { OutputHandler.error(stmt.keyword, "Can't return from top-level code.") } stmt.value?.let(::resolve) } override fun visitVarStmt(stmt: Stmt.Var) { declare(stmt.name) stmt.initializer?.let(::resolve) define(stmt.name) } override fun visitWhileStmt(stmt: Stmt.While) { resolve(stmt.condition) resolve(stmt.body) } fun resolve(statements: List<Stmt?>) { statements.forEach(::resolve) } private fun resolve(statement: Stmt?) { statement?.accept(this) } private fun resolve(expression: Expr) { expression.accept(this) } private fun resolveLocal(expression: Expr, name: Token) { // starts at innermost scope and works outwards for (i in (scopes.size - 1) downTo 0) { if (scopes[i].containsKey(name.lexeme)) { interpreter.resolve(expression, (scopes.size - 1) - i) return } } } private fun resolveFunction( function: Stmt.Function, type: FunctionType ) { val enclosingFunction = currentFunction currentFunction = type beginScope() function.params.forEach { declare(it) define(it) } resolve(function.body) endScope() currentFunction = enclosingFunction } private fun beginScope() { scopes.push(HashMap<String, Boolean>()) } private fun endScope() { scopes.pop() } private fun declare(name: Token) { if (scopes.isEmpty()) { return } val scope = scopes.peek() if (scope.containsKey(name.lexeme)) { OutputHandler.error(name, "Already a variable with this name in this scope.") } scope[name.lexeme] = false } private fun define(name: Token) { if (scopes.isEmpty()) { return } scopes.peek()[name.lexeme] = true } }
klox/klox/src/main/kotlin/parser/Parser.kt
3682287088
package parser import OutputHandler import parser.TokenType.* import ast.Expr import ast.Stmt class Parser( private val tokens: List<Token> ) { private var current = 0 // program → declaration* EOF fun parse(): List<Stmt?> { val statements = mutableListOf<Stmt?>() while(!isAtEnd()) { statements.add(declaration()) } return statements } // -- PRODUCTIONS -- // // declaration → classDecl | funDecl | varDecl | statement // funDecl → "fun" function ; private fun declaration(): Stmt? { try { return when { match(CLASS) -> classDeclaration() match(FUN) -> function("function") match(VAR) -> varDeclaration() else -> statement() } } catch (error: ParseError) { synchronize() return null } } // classDecl → "class" IDENTIFIER "{" function* "}" ; private fun classDeclaration(): Stmt { val name = consume(IDENTIFIER, "Expect class name.") consume(LEFT_BRACE, "Expect '{' before class body.") val methods: MutableList<Stmt.Function> = ArrayList() while (!check(RIGHT_BRACE) && !isAtEnd()) { methods.add(function("method") as Stmt.Function) } consume(RIGHT_BRACE, "Expect '}' after class body.") return Stmt.Class(name, methods) } // function → IDENTIFIER "(" parameters? ")" block; private fun function(kind: String): Stmt { val name: Token = consume(IDENTIFIER, "Expect $kind name.") consume(LEFT_PAREN, "Expect '(' after $kind name.") val parameters = mutableListOf<Token>() if (!check(RIGHT_PAREN)) { do { if (parameters.size >= 255) { error(peek(), "Can't have more than 255 parameters.") } parameters.add( consume(IDENTIFIER, "Expect parameter name.") ) } while (match(COMMA)) } consume(RIGHT_PAREN, "Expect ')' after parameters.") consume(LEFT_BRACE, "Expect '{' before $kind body.") val body = block() return Stmt.Function(name, parameters, body) } // varDecl → "var" IDENTIFIER ( "=" expression )? ";" ; private fun varDeclaration(): Stmt { val name: Token = consume(IDENTIFIER, "Expect variable name") var initializer: Expr? = null if (match(EQUAL)) { initializer = expression() } consume(SEMICOLON, "Expect ';' after variable declaration") return Stmt.Var(name, initializer) } // statement → exprStmt | forStmt | ifStmt | printStmt | returnStmt | whileStmt | block private fun statement(): Stmt { return when { match(FOR) -> forStatement() match(IF) -> ifStatement() match(PRINT) -> printStatement() match(RETURN) -> returnStatement() match(WHILE) -> whileStatement() match(LEFT_BRACE) -> Stmt.Block(block()) else -> expressionStatement() } } // forStmt → "for" "(" ( varDecl | exprStmt | ";" ) expression? ";" expression? ")" statement ; private fun forStatement(): Stmt { consume(LEFT_PAREN, "Expect '(' after 'for'.") val initializer: Stmt? = if (match(SEMICOLON)) { null } else if (match(VAR)) { varDeclaration() } else { expressionStatement() } val condition: Expr = if (!check(SEMICOLON)) expression() else Expr.Literal(true) consume(SEMICOLON, "Expect ';' after loop condition.") val increment: Expr? = if(!check(RIGHT_PAREN)) expression() else null consume(RIGHT_PAREN, "Expect ')' after for clauses.") var body = statement() increment?.let { body = Stmt.Block(listOf(body, Stmt.Expression(it))) } body = Stmt.While(condition, body) initializer?.let { body = Stmt.Block(listOf(it, body)) } return body } // ifStmt → "if" "(" expression ")" statement ( "else" statement )? ; private fun ifStatement(): Stmt { consume(LEFT_PAREN, "Expect '(' after 'if'.") val condition = expression() consume(RIGHT_PAREN, "Expect ') after 'if' condition.") val thenBranch = statement() val elseBranch: Stmt? = if (match(ELSE)) statement() else null return Stmt.If(condition, thenBranch, elseBranch) } private fun printStatement(): Stmt { val value = expression() consume(SEMICOLON, "Expect ';' after value.") return Stmt.Print(value) } // returnStmt → "return" expression? ";" ; private fun returnStatement(): Stmt { val keyword = previous() val value: Expr? = if (!check(SEMICOLON)) expression() else null consume(SEMICOLON, "Expect ';' after return value.") return Stmt.Return(keyword, value) } // whileStmt → "while" "(" expression ")" statement ; private fun whileStatement(): Stmt { consume(LEFT_PAREN, "Expect '(' after 'while'.") val condition = expression() consume(RIGHT_PAREN, "Expect ')' after condition.") val body = statement() return Stmt.While(condition, body) } private fun block(): List<Stmt?> { val statements = mutableListOf<Stmt?>() while (!check(RIGHT_BRACE) && !isAtEnd()) { statements.add(declaration()) } consume(RIGHT_BRACE, "Expect '}' after block.") return statements } private fun expressionStatement(): Stmt { val expr = expression() consume(SEMICOLON, "Expect ';' after expression.") return Stmt.Expression(expr) } // expression → assignment private fun expression(): Expr { return assignment() } // assignment → ( call "." )? IDENTIFIER "=" assignment | logic_or ; private fun assignment(): Expr { val expr: Expr = logicOr() if (match(EQUAL)) { val equals = previous() val value = assignment() if (expr is Expr.Variable) { val name = expr.name return Expr.Assign(name, value) } else if (expr is Expr.Get) { return Expr.Set(expr.instance, expr.name, value) } error(equals, "Invalid assignment target.") } return expr } // logic_or → logic_and ( "or" logic_and )* ; private fun logicOr(): Expr { var expr: Expr = logicAnd() while (match(OR)) { val operator = previous() val right = logicAnd() expr = Expr.Logical(expr, operator, right) } return expr } // logic_and → equality ( "and" equality )* ; private fun logicAnd(): Expr { var expr = equality() while (match(AND)) { val operator = previous() val right = equality() expr = Expr.Logical(expr, operator, right) } return expr } // equality → comparison ( ( "!=" | "==" ) comparison )* private fun equality(): Expr { var expr = comparison() while (match(BANG_EQUAL, EQUAL_EQUAL)) { val operator = previous() val right = comparison() expr = Expr.Binary(expr, operator, right) } return expr } // comparison → term ( ( ">" | ">=" | "<" | "<=" ) term )* private fun comparison(): Expr { var expr = term() while (match(GREATER, GREATER_EQUAL, LESS, LESS_EQUAL)) { val operator = previous() val right = term() expr = Expr.Binary(expr, operator, right) } return expr } // term → factor ( ( "-" | "+" ) factor )* private fun term(): Expr { var expr = factor() while (match(MINUS, PLUS)) { val operator = previous() val right = factor() expr = Expr.Binary(expr, operator, right) } return expr } // factor → unary ( ( "/" | "*" ) unary )* private fun factor(): Expr { var expr = unary() while (match(SLASH, STAR)) { val operator = previous() val right = unary() expr = Expr.Binary(expr, operator, right) } return expr } // unary → ( "!" | "-" ) unary | call ; private fun unary(): Expr { if (match(BANG, MINUS)) { val operator = previous() val right = unary() return Expr.Unary(operator, right) } return call() } // call → primary ( "(" arguments? ")" | "." IDENTIFIER )* ; private fun call(): Expr { var expr = primary() while (true) { if (match(LEFT_PAREN)) { expr = arguments(expr); } else if (match(DOT)) { val name = consume(IDENTIFIER, "Expect property name after '.'.") expr = Expr.Get(expr, name) } else { break } } return expr; } // primary → NUMBER | STRING | "true" | "false" | "nil" | "(" expression ")" private fun primary(): Expr { when { match(FALSE) -> return Expr.Literal(false) match(TRUE) -> return Expr.Literal(true) match(NIL) -> return Expr.Literal(null) match(NUMBER, STRING) -> return Expr.Literal(previous().literal) match(IDENTIFIER) -> return Expr.Variable(previous()) match(LEFT_PAREN) -> { val expr = expression() consume(RIGHT_PAREN, "Expect ')' after expression.") return Expr.Grouping(expr) } else -> throw error(peek(), "Expect expression.") } } // arguments → expression ( "," expression )* ; private fun arguments(callee: Expr): Expr { val arguments = mutableListOf<Expr>() if (!check(RIGHT_PAREN)) { do { if (arguments.size >= 255) { error(peek(), "Can't have more than 255 arguments.") } arguments.add(expression()); } while (match(COMMA)); } val paren = consume(RIGHT_PAREN, "Expect ')' after arguments.") return Expr.Call(callee, paren, arguments) } // -- utils -- // private fun match(vararg types: TokenType): Boolean { for(type in types) { if (check(type)) { advance() return true } } return false } private fun consume(type: TokenType, message: String): Token { if (check(type)) { return advance() } throw error(peek(), message) } private fun check(type: TokenType): Boolean { if (isAtEnd()) { return false } return peek().type == type } private fun advance(): Token { if (!isAtEnd()) { current++ } return previous() } private fun isAtEnd(): Boolean { return peek().type == EOF } private fun peek(): Token { return tokens[current] } private fun previous(): Token { return tokens[current - 1] } private fun error(token: Token, message: String): ParseError { OutputHandler.error(token, message) return ParseError() } class ParseError: RuntimeException() private fun synchronize() { advance() while (!isAtEnd()) { if (previous().type == SEMICOLON) { return } when (peek().type) { CLASS, FUN, VAR, FOR, IF, WHILE, PRINT, RETURN -> return else -> advance() } } } }
klox/klox/src/main/kotlin/parser/TokenType.kt
3791900391
package parser enum class TokenType { // single-character tokens LEFT_PAREN, RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE, COMMA, DOT, MINUS, PLUS, SEMICOLON, SLASH, STAR, // one or two character tokens BANG, BANG_EQUAL, EQUAL, EQUAL_EQUAL, GREATER, GREATER_EQUAL, LESS, LESS_EQUAL, // literals IDENTIFIER, STRING, NUMBER, // keywords AND, CLASS, ELSE, FALSE, FUN, FOR, IF, NIL, OR, PRINT, RETURN, SUPER, THIS, TRUE, VAR, WHILE, EOF }
klox/klox/src/main/kotlin/parser/Token.kt
2338674001
package parser data class Token( val type: TokenType, val lexeme: String, val literal: Any?, val line: Int )
klox/klox/src/main/kotlin/parser/Scanner.kt
4157861060
package parser import OutputHandler import parser.TokenType.* class Scanner( private val source: String ) { private val tokens: MutableList<Token> = ArrayList() private var start = 0 private var current = 0 private var line = 1 fun scanTokens(): List<Token> { while (!isAtEnd()) { start = current scanToken() } tokens.add(Token(EOF, "", null, line)) return tokens } private fun scanToken() { val c = advance() when(c) { '(' -> addToken(LEFT_PAREN) ')' -> addToken(RIGHT_PAREN) '{' -> addToken(LEFT_BRACE) '}' -> addToken(RIGHT_BRACE) ',' -> addToken(COMMA) '.' -> addToken(DOT) '-' -> addToken(MINUS) '+' -> addToken(PLUS) ';' -> addToken(SEMICOLON) '*' -> addToken(STAR) '!' -> addToken( if (match('=')) BANG_EQUAL else BANG ) '=' -> addToken( if (match('=')) EQUAL_EQUAL else EQUAL ) '<' -> addToken( if (match('=')) LESS_EQUAL else LESS ) '>' -> addToken( if (match('=')) GREATER_EQUAL else GREATER ) '/' -> { if (match('/')) { // comment goes to end of line, discard line while (peek() != '\n' && !isAtEnd()) { advance() } } else { addToken(SLASH) } } ' ', '\r', '\t' -> {} '\n' -> line++ '"' -> string() else -> { if (isDigit(c)) { number() } else if (isAlpha(c)) { identifier() } else { OutputHandler.error(line, "Unexpected character: $c") } } } } private fun string() { while (peek() != '"' && !isAtEnd()) { if (peek() == '\n') { line++ } advance() } if (isAtEnd()) { OutputHandler.error(line, "Unterminated string encountered") return } advance() // the closing double quote of the string // trim the surrounding quotes val value = source.substring(start + 1, current - 1) addToken(STRING, value) } private fun number() { while(isDigit(peek())) { advance() } // look for fractional part if (peek() == '.' && isDigit(peekNext())) { // consume the "." advance() while(isDigit(peek())) { advance() } } addToken(NUMBER, source.substring(start, current).toDouble()) } private fun identifier() { while (isAlphaNumeric(peek())) { advance() } val text = source.substring(start, current) val type: TokenType = keywords[text] ?: IDENTIFIER addToken(type) } private fun isAlphaNumeric(c: Char): Boolean { return isAlpha(c) || isDigit(c) } private fun isDigit(c: Char): Boolean { return c in '0'..'9' } private fun isAlpha(c: Char): Boolean { return c in 'a'..'z' || c in 'A'..'Z' || c == '_' } private fun isAtEnd(): Boolean { return current >= source.length } private fun advance(): Char { return source[current++] } private fun match(expected: Char): Boolean { if (isAtEnd()) { return false } if (source[current] != expected) { return false } current++ return true } private fun peek(): Char { if (isAtEnd()) { return '\u0000' } return source[current] } private fun peekNext(): Char { if (current + 1 >= source.length) { return '\u0000' } return source[current + 1] } private fun addToken(type: TokenType) { addToken(type, null) } private fun addToken(type: TokenType, literal: Any?) { val text = source.substring(start, current) tokens.add(Token(type, text, literal, line)) } companion object { private val keywords: Map<String, TokenType> = hashMapOf( Pair("and", AND), Pair("class", CLASS), Pair("else", ELSE), Pair("false", FALSE), Pair("for", FOR), Pair("fun", FUN), Pair("if", IF), Pair("nil", NIL), Pair("or", OR), Pair("print", PRINT), Pair("return", RETURN), Pair("super", SUPER), Pair("this", THIS), Pair("true", TRUE), Pair("var", VAR), Pair("while", WHILE) ) } }
klox/klox/src/main/kotlin/Main.kt
1153869136
import interpreter.Interpreter import parser.Parser import parser.Scanner import java.io.BufferedReader import java.io.InputStreamReader import java.nio.charset.Charset import java.nio.file.Files import java.nio.file.Paths import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.size > 1) { println("Usage: klox [script]") exitProcess(64) } else if (args.size == 1) { Main().runFile(args[0]) } else { Main().runPrompt() } } class Main { private val interpreter = Interpreter() private val resolver = Resolver(interpreter) fun runFile(path: String) { val byteArray = Files.readAllBytes(Paths.get(path)) val fileAsString = String(byteArray, Charset.defaultCharset()) run(fileAsString) if (hadError) { exitProcess(65) } if (hadRuntimeError) { exitProcess(70) } } fun runPrompt() { val input = InputStreamReader(System.`in`) val reader = BufferedReader(input) while(true) { print("> ") val line = reader.readLine() ?: break run(line) hadError = false } } private fun run(source: String) { val tokens = Scanner(source).scanTokens() val statements = Parser(tokens).parse() if (hadError) { return } resolver.resolve(statements) if (hadError) { return } interpreter.interpret(statements) } }
klox/klox/src/main/kotlin/OutputHandler.kt
1291541188
import interpreter.Interpreter import parser.Token import parser.TokenType var hadError = false var hadRuntimeError = false object OutputHandler { fun error(lineNumber: Int, message: String) { report(lineNumber, "", message) } fun error(token: Token, message: String) { if (token.type == TokenType.EOF) { report(token.line, " at end", message) } else { report(token.line, " at '${token.lexeme}'", message) } } fun report(lineNumber: Int, where: String, message: String) { System.err.println("[line $lineNumber] Error$where: $message") hadError = true } fun runtimeError(error: Interpreter.RuntimeError) { System.err.println("${error.message}\n[line ${error.token.line}]") hadRuntimeError = true } }
klox/klox/src/main/kotlin/ast/Expr.kt
3741503106
package ast import parser.Token abstract class Expr { interface Visitor<R> { fun visitAssignExpr(expr: Assign): R fun visitBinaryExpr(expr: Binary): R fun visitCallExpr(expr: Call): R fun visitGetExpr(expr: Get): R fun visitGroupingExpr(expr: Grouping): R fun visitLiteralExpr(expr: Literal): R fun visitLogicalExpr(expr: Logical): R fun visitSetExpr(expr: Set): R fun visitUnaryExpr(expr: Unary): R fun visitVariableExpr(expr: Variable): R } abstract fun <R> accept(visitor: Visitor<R>): R class Assign( val name: Token, val value: Expr ): Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitAssignExpr(this) } } class Binary( val left: Expr, val operator: Token, val right: Expr ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitBinaryExpr(this) } } class Call( val callee: Expr, val paren: Token, val arguments: List<Expr> ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitCallExpr(this) } } class Get( val instance: Expr, val name: Token ): Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitGetExpr(this) } } class Grouping( val expression: Expr, ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitGroupingExpr(this) } } class Literal( val value: Any? ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitLiteralExpr(this) } } class Logical( val left: Expr, val operator: Token, val right: Expr ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitLogicalExpr(this) } } class Set( val instance: Expr, val name: Token, val value: Expr, ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitSetExpr(this) } } class Unary( val operator: Token, val right: Expr, ) : Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitUnaryExpr(this) } } class Variable( val name: Token ): Expr() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitVariableExpr(this) } } }
klox/klox/src/main/kotlin/ast/Stmt.kt
1985569067
package ast import parser.Token abstract class Stmt { interface Visitor<R> { fun visitBlockStmt(stmt: Block): R fun visitClassStmt(stmt: Class): R fun visitExpressionStmt(stmt: Expression): R fun visitFunctionStmt(stmt: Function): R fun visitIfStmt(stmt: If): R fun visitPrintStmt(stmt: Print): R fun visitReturnStmt(stmt: Return): R fun visitVarStmt(stmt: Var): R fun visitWhileStmt(stmt: While): R } class Block( val statements: List<Stmt?> ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitBlockStmt(this) } } class Class( val name: Token, val methods: List<Function> ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitClassStmt(this) } } class Expression( val expression: Expr ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitExpressionStmt(this) } } class Function( val name: Token, val params: List<Token>, val body: List<Stmt?> ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitFunctionStmt(this) } } class If( val condition: Expr, val thenBranch: Stmt, val elseBranch: Stmt? ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitIfStmt(this) } } class Print( val expression: Expr ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitPrintStmt(this) } } class Return( val keyword: Token, val value: Expr? ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitReturnStmt(this) } } class Var( val name: Token, val initializer: Expr? ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitVarStmt(this) } } class While( val condition: Expr, val body: Stmt ): Stmt() { override fun <R> accept(visitor: Visitor<R>): R { return visitor.visitWhileStmt(this) } } abstract fun <R> accept(visitor: Visitor<R>): R }
UTSANMP_hobbyApp160421005/app/src/androidTest/java/com/ubayadev/hobbyapp_160421005/ExampleInstrumentedTest.kt
477656582
package com.ubayadev.hobbyapp_160421005 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.ubayadev.hobbyapp_160421005", appContext.packageName) } }
UTSANMP_hobbyApp160421005/app/src/test/java/com/ubayadev/hobbyapp_160421005/ExampleUnitTest.kt
3000452414
package com.ubayadev.hobbyapp_160421005 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) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/viewmodel/BeritaDetailViewModel.kt
2333828318
package com.ubayadev.hobbyapp_160421005.viewmodel import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.ubayadev.hobbyapp_160421005.model.Berita class BeritaDetailViewModel(application: Application): AndroidViewModel(application) { val beritaLD = MutableLiveData<Berita>() val beritaLoadErrorLD = MutableLiveData<Boolean>() val loadingLD = MutableLiveData<Boolean>() val TAG = "volleyTag" private var queue: RequestQueue? = null fun fetch(beritaId:Int) { beritaLoadErrorLD.value = false loadingLD.value = false queue = Volley.newRequestQueue(getApplication()) val url = "http://10.0.2.2/hobbyApp/beritas.json" val stringRequest = StringRequest( Request.Method.GET, url, { Log.d("showvolley", it) val sType = object : TypeToken<List<Berita>>() { }.type val result = Gson().fromJson<List<Berita>>(it, sType) val beritaList = result as ArrayList<Berita> beritaLD.value = beritaList[beritaId - 1] loadingLD.value = false Log.d("showvolley", result.toString()) }, { Log.d("showvolley", it.toString()) beritaLoadErrorLD.value = false loadingLD.value = false }) stringRequest.tag = TAG queue?.add(stringRequest) } override fun onCleared() { super.onCleared() queue?.cancelAll(TAG) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/viewmodel/BeritaListViewModel.kt
1060137008
package com.ubayadev.hobbyapp_160421005.viewmodel import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.ubayadev.hobbyapp_160421005.model.Berita class BeritaListViewModel(application: Application): AndroidViewModel(application) { val beritasLD = MutableLiveData<ArrayList<Berita>>() val beritasLoadErrorLD = MutableLiveData<Boolean>() val loadingLD = MutableLiveData<Boolean>() val TAG = "volleyTag" private var queue: RequestQueue? = null fun refresh() { beritasLoadErrorLD.value = false loadingLD.value = false queue = Volley.newRequestQueue(getApplication()) val url = "http://10.0.2.2/hobbyApp/beritas.json" val stringRequest = StringRequest( Request.Method.GET, url, { val sType = object : TypeToken<List<Berita>>() { }.type val result = Gson().fromJson<List<Berita>>(it, sType) beritasLD.value = result as ArrayList<Berita>? loadingLD.value = false Log.d("showvolley", result.toString()) }, { Log.d("showvolley", it.toString()) beritasLoadErrorLD.value = false loadingLD.value = false }) stringRequest.tag = TAG queue?.add(stringRequest) } override fun onCleared() { super.onCleared() queue?.cancelAll(TAG) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/model/Model.kt
908436698
package com.ubayadev.hobbyapp_160421005.model import com.google.gson.annotations.SerializedName data class User( val id:Int?, val username:String?, val nama_depan:String?, val nama_belakang:String?, val email:String?, val password:String? ) data class Berita( val id:String?, val judul:String?, val kreator:String?, val img_url:String?, val ringkasan:String?, val isi:String? )
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/BeritaListFragment.kt
2345753983
package com.ubayadev.hobbyapp_160421005.view import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentBeritaBinding import com.ubayadev.hobbyapp_160421005.viewmodel.BeritaListViewModel class BeritaListFragment : Fragment() { private lateinit var viewModel: BeritaListViewModel private val beritaListAdapter = BeritaListAdapter(arrayListOf()) private lateinit var binding: FragmentBeritaBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentBeritaBinding.inflate(inflater,container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this).get(BeritaListViewModel::class.java) viewModel.refresh() binding.recView.layoutManager = LinearLayoutManager(context) binding.recView.adapter = beritaListAdapter observeViewModel() binding.refreshLayout.setOnRefreshListener { binding.recView.visibility = View.GONE binding.txtError.visibility = View.GONE binding.progressLoad.visibility = View.VISIBLE viewModel.refresh() binding.refreshLayout.isRefreshing = false } } fun observeViewModel() { viewModel.beritasLD.observe(viewLifecycleOwner, Observer { beritaListAdapter.updateBeritaList(it) }) viewModel.beritasLoadErrorLD.observe(viewLifecycleOwner, Observer { if(it == true) { binding.txtError?.visibility = View.VISIBLE } else { binding.txtError?.visibility = View.GONE } }) viewModel.loadingLD.observe(viewLifecycleOwner, Observer { if(it == true) { binding.recView.visibility = View.GONE binding.progressLoad.visibility = View.VISIBLE } else { binding.recView.visibility = View.VISIBLE binding.progressLoad.visibility = View.GONE } }) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/SignUpFragment.kt
65275732
package com.ubayadev.hobbyapp_160421005.view import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentSignUpBinding import org.json.JSONObject /** * A simple [Fragment] subclass. * Use the [SignUpFragment.newInstance] factory method to * create an instance of this fragment. */ class SignUpFragment : Fragment() { private lateinit var binding:FragmentSignUpBinding private var queue: RequestQueue? = null val TAG = "volleyTag" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentSignUpBinding.inflate(inflater, container,false) return (binding.root) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnSignup.setOnClickListener { val username = binding.txtNewUsername.text.toString() val nama_depan = binding.txtNewNamaFirst.text.toString() val nama_belakang = binding.txtNewNamaLast.text.toString() val email = binding.txtNewEmail.text.toString() val password = binding.txtPassword.text.toString() val re_password = binding.txtRePass.text.toString() if(password == re_password) { signup(it, username, nama_depan, nama_belakang, email, password) } else { val dialog = AlertDialog.Builder(activity) dialog.setMessage("Cek apakah password yang dimasukkan ulang sudah sama.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } } binding.btnBackLogin.setOnClickListener { val action = SignUpFragmentDirections.actionToLogin() Navigation.findNavController(view).navigate(action) } } fun signup(view:View, username:String, nama_depan:String, nama_belakang:String, email:String, password:String) { Log.d("signup", "signupVolley") queue = Volley.newRequestQueue(context) val url = "http://10.0.2.2/hobbyApp/signup.php" val dialog = AlertDialog.Builder(activity) val stringRequest = object:StringRequest( Request.Method.POST, url, { Log.d("cek", it) val obj = JSONObject(it) if (obj.getString("result") == "OK") { dialog.setMessage("Silakan login menggunakan username dan password yang baru didaftarkan.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> val action = SignUpFragmentDirections.actionToLogin() Navigation.findNavController(view).navigate(action) }) } else { dialog.setMessage("User gagal didaftarkan. Silakan coba lagi.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> }) dialog.create().show() } dialog.create().show() }, { Log.e("cekError", it.toString()) } ) { override fun getParams(): MutableMap<String, String>? { val params = HashMap<String, String>() params["username"] = username params["nama_depan"] = nama_depan params["nama_belakang"] = nama_belakang params["email"] = email params["password"] = password return params } } stringRequest.tag = TAG queue?.add(stringRequest) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/MainActivity.kt
2558715539
package com.ubayadev.hobbyapp_160421005.view import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.setupWithNavController import androidx.viewpager2.widget.ViewPager2 import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding:ActivityMainBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) navController = (supportFragmentManager.findFragmentById(R.id.hobbyNav) as NavHostFragment).navController val appBarConfig = AppBarConfiguration(setOf( R.id.itemHome, R.id.itemReadHistory, R.id.itemProfile )) NavigationUI.setupActionBarWithNavController(this, navController, appBarConfig) binding.bottomNav.setupWithNavController(navController) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/LoginFragment.kt
973562128
package com.ubayadev.hobbyapp_160421005.view import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentLoginBinding import com.ubayadev.hobbyapp_160421005.model.User import com.ubayadev.hobbyapp_160421005.view.SignInActivity.Companion.currUserId import org.json.JSONObject class LoginFragment : Fragment() { private lateinit var binding:FragmentLoginBinding private var queue:RequestQueue? = null val TAG = "volleyTag" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnLogin.setOnClickListener { val username = binding.txtUsername.text.toString() val password = binding.txtPass.text.toString() login(username, password) } binding.btnCreateAcc.setOnClickListener { val action = LoginFragmentDirections.actionToSignUp() Navigation.findNavController(it).navigate(action) } } fun login(username:String, password:String){ Log.d("login", "loginVolley") queue = Volley.newRequestQueue(activity) val url = "http://10.0.2.2/hobbyApp/cek_login.php" val dialog = AlertDialog.Builder(activity) val stringRequest = object : StringRequest( Request.Method.POST, url, { Log.d("apiresult", it) val obj = JSONObject(it) if (obj.getString("result") == "OK") { val data = obj.getJSONArray("data") if (data.length() > 0) { val userData = data.getJSONObject(0) val sType = object : TypeToken<User>() { }.type val user = Gson().fromJson(userData.toString(), sType) as User dialog.setMessage("Login Successful, Welcome ${user.username}") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() SignInActivity.currUserId = user.id!! val intent = Intent(activity, MainActivity::class.java) startActivity(intent) activity?.finish() }) dialog.create().show() } else { dialog.setMessage("Username or Password is incorrect") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } } }, { Log.e("cekError", it.toString()) dialog.setMessage("Username or Password is incorrect") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } ) { override fun getParams(): MutableMap<String, String>? { val params = HashMap<String, String>() params["username"] = username params["password"] = password return params } } stringRequest.tag = TAG queue?.add(stringRequest) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/ProfilFragment.kt
2111130015
package com.ubayadev.hobbyapp_160421005.view import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.provider.Settings.Global.putInt import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentBeritaDetailBinding import com.ubayadev.hobbyapp_160421005.databinding.FragmentProfilBinding import com.ubayadev.hobbyapp_160421005.model.User import com.ubayadev.hobbyapp_160421005.view.SignInActivity.Companion.currUserId import org.json.JSONObject class ProfilFragment : Fragment() { private lateinit var binding:FragmentProfilBinding private var queue: RequestQueue? = null val TAG = "volleyTag" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentProfilBinding.inflate(inflater,container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Log.d("getData", "getDataVolley") queue = Volley.newRequestQueue(context) val url = "http://10.0.2.2/hobbyApp/get_user.php" val stringRequest = object : StringRequest(Request.Method.POST, url, { Log.d("apiresult", it) val obj = JSONObject(it) if (obj.getString("result") == "OK") { val data = obj.getJSONArray("data") if (data.length() > 0) { val userData = data.getJSONObject(0) val sType = object : TypeToken<User>() {}.type val user = Gson().fromJson(userData.toString(), sType) as User binding.txtNamaDepan.setText(user.nama_depan) binding.txtNamaBelakang.setText(user.nama_belakang) binding.txtNewPassword.setText(user.password) binding.btnSimpan.setOnClickListener { val newNamaDepan = binding.txtNamaDepan.text.toString() val newNamaBelakang = binding.txtNamaBelakang.text.toString() val newPassword = binding.txtNewPassword.text.toString() updateData(user, newNamaDepan, newNamaBelakang, newPassword) } }} }, { Log.e("error", "errorVolley") } ) { override fun getParams(): MutableMap<String, String>? { val params = HashMap<String, String>() params["id"] = currUserId.toString() return params } } stringRequest.tag = TAG queue?.add(stringRequest) binding.btnLogout.setOnClickListener { val intent = Intent(activity, SignInActivity::class.java) startActivity(intent) activity?.finish() } } fun updateData(user:User, newNamaDepan:String, newNamaBelakang:String, newPassword:String) { Log.d("updateData", "updateDataVolley") queue = Volley.newRequestQueue(context) val url = "http://10.0.2.2/hobbyApp/update_data.php" val dialog = AlertDialog.Builder(activity) val stringRequest = object:StringRequest( Request.Method.POST, url, { Log.d("cek", it) val obj = JSONObject(it) if (obj.getString("result") == "OK") { dialog.setMessage("Data berhasil diubah.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } else { dialog.setMessage("Data gagal diubah. \nSilakan coba lagi.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } }, { dialog.setMessage("Data gagal diubah. \nSilakan coba lagi.") dialog.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> dialog.dismiss() }) dialog.create().show() } ) { override fun getParams(): MutableMap<String, String>? { val params = HashMap<String, String>() params["id"] = user.id.toString() params["nama_depan"] = newNamaDepan.toString() params["nama_belakang"] = newNamaBelakang.toString() params["password"] = newPassword.toString() return params } } stringRequest.tag = TAG queue?.add(stringRequest) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/BeritaListAdapter.kt
175293815
package com.ubayadev.hobbyapp_160421005.view import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import com.ubayadev.hobbyapp_160421005.databinding.BeritaListItemBinding import com.ubayadev.hobbyapp_160421005.model.Berita class BeritaListAdapter (val beritaList:ArrayList<Berita>) : RecyclerView.Adapter<BeritaListAdapter.BeritaViewHolder>(){ class BeritaViewHolder(var binding: BeritaListItemBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BeritaViewHolder { val binding = BeritaListItemBinding.inflate( LayoutInflater.from(parent.context), parent, false) return BeritaViewHolder(binding) } override fun onBindViewHolder(holder: BeritaViewHolder, position: Int) { holder.binding.txtJudul.text = beritaList[position].judul holder.binding.txtCreator.text = beritaList[position].kreator holder.binding.txtRingkasan.text = beritaList[position].ringkasan val picasso = Picasso.Builder(holder.itemView.context) picasso.listener { picasso, uri, exception -> exception.printStackTrace() } picasso.build().load(beritaList[position].img_url) .into(holder.binding.imgBerita, object : Callback { override fun onSuccess() { holder.binding.progressImg.visibility = View.INVISIBLE holder.binding.imgBerita.visibility = View.VISIBLE } override fun onError(e: Exception?) { Log.e("picasso_error", e.toString()) } }) holder.binding.btnRead.setOnClickListener { val beritaId = beritaList[position].id!!.toString()!! val action = BeritaListFragmentDirections.actionBeritaDetail(beritaId) Navigation.findNavController(it).navigate(action) } } override fun getItemCount(): Int { return beritaList.size } fun updateBeritaList(newBeritaList: ArrayList<Berita>) { beritaList.clear() beritaList.addAll(newBeritaList) notifyDataSetChanged() } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/ReadHistoryFragment.kt
503606435
package com.ubayadev.hobbyapp_160421005.view import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentReadHistoryBinding import com.ubayadev.hobbyapp_160421005.databinding.FragmentSignUpBinding class ReadHistoryFragment : Fragment() { private lateinit var binding:FragmentReadHistoryBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentReadHistoryBinding.inflate(inflater, container,false) return (binding.root) } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/SignInActivity.kt
2513761477
package com.ubayadev.hobbyapp_160421005.view import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.ActivitySignInBinding class SignInActivity : AppCompatActivity() { private lateinit var binding:ActivitySignInBinding private lateinit var navController:NavController companion object { var currUserId = 0 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignInBinding.inflate(layoutInflater) setContentView(binding.root) navController = (supportFragmentManager.findFragmentById(R.id.signNav) as NavHostFragment).navController NavigationUI.setupActionBarWithNavController(this, navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } }
UTSANMP_hobbyApp160421005/app/src/main/java/com/ubayadev/hobbyapp_160421005/view/BeritaDetailFragment.kt
4074066793
package com.ubayadev.hobbyapp_160421005.view import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.squareup.picasso.Picasso import com.ubayadev.hobbyapp_160421005.R import com.ubayadev.hobbyapp_160421005.databinding.FragmentBeritaDetailBinding import com.ubayadev.hobbyapp_160421005.viewmodel.BeritaDetailViewModel class BeritaDetailFragment : Fragment() { private lateinit var detailViewModel: BeritaDetailViewModel private lateinit var binding:FragmentBeritaDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentBeritaDetailBinding.inflate(inflater,container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val beritaId = BeritaDetailFragmentArgs.fromBundle(requireArguments()).beritaId detailViewModel = ViewModelProvider(this).get(BeritaDetailViewModel::class.java) detailViewModel.fetch(beritaId.toInt()) observeViewModel() } fun observeViewModel() { detailViewModel.beritaLD.observe(viewLifecycleOwner, Observer { binding.txtJudul.text = it.judul binding.txtCreator.text = it.kreator var currPar = 0 val splitPar = it.isi?.split("\n") Log.d("cekParagraf", splitPar.toString()) val par_size = splitPar?.size binding.txtParagraf.text = splitPar?.get(currPar) cekPage(currPar, par_size!!.toInt()) Picasso.get().load(it.img_url).into(binding.imgBerita) var berita = it binding.btnNext.setOnClickListener() { currPar++ binding.txtParagraf.text = splitPar!!.get(currPar) cekPage(currPar, par_size) } binding.btnPrev.setOnClickListener() { currPar-- binding.txtParagraf.text = splitPar!!.get(currPar) cekPage(currPar, par_size) } }) detailViewModel.loadingLD.observe(viewLifecycleOwner, Observer { if(it == true) { binding.progressImage.visibility = View.VISIBLE } else { binding.progressImage.visibility = View.GONE } }) } fun cekPage(currpar:Int, par_size:Int) { when(currpar) { 0 -> { binding.btnPrev.isEnabled = false binding.btnNext.isEnabled = true } par_size - 1 -> { binding.btnPrev.isEnabled = true binding.btnNext.isEnabled = false } else -> { binding.btnPrev.isEnabled = true binding.btnNext.isEnabled = true } } } }
Projeto-PPDM-login/app/src/androidTest/java/br/senai/jandira/sp/apilivraria/ExampleInstrumentedTest.kt
3420322117
package br.senai.jandira.sp.apilivraria 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("br.senai.jandira.sp.apilivraria", appContext.packageName) } }
Projeto-PPDM-login/app/src/test/java/br/senai/jandira/sp/apilivraria/ExampleUnitTest.kt
2277237574
package br.senai.jandira.sp.apilivraria 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) } }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/ui/theme/Color.kt
2150137502
package br.senai.jandira.sp.apilivraria.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)
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/ui/theme/Theme.kt
4057076715
package br.senai.jandira.sp.apilivraria.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 APILivrariaTheme( 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 ) }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/ui/theme/Type.kt
4050551815
package br.senai.jandira.sp.apilivraria.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 ) */ )
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/MainActivity.kt
3591209253
package br.senai.jandira.sp.apilivraria 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 br.senai.jandira.sp.apilivraria.components.screen.foto import br.senai.jandira.sp.apilivraria.components.screen.loginScreen import br.senai.jandira.sp.apilivraria.ui.theme.APILivrariaTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { APILivrariaTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { loginScreen() //foto() } } } } }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/components/button.kt
1553758524
package br.senai.jandira.sp.apilivraria.components import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults 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.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun DefaultButton( onClick: () -> Unit, text: String ) { Button( onClick, modifier = Modifier .width(280.dp) .height(50.dp), colors = ButtonDefaults.buttonColors(Color(0xFF35225F)) ) { Text( text = text, fontSize = 18.sp, fontWeight = FontWeight(600), color = Color.White ) } } @Preview(showBackground = true) @Composable fun DefaultButtonPreview() { DefaultButton( text = "Entrar", onClick = {} ) }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/components/screen/perfil.kt
1025926182
package br.senai.jandira.sp.apilivraria.components.screen import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.os.Build import android.provider.MediaStore import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import br.senai.jandira.sp.apilivraria.R import com.google.firebase.Firebase import com.google.firebase.storage.storage import java.io.ByteArrayOutputStream @Composable fun foto(){ var showDialog by remember { mutableStateOf(false) } // com o Firebase val isUploading = remember { mutableStateOf(false) } val context = LocalContext.current val img: Bitmap = BitmapFactory.decodeResource(Resources.getSystem(),android.R.drawable.ic_menu_gallery) val bitmap = remember{ mutableStateOf(img) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicturePreview() ){ if (it!= null){ bitmap.value = it } } val launcherImage = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ){ if (Build.VERSION.SDK_INT < 28){ bitmap.value = MediaStore.Images.Media.getBitmap(context.contentResolver, it) } else{ val source = it?.let { it1 -> ImageDecoder.createSource(context.contentResolver, it1) } bitmap.value = source?.let { it1 -> ImageDecoder.decodeBitmap(it1)}!! } } Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier .fillMaxSize() .padding(top = 20.dp) .background(color = Color.Cyan), horizontalAlignment = Alignment.CenterHorizontally, ) { Image( bitmap = bitmap.value.asImageBitmap(), contentDescription = "FOTO", contentScale = ContentScale.Crop, modifier = Modifier .clip(CircleShape) .size(250.dp) .background(color = Color.Blue) .border( width = 1.dp, color = Color.White, shape = CircleShape ) ) } Box( modifier = Modifier .padding(top = 220.dp, start = 260.dp) ){ Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription ="Icone de Imagem", modifier = Modifier .clip(CircleShape) .background(Color.White) .size(50.dp) .padding(10.dp) .clickable { showDialog = true } ) } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(top = 180.dp) ) { Button(onClick = { isUploading.value =true bitmap.value.let { bitmap -> UploadingImageToFireBase(bitmap,context as ComponentActivity){ sucess -> isUploading.value = false if (sucess){ Toast.makeText(context, "Upaload Sucessofuy", Toast.LENGTH_SHORT).show() }else{ Toast.makeText(context, "Falid to Upaload", Toast.LENGTH_SHORT).show() } } } }, colors = ButtonDefaults.buttonColors( Color.Black ) ) { Text( text = "Upload Image", fontSize = 30.sp, fontWeight = FontWeight.Bold ) } } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() ) { if (showDialog){ Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .width(300.dp) .height(100.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.Blue) ) { Column( modifier = Modifier, verticalArrangement = Arrangement.Top ) { Text( text = "X", color = Color.White, modifier = Modifier .clickable { showDialog = false } ) } Column { Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription = "", modifier = Modifier .size(50.dp) .clickable { launcherImage.launch("image/*") showDialog = false } ) Text( text = "Galerya", color = Color.White ) } Column( modifier = Modifier.padding(start = 60.dp) ) { Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription = "", modifier = Modifier .size(50.dp) .clickable { launcher.launch() showDialog = false } ) Text( text = "Camera", color = Color.White ) } } } } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .height(450.dp) .fillMaxWidth() ) { if (isUploading.value){ CircularProgressIndicator( modifier = Modifier .padding(16.dp), color = Color.White ) } } } } //Função de Upload fun UploadingImageToFireBase(bitmap: Bitmap, context: ComponentActivity, callback: (Boolean) -> Unit) { val storageRef = Firebase.storage.reference val imageRef = storageRef.child("images/${bitmap}") val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val imageData = baos.toByteArray() imageRef.putBytes(imageData).addOnSuccessListener { callback(true) }.addOnFailureListener { callback(false) } }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/components/screen/LoginScreen.kt
3075307948
package br.senai.jandira.sp.apilivraria.components.screen import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.os.Build import android.provider.MediaStore import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight 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.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import br.senai.jandira.sp.apilivraria.R import br.senai.jandira.sp.apilivraria.components.DefaultButton import br.senai.jandira.sp.apilivraria.components.DefaultTextField import br.senai.jandira.sp.apilivraria.components.fotoFireBase @Composable fun loginScreen(){ //Variaveis // Modal Galerya & Foto var showDialog by remember { mutableStateOf(false) } // com o Firebase val isUploading = remember { mutableStateOf(false) } val context = LocalContext.current val img: Bitmap = BitmapFactory.decodeResource(Resources.getSystem(),android.R.drawable.ic_menu_gallery) val bitmap = remember{ mutableStateOf(img) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicturePreview() ){ if (it!= null){ bitmap.value = it } } val launcherImage = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ){ if (Build.VERSION.SDK_INT < 28){ bitmap.value = MediaStore.Images.Media.getBitmap(context.contentResolver, it) } else{ val source = it?.let { it1 -> ImageDecoder.createSource(context.contentResolver, it1) } bitmap.value = source?.let { it1 -> ImageDecoder.decodeBitmap(it1)}!! } } //Variaveis de estado var emailState by remember{ mutableStateOf("") } var SenhaState by remember{ mutableStateOf("") } Surface( modifier = Modifier .fillMaxSize() .background(color = Color.White) .padding(10.dp), ) { Column( verticalArrangement = Arrangement.SpaceBetween, horizontalAlignment = Alignment.CenterHorizontally ) { //Imagem Row( modifier = Modifier .height(250.dp) .fillMaxWidth(), verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.Center ) { Image( bitmap = bitmap.value.asImageBitmap(), contentDescription = "FOTO", contentScale = ContentScale.Crop, modifier = Modifier .clip(CircleShape) .size(250.dp) .background(color = Color.Blue) .border( width = 1.dp, color = Color.White, shape = CircleShape ) ) Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription ="Icone de Imagem", modifier = Modifier .clip(CircleShape) .background(Color.White) .size(50.dp) .padding(10.dp) .clickable { launcherImage.launch("image/*") showDialog = true } ) } } Spacer(modifier = Modifier.height(25.dp)) //Email e Senha Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { DefaultTextField( valor = emailState, label = "E-mail", onValueChange ={ emailState = it } ) DefaultTextField( valor = SenhaState, label = "Senha", onValueChange ={ SenhaState = it } ) //Botão Row( modifier = Modifier .height(200.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.Bottom ) { Button( onClick = { isUploading.value = true bitmap.value.let { bitmap -> br.senai.jandira.sp.apilivraria.components.UploadingImageToFireBase( bitmap, context as ComponentActivity ) { sucess -> isUploading.value = false if (sucess) { Toast.makeText( context, "Upaload Sucessofuy", Toast.LENGTH_SHORT ).show() } else { Toast.makeText(context, "Falid to Upaload", Toast.LENGTH_SHORT) .show() } } } }, colors = ButtonDefaults.buttonColors( Color.Black ) ) { Text( text = "Entrar", fontSize = 30.sp, fontWeight = FontWeight.Bold ) } } } } } @Preview @Composable fun loginscreenPreview(){ loginScreen() }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/components/foto.kt
2310396732
package br.senai.jandira.sp.apilivraria.components import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.os.Build import android.provider.MediaStore import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import br.senai.jandira.sp.apilivraria.R import com.google.firebase.Firebase import com.google.firebase.storage.storage import java.io.ByteArrayOutputStream @Composable fun fotoFireBase( ){ // Modal Galerya & Foto var showDialog by remember { mutableStateOf(false) } // com o Firebase val isUploading = remember { mutableStateOf(false) } val context = LocalContext.current val img: Bitmap = BitmapFactory.decodeResource(Resources.getSystem(),android.R.drawable.ic_menu_gallery) val bitmap = remember{ mutableStateOf(img) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicturePreview() ){ if (it!= null){ bitmap.value = it } } val launcherImage = rememberLauncherForActivityResult( contract = ActivityResultContracts.GetContent() ){ if (Build.VERSION.SDK_INT < 28){ bitmap.value = MediaStore.Images.Media.getBitmap(context.contentResolver, it) } else{ val source = it?.let { it1 -> ImageDecoder.createSource(context.contentResolver, it1) } bitmap.value = source?.let { it1 -> ImageDecoder.decodeBitmap(it1)}!! } } Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier .fillMaxSize() .padding(top = 20.dp) .background(color = Color.Cyan), horizontalAlignment = Alignment.CenterHorizontally, ) { Image( bitmap = bitmap.value.asImageBitmap(), contentDescription = "FOTO", contentScale = ContentScale.Crop, modifier = Modifier .clip(CircleShape) .size(250.dp) .background(color = Color.Blue) .border( width = 1.dp, color = Color.White, shape = CircleShape ) ) } Box( modifier = Modifier .padding(top = 220.dp, start = 260.dp) ){ Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription ="Icone de Imagem", modifier = Modifier .clip(CircleShape) .background(Color.White) .size(50.dp) .padding(10.dp) .clickable { showDialog = true } ) } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(top = 180.dp) ) { Button(onClick = { isUploading.value =true bitmap.value.let { bitmap -> UploadingImageToFireBase(bitmap,context as ComponentActivity){ sucess -> isUploading.value = false if (sucess){ Toast.makeText(context, "Upaload Sucessofuy", Toast.LENGTH_SHORT).show() }else{ Toast.makeText(context, "Falid to Upaload", Toast.LENGTH_SHORT).show() } } } }, colors = ButtonDefaults.buttonColors( Color.Black ) ) { Text( text = "Upload Image", fontSize = 30.sp, fontWeight = FontWeight.Bold ) } } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() ) { if (showDialog){ Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier .width(300.dp) .height(100.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.Blue) ) { Column( modifier = Modifier, verticalArrangement = Arrangement.Top ) { Text( text = "X", color = Color.White, modifier = Modifier .clickable { showDialog = false } ) } Column { Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription = "", modifier = Modifier .size(50.dp) .clickable { launcherImage.launch("image/*") showDialog = false } ) Text( text = "Galerya", color = Color.White ) } Column( modifier = Modifier.padding(start = 60.dp) ) { Image( painter = painterResource(id = R.drawable.baseline_photo_camera_24), contentDescription = "", modifier = Modifier .size(50.dp) .clickable { launcher.launch() showDialog = false } ) Text( text = "Camera", color = Color.White ) } } } } Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .height(450.dp) .fillMaxWidth() ) { if (isUploading.value){ CircularProgressIndicator( modifier = Modifier .padding(16.dp), color = Color.White ) } } } } //Função de Upload fun UploadingImageToFireBase(bitmap: Bitmap, context: ComponentActivity, callback: (Boolean) -> Unit){ val storageRef = Firebase.storage.reference val imageRef = storageRef.child("images/${bitmap}") val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos) val imageData = baos.toByteArray() imageRef.putBytes(imageData).addOnSuccessListener { callback (true) }.addOnFailureListener { callback(false) } }
Projeto-PPDM-login/app/src/main/java/br/senai/jandira/sp/apilivraria/components/textFild.kt
111793359
package br.senai.jandira.sp.apilivraria.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedTextField 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.unit.dp @OptIn(ExperimentalMaterial3Api::class) @Composable fun DefaultTextField( valor: String, label: String, onValueChange: (String) -> Unit ){ OutlinedTextField( value = valor, onValueChange = { onValueChange(it) }, modifier = Modifier.fillMaxWidth().background(Color.White), shape = RoundedCornerShape(4.dp), label = { Text( text = label ) } ) }
ExceptionManager/app/src/androidTest/java/com/example/exceptions/ExampleInstrumentedTest.kt
2903225260
package com.example.exceptions 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.exceptions", appContext.packageName) } }
ExceptionManager/app/src/test/java/com/example/exceptions/ExampleUnitTest.kt
2955049026
package com.example.exceptions 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) } }
ExceptionManager/app/src/main/java/com/example/exceptions/App.kt
3731849204
package com.example.exceptions import android.app.Application import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log import com.example.exceptions.logManager.ExceptionLogManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.acra.BuildConfig import org.acra.data.StringFormat import org.acra.ktx.initAcra class App : Application() { override fun onCreate() { ExceptionLogManager(applicationContext).enabled = true super.onCreate() CoroutineScope(Dispatchers.IO).launch { ExceptionLogManager.exceptionHandler.collectLatest { data -> data ?: return@collectLatest Log.d("ExceptionResult", "Application") } } //Сюда бы конечно хотелось бы прокидывать непосредственно экзепшн, но АПИ нужен от 22, а функционал getParcelable не доступен в этом АПИ applicationContext.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { intent?.apply { if (action == ExceptionLogManager.CUSTOM_INTENT_ACTION) { Log.d("ExceptionIntentFilter", "Application") } } } }, IntentFilter().apply { addAction(ExceptionLogManager.CUSTOM_INTENT_ACTION) }) } }
ExceptionManager/app/src/main/java/com/example/exceptions/MainActivity.kt
3125976609
package com.example.exceptions import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.util.Log import android.widget.Button import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.lifecycleScope import com.example.exceptions.logManager.ExceptionLogManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { @SuppressLint("UnspecifiedRegisterReceiverFlag") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) applicationContext.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { intent?.apply { if (action == ExceptionLogManager.CUSTOM_INTENT_ACTION) { Log.d("ExceptionIntentFilter", "MainActivity") } } } }, IntentFilter().apply { addAction(ExceptionLogManager.CUSTOM_INTENT_ACTION) }) lifecycleScope.launch(Dispatchers.IO) { ExceptionLogManager.exceptionHandler.collectLatest { data -> data ?: return@collectLatest //Так сделано для демонстрации. Код выше работает. Log.d("ExceptionResult", "MainActivity") } } ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } val array = ByteArray(8) override fun onStart() { super.onStart() val button = findViewById<Button>(R.id.button) button.setOnClickListener { //По кнопке троваем экзепшн CoroutineScope(Dispatchers.IO).launch { for (index in 0..array.size) array[index] = 12 } } } }
ExceptionManager/app/src/main/java/com/example/exceptions/FirstFragment.kt
3061222507
package com.example.exceptions import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.exceptions.databinding.FragmentFirstBinding /** * A simple [Fragment] subclass as the default destination in the navigation. */ class FirstFragment : Fragment() { private var _binding: FragmentFirstBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentFirstBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonFirst.setOnClickListener { findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
ExceptionManager/app/src/main/java/com/example/exceptions/LogsActivity.kt
1958945224
package com.example.exceptions 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 com.example.exceptions.databinding.ActivityLogsBinding class LogsActivity : AppCompatActivity() { private lateinit var binding: ActivityLogsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLogsBinding.inflate(layoutInflater) setContentView(binding.root) } }
ExceptionManager/app/src/main/java/com/example/exceptions/logManager/FileManager.kt
2010704402
package com.example.exceptions.logManager import android.content.Context import java.io.File class FileManager( private val context: Context, private val path: String? = null ) { private val sdCardPath by lazy { context.obbDir } private val directoryName by lazy { "${context.packageName}.LOG" } private var directoryFail = false private fun filePath(): String { return if (path.isNullOrEmpty()) { "${sdCardPath}/$directoryName/" } else { "${path}/$directoryName/" } } fun getFileListFromDirectory(): List<String> { val outList: MutableList<String> = mutableListOf() if (directoryFail) return outList val directory = File(filePath()).apply { directoryFail = if (!exists()) !mkdir() else false }.listFiles()?.toList() directory?.forEach { fileObj -> if (fileObj.isFile) outList += fileObj.name } return outList } fun readFromFile(file: String): String? { try { File(filePath()).apply { directoryFail = if (!exists()) !mkdir() else false } } catch (exception: java.lang.Exception) { directoryFail = true } if (directoryFail) return null var returnString = "" File(filePath() + "/$file").apply { try { returnString = bufferedReader().use { it.readText(); } } catch (ex: Exception) { try { createNewFile() readFromFile(file) } catch (e: Exception) { e.printStackTrace() } } } return returnString } fun writeToFile(data: String, fileName: String) { File(filePath() + fileName).writeText(data) } fun deleteLocalFile(fileName: String): Boolean { val file = File(filePath() + "/$fileName") return if (file.exists()) file.deleteRecursively() else true } }
ExceptionManager/app/src/main/java/com/example/exceptions/logManager/ExceptionLogManager.kt
1063062214
package com.example.exceptions.logManager import android.content.Context import android.content.Intent import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import java.io.File import java.util.Calendar class ExceptionLogManager(context: Context) { private val baseExceptionHandler: Thread.UncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler() as Thread.UncaughtExceptionHandler private lateinit var lastException: Pair<Thread?, Throwable?> data class ExceptionData( val thread: String? = null, val throwable: String? = null, val timestamp: Long? = null, ) var enabled = false var isShowLog = true private val gson = Gson() private val listType = object : TypeToken<List<ExceptionData>>() {}.type private val calendar = Calendar.getInstance() private val countDay = 7 private val dayInMilliseconds = 86400000L private val fileManager = FileManager(context) private val currentFileName get() = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis.toString() + ".json" companion object { private val _exceptionHandler: MutableStateFlow<ExceptionData?> = MutableStateFlow(null) val exceptionHandler: StateFlow<ExceptionData?> get() = _exceptionHandler.asStateFlow() const val CUSTOM_INTENT_ACTION = "exceptions.logManager" const val EXCEPTION_KEY = "exceptionKey" } init { Thread.setDefaultUncaughtExceptionHandler { thread: Thread?, throwable: Throwable? -> throwable?.let { throwableObject -> if (enabled) { val newExceptionData = ExceptionData( thread.toString(), throwable.toString(), calendar.timeInMillis ) val listData = convertDataToList(fileManager.readFromFile(currentFileName)) listData.add(newExceptionData) val outString = gson.toJson(listData, listType) fileManager.writeToFile(outString, currentFileName) lastException = Pair(thread, throwable) if (isShowLog) { val intent = Intent(CUSTOM_INTENT_ACTION).apply { putExtra(EXCEPTION_KEY, throwableObject.toString()) } context.sendBroadcast(intent) _exceptionHandler.value = newExceptionData } else { throwLastExceptionToDefaultHandler() } } } } fileManager.getFileListFromDirectory().forEach { currentFile -> if (currentFile.toLong() / dayInMilliseconds > countDay) { fileManager.deleteLocalFile(currentFileName) } } } private fun throwLastExceptionToDefaultHandler() { if ((lastException.first != null) and (lastException.second != null)) baseExceptionHandler.uncaughtException(lastException.first!!, lastException.second!!) } private fun convertDataToList(dataString: String?): MutableList<ExceptionData> { val list = mutableListOf<ExceptionData>() if (!dataString.isNullOrEmpty()) { list.addAll(gson.fromJson(dataString, listType)) } return list } }
ExceptionManager/app/src/main/java/com/example/exceptions/SecondFragment.kt
4079404807
package com.example.exceptions import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.example.exceptions.databinding.FragmentSecondBinding /** * A simple [Fragment] subclass as the second destination in the navigation. */ class SecondFragment : Fragment() { private var _binding: FragmentSecondBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSecondBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonSecond.setOnClickListener { findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
carnation/lily02/src/androidTest/java/com/example/lily02/ExampleInstrumentedTest.kt
1984201175
package com.example.lily02 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.lily02", appContext.packageName) } }
carnation/lily02/src/test/java/com/example/lily02/ExampleUnitTest.kt
430510847
package com.example.lily02 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) } }
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Color.kt
4116153557
package com.example.lily02.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)
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Theme.kt
4073700100
package com.example.lily02.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 CarnationTheme( 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 ) }
carnation/lily02/src/main/java/com/example/lily02/ui/theme/Type.kt
3773931958
package com.example.lily02.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 ) */ )
carnation/lily02/src/main/java/com/example/lily02/MainActivity.kt
3190870531
package com.example.lily02 import androidx.lifecycle.viewmodel.compose.viewModel import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.absolutePadding 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.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.magnifier import androidx.compose.material3.Button import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.Checkbox import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.lily02.data.Task import com.example.lily02.model.TodoListViewModel import com.example.lily02.ui.theme.CarnationTheme import androidx.compose.runtime.livedata.observeAsState class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme // TodoApp() TodoAppViewModel() } } } } val dummyTasks = mutableListOf( Task(id = 1, title = "买菜"), Task(id = 2, title = "做饭"), Task(id = 3, title = "洗衣服") ) @Composable fun TodoListScreen( tasks: List<Task>, onTaskCheckedChange: (Int, Boolean) -> Unit, delete: (Int) -> Unit ) { LazyColumn { items(tasks) { task -> TaskItem(task = task, onTaskCheckedChange = onTaskCheckedChange, delete) } } } @Composable fun TaskItem(task: Task, onTaskCheckedChange: (Int, Boolean) -> Unit, delete: (Int) -> Unit) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(16.dp) ) { Checkbox( checked = task.completed, onCheckedChange = { isChecked -> onTaskCheckedChange(task.id, isChecked) } ) Text( text = task.title, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(start = 8.dp) ) Button(onClick = { delete(task.id) }, modifier = Modifier.absolutePadding(left = 50.dp)) { Text(text = "删除") } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "MutableCollectionMutableState") @OptIn(ExperimentalMaterial3Api::class) @Composable fun TodoApp() { // remember 只会记住重组后的 但不会帮助您在配置更改后保持状态 //rememberSaveable 置更改后保持状态(横竖屏的切换) //mutableStateListOf不能被委托的原因委托属性需要实现 getValue() 和 setValue() 方法。 // 而 mutableStateListOf<Task>() 本身并没有实现这两个方法,因此无法作为委托属性使用。 // val todosList = rememberSaveable { mutableStateListOf<Task>() } var tasks by remember { mutableStateOf(dummyTasks) } var newTodo by remember { mutableStateOf("") } Scaffold( content = { Column { CenterAlignedTopAppBar(title = { Text(text = "TodoList") }) Spacer(modifier = Modifier.height(10.dp)) TodoListScreen(tasks = tasks, { taskId, isChecked -> tasks = tasks.map { task -> if (task.id == taskId) { task.copy(completed = isChecked) } else { task } }.toMutableList() }, { taskId -> tasks = tasks.filter { it.id != taskId }.toMutableList() }) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { tasks += Task(id = tasks.size + 1, title = newTodo) } ) { Text(text = "添加") } } } } ) } @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "MutableCollectionMutableState") @Composable fun TodoListWithAddDelete() { var todos by remember { mutableStateOf(mutableListOf("Todo 1", "Todo 2")) } var newTodo by remember { mutableStateOf("") } Column( modifier = Modifier.padding(16.dp) ) { // 添加新的待办事项 Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { if (newTodo.isNotBlank()) { todos.add(newTodo) newTodo = "" } } ) { Text(text = "添加") } } Spacer(modifier = Modifier.height(16.dp)) // 显示当前的待办事项列表 Column { todos.forEach { todo -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { Text(text = todo, modifier = Modifier.weight(1f)) Button(onClick = { todos.remove(todo) }) { Text(text = "删除") } } } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun TodoAppViewModel(viewModel: TodoListViewModel = TodoListViewModel()) { val tasks by viewModel.tasks.observeAsState(viewModel.dummyTaskModels) var newTodo by remember { mutableStateOf("") } Scaffold( content = { Column { CenterAlignedTopAppBar(title = { Text(text = "TodoList") }) Spacer(modifier = Modifier.height(10.dp)) TodoListScreen( tasks = tasks, onTaskCheckedChange = { taskId, isChecked -> viewModel.updateTask(taskId, isChecked) }, delete = { taskId -> viewModel.deleteTask(taskId) } ) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { TextField( value = newTodo, onValueChange = { newTodo = it }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(8.dp)) Button( onClick = { viewModel.addTask(newTodo) newTodo = "" } ) { Text(text = "添加") } } } } ) }
carnation/lily02/src/main/java/com/example/lily02/model/TodoListViewModel.kt
2052243229
package com.example.lily02.model import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.lily02.data.Task class TodoListViewModel : ViewModel() { val dummyTaskModels = mutableListOf( Task(id = 1, title = "买菜"), Task(id = 2, title = "做饭"), Task(id = 3, title = "洗衣服") ) //task为变实时数据 private val _tasks = MutableLiveData<MutableList<Task>>().apply { value = dummyTaskModels.toMutableList() } val tasks: LiveData<MutableList<Task>> = _tasks fun updateTask(taskId: Int, isChecked: Boolean) { val updatedTasks = _tasks.value?.map { task -> if (task.id == taskId) { task.copy(completed = isChecked) } else { task } }?.toMutableList() _tasks.value = updatedTasks } fun deleteTask(taskId: Int) { val updatedTasks = _tasks.value?.filter { it.id != taskId }?.toMutableList() _tasks.value = updatedTasks } fun addTask(title: String) { val newTask = Task(id = (_tasks.value?.size ?: 0) + 1, title = title) _tasks.value = _tasks.value?.plus(newTask)?.toMutableList() } }
carnation/lily02/src/main/java/com/example/lily02/data/Task.kt
3417034745
package com.example.lily02.data data class Task(val id: Int, val title: String, var completed: Boolean = false)
carnation/lily03/src/androidTest/java/com/example/lily03/ExampleInstrumentedTest.kt
2759303565
package com.example.lily03 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.lily03", appContext.packageName) } }
carnation/lily03/src/test/java/com/example/lily03/ExampleUnitTest.kt
3828562345
package com.example.lily03 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) } }
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Color.kt
4180651164
package com.example.lily03.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)
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Theme.kt
4011659504
package com.example.lily03.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 CarnationTheme( 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 ) }
carnation/lily03/src/main/java/com/example/lily03/ui/theme/Type.kt
914601358
package com.example.lily03.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 ) */ )
carnation/lily03/src/main/java/com/example/lily03/MainActivity.kt
3236888909
package com.example.lily03 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size 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.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.lily03.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Column { Text( text = "Hello $name!", modifier = modifier ) Image( painter = painterResource(id = R.drawable.local_image), contentDescription = "Local Image" ) AsyncImage( model = "https://marketplace.canva.cn/NsFNI/MADwRLNsFNI/1/screen_2x/canva-blue-textured-background-MADwRLNsFNI.jpg", contentDescription = "Translated description of what the image contains" ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/app/src/androidTest/java/com/example/carnation/ExampleInstrumentedTest.kt
3693745205
package com.example.carnation 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.carnation", appContext.packageName) } }
carnation/app/src/test/java/com/example/carnation/ExampleUnitTest.kt
1596470850
package com.example.carnation 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) } }
carnation/app/src/main/java/com/example/carnation/ui/theme/Color.kt
2753908392
package com.example.carnation.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)
carnation/app/src/main/java/com/example/carnation/ui/theme/Theme.kt
1766391820
package com.example.carnation.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 CarnationTheme( 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 ) }
carnation/app/src/main/java/com/example/carnation/ui/theme/Type.kt
1944784460
package com.example.carnation.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 ) */ )
carnation/app/src/main/java/com/example/carnation/MainActivity.kt
3261108219
package com.example.carnation import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.carnation.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") ArtistCard() } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun ArtistCard() { Column{ Text("Alfred Sisley") Text("3 minutes ago") WithConstraintsComposable() FlowRowSimpleUsageExample() } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun FlowRowSimpleUsageExample() { FlowRow( modifier = Modifier.padding(8.dp) , horizontalArrangement = Arrangement.SpaceAround ) { Text("3 minutes ago") Text("3 minutes ago") Text("3 minutes ago") Box(modifier = Modifier.padding(8.dp).height(200.dp).background(color = Color.Blue)){ Text("3 minutes ago") } } } @Composable fun WithConstraintsComposable() { BoxWithConstraints { Text("My minHeight is $minHeight while my maxWidth is $maxWidth") } } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/lily/src/androidTest/java/com/example/lily/ExampleInstrumentedTest.kt
2850923828
package com.example.lily 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.lily", appContext.packageName) } }
carnation/lily/src/test/java/com/example/lily/ExampleUnitTest.kt
2686021068
package com.example.lily 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) } }
carnation/lily/src/main/java/com/example/lily/ui/theme/Color.kt
736339034
package com.example.lily.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)
carnation/lily/src/main/java/com/example/lily/ui/theme/Theme.kt
1969905346
package com.example.lily.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 CarnationTheme( 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 ) }
carnation/lily/src/main/java/com/example/lily/ui/theme/Type.kt
1401923170
package com.example.lily.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 ) */ )
carnation/lily/src/main/java/com/example/lily/MainActivity3.kt
905388834
package com.example.lily import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.Person import androidx.compose.material.icons.rounded.Settings import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.Scaffold import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.vector.ImageVector import com.example.lily.ui.theme.CarnationTheme /////底部导航栏的实现 // class MainActivity3 : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { // A surface container using the 'background' color from the theme BottomNavigationExample() } } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun BottomNavigationExample() { // 创建底部导航栏的状态 var selectedIndex by remember { mutableIntStateOf(0) } // 创建底部导航栏的项目 val items = listOf( NavItem.Home, NavItem.Profile, NavItem.Settings ) Scaffold( bottomBar = { NavigationBar() { items.forEachIndexed { index, item -> NavigationBarItem( icon = { Icon(imageVector = item.icon, contentDescription = null) }, label = { Text(text = item.title) }, selected = selectedIndex == index, onClick = { selectedIndex = index } ) } } } ) { // 根据选中的索引显示不同的页面内容 when (selectedIndex) { 0 -> TabContent(text = "Tab 1 Content") 1 -> TabContent(text = "Tab 2 Content") 2 -> TabContent(text = "Tab 3 Content") } } } @Composable fun TabContent(text: String) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = text) } } // 底部导航 sealed class NavItem(var route: String, var icon: ImageVector, var title: String) { object Home : NavItem("home", Icons.Rounded.Home, "Home") object Profile : NavItem("profile", Icons.Rounded.Person, "Profile") object Settings : NavItem("settings", Icons.Rounded.Settings, "Settings") }
carnation/lily/src/main/java/com/example/lily/MainActivity.kt
3283292938
package com.example.lily 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.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.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.findNavController import com.example.lily.ui.theme.CarnationTheme import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { Greeting("你好,世界") } } } override fun onResume() { super.onResume() delayAndNavigate() } //直线任务kotlin的协程 private fun delayAndNavigate() { CoroutineScope(Dispatchers.Main).launch { delay(3000L) // 延时 3 秒,单位为毫秒 startActivityToNewScreen() // 调用跳转方法 } } private fun startActivityToNewScreen() { val intent = Intent(this, MainActivity3::class.java) startActivity(intent) } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = name, modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } }
carnation/lily/src/main/java/com/example/lily/MainActivity2.kt
3739084797
package com.example.lily import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api 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.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.lily.ui.theme.CarnationTheme class MainActivity2 : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { NavGraph() } } } } @Composable fun NavGraph() { val navController = rememberNavController() NavHost( navController = navController, startDestination = "home" ) { composable("home") { HomeScreen(navController = navController) } composable("details") { DetailsScreen() } } } @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailsScreen() { // Scaffold (topBar ={ AppBar()}){ // // } Column(modifier = Modifier.fillMaxWidth()) { Text(text = "详情页") } } @Composable fun AppBar() { Text(text = "详情页") } @Composable fun HomeScreen(navController: NavHostController) { Column(modifier = Modifier.fillMaxWidth()) { Text(text = "主页") Button(onClick = { navController.navigate("details") }) { Text(text = "跳转去详情页") } } }
carnation/lily01/src/androidTest/java/com/example/lily01/ExampleInstrumentedTest.kt
3680561016
package com.example.lily01 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.lily01", appContext.packageName) } }
carnation/lily01/src/test/java/com/example/lily01/ExampleUnitTest.kt
3296094532
package com.example.lily01 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) } }
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Color.kt
3789552654
package com.example.lily01.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)
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Theme.kt
3568846616
package com.example.lily01.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 CarnationTheme( 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 ) }
carnation/lily01/src/main/java/com/example/lily01/ui/theme/Type.kt
1092000703
package com.example.lily01.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 ) */ )
carnation/lily01/src/main/java/com/example/lily01/MainActivity.kt
3023500572
package com.example.lily01 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.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.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.lily01.ui.theme.CarnationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarnationTheme { Column( modifier = Modifier.fillMaxSize() ) { ItemExample("屏幕显示") { Item1() } ItemExample("简单布局") { Item2() } ItemExample("简单控件") { Item3() } ItemExample("图形基础") { Item4() } ItemExample("计算器") {Item5() } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { CarnationTheme { Greeting("Android") } } @Composable fun ItemExample(name: String, child: @Composable () -> Unit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Box(modifier= Modifier.height(10.dp)) Text(text = name, textAlign = TextAlign.Center) Box(modifier= Modifier.height(10.dp)) child() } } @Composable fun Item1() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "文本视图") GotoButton({}, "文字大小") GotoButton({}, "文字颜色") } } } @Composable fun Item2() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "视图宽高") GotoButton({}, "空白间隔") GotoButton({}, "对齐方式") } } } @Composable fun Item3() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "线性布局(方向)") GotoButton({}, "线性布局(权重)") GotoButton({}, "按钮点击") } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "英文大小写") GotoButton({}, "按钮点击") GotoButton({}, "按钮长按") } } } @Composable fun Item4() { Column { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { GotoButton({}, "图像拉伸") GotoButton({}, "图像按钮") GotoButton({}, "图文混排") } } } @Composable fun Item5() { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { GotoButton({}, "简单计算器") } } @Composable fun GotoButton(onClick: () -> Unit, name: String) { Button(onClick = onClick) { Text(text = name ) } }
FitLife/app/src/androidTest/java/com/application/fitlife/ExampleInstrumentedTest.kt
1866289734
package com.application.fitlife 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.application.fitlife", appContext.packageName) } }
FitLife/app/src/test/java/com/application/fitlife/ExampleUnitTest.kt
3943972416
package com.application.fitlife 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) } }
FitLife/app/src/main/java/com/application/fitlife/GraphSampleDataGenerator.kt
227613478
package com.application.fitlife class GraphSampleDataGenerator { fun dailyScoresArrayData(): IntArray { return intArrayOf(84,87,85,88,99,96,75,88,87,95,92,81,97,76,96,97,80,100,77,77,79,91,96,78,76,98,82,98,83) } fun heartRatesArrayData(): IntArray { return intArrayOf(72,67,78,66,66, 78, 78, 61, 67, 62, 76, 71, 76, 69, 61, 60, 62, 78, 79, 78, 72, 70, 70, 72, 60, 71, 79, 78, 70) } fun respiratoryRatesArrayData(): IntArray { return intArrayOf(13,18,17,18,17,14,13,12,17,17,13,12,13,15,17,14,14,14,12,12,13,18,15,15,16,12,12,15,16) } fun userWeightArrayData(): IntArray { return intArrayOf(90,90,90,90,90,90,90,90,89,89,89,89,88,88,88,88,88,87,87,87,87,87,86,86,86,85,85,85,85) } fun createAndPopulateArray(): IntArray { // Step 1: Define an array to store integers val intArray = IntArray(5) // You can change the size as needed // Step 2: Write a loop to push a new value into the array for (i in intArray.indices) { // You can replace the logic here to get the value you want to push val newValue = i * 2 intArray[i] = newValue } // Step 3: Return the populated array return intArray } }
FitLife/app/src/main/java/com/application/fitlife/MainActivity.kt
3682821780
package com.application.fitlife import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.app.Activity import android.content.ContentValues import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Color import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.media.MediaMetadataRetriever import android.net.Uri import android.os.AsyncTask import android.os.Handler import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.application.fitlife.data.MyDatabaseHelper import java.util.* import kotlin.math.abs import kotlin.math.pow import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter class MainActivity : AppCompatActivity() { // defining the UI elements private lateinit var heartRateText: TextView private lateinit var userAge: EditText private lateinit var userWeight: EditText private lateinit var userHeight: EditText // maintaining a unique ID to acts a primary key reference for the database table. // for this project we are using the current date as the primary key as we are interested in only maintaining one row per day. // so any new data coming into the table for the current date which is already present in the table, then the code logic would only update the table instead of inserting a new row. private lateinit var sharedPreferences: SharedPreferences // camera implementation pre requisites val CAMERA_ACTIVITY_REQUEST_CODE = 1 // Define a request code (any integer) private val eventHandler = Handler() // respiratory rate accelerometer pre-requisites private val dataCollectionIntervalMillis = 100 // Sampling interval in milliseconds private val accelValuesX = ArrayList<Float>() private val accelValuesY = ArrayList<Float>() private val accelValuesZ = ArrayList<Float>() private var isMeasuringRespiratoryRate = false private val measurementDuration = 45000L // 45 seconds private val slowTask = SlowTask() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // sharedPreferences is something similar to the localStorage and sessionStorage we get in JavaScript sharedPreferences = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE) // generating a new unique ID val uniqueId = generateUniqueId() // Store the unique ID in SharedPreferences val editor = sharedPreferences.edit() editor.putString(getString(R.string.unique_id), uniqueId) editor.apply() // accessing the heart Rate UI element and setting the TextView to be disabled so that the user cannot edit it. heartRateText = findViewById<TextView>(R.id.heartRateText) heartRateText.text = "0" heartRateText.isEnabled = false // accessing the respiratory Rate UI element and setting the TextView to be disabled so that the user cannot edit it. val respiratoryRateText = findViewById<TextView>(R.id.respiratoryRateText) respiratoryRateText.isEnabled = false // accessing the user age, weight and height metric fields. userAge = findViewById(R.id.editTextAge) userHeight = findViewById(R.id.editTextHeight) userWeight = findViewById(R.id.editTextWeight) val userAgeValue = userAge.text.toString() val userHeightValue = userHeight.text.toString() val userWeightValue = userWeight.text.toString() Log.d("userMetricValues", "age = $userAgeValue ; height = $userHeightValue ; weight = $userWeightValue"); // making sure that the text view components that is: app title and the tag line for the app title are disabled so that the user cannot edit it. val tagLinePartViewTwo: TextView = findViewById(R.id.tagLinePart2) tagLinePartViewTwo.isEnabled = false val appTitleView: TextView = findViewById(R.id.appTitle) appTitleView.isEnabled = false // Measure heart rate button val measureHeartRateButton = findViewById<Button>(R.id.heartRate) measureHeartRateButton.setOnClickListener { val intent = Intent(this@MainActivity, CameraActivity::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivityForResult(intent, CAMERA_ACTIVITY_REQUEST_CODE) } // Respiratory rate calculation val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) val sensorListener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent?) { // Handle accelerometer data here if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) { val x = event.values[0] val y = event.values[1] val z = event.values[2] accelValuesX.add(x) accelValuesY.add(y) accelValuesZ.add(z) } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { // Handle accuracy changes if needed } } val measureRespiratoryRate = findViewById<Button>(R.id.respiratoryRate) measureRespiratoryRate.setOnClickListener { Toast.makeText(baseContext, "Started measuring respiratory rate", Toast.LENGTH_SHORT).show() if (!isMeasuringRespiratoryRate) { isMeasuringRespiratoryRate = true accelValuesX.clear() accelValuesY.clear() accelValuesZ.clear() sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) eventHandler.postDelayed({ sensorManager.unregisterListener(sensorListener) val respiratoryRate = calculateRespiratoryRate() respiratoryRateText.text = respiratoryRate.toString() Toast.makeText(baseContext, "Respiratory rate calculation completed :" + respiratoryRate.toString(), Toast.LENGTH_SHORT).show() isMeasuringRespiratoryRate = false }, measurementDuration) } } val dbHelper = MyDatabaseHelper(this) val recordMetricsButton = findViewById<Button>(R.id.recordMetrics) recordMetricsButton.setOnClickListener { val userAgeValueRecordedOnButtonClick = userAge.text.toString() val userHeightValueRecordedOnButtonClick = userHeight.text.toString() val userWeightValueRecordedOnButtonClick = userWeight.text.toString() Log.d("recordMetricsButtonuserMetricValues", "age = $userAgeValueRecordedOnButtonClick ; height = $userHeightValueRecordedOnButtonClick ; weight = $userWeightValueRecordedOnButtonClick"); insertOrUpdateDatabaseEntry(dbHelper, uniqueId, heartRateText.text.toString(), respiratoryRateText.text.toString(), userAgeValueRecordedOnButtonClick, userWeightValueRecordedOnButtonClick, userHeightValueRecordedOnButtonClick) Toast.makeText(baseContext, "Uploaded Metrics to database", Toast.LENGTH_SHORT).show() } val recentAnalyticsButton = findViewById<Button>(R.id.recentAnalytics) recentAnalyticsButton.setOnClickListener { val intent = Intent(this@MainActivity, GraphsAndAnalyticsActivity::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivity(intent) } val startExerciseButton = findViewById<Button>(R.id.startExercise) startExerciseButton.setOnClickListener { val intent = Intent(this@MainActivity, ShowExercise::class.java) intent.putExtra(getString(R.string.unique_id), uniqueId) startActivity(intent) } } fun insertOrUpdateDatabaseEntry(dbHelper: MyDatabaseHelper, uniqueDate: String, heart_rate: String, respiratory_rate: String, age: String, weight: String, height: String) { val db = dbHelper.writableDatabase // Check if the entry with the given vitals_id exists val generatedUniqueDateFromFunction = generateUniqueDate() Log.d("generatedUniqueDateFromFunction", generatedUniqueDateFromFunction) val cursor = db.rawQuery("SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(generatedUniqueDateFromFunction)) val values = ContentValues() if (heart_rate == "") { values.put("heart_rate", "72") } else { values.put("heart_rate", heart_rate) } if (respiratory_rate == "") { values.put("respiratory_rate", "15") } else { values.put("respiratory_rate", respiratory_rate) } if (weight == "") { values.put("weight", "90") } else { values.put("weight", weight) } if (height == "") { values.put("height", "170") } else { values.put("height", height) } // values.put("heart_rate", heart_rate.toFloatOrNull() ?: 0.0f) // values.put("respiratory_rate", respiratory_rate.toFloatOrNull() ?: 0.0f) // values.put("weight", weight.toFloatOrNull() ?: 0.0f) // values.put("height", height.toFloatOrNull() ?: 0.0f) Log.d("insertOrUpdateDatabaseEntry", "Primary Key Date = $generatedUniqueDateFromFunction heart_rate: $heart_rate, respiratory_rate: $respiratory_rate, weight: $weight, height: $height") if (cursor.count > 0) { // Entry with the vitals_id already exists, update it db.update( MyDatabaseHelper.TABLE_NAME_USER_METRICS, values, "${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(generatedUniqueDateFromFunction) ) } else { values.put("date", generatedUniqueDateFromFunction) // Entry with the vitals_id doesn't exist, insert a new record db.insert(MyDatabaseHelper.TABLE_NAME_USER_METRICS, null, values) } cursor.close() db.close() } private fun generateUniqueId(): String { // Get current timestamp in milliseconds val timestamp = System.currentTimeMillis() // Generate a random UUID val randomUUID = UUID.randomUUID() // Combine the timestamp and randomUUID to create a unique ID return "$timestamp-${randomUUID.toString()}" } private fun generateUniqueDate(): String { val currentDate = LocalDate.now(ZoneId.systemDefault()) val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") var formattedDate = currentDate.format(formatter) formattedDate = formattedDate.toString() return formattedDate } private fun calculateRespiratoryRate():Int { var previousValue = 0f var currentValue = 0f previousValue = 10f var k = 0 println("x size : " + accelValuesX.size) println("Y size : " + accelValuesY.size) println("Z size : " + accelValuesZ.size) for (i in 11 until accelValuesX.size) { currentValue = kotlin.math.sqrt( accelValuesZ[i].toDouble().pow(2.0) + accelValuesX[i].toDouble().pow(2.0) + accelValuesY[i].toDouble() .pow(2.0) ).toFloat() if (abs(x = previousValue - currentValue) > 0.10) { k++ } previousValue=currentValue } val ret= (k/45.00) return (ret*30).toInt() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CAMERA_ACTIVITY_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { val videoUri = data?.getStringExtra("videoUri") if (videoUri != null) { Toast.makeText(baseContext, "Calculating heart rate", Toast.LENGTH_SHORT).show() val path = convertMediaUriToPath(Uri.parse(videoUri)) slowTask.execute(path) // heartRateText.text = data?.getStringExtra("heartRate") } } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(baseContext, "Video not recorded", Toast.LENGTH_SHORT).show() } } } fun convertMediaUriToPath(uri: Uri?): String { val proj = arrayOf(MediaStore.Images.Media.DATA) val cursor = contentResolver.query(uri!!, proj, null, null, null) val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() val path = cursor.getString(column_index) cursor.close() return path } inner class SlowTask : AsyncTask<String, String, String?>() { public override fun doInBackground(vararg params: String?): String? { Log.d("MainActivity", "Executing slow task in background") var m_bitmap: Bitmap? = null var retriever = MediaMetadataRetriever() var frameList = ArrayList<Bitmap>() try { retriever.setDataSource(params[0]) var duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT) var aduration = duration!!.toInt() var i = 10 while (i < aduration) { val bitmap = retriever.getFrameAtIndex(i) frameList.add(bitmap!!) i += 5 } } catch (m_e: Exception) { } finally { retriever?.release() var redBucket: Long = 0 var pixelCount: Long = 0 val a = mutableListOf<Long>() for (i in frameList) { redBucket = 0 i.width i.height for (y in 0 until i.height) { for (x in 0 until i.width) { val c: Int = i.getPixel(x, y) pixelCount++ redBucket += Color.red(c) + Color.blue(c) + Color.green(c) } } a.add(redBucket) } val b = mutableListOf<Long>() for (i in 0 until a.lastIndex - 5) { var temp = (a.elementAt(i) + a.elementAt(i + 1) + a.elementAt(i + 2) + a.elementAt(i + 3) + a.elementAt(i + 4)) / 4 b.add(temp) } var x = b.elementAt(0) var count = 0 for (i in 1 until b.lastIndex) { var p=b.elementAt(i.toInt()) if ((p-x) > 3500) { count = count + 1 } x = b.elementAt(i.toInt()) } var rate = ((count.toFloat() / 45) * 60).toInt() return (rate/2).toString() } } override fun onPostExecute(result: String?) { super.onPostExecute(result) if (result != null) { Toast.makeText(baseContext, "Heart rate calculation completed : $result", Toast.LENGTH_SHORT).show() heartRateText.text = result } } } }
FitLife/app/src/main/java/com/application/fitlife/GraphsAndAnalyticsActivity.kt
1262602412
package com.application.fitlife import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.ProgressBar import android.widget.Spinner import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.application.fitlife.data.MyDatabaseHelper import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.BarGraphSeries import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries import com.application.fitlife.GraphSampleDataGenerator class GraphsAndAnalyticsActivity : AppCompatActivity() { private lateinit var spinner: Spinner private lateinit var graphView: GraphView private lateinit var scoreButton: Button private lateinit var weightButton: Button private lateinit var heartRateButton: Button private lateinit var respiratoryRateButton: Button private var progressBar: ProgressBar? = null private var progressText: TextView? = null private var currentAttribute = "score" private var todaysDailyScore = 0; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_graphs_and_analytics) spinner = findViewById(R.id.spinner) graphView = findViewById(R.id.graphView) scoreButton = findViewById(R.id.scoreButton) weightButton = findViewById(R.id.weightButton) heartRateButton = findViewById(R.id.heartRateButton) respiratoryRateButton = findViewById(R.id.respiratoryRateButton) // set the id for the progressbar and progress text progressBar = findViewById(R.id.progress_bar); progressText = findViewById(R.id.progress_text); ArrayAdapter.createFromResource( this, R.array.graph_types, android.R.layout.simple_spinner_item ).also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = adapter graphView.removeAllSeries() } // by default showing the line graph for score for the past recent data defaultUpdateGraph("score") scoreButton.setOnClickListener { currentAttribute = "score" updateGraph("score") } weightButton.setOnClickListener { currentAttribute = "weight" updateGraph("weight") } heartRateButton.setOnClickListener { currentAttribute = "heart_rate" updateGraph("heart_rate") } respiratoryRateButton.setOnClickListener { currentAttribute = "respiratory_rate" updateGraph("respiratory_rate") } graphView.removeAllSeries() spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long ) { // Handle the selected item here val selectedItem = parentView?.getItemAtPosition(position).toString() // You can perform actions based on the selected item // For example, update the UI, trigger a function, etc. // Example: updateGraph(selectedItem) Log.d("dropDownSelectedItem" , selectedItem) println("dropDown Selected Item - $selectedItem") updateGraph(currentAttribute) } override fun onNothingSelected(parentView: AdapterView<*>?) { // Do nothing here } } } private fun updateGraph(metric: String) { val series = when (spinner.selectedItem.toString()) { "Line Graph" -> LineGraphSeries<DataPoint>(getDataPoints(metric)) "Bar Graph" -> BarGraphSeries<DataPoint>(getDataPoints(metric)) else -> throw IllegalArgumentException("Invalid graph type") } graphView.removeAllSeries() graphView.addSeries(series) //graphView.viewport.isXAxisBoundsManual = true graphView.viewport.setMinX(0.0) // need to update this to show case the past 10 days data so the maximum value of x should be 10. graphView.viewport.setMaxX(30.0) // Enable scrolling graphView.viewport.isScrollable = true } private fun defaultUpdateGraph(metric: String) { val series = LineGraphSeries<DataPoint>(getDataPoints(metric)) graphView.removeAllSeries() graphView.addSeries(series) //graphView.viewport.isXAxisBoundsManual = true graphView.viewport.setMinX(0.0) // need to update this to show case the past 10 days data so the maximum value of x should be 10. graphView.viewport.setMaxX(30.0) // Enable scrolling graphView.viewport.isScrollable = true } private fun getDataPoints(metric: String): Array<DataPoint> { // Replace this with your actual logic to get the data points val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase val cursor = db.rawQuery( "SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} ORDER BY ${MyDatabaseHelper.COLUMN_NAME_DATE} DESC LIMIT 30", arrayOf() ) val scoresDataArray = mutableListOf<DataPoint>() val weightDataArray = mutableListOf<DataPoint>() val heartRateDataArray = mutableListOf<DataPoint>() val respiratoryRateDataArray = mutableListOf<DataPoint>() val emptyDataArray = mutableListOf<DataPoint>() if (cursor != null && cursor.moveToFirst()) { var day = 1 do { // You can retrieve data from the cursor using column indices or column names val dateIDIndex = cursor.getColumnIndex("date") val dateValue = cursor.getString(dateIDIndex) val scoreIndex = cursor.getColumnIndex("score") val scoreValue = cursor.getDouble(scoreIndex) val heartRateIndex = cursor.getColumnIndex("heart_rate") val heartRateValue = cursor.getDouble(heartRateIndex) val respiratoryRateIndex = cursor.getColumnIndex("respiratory_rate") val respiratoryRateValue = cursor.getDouble(respiratoryRateIndex) val weightIndex = cursor.getColumnIndex("weight") val weightValue = cursor.getDouble(weightIndex) // Now you can use the retrieved data as needed // Example: Log the values Log.d("getDataPointsQueryResponse", "Primary Key Date = $dateValue Score: $scoreValue, Weight: $weightValue, Heart Rate: $heartRateValue, Respiratory Rate: $respiratoryRateValue") // update the mutable scores data array var scoreDataPoint = DataPoint(day.toDouble(), scoreValue.toDouble()) scoresDataArray.add(scoreDataPoint) // update the mutable weights data array var weightDataPoint = DataPoint(day.toDouble(), weightValue.toDouble()) weightDataArray.add(weightDataPoint) // update the mutable heart rate data array var heartRateDataPoint = DataPoint(day.toDouble(), heartRateValue.toDouble()) heartRateDataArray.add(heartRateDataPoint) // update the mutable respiratory rate data array var respiratoryRateDataPoint = DataPoint(day.toDouble(), respiratoryRateValue.toDouble()) respiratoryRateDataArray.add(respiratoryRateDataPoint) if (day == 1) { todaysDailyScore = scoreValue.toInt(); if (todaysDailyScore == 0) { progressText?.text = "00" } else { progressText?.text = "" + todaysDailyScore } progressBar?.setProgress(todaysDailyScore) Log.d("todaysDailyScore" , todaysDailyScore.toString()) } day += 1 // Continue iterating if there are more rows } while (false) } // while (cursor.moveToNext()) // val dataArray = mutableListOf<DataPoint>() // // var dataPoint = DataPoint(0.0, 1.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(1.0, 5.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(2.0, 3.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(3.0, 2.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(4.0, 6.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(5.0, 7.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(6.0, 8.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(7.0, 9.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(8.0, 10.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(9.0, 11.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(10.0, 12.0) // dataArray.add(dataPoint) // // dataPoint = DataPoint(11.0, 13.0) // dataArray.add(dataPoint) var graphSampleDataGeneratorClassObject = GraphSampleDataGenerator() // getting random data for scores val randomDailyScoresDataArray = graphSampleDataGeneratorClassObject.dailyScoresArrayData() var day = 2 for (randomScoreValue in randomDailyScoresDataArray) { var dataPoint = DataPoint(day.toDouble(), randomScoreValue.toDouble()) scoresDataArray.add(dataPoint) day += 1 } // getting random data for heart rates val randomHeartRatesDataArray = graphSampleDataGeneratorClassObject.heartRatesArrayData() day = 2 for (randomHeartRate in randomHeartRatesDataArray) { var dataPoint = DataPoint(day.toDouble(), randomHeartRate.toDouble()) heartRateDataArray.add(dataPoint) day += 1 } // getting random data for respiratory rates val randomRespiratoryRatesDataArray = graphSampleDataGeneratorClassObject.respiratoryRatesArrayData() day = 2 for (randomRespiratoryRate in randomRespiratoryRatesDataArray) { var dataPoint = DataPoint(day.toDouble(), randomRespiratoryRate.toDouble()) respiratoryRateDataArray.add(dataPoint) day += 1 } // getting random data for respiratory rates val randomWeightDataArray = graphSampleDataGeneratorClassObject.userWeightArrayData() day = 2 for (randomWeight in randomWeightDataArray) { var dataPoint = DataPoint(day.toDouble(), randomWeight.toDouble()) weightDataArray.add(dataPoint) day += 1 } if (metric == "score") { return scoresDataArray.toTypedArray() } if (metric == "weight") { return weightDataArray.toTypedArray() } if (metric == "heart_rate") { return heartRateDataArray.toTypedArray() } if (metric == "respiratory_rate") { return respiratoryRateDataArray.toTypedArray() } return emptyDataArray.toTypedArray() // return arrayOf( // DataPoint(0.0, 1.0), // DataPoint(1.0, 5.0), // DataPoint(2.0, 3.0), // DataPoint(3.0, 2.0), // DataPoint(4.0, 6.0), // DataPoint(5.0, 7.0), // DataPoint(6.0, 8.0), // DataPoint(7.0, 9.0), // DataPoint(8.0, 10.0), // DataPoint(9.0, 11.0), // DataPoint(10.0, 12.0), // DataPoint(11.0, 13.0) // ) } }
FitLife/app/src/main/java/com/application/fitlife/FuzzyLogicControllerWorkoutSuggestions.kt
2564423673
package com.application.fitlife import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import com.application.fitlife.data.Workout import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.UserMetrics import java.time.LocalDate import java.time.format.DateTimeFormatter import kotlin.math.abs import kotlin.math.ceil import kotlin.random.Random class FuzzyLogicControllerWorkoutSuggestions { companion object { // Format a Date object to a String using the specified pattern fun suggestWorkouts(db: SQLiteDatabase, muscleGroups: List<String>, workoutTypes: List<String>, userMetrics: UserMetrics, sessionId: String): List<Long> { // profile the user metrics and rate the user // Calculate user BMI var userBMI = 23.5 userBMI = calculateBMI(userMetrics.height, userMetrics.weight) val bmiRating = calculateBMIRating(userBMI, 18.5, 29.9) val heartRateRating = calculateHeartRateRating( userMetrics.heartRate, 60.0, 100.0 ) val respiratoryRateRating = calculateRespiratoryRateRating( userMetrics.respiratoryRate, 12.0, 20.0 ) val bmiWeight = 0.4 val heartRateWeight = 0.3 val respiratoryRateWeight = 0.3 val overallRating = (bmiRating * bmiWeight + heartRateRating * heartRateWeight + respiratoryRateRating * respiratoryRateWeight) val selectedWorkouts: List<Workout> = getWorkoutsByFiltersAndRating(db, muscleGroups, workoutTypes, overallRating) for (workout in selectedWorkouts) { println("Workout ID: ${workout.id} Title: ${workout.title} ${workout.description}") } return insertWorkoutSuggestions(db, sessionId, selectedWorkouts) } private fun insertWorkoutSuggestions(db: SQLiteDatabase, sessionId: String, selectedWorkouts: List<Workout>): List<Long> { val contentValues = ContentValues() contentValues.put(MyDatabaseHelper.COLUMN_NAME_SESSION_ID, sessionId) contentValues.put(MyDatabaseHelper.COLUMN_NAME_DATE, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) val insertedSuggestionIds = mutableListOf<Long>() for (workout in selectedWorkouts) { contentValues.put(MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID, workout.id) contentValues.put(MyDatabaseHelper.COLUMN_NAME_SCORE, 0.0) contentValues.put(MyDatabaseHelper.COLUMN_NAME_IS_PERFORMED, 0) // Assuming 0 for not performed val suggestionId = db.insert(MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS, null, contentValues) if (suggestionId != -1L) { insertedSuggestionIds.add(suggestionId) } } return insertedSuggestionIds } private fun getWorkoutsByFiltersAndRating(db: SQLiteDatabase, bodyParts: List<String>, types: List<String>, targetRating: Double): List<Workout> { val bodyPartsCondition = if (bodyParts.isNotEmpty()) { "AND ${MyDatabaseHelper.COLUMN_NAME_BODYPART} IN (${bodyParts.joinToString(", ") { "'$it'" }})" } else { "" // Empty string when the list is empty } val typesCondition = if (types.isNotEmpty()) { "AND ${MyDatabaseHelper.COLUMN_NAME_TYPE} IN (${types.joinToString(", ") { "'$it'" }})" } else { "" // Empty string when the list is empty } val lowerBound = targetRating - 2.0 val upperBound = targetRating + 2.0 println("Running query to fetch workouts matching user preferences") val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUTS_INFORMATION} WHERE 1 = 1 $bodyPartsCondition $typesCondition AND ${MyDatabaseHelper.COLUMN_NAME_RATING} >= $lowerBound AND ${MyDatabaseHelper.COLUMN_NAME_RATING} <= $upperBound """.trimIndent() val cursor = db.rawQuery(query, null) val workoutsByMuscleGroup = mutableMapOf<String, MutableList<Workout>>() while (cursor.moveToNext()) { val workout = Workout( id = cursor.getLong(0), title = cursor.getString(1), description = cursor.getString(2), type = cursor.getString(3), bodyPart = cursor.getString(4), equipment = cursor.getString(5), level = cursor.getString(6), rating = cursor.getString(7), ratingDesc = cursor.getString(8), ) workoutsByMuscleGroup.computeIfAbsent(workout.bodyPart) { mutableListOf() }.add(workout) } val totalExercisesToSelect = 10.0 val exercisesPerGroup = if (workoutsByMuscleGroup.isNotEmpty()) { ceil(totalExercisesToSelect / workoutsByMuscleGroup.size) } else { 0 } // Randomly select proportional number of exercises from each group val selectedWorkouts = workoutsByMuscleGroup.flatMap { (_, workouts) -> workouts.shuffled().take(exercisesPerGroup.toInt()) }.take(totalExercisesToSelect.toInt()) return selectedWorkouts } /**Underweight = <18.5 Normal weight = 18.5–24.9 Overweight = 25–29.9 Obesity = BMI of 30 or greater */ private fun calculateBMI(height: Double, weight: Double): Double { if (height == 0.0 || weight == 0.0) return 23.5 return (weight * 100 * 100) / (height * height) } private fun calculateBMIRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 23.0 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateHeartRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 72 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateRespiratoryRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 15 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } } }
FitLife/app/src/main/java/com/application/fitlife/CameraActivity.kt
1882911439
package com.application.fitlife import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.Manifest import android.app.Activity import android.content.ContentValues import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Color import android.media.MediaMetadataRetriever import android.net.Uri import android.os.AsyncTask import android.os.Build import android.os.Handler import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.* import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import androidx.core.content.PermissionChecker import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class CameraActivity : AppCompatActivity() { private var videoCapture: VideoCapture<Recorder>? = null private var recording: Recording? = null private lateinit var cameraExecutor: ExecutorService private lateinit var captureVideo: Button private lateinit var intentToReturn: Intent private lateinit var hiddenButton: Button private var readyToReturn = false private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { requestPermissions() } cameraExecutor = Executors.newSingleThreadExecutor() captureVideo = findViewById<Button>(R.id.video_capture_button) captureVideo.setOnClickListener { handler.postDelayed({ captureVideo() }, 45000) // Stop recording after 10 seconds (10000 milliseconds) captureVideo() } hiddenButton = findViewById<Button>(R.id.hiddenButton) hiddenButton.setOnClickListener { if (readyToReturn) { setResult(Activity.RESULT_OK, intentToReturn) // Finish the activity to return to the calling activity finish() } } } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } companion object { private const val TAG = "BHealthy" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private val REQUIRED_PERMISSIONS = mutableListOf ( Manifest.permission.CAMERA ).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } }.toTypedArray() } private fun requestPermissions() { activityResultLauncher.launch(REQUIRED_PERMISSIONS) } private val activityResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { permissions -> // Handle Permission granted/rejected var permissionGranted = true permissions.entries.forEach { if (it.key in REQUIRED_PERMISSIONS && it.value == false) permissionGranted = false } if (!permissionGranted) { Toast.makeText(baseContext, "Permission request denied", Toast.LENGTH_SHORT).show() } else { startCamera() } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) val cameraView = findViewById<PreviewView>(R.id.viewFinder) cameraProviderFuture.addListener({ // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(cameraView.surfaceProvider) } val recorder = Recorder.Builder() .setQualitySelector(QualitySelector.from(Quality.SD)) .build() videoCapture = VideoCapture.withOutput(recorder) // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { // Unbind use cases before rebinding cameraProvider.unbindAll() // Bind use cases to camera val camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, videoCapture) // Turn on the flash (torch mode) camera.cameraControl.enableTorch(true) } catch(exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } private fun captureVideo() { val videoCapture = this.videoCapture ?: return captureVideo.isEnabled = false val curRecording = recording if (curRecording != null) { // Stop the current recording session. Toast.makeText(baseContext, "Stopped video recording", Toast.LENGTH_SHORT).show() curRecording.stop() recording = null return } // create and start a new recording session val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, name) put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/BHealthy") } } val mediaStoreOutputOptions = MediaStoreOutputOptions .Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() recording = videoCapture.output .prepareRecording(this, mediaStoreOutputOptions) // .apply { // if (PermissionChecker.checkSelfPermission(this@CameraActivity, // Manifest.permission.RECORD_AUDIO) == // PermissionChecker.PERMISSION_GRANTED) // { // withAudioEnabled() // } // } .start(ContextCompat.getMainExecutor(this)) { recordEvent -> when(recordEvent) { is VideoRecordEvent.Start -> { println("started video recording") Toast.makeText(baseContext, "Video capture started", Toast.LENGTH_SHORT).show() } is VideoRecordEvent.Finalize -> { if (!recordEvent.hasError()) { intentToReturn = Intent() intentToReturn.putExtra("videoUri", recordEvent.outputResults.outputUri.toString()) readyToReturn = true hiddenButton.performClick() } else { recording?.close() recording = null Log.e(TAG, "Video capture ends with error: ${recordEvent.error}") } } } } } }
FitLife/app/src/main/java/com/application/fitlife/ShowExercise.kt
4013248508
package com.application.fitlife import android.app.AlertDialog import android.content.ContentValues import android.content.Intent import android.database.sqlite.SQLiteDatabase import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.application.fitlife.FuzzyLogicControllerWorkoutSuggestions.Companion.suggestWorkouts import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.Workout import java.time.LocalDate import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.UUID class ShowExercise<SQLiteDatabase> : AppCompatActivity() { companion object { const val USER_HEIGHT = "height" const val USER_WEIGHT = "weight" const val USER_HEART_RATE = "heartRate" const val USER_RESPIRATORY_RATE = "respiratoryRate" } private lateinit var muscleGroupSpinner: Spinner private lateinit var showExercisesButton: Button private lateinit var showExercisesText: TextView private lateinit var submitButton: Button private lateinit var selectedMuscleGroupsText: TextView private lateinit var selectedExerciseTypesText: TextView private lateinit var selectMuscleGroupsButton: Button private lateinit var exercisesList: RecyclerView private lateinit var exercisesAdapter: ExercisesAdapter private lateinit var recyclerView: RecyclerView private lateinit var workoutAdapter: WorkoutCheckboxAdapter private lateinit var selectExerciseTypeButton: Button private val exerciseTypes by lazy { resources.getStringArray(R.array.exercise_types) } private var selectedExerciseTypes: BooleanArray? = null private val muscleGroups by lazy { resources.getStringArray(R.array.muscle_groups) } private var selectedMuscleGroups: BooleanArray? = null private val selectedExercises = mutableListOf<Exercise>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show_exercise) val sessionId = intent.getStringExtra(getString(R.string.unique_id))?: "default_value" selectMuscleGroupsButton = findViewById(R.id.selectMuscleGroupsButton) showExercisesButton = findViewById(R.id.showExercisesButton) selectedMuscleGroupsText = findViewById(R.id.selectedMuscleGroupsText) selectedExerciseTypesText = findViewById(R.id.selectedExerciseTypesText) //showExercisesText = findViewById(R.id.showExercisesText) //exercisesList = findViewById(R.id.exercisesList) selectedMuscleGroups = BooleanArray(muscleGroups.size) selectExerciseTypeButton = findViewById(R.id.selectExerciseTypeButton) recyclerView = findViewById(R.id.exercisesList) recyclerView.layoutManager = LinearLayoutManager(this) selectedExerciseTypes = BooleanArray(exerciseTypes.size) selectExerciseTypeButton.setOnClickListener { showExerciseTypeDialog() } //setupSpinner() submitButton = findViewById(R.id.submitExercisesButton) selectMuscleGroupsButton.setOnClickListener { showMuscleGroupDialog() } val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase showExercisesButton.setOnClickListener { //displaySelectedExercises() val muscleGroupSelections = muscleGroups.filterIndexed { index, _ -> selectedMuscleGroups?.get(index) == true } //Toast.makeText(this, "Selected Exercises: $muscleGroupSelections", Toast.LENGTH_LONG).show() val exerciseTypeSelections = exerciseTypes.filterIndexed { index, _ -> selectedExerciseTypes?.get(index) == true } val userMetrics = MyDatabaseHelper.getUserMetrics(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) val suggestedWorkoutIds = suggestWorkouts( db, muscleGroupSelections, exerciseTypeSelections, userMetrics, sessionId ) //Toast.makeText(this, "Number of Suggested workout Ids: ${suggestedWorkoutIds.size}", Toast.LENGTH_SHORT).show() val workouts = getWorkoutsByIds(db, suggestedWorkoutIds) Toast.makeText(this, "Number of workouts: ${workouts.size}", Toast.LENGTH_SHORT).show() workoutAdapter = WorkoutCheckboxAdapter(workouts) recyclerView.adapter = workoutAdapter // val adapter = WorkoutAdapter(workouts) // recyclerView.adapter = adapter //displayWorkouts(workouts) //Toast.makeText(this, "$suggestedWorkoutIds.size()", Toast.LENGTH_LONG).show(); // Do something with the suggestedWorkoutIds, like displaying them // FuzzyLogicControllerWorkoutSuggestions.showSelectedExercises() } submitButton.setOnClickListener { updateSuggestionScore(db , sessionId) } // exercisesAdapter = ExercisesAdapter(emptyList()) // exercisesList.layoutManager = LinearLayoutManager(this) // exercisesList.adapter = exercisesAdapter } private fun displayWorkouts(workouts: List<Workout>) { //: ${workout.description}Type: ${workout.type}, Body Part: ${workout.bodyPart} val workoutDetails = workouts.map { workout -> "${workout.title}" } // Assuming you have a TextView or any other component to display the workouts val workoutsDisplay = showExercisesText // Replace with your actual TextView ID workoutsDisplay.text = workoutDetails.joinToString("\n\n") } private fun getWorkoutsByIds(db: android.database.sqlite.SQLiteDatabase, ids: List<Long>): List<Workout> { val workouts = mutableListOf<Workout>() // Convert the List<Long> of workout IDs to a comma-separated string for the SQL query val workoutIdList = ids.joinToString(separator = ", ") //Toast.makeText(this, "Workout ID list length: ${workoutIdList.length}", Toast.LENGTH_SHORT).show() Log.d("workoutId", workoutIdList) Toast.makeText(this, "All the Ids: $workoutIdList", Toast.LENGTH_SHORT).show() // SQL query to retrieve exercises val query = """ SELECT wi.*, ws.${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID}, ws.${MyDatabaseHelper.COLUMN_NAME_SCORE} FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} ws JOIN ${MyDatabaseHelper.TABLE_NAME_WORKOUTS_INFORMATION} wi ON wi.${MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID} = ws.${MyDatabaseHelper.COLUMN_NAME_EXERCISE_ID} WHERE ws.${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID} IN ($workoutIdList) """ Log.d("SQLQuery", query) Toast.makeText(this, "All the query: $query", Toast.LENGTH_SHORT).show() val cursor = db.rawQuery(query, null) try { while (cursor.moveToNext()) { val workout = Workout( id = cursor.getLong(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_WORKOUT_ID)), title = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_TITLE)), description = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_DESCRIPTION)), type = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_TYPE)), bodyPart = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_BODYPART)), equipment = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_EQUIPMENT)), level = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_LEVEL)), rating = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_RATING)), ratingDesc = cursor.getString(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_RATING_DESC)), score = cursor.getDouble(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_SCORE)), suggestionId = cursor.getLong(cursor.getColumnIndexOrThrow(MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID)) ) workouts.add(workout) } } finally { cursor.close() // Ensure the cursor is closed after use } return workouts } private fun showExerciseTypeDialog() { AlertDialog.Builder(this) .setTitle("Select Exercise Types") .setMultiChoiceItems(exerciseTypes, selectedExerciseTypes) { _, which, isChecked -> selectedExerciseTypes?.set(which, isChecked) } .setPositiveButton("OK") { dialog, _ -> updateSelectedExerciseTypesText() dialog.dismiss() } .setNegativeButton("Cancel", null) .show() } private fun updateSelectedExerciseTypesText() { val selectedTypes = exerciseTypes .filterIndexed { index, _ -> selectedExerciseTypes?.get(index) == true } .joinToString(separator = ", ") selectedExerciseTypesText.text = if (selectedTypes.isEmpty()) { "Selected Exercise Types: None" } else { "Selected Exercise Types: $selectedTypes" } } private fun showMuscleGroupDialog() { AlertDialog.Builder(this) .setTitle("Select Muscle Groups") .setMultiChoiceItems(muscleGroups, selectedMuscleGroups) { _, which, isChecked -> selectedMuscleGroups?.set(which, isChecked) } .setPositiveButton("OK") { dialog, _ -> //updateExercisesList() prepareSelectedExercises() updateSelectedMuscleGroupsText() dialog.dismiss() } .setNegativeButton("Cancel", null) .show() } private fun updateSelectedMuscleGroupsText() { val selectedGroups = muscleGroups .filterIndexed { index, _ -> selectedMuscleGroups?.get(index) == true } .joinToString(separator = ", ") selectedMuscleGroupsText.text = if (selectedGroups.isEmpty()) { "Selected Muscle Groups: None" } else { "Selected Muscle Groups: $selectedGroups" } } private fun displaySelectedExercises() { exercisesAdapter.exercises = selectedExercises exercisesAdapter.notifyDataSetChanged() } private fun prepareSelectedExercises() { selectedExercises.clear() muscleGroups.forEachIndexed { index, muscleGroup -> selectedMuscleGroups?.let { if (it[index]) { selectedExercises.addAll(getExercisesForMuscleGroup(muscleGroup)) } } } } private fun updateSuggestionScore(db: android.database.sqlite.SQLiteDatabase , sessionId: String) { // If workouts are not yet suggested, nothing to update if (!::workoutAdapter.isInitialized) { return } // profile the user metrics and rate the user val selectedExercises = workoutAdapter.workouts .filter { it.isSelected } .map { it.id } // Iterate through selected exercises and update the score in the original list for (suggestionId in selectedExercises) { val selectedWorkout = workoutAdapter.workouts.find { it.id == suggestionId } selectedWorkout?.let { println("Score cxheck ${selectedWorkout.score}") // val updateScoreQuery = """ // UPDATE ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} SET // ${MyDatabaseHelper.COLUMN_NAME_SCORE} = ${selectedWorkout.score} // WHERE ${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID} = ${selectedWorkout.suggestionId} // """ // println(updateScoreQuery) val dbHelper = MyDatabaseHelper(this) val db = dbHelper.writableDatabase var values = ContentValues() values.put("score", selectedWorkout.score) db.update( MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS, values, "${MyDatabaseHelper.COLUMN_NAME_SUGGESTION_ID}=?", arrayOf(selectedWorkout.suggestionId.toString()) ) //val cursor = db.rawQuery(updateScoreQuery, null) //cursor.close() } } val dailyScoreCalculatedForUser = ScoringEngine.calculateScore(db , sessionId) Toast.makeText(baseContext, "Today's workout score : $dailyScoreCalculatedForUser", Toast.LENGTH_SHORT).show() val uniqueDate = generateUniqueDate(); val cursor = db.rawQuery("SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(uniqueDate)) var values = ContentValues() values.put("score", dailyScoreCalculatedForUser) if (cursor.count > 0) { // Entry with the vitals_id already exists, update it db.update( MyDatabaseHelper.TABLE_NAME_USER_METRICS, values, "${MyDatabaseHelper.COLUMN_NAME_DATE}=?", arrayOf(uniqueDate) ) } else { values.put("date", uniqueDate) // Entry with the vitals_id doesn't exist, insert a new record db.insert(MyDatabaseHelper.TABLE_NAME_USER_METRICS, null, values) } } fun generateUniqueDate(): String { val currentDate = LocalDate.now(ZoneId.systemDefault()) val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") var formattedDate = currentDate.format(formatter) formattedDate = formattedDate.toString() return formattedDate } // private fun setupSpinner() { // ArrayAdapter.createFromResource( // this, // R.array.muscle_groups, // Make sure this array is defined in your resources // android.R.layout.simple_spinner_item // ).also { adapter -> // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // muscleGroupSpinner.adapter = adapter // } // // muscleGroupSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { // override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { // val muscleGroup = parent.getItemAtPosition(position).toString() // updateExercisesList(muscleGroup) // } // // override fun onNothingSelected(parent: AdapterView<*>) {} // } // } private fun updateExercisesList() { val exercises = mutableListOf<Exercise>() muscleGroups.forEachIndexed { index, muscleGroup -> selectedMuscleGroups?.let { if (it[index]) { exercises.addAll(getExercisesForMuscleGroup(muscleGroup)) } } } // exercisesAdapter.exercises = exercises // exercisesAdapter.notifyDataSetChanged() // private fun updateExercisesList(muscleGroup: String) { // val exercises = getExercisesForMuscleGroup(muscleGroup) // exercisesAdapter = ExercisesAdapter(exercises) // exercisesList.adapter = exercisesAdapter // exercisesList.layoutManager = LinearLayoutManager(this) // } } } fun getExercisesForMuscleGroup(muscleGroup: String): List<Exercise> { return when (muscleGroup) { "Abdominals" -> listOf(Exercise("Bicep Curls"), Exercise("Tricep Dips"), Exercise("Hammer Curls")) "Adductors" -> listOf(Exercise("Bench Press"), Exercise("Push Ups"), Exercise("Chest Fly")) "Abductors" -> listOf(Exercise("Pull Ups"), Exercise("Deadlifts"), Exercise("Lat Pulldowns")) "Biceps" -> listOf(Exercise("Squats"), Exercise("Leg Press"), Exercise("Lunges")) "Calves" -> listOf(Exercise("Shoulder Press"), Exercise("Lateral Raises"), Exercise("Front Raises")) "Chest" -> listOf(Exercise("Shoulder Press"), Exercise("Lateral Raises"), Exercise("Front Raises")) // Add more muscle groups and exercises as needed else -> emptyList() } } data class Exercise(val name: String, var isSelected: Boolean = false) class WorkoutCheckboxAdapter(val workouts: List<Workout>) : RecyclerView.Adapter<WorkoutCheckboxAdapter.WorkoutViewHolder>() { class WorkoutViewHolder(view: View) : RecyclerView.ViewHolder(view) { val workoutCheckBox: CheckBox = view.findViewById(R.id.workoutCheckBox) val workoutTitleTextView: TextView = view.findViewById(R.id.workoutTitleTextView) val percentageEditText: EditText = view.findViewById(R.id.percentageEditText) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkoutViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.workout_item_checkbox, parent, false) return WorkoutViewHolder(itemView) } override fun onBindViewHolder(holder: WorkoutViewHolder, position: Int) { val workout = workouts[position] holder.workoutTitleTextView.text = workout.title holder.workoutCheckBox.isChecked = false // or any logic you want to determine checked state // Add any click listener if required holder.workoutCheckBox.setOnCheckedChangeListener { _, isChecked -> // Handle checkbox check changes if needed workout.isSelected = isChecked } holder.percentageEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { // This method is called to notify you that characters within `charSequence` are about to be replaced. } override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { // This method is called to notify you that somewhere within `charSequence` has been changed. } override fun afterTextChanged(editable: Editable?) { // This method is called to notify you that somewhere within `editable` has been changed. // This is the ideal place to perform your actions after the text has been changed. val enteredText = editable.toString() var convertedScore = enteredText.toDoubleOrNull() ?: 0.0 workout.score = convertedScore // Do something with the entered text, e.g., update a variable, trigger some logic, etc. } }) } override fun getItemCount() = workouts.size } class ExercisesAdapter(var exercises: List<Exercise>) : RecyclerView.Adapter<ExercisesAdapter.ExerciseViewHolder>() { class ExerciseViewHolder(view: View) : RecyclerView.ViewHolder(view) { val checkBox: CheckBox = view.findViewById(R.id.exerciseCheckBox) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.exercise_item, parent, false) return ExerciseViewHolder(view) } override fun onBindViewHolder(holder: ExerciseViewHolder, position: Int) { val exercise = exercises[position] holder.checkBox.text = exercise.name holder.checkBox.isChecked = exercise.isSelected holder.checkBox.setOnCheckedChangeListener { _, isChecked -> exercise.isSelected = isChecked } } override fun getItemCount() = exercises.size }
FitLife/app/src/main/java/com/application/fitlife/ScoringEngine.kt
1014515485
package com.application.fitlife import kotlin.math.abs import com.application.fitlife.data.MyDatabaseHelper import com.application.fitlife.data.WorkoutSuggestion import android.database.sqlite.SQLiteDatabase import android.util.Log import com.application.fitlife.data.UserMetrics import java.time.LocalDate import java.time.format.DateTimeFormatter import kotlin.math.min class ScoringEngine { companion object{ const val USER_HEIGHT = "height" const val USER_WEIGHT = "weight" const val USER_HEART_RATE = "heartRate" const val USER_RESPIRATORY_RATE = "respiratoryRate" fun calculateScore(db: SQLiteDatabase , sessionId: String): Double{ var userBMI = 23.5 var userMetrics = MyDatabaseHelper.getUserMetrics(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd"))) userBMI = ScoringEngine.calculateBMI( userMetrics.height, userMetrics.weight ) val bmiRating = ScoringEngine.calculateBMIRating(userBMI, 18.5, 29.9) val heartRateRating = ScoringEngine.calculateHeartRateRating( userMetrics.heartRate, 60.0, 100.0 ) val respiratoryRateRating = ScoringEngine.calculateRespiratoryRateRating( userMetrics.respiratoryRate, 12.0, 20.0 ) val bmiWeight = 0.2 val heartRateWeight = 0.4 val respiratoryRateWeight = 0.4 val overallRating = (bmiRating * bmiWeight + heartRateRating * heartRateWeight + respiratoryRateRating * respiratoryRateWeight) val workoutSuggestions = getPerformedExercisesByDate(db, LocalDate.now().format( DateTimeFormatter.ofPattern("yyyy-MM-dd")) , sessionId) Log.d("workoutSuggestions" , workoutSuggestions.toString()); println("checking where it crashes - step 1 - ${workoutSuggestions.size}") val top10Exercise = workoutSuggestions.slice(0 until min(10, workoutSuggestions.size)) println("checking where it crashes - step 2") val averageScoreTop10 = top10Exercise .map { it.score.toInt() } .toList() .average() println("checking where it crashes - step 3") val totalAvg = workoutSuggestions .map { it.score.toInt() } .toList() .average() println("checking where it crashes - step 4") val restAvg = (totalAvg * workoutSuggestions.size - averageScoreTop10 * top10Exercise.size) / ((workoutSuggestions.size - top10Exercise.size)+1) println("checking where it crashes - step 5 - restAvg = ${restAvg}") val newMin = 70 val newMax = 100 val overallScoring = (newMin + (averageScoreTop10 - 0) * (newMax - newMin) / (100 - 0)) + (overallRating * restAvg / 100) println("checking where it crashes - step 6") println("overallScoring: ${overallScoring} overallRating: ${overallRating} averageScoreTop10: ${averageScoreTop10}") return overallScoring.coerceIn(1.0, 100.0) } private fun getPerformedExercisesByDate(db: SQLiteDatabase, targetDate: String , sessionId: String): List<WorkoutSuggestion> { val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_WORKOUT_SUGGESTIONS} WHERE ${MyDatabaseHelper.COLUMN_NAME_SESSION_ID} = '$sessionId' ORDER BY ${MyDatabaseHelper.COLUMN_NAME_SCORE} DESC """.trimIndent() val cursor = db.rawQuery(query, null) val workoutSuggestions = mutableListOf<WorkoutSuggestion>() while (cursor.moveToNext()) { val suggestion = WorkoutSuggestion( id = cursor.getLong(0), sessionId = cursor.getString(1), date = cursor.getString(2), exerciseId = cursor.getString(3), score = cursor.getString(4), isPerformed = cursor.getString(5) ) workoutSuggestions.add(suggestion) } cursor.close() return workoutSuggestions } private fun calculateBMI(height: Double, weight: Double): Double { if (height == 0.0 || weight == 0.0) return 23.5 return (weight * 100 * 100) / (height * height) } private fun calculateBMIRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 23.0 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateHeartRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 72 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } private fun calculateRespiratoryRateRating(value: Double, lowerBound: Double, upperBound: Double): Double { val peakValue = 15 val rating = 10.0 - 9.0 * (abs(value - peakValue) * 1.5 / (upperBound - lowerBound)) return rating.coerceIn(1.0, 10.0) } } }
FitLife/app/src/main/java/com/application/fitlife/data/AppPreferences.kt
3113041641
import android.content.Context class AppPreferences(context: Context) { private val sharedPreferences = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE) fun isDataLoaded(): Boolean { return sharedPreferences.getBoolean("data_loaded", false) } fun setDataLoaded(isLoaded: Boolean) { sharedPreferences.edit().putBoolean("data_loaded", isLoaded).apply() } }
FitLife/app/src/main/java/com/application/fitlife/data/WorkoutSuggestion.kt
761908354
package com.application.fitlife.data data class WorkoutSuggestion( val id: Long, val sessionId: String, val date: String, val exerciseId: String, val score: String, val isPerformed: String, )
FitLife/app/src/main/java/com/application/fitlife/data/MyDatabaseHelper.kt
2492098470
package com.application.fitlife.data import AppPreferences import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.provider.BaseColumns import com.opencsv.CSVReaderBuilder import java.io.InputStreamReader class MyDatabaseHelper(private val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { // Table contents are grouped together in an anonymous object. companion object FitLife : BaseColumns { const val DATABASE_NAME = "fit_life_db" const val DATABASE_VERSION = 1 const val TABLE_NAME_WORKOUT_SUGGESTIONS = "workout_suggestions" const val WORKOUTS_INFORMATION_FILENAME = "WorkoutsInformation.csv" const val TABLE_NAME_WORKOUTS_INFORMATION = "workouts_information" const val TABLE_NAME_USER_METRICS = "userMetrics" const val COLUMN_NAME_TITLE = "title" const val COLUMN_NAME_DESCRIPTION = "description" const val COLUMN_NAME_HEART_RATE = "heart_rate" const val COLUMN_NAME_WORKOUT_ID = "workout_id" const val COLUMN_NAME_DATE = "date" const val COLUMN_NAME_TYPE = "type" const val COLUMN_NAME_BODYPART = "bodyPart" const val COLUMN_NAME_EQUIPMENT = "equipment" const val COLUMN_NAME_LEVEL = "level" const val COLUMN_NAME_RATING = "rating" const val COLUMN_NAME_RATING_DESC = "ratingDesc" const val USER_TABLE_NAME = "userDetails" const val COLUMN_NAME_IS_PERFORMED = "is_performed" const val COLUMN_NAME_SUGGESTION_ID = "suggestion_id" const val COLUMN_NAME_SESSION_ID = "session_id" const val COLUMN_NAME_RESPIRATORY_RATE = "respiratory_rate" const val COLUMN_NAME_SCORE = "score" const val COLUMN_NAME_WEIGHT = "weight" const val COLUMN_NAME_HEIGHT = "height" const val COLUMN_NAME_EXERCISE_ID = "workout_id" const val COLUMN_NAME_USER_ID = "user_id" const val COLUMN_NAME_AGE = "age" const val COLUMN_NAME_USERNAME = "user_name" fun getUserMetrics(db: SQLiteDatabase, targetDate: String): UserMetrics { val query = """ SELECT * FROM ${MyDatabaseHelper.TABLE_NAME_USER_METRICS} WHERE ${MyDatabaseHelper.COLUMN_NAME_DATE} = '$targetDate' """.trimIndent() val cursor = db.rawQuery(query, null) val userMetrics = UserMetrics( id = 0, height = 0.0, weight = 0.0, score = 0.0, heartRate = 0.0, respiratoryRate = 0.0 ) while (cursor.moveToNext()) { val userMetrics = UserMetrics( id = cursor.getLong(0), height = cursor.getDouble(1), weight = cursor.getDouble(2), score = cursor.getDouble(3), heartRate = cursor.getDouble(4), respiratoryRate = cursor.getDouble(5) ) } cursor.close() return userMetrics } } override fun onCreate(db: SQLiteDatabase?) { println("Creating database and tables required") val createUserMetricsTableQuery = "CREATE TABLE $TABLE_NAME_USER_METRICS (" + "$COLUMN_NAME_DATE TEXT PRIMARY KEY, " + "$COLUMN_NAME_HEIGHT REAL," + "$COLUMN_NAME_WEIGHT REAL," + "$COLUMN_NAME_SCORE REAL," + "$COLUMN_NAME_HEART_RATE REAL," + "$COLUMN_NAME_RESPIRATORY_RATE REAL)" db?.execSQL(createUserMetricsTableQuery) val createUserDetailsTableQuery = "CREATE TABLE $USER_TABLE_NAME (" + "$COLUMN_NAME_USER_ID TEXT PRIMARY KEY, " + "$COLUMN_NAME_AGE REAL," + "$COLUMN_NAME_USERNAME TEXT)" db?.execSQL(createUserDetailsTableQuery) val workoutsInformationTableQuery = "CREATE TABLE $TABLE_NAME_WORKOUTS_INFORMATION (" + "$COLUMN_NAME_WORKOUT_ID INTEGER PRIMARY KEY, " + "$COLUMN_NAME_TITLE TEXT," + "$COLUMN_NAME_DESCRIPTION TEXT," + "$COLUMN_NAME_TYPE TEXT," + "$COLUMN_NAME_BODYPART TEXT," + "$COLUMN_NAME_EQUIPMENT TEXT," + "$COLUMN_NAME_LEVEL TEXT," + "$COLUMN_NAME_RATING REAL," + "$COLUMN_NAME_RATING_DESC TEXT)" val workoutSuggestionsTableQuery = "CREATE TABLE $TABLE_NAME_WORKOUT_SUGGESTIONS (" + "$COLUMN_NAME_SUGGESTION_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "$COLUMN_NAME_SESSION_ID TEXT," + "$COLUMN_NAME_DATE TEXT," + "$COLUMN_NAME_EXERCISE_ID INTEGER," + "$COLUMN_NAME_SCORE REAL," + "$COLUMN_NAME_IS_PERFORMED INTEGER," + "FOREIGN KEY($COLUMN_NAME_EXERCISE_ID) REFERENCES $TABLE_NAME_WORKOUTS_INFORMATION($COLUMN_NAME_WORKOUT_ID))" db?.execSQL(workoutsInformationTableQuery) insertDataFromCsvIfNotLoaded(db, WORKOUTS_INFORMATION_FILENAME) db?.execSQL(workoutSuggestionsTableQuery) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_USER_METRICS") db?.execSQL("DROP TABLE IF EXISTS $USER_TABLE_NAME") db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_WORKOUTS_INFORMATION") db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME_WORKOUT_SUGGESTIONS") onCreate(db) } fun readCsvFile(fileName: String): List<Array<String>> { context.assets.open(fileName).use { inputStream -> InputStreamReader(inputStream).use { inputStreamReader -> return CSVReaderBuilder(inputStreamReader) .withSkipLines(1) .build() .readAll() } } } fun insertDataFromCsvIfNotLoaded(db: SQLiteDatabase?, fileName: String) { val preferences = AppPreferences(context) println("Loading workout data to app") if (!preferences.isDataLoaded()) { val csvData = readCsvFile(fileName) for (row in csvData) { val values = ContentValues().apply { put(COLUMN_NAME_WORKOUT_ID, row[0]) put(COLUMN_NAME_TITLE, row[1]) put(COLUMN_NAME_DESCRIPTION, row[2]) put(COLUMN_NAME_TYPE, row[3]) put(COLUMN_NAME_BODYPART, row[4]) put(COLUMN_NAME_EQUIPMENT, row[5]) put(COLUMN_NAME_LEVEL, row[6]) put(COLUMN_NAME_RATING, row[7]) put(COLUMN_NAME_RATING_DESC, row[8]) } db?.insert(TABLE_NAME_WORKOUTS_INFORMATION, null, values) } // Mark data as loaded preferences.setDataLoaded(true) } } }
FitLife/app/src/main/java/com/application/fitlife/data/UserMetrics.kt
2641299083
package com.application.fitlife.data data class UserMetrics ( val id: Long, val height: Double, val weight: Double, val score: Double, val heartRate: Double, val respiratoryRate: Double, )
FitLife/app/src/main/java/com/application/fitlife/data/Workout.kt
425237246
package com.application.fitlife.data data class Workout( val id: Long, val title: String, val description: String, val type: String, val bodyPart: String, val equipment: String, val level: String, val rating: String, val ratingDesc: String, var isSelected: Boolean = false, var suggestionId: Long = 0, var score: Double = 0.0 )
KotlinDelivery_Frontend/app/src/androidTest/java/com/andy/kotlindelivery/ExampleInstrumentedTest.kt
1000394233
package com.andy.kotlindelivery 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.andy.kotlindelivery", appContext.packageName) } }
KotlinDelivery_Frontend/app/src/test/java/com/andy/kotlindelivery/ExampleUnitTest.kt
3235825342
package com.andy.kotlindelivery 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) } }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/UsuariosRoutes.kt
2682221528
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Part interface UsuariosRoutes { @POST("usuarios/create") fun register (@Body usuario: Usuario) : Call<ResponseHttp> @FormUrlEncoded @POST("usuarios/login") fun login(@Field("email") email:String, @Field("contrasena") contrasena: String) : Call<ResponseHttp> @Multipart @PUT("usuarios/update") fun update( @Part image: MultipartBody.Part, @Part("user") user: RequestBody, @Header("Authorization") token: String ): Call<ResponseHttp> @PUT("usuarios/updateWithoutImage") fun updateWithoutImage( @Body usuario: Usuario, @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/ProductosRoutes.kt
1760282437
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.ResponseHttp import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path interface ProductosRoutes { @GET("productos/findByCategoria/{id_categoria}") fun findByCategoria( @Path("id_categoria") idCategoria: String, @Header("Authorization") token: String ): Call<ArrayList<Producto>> @Multipart //Es multipart porque se enviara una imagen @POST("productos/create") fun create( @Part images: Array<MultipartBody.Part?>, @Part("producto") producto: RequestBody, //el nombre debe ser igual al del archivo controller del backend @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/routers/CategoriasRoutes.kt
2785279235
package com.andy.kotlindelivery.routers import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Part interface CategoriasRoutes { @GET("categorias/getAll") fun getAll( @Header("Authorization") token: String ): Call<ArrayList<Categoria>> @Multipart //Es multipart porque se enviara una imagen @POST("categorias/create") fun create( @Part image: MultipartBody.Part, @Part("categoria") categoria: RequestBody, //el nombre debe ser igual al del archivo controller del backend @Header("Authorization") token: String ): Call<ResponseHttp> }
KotlinDelivery_Frontend/app/src/main/java/com/andy/kotlindelivery/fragments/restaurant/RestaurantProductFragment.kt
406402727
package com.andy.kotlindelivery.fragments.restaurant import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Spinner import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import com.andy.kotlindelivery.R import com.andy.kotlindelivery.adapters.CategoriasAdapters import com.andy.kotlindelivery.models.Categoria import com.andy.kotlindelivery.models.Producto import com.andy.kotlindelivery.models.ResponseHttp import com.andy.kotlindelivery.models.Usuario import com.andy.kotlindelivery.providers.CategoriasProviders import com.andy.kotlindelivery.providers.ProductosProviders import com.andy.kotlindelivery.utils.SharedPref import com.github.dhaval2404.imagepicker.ImagePicker import com.google.gson.Gson import com.tommasoberlose.progressdialog.ProgressDialogFragment import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File class RestaurantProductFragment : Fragment() { var TAG = "RestaurantProductFragment" var gson = Gson() var myView: View? = null var editTextNombre: EditText? = null var editTextDescription: EditText? = null var editTextPreeio: EditText? = null var imageViewProduct1: ImageView? = null var imageViewProduct2: ImageView? = null var imageViewProduct3: ImageView? = null var spinnerCategoria: Spinner? = null var btnCreateProduct : Button? = null var imageFile1: File? = null var imageFile2: File? = null var imageFile3: File? = null var categoriasProvider: CategoriasProviders? = null var productosProviders: ProductosProviders? = null var usuario: Usuario? = null var sharedPref: SharedPref? = null var categorias = ArrayList<Categoria>() var idCategoria = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment myView = inflater.inflate(R.layout.fragment_restaurant_product, container, false) editTextNombre= myView?.findViewById(R.id.edittxt_nombre) editTextDescription= myView?.findViewById(R.id.edittxt_description) editTextPreeio = myView?.findViewById(R.id.edittxt_precio) imageViewProduct1= myView?.findViewById(R.id.imageview_prodcut1) imageViewProduct2 = myView?.findViewById(R.id.imageview_prodcut2) imageViewProduct3 =myView?.findViewById(R.id.imageview_prodcut3) spinnerCategoria = myView?.findViewById(R.id.spinner_categoria) btnCreateProduct = myView?.findViewById(R.id.btn_create_product) btnCreateProduct?.setOnClickListener { createProduct() } imageViewProduct1?.setOnClickListener { selectImage(101) } imageViewProduct2?.setOnClickListener { selectImage(102) } imageViewProduct3?.setOnClickListener { selectImage(103) } sharedPref = SharedPref(requireActivity()) getUserFromSession() categoriasProvider = CategoriasProviders(usuario?.sessionToken!!) productosProviders = ProductosProviders(usuario?.sessionToken!!) getCategorias() return myView } ///////////////////////////////////////////////////////////////////////// private fun createProduct() { val nombreProducto = editTextNombre?.text.toString() val descriptionProducto = editTextDescription?.text.toString() val precioText = editTextPreeio?.text.toString() val files = ArrayList<File>() if ( isValidForm(nombreProducto, descriptionProducto,precioText) ){ val producto = Producto( nombre = nombreProducto, descripcion = descriptionProducto, precio = precioText.toDouble(), idCategoria = idCategoria ) Log.d(TAG, "Producto $producto") files.add(imageFile1!!) files.add(imageFile2!!) files.add(imageFile3!!) Log.d(TAG, "Imagenes $files") ProgressDialogFragment.showProgressBar(requireActivity()) productosProviders?.create(files, producto)?.enqueue(object: Callback<ResponseHttp> { override fun onResponse( call: Call<ResponseHttp>, response: Response<ResponseHttp> ) { ProgressDialogFragment.hideProgressBar(requireActivity()) Log.d(TAG, "Response: ${response}") Log.d(TAG, "Body: ${response.body()}") Toast.makeText(requireContext(), response.body()?.message, Toast.LENGTH_LONG).show() if(response.body()?.isSucces == true){ resetForm() } } override fun onFailure(call: Call<ResponseHttp>, t: Throwable) { ProgressDialogFragment.hideProgressBar(requireActivity()) Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////// private fun getCategorias(){ Log.d(TAG, "getCategorias() : ${categoriasProvider}") categoriasProvider?.getAll()?.enqueue(object: Callback<ArrayList<Categoria>> { override fun onResponse( call: Call<ArrayList<Categoria>>, response: Response<ArrayList<Categoria>> ) { if(response.body() != null){ categorias = response.body()!! val arrayAdapter = ArrayAdapter<Categoria>(requireActivity(), android.R.layout.simple_dropdown_item_1line, categorias) spinnerCategoria?.adapter = arrayAdapter spinnerCategoria?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View?, position: Int, l: Long ) { idCategoria = categorias[position].id!! Log.d(TAG, "Id categoria : $idCategoria") } override fun onNothingSelected(parent: AdapterView<*>?) { } } } } override fun onFailure(call: Call<ArrayList<Categoria>>, t: Throwable) { Log.d(TAG, "Error: ${t.message}") Toast.makeText(requireContext(), "Error ${t.message}", Toast.LENGTH_LONG).show() } }) } /////////////////////////////////////////////////////////////////////////////// ////FUNCIONES PARA SELECCIONAR LA IMAGEN DESDE GALERIA override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { val fileUri = data?.data if(requestCode == 101){ imageFile1 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct1?.setImageURI(fileUri) } else if(requestCode == 102){ imageFile2 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct2?.setImageURI(fileUri) } else if(requestCode == 103){ imageFile3 = File(fileUri?.path) //el archivo que se guarda como imagen en el servidor imageViewProduct3?.setImageURI(fileUri) } } else if (resultCode == ImagePicker.RESULT_ERROR) { Toast.makeText(requireContext(), ImagePicker.getError(data), Toast.LENGTH_SHORT).show() } else { Toast.makeText(requireContext(), "Task Cancelled", Toast.LENGTH_SHORT).show() } } private fun selectImage(requestCode: Int) { ImagePicker.with(this) .crop() .compress(1024) .maxResultSize(1080,1080) .start(requestCode) } ///////////////////////////////////////////////////////////////// //////////////funcion de validacion private fun isValidForm(nombre: String, descripcion: String, precio: String): Boolean{ if(nombre.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa el nombre del producto", Toast.LENGTH_LONG).show() return false } if(descripcion.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa la descripcion del producto", Toast.LENGTH_LONG).show() return false } if(precio.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa el precio del producto", Toast.LENGTH_LONG).show() return false } if(imageFile1 == null){ Toast.makeText(requireContext(), "Ingresa al menos la primer imagen", Toast.LENGTH_LONG).show() return false } if(idCategoria.isNullOrBlank()){ Toast.makeText(requireContext(), "Ingresa la categoria del producto", Toast.LENGTH_LONG).show() return false } return true } ////////////////////////////////// ////Funcion para limpiar formulario private fun resetForm() { editTextNombre?.setText("") editTextDescription?.setText("") editTextPreeio?.setText("") imageFile1 = null imageFile2 = null imageFile3 = null imageViewProduct1?.setImageResource(R.drawable.ic_image) imageViewProduct2?.setImageResource(R.drawable.ic_image) imageViewProduct3?.setImageResource(R.drawable.ic_image) } ////////////////// /////funciones de sesion private fun getUserFromSession() { //val sharedPref = SharedPref(this,) if (!sharedPref?.getData("user").isNullOrBlank()) { //Si el usuario existe en sesion usuario = gson.fromJson(sharedPref?.getData("user"), Usuario::class.java) Log.d(TAG, "Usuario: $usuario") } } /////////////////////////////// }