content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.phonebook_assignment
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.example.phonebook_assignment.databinding.ActivityMainBinding
import com.example.phonebook_assignment.viewmodel.ExitAppViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
private lateinit var exitAppViewModel: ExitAppViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
exitAppViewModel = ViewModelProvider(this).get(ExitAppViewModel::class.java)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
navController = navHostFragment.navController
}
override fun onBackPressed() {
// Check if the current destination is the home fragment
var exit = false
lifecycleScope.launch(Dispatchers.IO) {
exit = exitAppViewModel.getExitValue()
}
if(exit == true){
finish()
}
if (navController.currentDestination?.id == R.id.homeFragment) {
// If on the home fragment, finish the activity to exit the app
AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes") { dialog, which ->
// If the user confirms, finish the activity to exit the app
finish()
}
.setNegativeButton("No", null) // Do nothing if the user cancels
.show()
} else {
// If not on the home fragment, let the system handle back button behavior
super.onBackPressed()
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/MainActivity.kt | 2383322160 |
package com.example.phonebook_assignment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import com.example.phonebook_assignment.databinding.FragmentLoginBinding
import com.example.phonebook_assignment.db.ContactDatabase
import com.example.phonebook_assignment.db.ContactRepository
import com.example.phonebook_assignment.viewmodel.ContactViewModel
import com.example.phonebook_assignment.viewmodel.ExitAppViewModel
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private lateinit var preference:SharedPreferencesManager
private lateinit var exitViewMOdel: ExitAppViewModel
private lateinit var contactViewModel: ContactViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false)
val dao = ContactDatabase.getInstance(requireContext()).contactDAO
val repository = ContactRepository(dao)
val factory = ContactViewModelFactory(repository)
contactViewModel = ViewModelProvider(this, factory)[ContactViewModel::class.java]
binding.myViewModel = contactViewModel
binding.lifecycleOwner = this
preference = SharedPreferencesManager.getInstance([email protected](),"123")
exitViewMOdel = ViewModelProvider(this).get(ExitAppViewModel::class.java)
binding.loginButton.setOnClickListener {
val name = contactViewModel.loginUsername.value
val pass = contactViewModel.loginPassword.value
var bundle = bundleOf("user_name" to name)
if (name == null || name == ""|| pass == null || pass=="" ){
Toast.makeText([email protected](),
"Please enter values for the fields!",
Toast.LENGTH_SHORT).show()
}
else if(pass.equals(preference.getData(name!!,""))) {
it.findNavController().navigate(R.id.action_loginFragment_to_homeFragment,bundle)
}
else{
// Toast.makeText([email protected](),"User Not Found",Toast.LENGTH_SHORT).show()
AlertDialog.Builder(this.requireContext())
.setMessage("You don't have an account, Create one?")
.setPositiveButton("Yes") { dialog, which ->
// If the user confirms, finish the activity to exit the app
it.findNavController().navigate(R.id.action_loginFragment_to_signUpFragment2)
}
.setNegativeButton("No") { dialog, which ->
activity?.finish()
}
.show()
//it.findNavController().navigate(R.id.action_loginFragment_to_newUserFragment)
}
}
return binding.root
}
private fun isValidCredentials(username: String, password: String): Boolean {
// val savedUsername = preferenceManager.getSavedUsername()
// val savedPassword = preferenceManager.getSavedPassword()
val savedUsername = "sourav"
val savedPassword = "1234"
return username.equals(savedUsername) && password.equals(savedPassword)
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/LoginFragment.kt | 2416912013 |
package com.example.phonebook_assignment
import android.view.LayoutInflater
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.phonebook_assignment.databinding.ListItemBinding
import com.example.phonebook_assignment.db.Contact
class MyRecyclerViewAdapter(private val contactList: List<Contact>,
private val clickListener:(Contact) -> Unit):
RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding: ListItemBinding =
DataBindingUtil.inflate(layoutInflater, R.layout.list_item, parent, false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return contactList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(contactList[position], clickListener)
}
}
class MyViewHolder(val binding: ListItemBinding): RecyclerView.ViewHolder(binding.root){
fun bind(contact: Contact, clickListener:(Contact) -> Unit){
binding.firstNameTextView.text = contact.firstName
binding.lastNameTextView.text = contact.lastName
binding.listItemLayout.setOnClickListener{
clickListener(contact)
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/MyRecyclerViewAdapter.kt | 690059265 |
package com.example.phonebook_assignment
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.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import com.example.phonebook_assignment.viewmodel.ContactViewModel
import com.example.phonebook_assignment.databinding.FragmentAddContactBinding
import com.example.phonebook_assignment.db.ContactDatabase
import com.example.phonebook_assignment.db.ContactRepository
import java.lang.Exception
class AddContactFragment : Fragment() {
private lateinit var binding: FragmentAddContactBinding
private lateinit var contactViewModel: ContactViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_add_contact, container, false)
val dao = ContactDatabase.getInstance(requireContext()).contactDAO
val repository = ContactRepository(dao)
val factory = ContactViewModelFactory(repository)
contactViewModel = ViewModelProvider(this, factory)[ContactViewModel::class.java]
binding.myViewModel = contactViewModel
binding.lifecycleOwner = this
try {
val primaryKey = requireArguments().getInt("contact_key")
val first_name = requireArguments().getString("first_name")
val last_name = requireArguments().getString("last_name")
val mobileno = requireArguments().getString("mobileno")
val email = requireArguments().getString("email")
contactViewModel.firstName.value = first_name
contactViewModel.lastName.value = last_name
contactViewModel.email.value = email
contactViewModel.mobileno.value = mobileno
binding.saveContactButton.setOnClickListener {
contactViewModel.updateContact(primaryKey)
contactViewModel.contacts.observe(viewLifecycleOwner, Observer {
Log.i("MYTAG", it.toString())
})
var flag = ""
contactViewModel.message.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let{
flag = it
}
})
if(flag.equals("success")) {
Toast.makeText([email protected](),
"Contact updated sucessfully!", Toast.LENGTH_SHORT).show()
it.findNavController().navigate(R.id.action_addContactFragment_to_homeFragment)
} else{
Toast.makeText([email protected](),
flag, Toast.LENGTH_SHORT).show()
}
}
} catch (e: Exception) {
binding.saveContactButton.setOnClickListener {
contactViewModel.saveContact()
contactViewModel.contacts.observe(viewLifecycleOwner, Observer {
Log.i("MYTAG", it.toString())
})
var flag = ""
contactViewModel.message.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let{
flag = it
}
})
if(flag.equals("success")) {
Toast.makeText([email protected](),
"Contact added sucessfully!", Toast.LENGTH_SHORT).show()
it.findNavController().navigate(R.id.action_addContactFragment_to_homeFragment)
} else {
Toast.makeText(
[email protected](),
flag, Toast.LENGTH_SHORT
).show()
}
}
}
binding.discardButton.setOnClickListener {
it.findNavController().navigate(R.id.action_addContactFragment_to_homeFragment)
}
return binding.root
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/AddContactFragment.kt | 5863770 |
package com.example.phonebook_assignment
import android.content.Context
import android.content.SharedPreferences
class SharedPreferencesManager private constructor(context: Context, userId: String) {
private val sharedPreferences: SharedPreferences
init {
val sharedPrefFileName = "$userId"
sharedPreferences = context.getSharedPreferences(sharedPrefFileName, Context.MODE_PRIVATE)
}
fun saveData(key: String, value: String) {
val editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun getData(key: String, defaultValue: String): String? {
return sharedPreferences.getString(key, defaultValue)
}
fun clear() {
val editor = sharedPreferences.edit()
editor.clear()
editor.apply()
}
companion object {
private const val SHARED_PREF_NAME = "your_app_shared_pref"
fun getInstance(context: Context, userId: String): SharedPreferencesManager {
synchronized(this){ return SharedPreferencesManager(context, userId) }
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/SharedPreferencesManager.kt | 1338063782 |
package com.example.phonebook_assignment
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/Event.kt | 905616822 |
package com.example.phonebook_assignment.db
class ContactRepository(private val dao: ContactDAO) {
val contacts = dao.getAllContacts()
fun insert(contact: Contact){
return dao.insertContact(contact)
}
fun update(contact: Contact){
return dao.updateContact(contact)
}
fun delete(contact: Contact){
return dao.deleteContact(contact)
}
fun deleteAll(){
return dao.deleteAll()
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/db/ContactRepository.kt | 1925505817 |
package com.example.phonebook_assignment.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "contact_list")
data class Contact (
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "contact_id")
val id : Int,
@ColumnInfo(name = "first_name")
var firstName : String,
@ColumnInfo(name = "last_name")
var lastName : String,
@ColumnInfo(name = "contact_number")
val number : String,
@ColumnInfo(name = "contact_email")
var email : String
) | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/db/Contact.kt | 4078310339 |
package com.example.phonebook_assignment.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Contact::class],version = 1)
abstract class ContactDatabase: RoomDatabase() {
abstract val contactDAO : ContactDAO
companion object{
@Volatile
private var INSTANCE : ContactDatabase? = null
fun getInstance(context: Context):ContactDatabase{
synchronized(this){
var instance = INSTANCE
if(instance==null){
instance = Room.databaseBuilder(
context.applicationContext,
ContactDatabase::class.java,
"contact_db"
).build()
INSTANCE = instance
}
return instance
}
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/db/ContactDatabase.kt | 2911853299 |
package com.example.phonebook_assignment.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface ContactDAO {
@Insert
fun insertContact(contact: Contact)
@Update
fun updateContact(contact: Contact)
@Delete
fun deleteContact(contact: Contact)
@Query("DELETE FROM contact_list")
fun deleteAll()
@Query("SELECT * FROM contact_list")
fun getAllContacts(): LiveData<List<Contact>>
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/db/ContactDAO.kt | 4265688485 |
package com.example.phonebook_assignment
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.Toast
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.phonebook_assignment.databinding.FragmentHomeBinding
import com.example.phonebook_assignment.db.Contact
import com.example.phonebook_assignment.db.ContactDatabase
import com.example.phonebook_assignment.db.ContactRepository
import com.example.phonebook_assignment.viewmodel.ContactViewModel
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var contactViewModel: ContactViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
val dao = ContactDatabase.getInstance(requireContext()).contactDAO
val repository = ContactRepository(dao)
val factory = ContactViewModelFactory(repository)
contactViewModel = ViewModelProvider(this,factory)[ContactViewModel::class.java]
binding.myViewModel = contactViewModel
binding.lifecycleOwner = this
initReyclerView()
binding.addContactFAB.setOnClickListener {
it.findNavController().navigate(R.id.action_homeFragment_to_addContactFragment)
}
return binding.root
}
private fun initReyclerView() {
binding.contactRecyclerView.layoutManager = LinearLayoutManager(requireContext())
displayContactList()
}
private fun displayContactList(){
contactViewModel.contacts.observe(viewLifecycleOwner, Observer {
Log.i("MYTAG",it.toString())
binding.contactRecyclerView.adapter = MyRecyclerViewAdapter(it, {selectedItem:Contact->listItemClicked(selectedItem)})
})
}
private fun listItemClicked(contact: Contact){
try {
val bundle = bundleOf("contact_key" to contact.id,
"first_name" to contact.firstName,
"last_name" to contact.lastName,
"email" to contact.email,
"mobileno" to contact.number)
requireView().findNavController()
.navigate(R.id.action_homeFragment_to_contactDetailsFragment2, bundle)
} catch (e: Exception){
Toast.makeText([email protected](), e.toString(),
Toast.LENGTH_LONG).show()
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/HomeFragment.kt | 2988389950 |
package com.example.phonebook_assignment
import android.app.AlertDialog
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import com.example.phonebook_assignment.databinding.FragmentContactDetailsBinding
import com.example.phonebook_assignment.db.Contact
import com.example.phonebook_assignment.db.ContactDatabase
import com.example.phonebook_assignment.db.ContactRepository
import com.example.phonebook_assignment.viewmodel.ContactViewModel
class ContactDetailsFragment : Fragment() {
private lateinit var binding: FragmentContactDetailsBinding
private lateinit var contactViewModel: ContactViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_contact_details, container, false)
val dao = ContactDatabase.getInstance(requireContext()).contactDAO
val repository = ContactRepository(dao)
val factory = ContactViewModelFactory(repository)
contactViewModel = ViewModelProvider(this, factory)[ContactViewModel::class.java]
binding.myViewModel = contactViewModel
binding.lifecycleOwner = this
val primaryKey = requireArguments().getInt("contact_key")
val first_name = requireArguments().getString("first_name")
val last_name = requireArguments().getString("last_name")
val mobileno = requireArguments().getString("mobileno")
val email = requireArguments().getString("email")
binding.showDetailsNameTextView.text = first_name + " " + last_name
binding.showDetailsNumberTextView.text = mobileno
binding.showDetailsEmailTextView.text = email
binding.editContactFAB.setOnClickListener {
val bundle = bundleOf(
"contact_key" to primaryKey,
"first_name" to first_name,
"last_name" to last_name,
"email" to email,
"mobileno" to mobileno
)
it.findNavController()
.navigate(R.id.action_contactDetailsFragment_to_addContactFragment, bundle)
}
binding.deleteContactFAB.setOnClickListener {
val dialog = AlertDialog.Builder([email protected]())
dialog.setMessage("Are you sure you want to delete?")
dialog.setTitle("Delete Contact")
dialog.setPositiveButton("Yes") { _, _ ->
contactViewModel.delete(Contact(primaryKey, first_name!!, last_name!!, mobileno!!, email!!))
it.findNavController().navigate(R.id.action_contactDetailsFragment_to_homeFragment2)
Toast.makeText([email protected](),
"Contact deleted successfully", Toast.LENGTH_SHORT).show()
}
dialog.setNegativeButton("No"){_,_ ->}
val dialogBox = dialog.create()
dialogBox.show()
}
return binding.root
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/ContactDetailsFragment.kt | 2398756539 |
package com.example.phonebook_assignment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.phonebook_assignment.db.ContactRepository
import com.example.phonebook_assignment.viewmodel.ContactViewModel
class ContactViewModelFactory(private val repository: ContactRepository): ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(ContactViewModel::class.java)) {
return ContactViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel Class")
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/ContactViewModelFactory.kt | 2776209397 |
package com.example.mindy_1
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.mindy_1", appContext.packageName)
}
} | mobileee/app/src/androidTest/java/com/example/mindy_1/ExampleInstrumentedTest.kt | 219484582 |
package com.example.mindy_1
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)
}
} | mobileee/app/src/test/java/com/example/mindy_1/ExampleUnitTest.kt | 2293827207 |
package com.example.mindy_1
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun RegisterEmail(view: View){
val intent = Intent(this, RegisterEmail::class.java)
startActivity(intent)
}
fun Login(view: View){
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
} | mobileee/app/src/main/java/com/example/mindy_1/MainActivity.kt | 3848773594 |
package com.example.mindy_1
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
class Login : AppCompatActivity() {
private var firebaseAuth: FirebaseAuth? = null
private var email: EditText? = null
private var password: EditText? = null
private var konfirmasipw: EditText? = null
private var login: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
firebaseAuth = FirebaseAuth.getInstance()
FirebaseApp.initializeApp(this)
email = findViewById(R.id.email)
password = findViewById(R.id.password)
login = findViewById(R.id.login)
login?.setOnClickListener {
firebaseAuth?.signInWithEmailAndPassword(email?.text.toString(), password?.text.toString())
?.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val intent = Intent(this, Home::class.java)
startActivity(intent)
} else {
Toast.makeText(this, task.exception?.message, Toast.LENGTH_LONG).show()
}
}
}
}
fun RegisterEmail(view: View){
val intent = Intent(this, RegisterEmail::class.java)
startActivity(intent)
}
} | mobileee/app/src/main/java/com/example/mindy_1/Login.kt | 2560203154 |
package com.example.mindy_1
import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
class SplashScreenLogo : AppCompatActivity() {
// Define SPLASH_SCREEN constant with the desired delay
private val SPLASH_SCREEN: Long = 2000 // Adjust the delay as needed
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
setContentView(R.layout.activity_splash_screen_logo)
var logoanimation: Animation
var logo: ImageView
logoanimation = AnimationUtils.loadAnimation(this, R.anim.logoanimation)
logo = findViewById<ImageView>(R.id.logo)
logo.animation = logoanimation
Handler().postDelayed({
val intent = Intent(this@SplashScreenLogo, SplashScreen2::class.java)
val pairs: Array<Pair<View, String>> = arrayOf(Pair(logo, "logo_image"))
val options = ActivityOptions.makeSceneTransitionAnimation(
this@SplashScreenLogo,
)
startActivity(intent, options.toBundle())
}, SPLASH_SCREEN)
}
}
| mobileee/app/src/main/java/com/example/mindy_1/SplashScreenLogo.kt | 2769999276 |
package com.example.mindy_1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Home : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
}
} | mobileee/app/src/main/java/com/example/mindy_1/Home.kt | 4163942914 |
package com.example.mindy_1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Bottom_nav : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bottom_nav)
}
} | mobileee/app/src/main/java/com/example/mindy_1/Bottom_nav.kt | 3341862059 |
package com.example.mindy_1
import androidx.appcompat.app.AppCompatActivity
import android.content.Intent
import android.os.Bundle
class SplashScreen2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen2)
val thread = Thread {
try {
Thread.sleep(3000)
val intent = Intent(this@SplashScreen2, MainActivity::class.java)
startActivity(intent)
finish()
} catch (e: Exception) {
// Handle exceptions here if necessary
}
}
thread.start()
}
}
| mobileee/app/src/main/java/com/example/mindy_1/SplashScreen2.kt | 260057915 |
package com.example.mindy_1
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.AuthResult
import com.google.firebase.FirebaseApp
import android.widget.Toast
class RegisterEmail : AppCompatActivity() {
private var firebaseAuth: FirebaseAuth? = null
private var email: EditText? = null
private var password: EditText? = null
private var konfirmasipw: EditText? = null
private var daftar: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_email)
firebaseAuth = FirebaseAuth.getInstance()
FirebaseApp.initializeApp(this)
email = findViewById(R.id.email) // Replace 'R.id.email' with the actual ID of your EditText in the layout.
password = findViewById(R.id.password) // Replace 'R.id.password' with the actual ID of your EditText in the layout.
konfirmasipw = findViewById(R.id.konfirmasipw) // Replace 'R.id.konfirmasipw' with the actual ID of your EditText in the layout.
daftar = findViewById(R.id.daftar) // Replace 'R.id.daftar' with the actual ID of your Button in the layout.
daftar?.setOnClickListener {
firebaseAuth?.createUserWithEmailAndPassword(email?.text.toString(), password?.text.toString())
?.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Registered successfully", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, task.exception?.message, Toast.LENGTH_LONG).show()
}
}
}
}
fun Login(view: View) {
val intent = Intent(this, Login::class.java) // Change 'Login::class.java' to the actual LoginActivity class name.
startActivity(intent)
}
}
| mobileee/app/src/main/java/com/example/mindy_1/RegisterEmail.kt | 2912700825 |
package com.xenia.testvk
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.xenia.testvk", appContext.packageName)
}
} | TestVKPasswordManager/app/src/androidTest/java/com/xenia/testvk/ExampleInstrumentedTest.kt | 120434361 |
package com.xenia.testvk
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)
}
} | TestVKPasswordManager/app/src/test/java/com/xenia/testvk/ExampleUnitTest.kt | 4204237049 |
package com.xenia.testvk.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)
val Error200 = Color(0xFFEBADB5)
val GreyLight = Color(0xFFB5B6BA)
val GreyDark = Color(0xFF60626C)
val ButtonColor = Color(0xFF039BE5) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/ui/theme/Color.kt | 4206574935 |
package com.xenia.testvk.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.Color
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 TestVKTheme(
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 = Color.Black.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/ui/theme/Theme.kt | 2072483193 |
package com.xenia.testvk.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
)
*/
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/ui/theme/Type.kt | 3677072200 |
package com.xenia.testvk
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.ui.Modifier
import androidx.navigation.compose.rememberNavController
import com.xenia.testvk.navigation.NavGraph
import com.xenia.testvk.ui.theme.TestVKTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TestVKTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavGraph(navController = navController, filesDir)
}
}
}
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/MainActivity.kt | 921943195 |
package com.xenia.testvk.di
import android.content.Context
import androidx.room.Room
import com.xenia.testvk.data.data_source.CryptoClass
import com.xenia.testvk.data.data_source.Database
import com.xenia.testvk.data.data_source.PasswordDao
import com.xenia.testvk.data.mapper.PasswordMapper
import com.xenia.testvk.data.repository.PassphraseRepository
import com.xenia.testvk.data.repository.PasswordRepositoryImpl
import com.xenia.testvk.domain.repository.PasswordRepository
import com.xenia.testvk.domain.usecases.passwords_usecases.AddNewPasswordUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.DeletePasswordUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.GetPasswordByIdUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.GetPasswordsUseCase
import com.xenia.testvk.domain.usecases.UseCases
import com.xenia.testvk.domain.usecases.enter_usecases.CheckFileMasterPasswordUseCase
import com.xenia.testvk.domain.usecases.enter_usecases.SetMasterPasswordUseCase
import com.xenia.testvk.domain.usecases.enter_usecases.ValidateMasterPasswordUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import net.sqlcipher.database.SupportFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideAppDatabase(
@ApplicationContext context: Context,
passphraseRepository: PassphraseRepository
): Database =
Room.databaseBuilder(context, Database::class.java, "PasswordDB")
.openHelperFactory(SupportFactory(passphraseRepository.getPassphrase()))
.fallbackToDestructiveMigration()
.build()
@Provides
fun providesPasswordRepo(
passwordDao: PasswordDao,
mapper: PasswordMapper,
cryptoClass: CryptoClass
): PasswordRepository {
return PasswordRepositoryImpl(
passwordDao,
mapper,
cryptoClass
)
}
@Provides
fun providesPassphraseRepo(@ApplicationContext context: Context): PassphraseRepository {
return PassphraseRepository(context)
}
@Provides
fun providesDataMapper(): PasswordMapper {
return PasswordMapper()
}
@Provides
fun providesCryptoClass(): CryptoClass {
return CryptoClass()
}
@Provides
@Singleton
fun providesUseCases(passwordRepository: PasswordRepository): UseCases {
return UseCases(
allPasswords = GetPasswordsUseCase(passwordRepository),
getPasswordById = GetPasswordByIdUseCase(passwordRepository),
addPassword = AddNewPasswordUseCase(passwordRepository),
deletePassword = DeletePasswordUseCase(passwordRepository),
checkFileMasterPassword = CheckFileMasterPasswordUseCase(passwordRepository),
setMasterPassword = SetMasterPasswordUseCase(passwordRepository),
validateMasterPassword = ValidateMasterPasswordUseCase(passwordRepository)
)
}
@Provides
fun provideItemDao(appDatabase: Database): PasswordDao = appDatabase.passwordDao
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/di/AppModule.kt | 1977392137 |
package com.xenia.testvk.di
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class PasswordManagerApp: Application() | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/di/PasswordManagerApp.kt | 2763935003 |
package com.xenia.testvk.navigation
sealed class Screens(val route: String) {
data object EnterScreen: Screens("enter_screen")
data object MainScreen: Screens("main_screen")
data object AddEditPasswordScreen: Screens("add_edit_password")
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/navigation/Screens.kt | 1444639864 |
package com.xenia.testvk.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.xenia.testvk.presentation.add_edit_password_screen.AddEditPasswordScreen
import com.xenia.testvk.presentation.enter_screen.EnterScreen
import com.xenia.testvk.presentation.main_screen.MainScreen
import java.io.File
@Composable
fun NavGraph(
navController: NavHostController,
filesDir: File
) {
NavHost(
navController = navController,
startDestination = Screens.EnterScreen.route
)
{
composable(route = Screens.EnterScreen.route) {
EnterScreen(navController, filesDir)
}
composable(route = Screens.MainScreen.route) {
MainScreen(navController)
}
composable(Screens.AddEditPasswordScreen.route + "?passwordId={passwordId}",
arguments = listOf(
navArgument(
name = "passwordId",
) {
type = NavType.IntType
defaultValue = -1
}
)
) {
AddEditPasswordScreen(navController = navController)
}
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/navigation/NavGraph.kt | 1320632945 |
package com.xenia.testvk.data.repository
import android.content.Context
import androidx.security.crypto.EncryptedFile
import androidx.security.crypto.MasterKeys
import java.io.File
import java.security.SecureRandom
private const val PASSPHRASE_LENGTH = 32
class PassphraseRepository(
private val context: Context
) {
fun getPassphrase(): ByteArray {
val file = File(context.filesDir, "passphrase.bin")
val encryptedFile = EncryptedFile.Builder(
file,
context,
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build()
return if (file.exists()) {
encryptedFile.openFileInput().use { it.readBytes() }
} else {
generatePassphrase().also { passphrase ->
encryptedFile.openFileOutput().use { it.write(passphrase) }
}
}
}
private fun generatePassphrase(): ByteArray {
val random = SecureRandom.getInstanceStrong()
val result = ByteArray(PASSPHRASE_LENGTH)
random.nextBytes(result)
// filter out zero byte values, as SQLCipher does not like them
while (result.contains(0)) {
random.nextBytes(result)
}
return result
}
}
| TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/repository/PassphraseRepository.kt | 1832327547 |
package com.xenia.testvk.data.repository
import com.xenia.testvk.data.data_source.CryptoClass
import com.xenia.testvk.data.data_source.PasswordDao
import com.xenia.testvk.data.mapper.PasswordMapper
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.repository.PasswordRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.io.File
class PasswordRepositoryImpl(
private val passwordDao: PasswordDao,
private val mapper: PasswordMapper,
private val cryptoClass: CryptoClass
): PasswordRepository {
override fun allPasswords(): Flow<List<ItemModel>> =
passwordDao.allPasswords().map { item ->
mapper.mapListEntityToListModel(item)
}
override fun getPasswordById(id: Int): ItemModel {
return mapper.mapEntityToModel(passwordDao.getPasswordById(id))
}
override suspend fun addPassword(password: ItemModel) {
passwordDao.addPassword(mapper.mapModelToEntity(password))
}
override suspend fun deletePassword(password: ItemModel) {
passwordDao.deletePassword(mapper.mapModelToEntity(password))
}
override suspend fun setMasterPassword(filesDir: File, otpValue: String) {
cryptoClass.setMasterPassword(filesDir, otpValue)
}
override fun checkFileIsExist(filesDir: File): Boolean? {
return cryptoClass.checkFileIsExist(filesDir)
}
override fun validateMasterPassword(filesDir: File, originalPassword: String): Boolean {
return cryptoClass.validateMasterPassword(filesDir, originalPassword)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/repository/PasswordRepositoryImpl.kt | 3586978201 |
package com.xenia.testvk.data.data_source
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.math.BigInteger
import java.security.SecureRandom
import java.security.spec.KeySpec
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.xor
private const val ALGORITHM = "PBKDF2WithHmacSHA512"
private const val ITERATIONS = 1000
private const val KEY_LENGTH = 64 * 8
class CryptoClass {
fun generateHash(password: String, salt: ByteArray): String {
val factory: SecretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM)
val spec: KeySpec = PBEKeySpec(password.toCharArray(), salt, ITERATIONS, KEY_LENGTH)
val key: SecretKey = factory.generateSecret(spec)
val hash: ByteArray = key.encoded
return "$ITERATIONS:${toHex(salt)}:${toHex(hash)}"
}
fun generateRandomSalt(): ByteArray {
val random = SecureRandom.getInstance("SHA1PRNG")
val salt = ByteArray(16)
random.nextBytes(salt)
return salt
}
fun getHashFromFile(
filesDir: File
): String {
val file = File(filesDir, "master_password.txt")
val fin = FileInputStream(file)
val bytes = fin.readBytes()
return bytes.toString(Charsets.UTF_8)
}
private fun fromHex(hex: String): ByteArray {
val bytes = ByteArray(hex.length / 2)
for (i in bytes.indices) {
bytes[i] = hex.substring(2 * i, 2 * i + 2).toInt(16).toByte()
}
return bytes
}
private fun toHex(array: ByteArray): String {
val bi = BigInteger(1, array)
var hex = bi.toString(16)
val paddingLength = array.size * 2 - hex.length
if (paddingLength > 0) {
hex = String.format("%0" + paddingLength + "d", 0) + hex
}
return hex
}
fun checkFileIsExist(
filesDir: File
): Boolean? {
val file = File(filesDir, "master_password.txt")
if (!file.exists()) {
return null
}
return true
}
suspend fun setMasterPassword(filesDir: File, otpValue: String) {
val salt = generateRandomSalt()
val newPassword = generateHash(otpValue, salt)
val file = File(filesDir, "master_password.txt")
if (!file.exists()) {
withContext(Dispatchers.IO) {
file.createNewFile()
}
}
try {
val fos = withContext(Dispatchers.IO) {
FileOutputStream(file)
}
withContext(Dispatchers.IO) {
fos.write(newPassword.toByteArray())
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun validateMasterPassword(filesDir: File, originalPassword: String): Boolean {
val currentPasswordHash = getHashFromFile(filesDir)
val parts = currentPasswordHash.split(":").toTypedArray()
val iterations = parts[0].toInt()
val salt = fromHex(parts[1])
val hash = fromHex(parts[2])
val spec = PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.size * 8)
val skf = SecretKeyFactory.getInstance(ALGORITHM)
val testHash = skf.generateSecret(spec).encoded
var diff = hash.size xor testHash.size
for (i in hash.indices) {
diff = diff or ((hash[i] xor testHash[i]).toInt()) // ???
}
return diff == 0
}
// fun generatePassword(value: String): String {
// val salt = generateRandomSalt()
// val password = generateHash(value, salt)
//
// return password
// }
fun generatePassword(
plainTextBytes: ByteArray,
passwordString: String
): HashMap<String, ByteArray> {
val map = HashMap<String, ByteArray>()
try {
//Random salt for next step
val random = SecureRandom()
val salt = ByteArray(256)
random.nextBytes(salt)
//PBKDF2 - derive the key from the password, don't use passwords directly
val passwordChar = passwordString.toCharArray() //Turn password into char[] array
val pbKeySpec = PBEKeySpec(passwordChar, salt, 1324, 256) //1324 iterations
val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val keyBytes = secretKeyFactory.generateSecret(pbKeySpec).encoded
val keySpec = SecretKeySpec(keyBytes, "AES")
//Create initialization vector for AES
val ivRandom = SecureRandom() //not caching previous seeded instance of SecureRandom
val iv = ByteArray(16)
ivRandom.nextBytes(iv)
val ivSpec = IvParameterSpec(iv)
//Encrypt
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec)
val encrypted = cipher.doFinal(plainTextBytes)
map["salt"] = salt
map["iv"] = iv
map["encrypted"] = encrypted
} catch (e: java.lang.Exception) {
Log.e("MYAPP", "encryption exception", e)
}
return map
}
fun decryptPassword(map: HashMap<String, ByteArray>, passwordString: String): ByteArray? {
var decrypted: ByteArray? = null
try {
val salt = map["salt"]
val iv = map["iv"]
val encrypted = map["encrypted"]
//regenerate key from password
val passwordChar = passwordString.toCharArray()
val pbKeySpec = PBEKeySpec(passwordChar, salt, 1324, 256)
val secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val keyBytes = secretKeyFactory.generateSecret(pbKeySpec).encoded
val keySpec = SecretKeySpec(keyBytes, "AES")
//Decrypt
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
val ivSpec = IvParameterSpec(iv)
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec)
decrypted = cipher.doFinal(encrypted)
} catch (e: java.lang.Exception) {
Log.e("MYAPP", "decryption exception", e)
}
return decrypted
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/data_source/CryptoClass.kt | 1143065546 |
package com.xenia.testvk.data.data_source
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.xenia.testvk.data.entities.ItemEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface PasswordDao {
@Query("SELECT * FROM password")
fun allPasswords(): Flow<List<ItemEntity>>
@Query("SELECT * FROM password WHERE id=:id")
fun getPasswordById(id: Int): ItemEntity
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addPassword(password: ItemEntity)
@Delete
suspend fun deletePassword(password: ItemEntity)
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/data_source/PasswordDao.kt | 3929428 |
package com.xenia.testvk.data.data_source
import androidx.room.Database
import androidx.room.RoomDatabase
import com.xenia.testvk.data.entities.ItemEntity
@Database(entities = [ItemEntity::class], version = 1, exportSchema = false)
abstract class Database: RoomDatabase() {
abstract val passwordDao: PasswordDao
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/data_source/Database.kt | 959009593 |
package com.xenia.testvk.data.mapper
import com.xenia.testvk.data.entities.ItemEntity
import com.xenia.testvk.domain.ItemModel
class PasswordMapper() {
fun mapListEntityToListModel(items: List<ItemEntity>): List<ItemModel> {
val list = mutableListOf<ItemModel>()
items.forEach {
list.add(ItemModel(
it.id,
it.imageUrl,
it.websiteUrl,
it.login,
it.password
))
}
return list
}
fun mapListModelToListEntity(items: List<ItemModel>): List<ItemEntity> {
val list = mutableListOf<ItemEntity>()
items.forEach {
list.add(ItemEntity(
it.id,
it.imageUrl,
it.websiteUrl,
it.login,
it.password
))
}
return list
}
fun mapModelToEntity(items: ItemModel): ItemEntity {
return ItemEntity(
items.id,
items.imageUrl,
items.websiteUrl,
items.login,
items.password
)
}
fun mapEntityToModel(items: ItemEntity): ItemModel {
return ItemModel(
items.id,
items.imageUrl,
items.websiteUrl,
items.login,
items.password
)
}
}
| TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/mapper/PasswordMapper.kt | 3869093085 |
package com.xenia.testvk.data.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "password")
data class ItemEntity(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val imageUrl: String,
val websiteUrl: String,
val login: String,
val password: String,
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/data/entities/ItemEntity.kt | 3021069012 |
package com.xenia.testvk.domain.repository
import com.xenia.testvk.domain.ItemModel
import kotlinx.coroutines.flow.Flow
import java.io.File
interface PasswordRepository {
fun allPasswords(): Flow<List<ItemModel>>?
fun getPasswordById(id: Int): ItemModel
suspend fun addPassword(password: ItemModel)
suspend fun deletePassword(password: ItemModel)
suspend fun setMasterPassword(filesDir: File, otpValue: String)
fun checkFileIsExist(filesDir: File): Boolean?
fun validateMasterPassword(filesDir: File, originalPassword: String): Boolean
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/repository/PasswordRepository.kt | 3795407472 |
package com.xenia.testvk.domain
data class ItemModel(
val id: Int = 0,
val imageUrl: String,
val websiteUrl: String,
val login: String,
val password: String,
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/ItemModel.kt | 2951329569 |
package com.xenia.testvk.domain.usecases
import com.xenia.testvk.domain.usecases.enter_usecases.CheckFileMasterPasswordUseCase
import com.xenia.testvk.domain.usecases.enter_usecases.SetMasterPasswordUseCase
import com.xenia.testvk.domain.usecases.enter_usecases.ValidateMasterPasswordUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.AddNewPasswordUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.DeletePasswordUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.GetPasswordByIdUseCase
import com.xenia.testvk.domain.usecases.passwords_usecases.GetPasswordsUseCase
data class UseCases(
val allPasswords: GetPasswordsUseCase,
val getPasswordById: GetPasswordByIdUseCase,
val addPassword: AddNewPasswordUseCase,
val deletePassword: DeletePasswordUseCase,
val checkFileMasterPassword: CheckFileMasterPasswordUseCase,
val setMasterPassword: SetMasterPasswordUseCase,
val validateMasterPassword: ValidateMasterPasswordUseCase
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/UseCases.kt | 2335199006 |
package com.xenia.testvk.domain.usecases.enter_usecases
import com.xenia.testvk.domain.repository.PasswordRepository
import java.io.File
class CheckFileMasterPasswordUseCase(
private val passwordRepository: PasswordRepository
) {
operator fun invoke(filesDir: File): Boolean? {
return passwordRepository.checkFileIsExist(filesDir)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/enter_usecases/CheckFileMasterPasswordUseCase.kt | 3555360825 |
package com.xenia.testvk.domain.usecases.enter_usecases
import com.xenia.testvk.domain.repository.PasswordRepository
import java.io.File
class SetMasterPasswordUseCase(
private val passwordRepository: PasswordRepository
) {
suspend operator fun invoke(filesDir: File, otpValue: String) {
passwordRepository.setMasterPassword(filesDir, otpValue)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/enter_usecases/SetMasterPasswordUseCase.kt | 978413325 |
package com.xenia.testvk.domain.usecases.enter_usecases
import com.xenia.testvk.domain.repository.PasswordRepository
import java.io.File
class ValidateMasterPasswordUseCase(
private val passwordRepository: PasswordRepository
) {
operator fun invoke(filesDir: File, originalPassword: String): Boolean {
return passwordRepository.validateMasterPassword(filesDir, originalPassword)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/enter_usecases/ValidateMasterPasswordUseCase.kt | 3740643143 |
package com.xenia.testvk.domain.usecases.passwords_usecases
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.repository.PasswordRepository
import kotlinx.coroutines.flow.Flow
class GetPasswordsUseCase(
private val passwordRepository: PasswordRepository
) {
operator fun invoke(): Flow<List<ItemModel>>? {
return passwordRepository.allPasswords()
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/passwords_usecases/GetPasswordsUseCase.kt | 3232233245 |
package com.xenia.testvk.domain.usecases.passwords_usecases
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.repository.PasswordRepository
class AddNewPasswordUseCase(
private val passwordRepository: PasswordRepository
) {
suspend operator fun invoke(password: ItemModel){
if (password.password.isNotBlank() && password.login.isNotBlank())
passwordRepository.addPassword(password)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/passwords_usecases/AddNewPasswordUseCase.kt | 245476936 |
package com.xenia.testvk.domain.usecases.passwords_usecases
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.repository.PasswordRepository
class DeletePasswordUseCase(
private val passwordRepository: PasswordRepository
) {
suspend operator fun invoke(password: ItemModel){
passwordRepository.deletePassword(password)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/passwords_usecases/DeletePasswordUseCase.kt | 4273389452 |
package com.xenia.testvk.domain.usecases.passwords_usecases
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.repository.PasswordRepository
class GetPasswordByIdUseCase(
private val passwordRepository: PasswordRepository
) {
operator fun invoke(id: Int): ItemModel {
return passwordRepository.getPasswordById(id)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/domain/usecases/passwords_usecases/GetPasswordByIdUseCase.kt | 1681675866 |
package com.xenia.testvk.presentation.enter_screen
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.xenia.testvk.ui.theme.GreyDark
import com.xenia.testvk.ui.theme.GreyLight
@Composable
fun OtpTextField(
modifier: Modifier = Modifier,
otpText: String,
otpCount: Int = 6,
onOtpTextChange: (String, Boolean) -> Unit
) {
LaunchedEffect(Unit) {
if (otpText.length > otpCount) {
throw IllegalArgumentException("Otp text value must not have more than otpCount: $otpCount characters")
}
}
BasicTextField(
modifier = modifier,
value = TextFieldValue(otpText, selection = TextRange(otpText.length)),
onValueChange = {
if (it.text.length <= otpCount) {
onOtpTextChange.invoke(it.text, it.text.length == otpCount)
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
decorationBox = {
Row(horizontalArrangement = Arrangement.Center) {
repeat(otpCount) { index ->
CharView(
index = index,
text = otpText
)
Spacer(modifier = Modifier.width(8.dp))
}
}
}
)
}
@Composable
private fun CharView(
index: Int,
text: String
) {
val isFocused = text.length == index
val char = when {
index == text.length -> "0"
index > text.length -> ""
else -> text[index].toString()
}
Text(
modifier = Modifier.size(50.dp)
.border(
1.dp, when {
isFocused -> GreyDark
else -> GreyLight
}, RoundedCornerShape(8.dp)
)
.padding(2.dp),
text = char,
fontSize = 30.sp,
color = if (isFocused) {
GreyLight
} else {
GreyDark
},
textAlign = TextAlign.Center
)
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/enter_screen/OtpTextField.kt | 3575654868 |
package com.xenia.testvk.presentation.enter_screen
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.xenia.testvk.navigation.Screens
import com.xenia.testvk.ui.theme.ButtonColor
import java.io.File
@Composable
fun EnterScreen(
navController: NavController,
filesDir: File,
viewModel: EnterViewModel = hiltViewModel()
) {
var otpValue by remember {
mutableStateOf("")
}
val masterPassword = viewModel.checkFileIsExist(filesDir)
val context = LocalContext.current
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
if (masterPassword == null) {
Text(
text = "Создайте пароль и нажмите кнопку",
Modifier.padding(bottom = 20.dp)
)
}
OtpTextField(
otpText = otpValue,
onOtpTextChange = { value, _ ->
otpValue = value
}
)
Button(
modifier = Modifier.padding(top = 20.dp),
onClick = {
if (masterPassword != null) {
val validate = viewModel.validatePassword(filesDir, otpValue)
if (validate) {
navController.navigate(Screens.MainScreen.route)
}
else {
Toast.makeText(
context,
"Неверный пароль",
Toast.LENGTH_SHORT
).show()
}
} else {
viewModel.setPassword(filesDir, otpValue)
navController.navigate(Screens.MainScreen.route)
}
},
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.buttonColors(
containerColor = ButtonColor
)
) {
Text(
text = "Войти",
textAlign = TextAlign.Center
)
}
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/enter_screen/EnterScreen.kt | 89013850 |
package com.xenia.testvk.presentation.enter_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.xenia.testvk.domain.usecases.UseCases
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject
@HiltViewModel
class EnterViewModel @Inject constructor(
private val useCases: UseCases
): ViewModel() {
fun setPassword(filesDir: File, otpValue: String) {
viewModelScope.launch {
useCases.setMasterPassword(filesDir, otpValue)
}
}
fun checkFileIsExist(filesDir: File): Boolean? {
return useCases.checkFileMasterPassword(filesDir)
}
fun validatePassword(filesDir: File, originalPassword: String): Boolean {
return useCases.validateMasterPassword(filesDir, originalPassword)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/enter_screen/EnterViewModel.kt | 3486233775 |
package com.xenia.testvk.presentation.main_screen
import com.xenia.testvk.domain.ItemModel
data class PasswordState(
var passwords: List<ItemModel> = emptyList()
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/main_screen/PasswordState.kt | 2204886424 |
package com.xenia.testvk.presentation.main_screen
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.usecases.UseCases
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PasswordsViewModel @Inject constructor(
private val useCases: UseCases
): ViewModel() {
private val _passwordsState = mutableStateOf(PasswordState())
val passwordsState: State<PasswordState> = _passwordsState
private var recentlyDeletedPassword: ItemModel? = null
private var allPasswords: Job? = null
init {
getPasswords()
}
private fun getPasswords(){
allPasswords?.cancel()
allPasswords = useCases.allPasswords()?.onEach {
_passwordsState.value = _passwordsState.value.copy(
passwords = it
)
}?.launchIn(viewModelScope)
}
fun onEvent(event: PasswordsEvents){
when (event){
is PasswordsEvents.DeletePassword -> {
viewModelScope.launch {
useCases.deletePassword(event.password)
}
recentlyDeletedPassword = event.password
}
is PasswordsEvents.RestorePassword -> {
viewModelScope.launch {
useCases.addPassword(recentlyDeletedPassword ?: return@launch)
}
}
}
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/main_screen/PasswordsViewModel.kt | 1983685698 |
package com.xenia.testvk.presentation.main_screen
import com.xenia.testvk.domain.ItemModel
sealed class PasswordsEvents {
data class DeletePassword(val password: ItemModel): PasswordsEvents()
data object RestorePassword: PasswordsEvents()
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/main_screen/PasswordEvents.kt | 4021312795 |
package com.xenia.testvk.presentation.main_screen
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.Log
import androidx.compose.foundation.Image
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.squareup.picasso.Picasso
import com.xenia.testvk.R
import com.xenia.testvk.domain.ItemModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable
fun PasswordItem(
modifier: Modifier = Modifier,
password: ItemModel,
onDeleteClick: () -> Unit,
onItemClick: () -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 5.dp)
.clickable {
onItemClick()
},
elevation = CardDefaults.elevatedCardElevation(
defaultElevation = 5.dp
),
shape = RoundedCornerShape(10.dp)
) {
Row(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
Box(
modifier = Modifier.fillMaxHeight()
) {
LoadImageFromUrl(context = LocalContext.current , url = password.imageUrl)
}
Column(
modifier = Modifier.padding(start = 10.dp).fillMaxWidth(),
verticalArrangement = Arrangement.Center
) {
Text(text = password.websiteUrl)
Text(text = password.login)
Text(text = password.password)
IconButton(onClick = onDeleteClick, modifier = Modifier.align(Alignment.End)) {
Icon(imageVector = Icons.Filled.Delete, contentDescription = "Delete Password")
}
}
}
}
}
@Composable
fun LoadImageFromUrl(context: Context, url: String) {
var image by remember { mutableStateOf<Bitmap?>(null) }
LaunchedEffect(url) {
image = try {
val bitmap = withContext(Dispatchers.IO) {
Picasso.get().load(url).get()
}
bitmap
} catch (e: Exception) {
Log.d("TAG", "bitmap null")
val db = ContextCompat.getDrawable(context, R.drawable.ic_empty_content_5)
val bit = Bitmap.createBitmap(
db!!.intrinsicWidth, db.intrinsicHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bit)
db.setBounds(0, 0, canvas.width, canvas.height)
db.draw(canvas)
bit
}
}
image?.let {
Image(
bitmap = it.asImageBitmap(),
contentDescription = null,
modifier = Modifier
.fillMaxHeight().size(50.dp),
alignment = Alignment.BottomCenter
)
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/main_screen/PasswordItem.kt | 8815395 |
package com.xenia.testvk.presentation.main_screen
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.xenia.testvk.navigation.Screens
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MainScreen(
navController: NavController,
viewModel: PasswordsViewModel = hiltViewModel()
) {
val snackBarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val passwords = viewModel.passwordsState.value
Scaffold(
snackbarHost = { SnackbarHost(snackBarHostState) },
topBar = {
TopAppBar(colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Black
),
title = {
Text(
text = "Менеджер паролей",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
color = Color.White
)
}
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
navController.navigate(Screens.AddEditPasswordScreen.route) {
popUpTo(Screens.AddEditPasswordScreen.route) {
inclusive = true
}
}
},
) {
Icon(Icons.Filled.Add, "Add data button.")
}
},
floatingActionButtonPosition = FabPosition.End,
content = { paddingValues ->
LazyColumn(
modifier = Modifier.padding(top = paddingValues.calculateTopPadding())
) {
itemsIndexed(
passwords.passwords,
key = { _, password -> password.hashCode() }
) { _, password ->
PasswordItem(
modifier = Modifier.animateItemPlacement(),
password = password,
onDeleteClick = {
viewModel.onEvent(PasswordsEvents.DeletePassword(password))
scope.launch {
val result = snackBarHostState.showSnackbar(
message = "Password Deleted",
actionLabel = "Undo",
duration = SnackbarDuration.Long
)
if (result == SnackbarResult.ActionPerformed){
viewModel.onEvent(PasswordsEvents.RestorePassword)
}
}
},
onItemClick = {
navController.navigate(Screens.AddEditPasswordScreen.route + "?passwordId=${password.id}")
}
)
}
}
}
)
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/main_screen/MainScreen.kt | 2116855589 |
package com.xenia.testvk.presentation.add_edit_password_screen
data class PasswordTextFieldState(
var text: String = "",
val hint: String = "",
) | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/add_edit_password_screen/PasswordTextFieldState.kt | 1776633813 |
package com.xenia.testvk.presentation.add_edit_password_screen
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.xenia.testvk.domain.ItemModel
import com.xenia.testvk.domain.usecases.UseCases
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class AddEditViewModel @Inject constructor(
private val useCases: UseCases,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val _imageState = mutableStateOf(PasswordTextFieldState(hint = "Image"))
val imageState: State<PasswordTextFieldState> = _imageState
private val _websiteState = mutableStateOf(PasswordTextFieldState(hint = "Website"))
val websiteState: State<PasswordTextFieldState> = _websiteState
private val _loginState = mutableStateOf(PasswordTextFieldState(hint = "Login..."))
val loginState: State<PasswordTextFieldState> = _loginState
private val _passwordState = mutableStateOf(PasswordTextFieldState(hint = "Password"))
val passwordState: State<PasswordTextFieldState> = _passwordState
private var _uiEvent = MutableSharedFlow<UIEvents>()
val uiEvents: SharedFlow<UIEvents> = _uiEvent
private var pressedPasswordId: Int? = null
init {
savedStateHandle.get<Int>("passwordId")?.let { passwordId ->
if (passwordId != -1) {
pressedPasswordId = passwordId
viewModelScope.launch(Dispatchers.IO) {
delay(100)
useCases.getPasswordById(passwordId).let { password ->
_imageState.value = _imageState.value.copy(
text = password.imageUrl,
)
_passwordState.value = _passwordState.value.copy(
text = password.password,
)
_websiteState.value = _websiteState.value.copy(
text = password.websiteUrl,
)
_loginState.value = _loginState.value.copy(
text = password.login,
)
}
}
}
}
}
fun onEvent(event: AddEditPasswordEvent) {
when (event) {
is AddEditPasswordEvent.SavePassword -> {
viewModelScope.launch {
Log.d("TAG", pressedPasswordId.toString())
if (pressedPasswordId == null) {
useCases.addPassword(
ItemModel(
imageUrl = "https://www.google.com/s2/favicons?domain=https://" + "${_websiteState.value.text}&sz=128",
password = _passwordState.value.text,
websiteUrl = _websiteState.value.text,
login = _loginState.value.text
)
)
} else {
useCases.addPassword(
ItemModel(
id = pressedPasswordId!!,
imageUrl = "https://www.google.com/s2/favicons?domain=https://" + "${_websiteState.value.text}&sz=128",
password = _passwordState.value.text,
websiteUrl = _websiteState.value.text,
login = _loginState.value.text
)
)
}
_uiEvent.emit(UIEvents.SavePassword)
}
}
is AddEditPasswordEvent.EnteringPassword -> {
_passwordState.value = _passwordState.value.copy(
text = event.value
)
}
is AddEditPasswordEvent.EnteringWebsite -> {
_websiteState.value = _websiteState.value.copy(
text = event.value
)
}
is AddEditPasswordEvent.EnteringLogin -> {
_loginState.value = _loginState.value.copy(
text = event.value
)
}
}
}
sealed class UIEvents {
data object SavePassword : UIEvents()
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/add_edit_password_screen/AddEditViewModel.kt | 2027233011 |
package com.xenia.testvk.presentation.add_edit_password_screen
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Place
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.xenia.testvk.presentation.add_edit_password_screen.component.CustomTextField
import kotlinx.coroutines.flow.collectLatest
@Composable
fun AddEditPasswordScreen(
navController: NavController,
viewModel: AddEditViewModel = hiltViewModel()
) {
val snackBarHostState = remember { SnackbarHostState() }
val passwordState = viewModel.passwordState.value
val loginState = viewModel.loginState.value
val websiteState = viewModel.websiteState.value
LaunchedEffect(key1 = true, block = {
viewModel.uiEvents.collectLatest { event ->
when (event) {
is AddEditViewModel.UIEvents.SavePassword -> {
navController.navigateUp()
}
}
}
})
Scaffold(
snackbarHost = { SnackbarHost(snackBarHostState) },
floatingActionButton = {
FloatingActionButton(onClick = {
viewModel.onEvent(AddEditPasswordEvent.SavePassword)
}) {
Icon(imageVector = Icons.Filled.Done, contentDescription = "Save Password")
}
}
) { contentPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(top = contentPadding.calculateTopPadding()),
contentAlignment = Alignment.Center
) {
Column {
CustomTextField(
text = loginState.text,
hint = loginState.hint,
onTextChange = {
viewModel.onEvent(AddEditPasswordEvent.EnteringLogin(it))
},
leadingIcon = {
Icon(
imageVector = Icons.Filled.Email,
contentDescription = "Login"
)
})
Spacer(modifier = Modifier.padding(20.dp))
CustomTextField(
text = passwordState.text,
hint = passwordState.hint,
onTextChange = {
viewModel.onEvent(AddEditPasswordEvent.EnteringPassword(it))
},
leadingIcon = {
Icon(
imageVector = Icons.Filled.Lock,
contentDescription = "Password"
)
}
)
Spacer(modifier = Modifier.padding(20.dp))
CustomTextField(
text = websiteState.text,
hint = websiteState.hint,
isNotes = true,
onTextChange = {
viewModel.onEvent(AddEditPasswordEvent.EnteringWebsite(it))
},
leadingIcon = {
Icon(imageVector = Icons.Filled.Place, contentDescription = "Website")
})
}
}
}
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/add_edit_password_screen/AddEditPasswordScreen.kt | 3776243853 |
package com.xenia.testvk.presentation.add_edit_password_screen.component
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
@Composable
fun CustomTextField(
modifier: Modifier = Modifier,
text: String,
hint: String,
isNotes: Boolean = false,
textStyle: TextStyle = TextStyle(),
onTextChange: (String) -> Unit,
leadingIcon: @Composable () -> Unit,
) {
TextField(
modifier = modifier.fillMaxWidth(0.8f),
value = text,
onValueChange = onTextChange,
textStyle = textStyle,
leadingIcon = leadingIcon,
singleLine = !isNotes,
label = {
Text(text = hint)
},
)
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/add_edit_password_screen/component/CustomTextField.kt | 2071305197 |
package com.xenia.testvk.presentation.add_edit_password_screen
sealed class AddEditPasswordEvent{
data class EnteringWebsite(val value: String): AddEditPasswordEvent()
data class EnteringLogin(val value: String): AddEditPasswordEvent()
data class EnteringPassword(val value: String): AddEditPasswordEvent()
data object SavePassword: AddEditPasswordEvent()
} | TestVKPasswordManager/app/src/main/java/com/xenia/testvk/presentation/add_edit_password_screen/AddEditPasswordEvent.kt | 2504360043 |
package com.example.gofish
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.gofish", appContext.packageName)
}
} | Go-fish/app/src/androidTest/java/com/example/gofish/ExampleInstrumentedTest.kt | 4200509805 |
package com.example.gofish
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)
}
} | Go-fish/app/src/test/java/com/example/gofish/ExampleUnitTest.kt | 1851650474 |
package com.example.gofish
import android.util.Log
import java.lang.IllegalStateException
class Carddeck {
var cardpile = mutableListOf<Card>()
init {
initializeCards()
shuffleDeck()
}
fun shuffleDeck() {
cardpile.shuffle()
}
fun dealCardsToPlayers(players: List<Player>) {
repeat(4) {
for (player in players) {
val card = drawCard()
player.addCardToHand(card)
}
}
}
fun drawCard(): Card {
if (cardpile.isEmpty()) {
throw IllegalStateException("The card is empty")
}
return cardpile.removeAt(0)
}
fun fillPlayerHand(player: Player) {
var numberOfCards:Int = 4
while (cardpile.isNotEmpty() && player.hand.size < numberOfCards) {
val card = cardpile.removeAt(0)
player.hand.add(card)
card.flipCardUp()
}
}
fun findAndRemovePairs(player: Player): List<Pair<Card, Card>> {
val pairs = mutableListOf<Pair<Card, Card>>()
val uniqueHand = player.hand.distinct()
val toRemove = mutableListOf<Card>()
for (card1 in 0 until uniqueHand.size) {
for (card2 in card1 + 1 until uniqueHand.size) {
if (uniqueHand[card1].value == uniqueHand[card2].value) {
pairs.add(Pair(uniqueHand[card1], uniqueHand[card2]))
toRemove.add(uniqueHand[card1])
toRemove.add(uniqueHand[card2])
player.score++
}
}
}
player.hand.removeAll(toRemove)
return pairs
}
fun initializeCards() {
cardpile.add(Card("Hearts", 1, false, R.drawable.hearts_1, R.drawable.facedown))
cardpile.add(Card("Hearts", 2, false, R.drawable.hearts_2, R.drawable.facedown))
cardpile.add(Card("Hearts", 3, false, R.drawable.hearts_3, R.drawable.facedown))
cardpile.add(Card("Hearts", 4, false, R.drawable.hearts_4, R.drawable.facedown))
cardpile.add(Card("Hearts", 5, false, R.drawable.hearts_5, R.drawable.facedown))
cardpile.add(Card("Hearts", 6, false, R.drawable.hearts_6, R.drawable.facedown))
cardpile.add(Card("Hearts", 7, false, R.drawable.hearts_7, R.drawable.facedown))
cardpile.add(Card("Hearts", 8, false, R.drawable.hearts_8, R.drawable.facedown))
cardpile.add(Card("Hearts", 9, false, R.drawable.hearts_9, R.drawable.facedown))
cardpile.add(Card("Hearts", 10, false, R.drawable.hearts_10, R.drawable.facedown))
cardpile.add(Card("Hearts", 11, false, R.drawable.hearts_11, R.drawable.facedown))
cardpile.add(Card("Hearts", 12, false, R.drawable.hearts_12, R.drawable.facedown))
cardpile.add(Card("Hearts", 13, false, R.drawable.hearts_13, R.drawable.facedown))
cardpile.add(Card("Spades", 1, false, R.drawable.spades_1, R.drawable.facedown))
cardpile.add(Card("Spades", 2, false, R.drawable.spades_2, R.drawable.facedown))
cardpile.add(Card("Spades", 3, false, R.drawable.spades_3, R.drawable.facedown))
cardpile.add(Card("Spades", 4, false, R.drawable.spades_4, R.drawable.facedown))
cardpile.add(Card("Spades", 5, false, R.drawable.spades_5, R.drawable.facedown))
cardpile.add(Card("Spades", 6, false, R.drawable.spades_6, R.drawable.facedown))
cardpile.add(Card("Spades", 7, false, R.drawable.spades_7, R.drawable.facedown))
cardpile.add(Card("Spades", 8, false, R.drawable.spades_8, R.drawable.facedown))
cardpile.add(Card("Spades", 9, false, R.drawable.spades_9, R.drawable.facedown))
cardpile.add(Card("Spades", 10, false, R.drawable.spades_10, R.drawable.facedown))
cardpile.add(Card("Spades", 11, false, R.drawable.spades_11, R.drawable.facedown))
cardpile.add(Card("Spades", 12, false, R.drawable.spades_12, R.drawable.facedown))
cardpile.add(Card("Spades", 13, false, R.drawable.spades_13, R.drawable.facedown))
cardpile.add(Card("Diamonds", 1, false, R.drawable.diamonds_1, R.drawable.facedown))
cardpile.add(Card("Diamonds", 2, false, R.drawable.diamonds_2, R.drawable.facedown))
cardpile.add(Card("Diamonds", 3, false, R.drawable.diamonds_3, R.drawable.facedown))
cardpile.add(Card("Diamonds", 4, false, R.drawable.diamonds_4, R.drawable.facedown))
cardpile.add(Card("Diamonds", 5, false, R.drawable.diamonds_5, R.drawable.facedown))
cardpile.add(Card("Diamonds", 6, false, R.drawable.diamonds_6, R.drawable.facedown))
cardpile.add(Card("Diamonds", 7, false, R.drawable.diamonds_7, R.drawable.facedown))
cardpile.add(Card("Diamonds", 8, false, R.drawable.diamonds_8, R.drawable.facedown))
cardpile.add(Card("Diamonds", 9, false, R.drawable.diamonds_9, R.drawable.facedown))
cardpile.add(Card("Diamonds", 10, false, R.drawable.diamonds_10, R.drawable.facedown))
cardpile.add(Card("Diamonds", 11, false, R.drawable.diamonds_11, R.drawable.facedown))
cardpile.add(Card("Diamonds", 12, false, R.drawable.diamonds_12, R.drawable.facedown))
cardpile.add(Card("Diamonds", 13, false, R.drawable.diamonds_13, R.drawable.facedown))
cardpile.add(Card("Clubs", 1, false, R.drawable.clubs_1, R.drawable.facedown))
cardpile.add(Card("Clubs", 2, false, R.drawable.clubs_2, R.drawable.facedown))
cardpile.add(Card("Clubs", 3, false, R.drawable.clubs_3, R.drawable.facedown))
cardpile.add(Card("Clubs", 4, false, R.drawable.clubs_4, R.drawable.facedown))
cardpile.add(Card("Clubs", 5, false, R.drawable.clubs_5, R.drawable.facedown))
cardpile.add(Card("Clubs", 6, false, R.drawable.clubs_6, R.drawable.facedown))
cardpile.add(Card("Clubs", 7, false, R.drawable.clubs_7, R.drawable.facedown))
cardpile.add(Card("Clubs", 8, false, R.drawable.clubs_8, R.drawable.facedown))
cardpile.add(Card("Clubs", 9, false, R.drawable.clubs_9, R.drawable.facedown))
cardpile.add(Card("Clubs", 10, false, R.drawable.clubs_10, R.drawable.facedown))
cardpile.add(Card("Clubs", 11, false, R.drawable.clubs_11, R.drawable.facedown))
cardpile.add(Card("Clubs", 12, false, R.drawable.clubs_12, R.drawable.facedown))
cardpile.add(Card("Clubs", 13, false, R.drawable.clubs_13, R.drawable.facedown))
}
}
| Go-fish/app/src/main/java/com/example/gofish/Carddeck.kt | 2030894566 |
package com.example.gofish
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class GameActivity : AppCompatActivity() , CardClickListener {
lateinit var cardAdapter1: CardAdapter
lateinit var cardAdapter2: CardAdapter
var carddeck = Carddeck()
val animation = Animations()
lateinit var recyclerView1: RecyclerView
lateinit var recyclerView2: RecyclerView
val player1 = Human("Player 1")
val player2 = Computer("Player 2")
var currentPlayer: Player = player1
var otherPlayer: Player = player2
var computerCard : Card? = null
lateinit var seaCard1: ImageView
lateinit var seaCard2: ImageView
lateinit var seaCard3: ImageView
lateinit var seaCard4: ImageView
lateinit var seaCard5: ImageView
lateinit var seaCard6: ImageView
lateinit var seaCard7: ImageView
lateinit var seaCard8: ImageView
lateinit var seaCard9: ImageView
lateinit var seaCard10: ImageView
lateinit var playerTurnTextView: TextView
lateinit var chatBubble1: ImageView
lateinit var chatBubble2: ImageView
lateinit var chatBubbleText1: TextView
lateinit var chatBubbleText2: TextView
lateinit var goFishText: TextView
lateinit var showCard1: ImageView
lateinit var player1score: TextView
lateinit var player2score : TextView
lateinit var homeButton : Button
lateinit var helpTextView: TextView
lateinit var goFishButton: Button
var askClickable : Boolean = true
var giveClickable : Boolean = false
var seaCardsClickable : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
initializeViews()
initializeGame()
homeButton.setOnClickListener {
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
}
fun initializeGame(){
carddeck.shuffleDeck()
val players = listOf(player1, player2)
carddeck.dealCardsToPlayers(players)
placeCardsInSea()
player1score.text = player1.showScore()
player2score.text = player2.showScore()
for (card in player1.hand) {
card.flipCardUp()
}
for (card in player2.hand) {
card.flipCardUp()
}
}
override fun onCardClick(card: Card) {
//A function for when human player click on their cards
if(ifGameIsOver()){
return
}
//If if's the human's turn
if(currentPlayer==player1) {
if (askClickable) {
askPlayerForACard(card)
//Askclickable is true, if the computer player has the card requested.
// If that's the case, the human can ask for a card again
askClickable = answerOtherPlayer(card)
}
}
//If it's the computer player's turn
if(currentPlayer==player2) {
if (giveClickable) {
helpTextView.text = "Click on a card to give"
if (card.value == computerCard?.value) {
chatBubbleText1.text = "YES"
chatBubbleText2.text = "WOWOOHOOHO!"
player1.removeCardFromHand(card)
animateGivenCard(card)
player2.addCardToHand(card)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
updateRecyclerView()
//If the human has the card computer asks for. It's the computer's turn to ask again
switchPlayers()
switchPlayers()
}, 1600)
} else if (card.value!=computerCard?.value){
chatBubbleText1.textSize=10f
chatBubbleText1.text = "No, go fish"
helpTextView.text = "Click on the Go Fish-button"
giveClickable=false
goFishButtonClick()
}
}
}
}
fun askPlayerForACard(card: Card) {
chatBubble1.setImageResource(R.drawable.chaticon4)
chatBubble2.setImageResource(R.drawable.chaticon4)
chatBubble1.visibility = View.VISIBLE
chatBubble2.visibility = View.VISIBLE
val askingPlayerText: TextView
if (currentPlayer == player1) {
askingPlayerText = chatBubbleText1
} else {
askingPlayerText = chatBubbleText2
}
askingPlayerText.text = "Do you have ${card.value}?"
fillPlayerHands()
ifGameIsOver()
placeCardsInSea()
}
fun answerOtherPlayer(card: Card) : Boolean {
val answerPlayerText: TextView
if (currentPlayer == player1) {
answerPlayerText = chatBubbleText2
} else {
answerPlayerText = chatBubbleText1
}
val hasCard = otherPlayer.hand.any {
it.value == card.value
}
if (hasCard) {
answerPlayerText.text = "YES"
hasCard(card)
} else if(!hasCard){
answerPlayerText.text = "No sorry! Go fish!"
goFish()
}
return hasCard
}
fun goFish(){
//A method for when the player has to pick a card from the sea
val seaCards = listOf(seaCard1,seaCard2,seaCard3,seaCard4, seaCard5,seaCard6,seaCard7,seaCard8,seaCard9,seaCard10)
if(currentPlayer==player1) {
helpTextView.text = "Click on a card in the sea"
animateGoFish()
seaCardsClickable = true
//goFish()
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
goFishText.visibility = View.VISIBLE
}, 500)
if (seaCardsClickable) {
seaCardsClickable = false
for (seaCard in seaCards) {
seaCard.setOnClickListener {
for (card in seaCards) {
card.setOnClickListener(null)
}
var card = carddeck.drawCard()
currentPlayer.addCardToHand(card)
card.flipCardUp()
animateCardFromSea(card)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
updateRecyclerView()
goFishText.visibility = View.GONE
switchPlayers()
}, 1600)
}
}
}
}
}
fun switchPlayers(){
fillPlayerHands()
ifGameIsOver()
placeCardsInSea()
updateScore()
if(currentPlayer==player1){
currentPlayer=player2
computerCard = computerPlayer2Turn()
Log.d("!!!","computerCard : ${computerCard?.value}")
playerTurnTextView.text = "${currentPlayer.name}'s turn"
}
else{
currentPlayer=player1
humanPlayer1turn()
computerCard=null
playerTurnTextView.text = "${currentPlayer.name}'s turn"
}
}
fun humanPlayer1turn(){
ifGameIsOver()
chatBubbleText1.textSize = 10f
askClickable=true
seaCardsClickable=false
helpTextView.text = "Choose the card you want to ask for"
}
fun computerPlayer2Turn():Card?{
ifGameIsOver()
val randomCard = player2.selectCardToChoose(player2.hand)
chatBubbleText1.textSize = 24f
chatBubbleText1.text = "..."
if(randomCard!=null){
askPlayerForACard(randomCard)
helpTextView.text = "Click on a card to give or click the button"
goFishButton.visibility = View.VISIBLE
giveClickable = true
goFishButtonClick()
return randomCard
}
return null
}
fun goFishButtonClick(){
ifGameIsOver()
goFishButton.isEnabled=true
if(currentPlayer==player2){
goFishButton.setOnClickListener {
var card = carddeck.drawCard()
player2.addCardToHand(card)
card.flipCardUp()
goFishButton.isEnabled = false
goFishButton.visibility = View.GONE
animateCardFromSea(card)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
updateRecyclerView()
//giveClickable = false
goFishText.visibility = View.GONE
switchPlayers()
chatBubbleText1.text=""
chatBubbleText2.text=""
}, 1600)
}
}
}
fun fillPlayerHands(){
val players = listOf(player1,player2)
for(player in players ){
carddeck.fillPlayerHand(player)
for (card in player1.hand) {
card.flipCardUp()
}
for (card in player2.hand) {
card.flipCardUp()
}
}
}
fun ifGameIsOver() : Boolean {
if(carddeck.cardpile.isEmpty()||player1.hand.isEmpty()||player2.hand.isEmpty()){
updateScore()
val winner = checkWhoIsWinner()
helpTextView.text = "${winner.name} wins!"
goFishButton.visibility=View.GONE
goFishText.visibility = View.VISIBLE
playerTurnTextView.visibility=View.GONE
goFishText.text = "${winner.name} wins!"
if(winner==player1)
{
chatBubbleText2.text = "Good job!"
chatBubbleText1.textSize = 12f
chatBubbleText1.text = "Thank you :D"
}
else{
chatBubbleText2.text = "Thank you :) "
chatBubbleText1.textSize = 12f
chatBubbleText1.text = "Good job"
}
return true
}
return false
}
fun checkWhoIsWinner():Player{
if(player1.score>player2.score){
return player1
}
else{
return player2
}
}
fun placeCardsInSea() {
val seaCardViews = listOf(
seaCard1,
seaCard2,
seaCard3,
seaCard4,
seaCard5,
seaCard6,
seaCard7,
seaCard8,
seaCard9,
seaCard10
)
for (i in seaCardViews.indices) {
if (i < carddeck.cardpile.size) {
seaCardViews[i].setImageResource(carddeck.cardpile[i].faceDownImage)
} else {
seaCardViews[i].visibility = View.GONE
}
}
}
fun updateScore(){
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
val players = listOf(player1,player2)
for(player in players){
carddeck.findAndRemovePairs(player)
player.showScore()
}
player1score.text = player1.showScore()
player2score.text = player2.showScore()
updateRecyclerView()
}, 2000)
}
fun giveCard(card : Card){
player1.giveCard(player2,card)
}
fun updateRecyclerView() {
cardAdapter1.notifyDataSetChanged()
cardAdapter2.notifyDataSetChanged()
}
fun hasCard(clickedCard: Card){
//A method for when the computer player has the card the human asks for.
var givenCard = otherPlayer.giveCard(currentPlayer, clickedCard)
if (givenCard != null) {
animateGivenCard(givenCard)
}
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
updateRecyclerView()
if(currentPlayer==player1){
helpTextView.text = "Choose another card"
}
}, 1500)
}
fun animateGoFish() {
val seaCardViews = listOf(
seaCard1,
seaCard2,
seaCard3,
seaCard4,
seaCard5,
seaCard6,
seaCard7,
seaCard8,
seaCard9,
seaCard10
)
for (seaCardView in seaCardViews) {
animation.goFish(seaCardView)
}
}
fun animateGivenCard(card: Card) {
showCard1.visibility = View.VISIBLE
if (currentPlayer == player1) {
showCard1.setImageResource(card.faceUpImage)
animation.givenCardHuman(showCard1)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
showCard1.visibility = View.GONE
}, 1000)
} else if (currentPlayer == player2) {
showCard1.setImageResource(card.faceUpImage)
animation.givenCardComputer(showCard1)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
showCard1.visibility = View.GONE
}, 1000)
}
}
fun animateCardFromSea(card : Card) {
showCard1.visibility = View.VISIBLE
showCard1.setImageResource(card.faceUpImage)
if (currentPlayer == player1) {
animation.cardFromSeaHuman(showCard1)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
showCard1.visibility = View.GONE
goFishText.visibility = View.GONE
}, 1500)
} else if (currentPlayer==player2) {
animation.cardFromSeaComputer(showCard1)
Handler(Looper.getMainLooper()).postDelayed({
// Code to be executed after 3 seconds
showCard1.visibility = View.GONE
goFishText.visibility = View.GONE
}, 1500)
}
}
fun initializeViews(){
seaCard1 = findViewById(R.id.seaCard1)
seaCard2 = findViewById(R.id.seaCard2)
seaCard3 = findViewById(R.id.seaCard3)
seaCard4 = findViewById(R.id.seaCard4)
seaCard5 = findViewById(R.id.seaCard5)
seaCard6 = findViewById(R.id.seaCard6)
seaCard7 = findViewById(R.id.seaCard7)
seaCard8 = findViewById(R.id.seaCard8)
seaCard9 = findViewById(R.id.seaCard9)
seaCard10 = findViewById(R.id.seaCard10)
goFishText = findViewById(R.id.goFishTextView)
goFishText.visibility = View.GONE
showCard1 = findViewById(R.id.showCard1)
player1score = findViewById(R.id.player1score)
player2score = findViewById(R.id.player2score)
val roundImage = findViewById<ImageView>(R.id.roundOceanImage)
roundImage.setImageResource(R.drawable.roundocean)
cardAdapter1 = CardAdapter(this, player1.hand, this, true)
cardAdapter2 = CardAdapter(this, player2.hand, this, false)
recyclerView1 = findViewById(R.id.recyclerView1)
recyclerView2 = findViewById(R.id.recyclerView2)
chatBubble1 = findViewById<ImageView>(R.id.chatBubble1)
chatBubble2 = findViewById<ImageView>(R.id.chatBubble2)
chatBubble1.visibility = View.GONE
chatBubble2.visibility = View.GONE
chatBubbleText1 = findViewById<TextView>(R.id.player1textView)
chatBubbleText2 = findViewById<TextView>(R.id.player2textView)
recyclerView1.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
recyclerView2.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
recyclerView1.adapter = cardAdapter1
recyclerView2.adapter = cardAdapter2
homeButton = findViewById(R.id.homeButton)
goFishButton = findViewById(R.id.gofishButton)
helpTextView = findViewById(R.id.helpTextView)
goFishButton.visibility = View.GONE
playerTurnTextView = findViewById(R.id.playerTurnTextView)
helpTextView.text = "Choose the card you want to ask for"
playerTurnTextView.text = "${currentPlayer.name}'s turn"
}
}
| Go-fish/app/src/main/java/com/example/gofish/GameActivity.kt | 3931001301 |
package com.example.gofish
class Card( val suit:String , val value:Int, var isFaceUp: Boolean = false, val faceUpImage:Int, val faceDownImage:Int) {
fun flipCardUp() {
isFaceUp = true
}
fun flipCardDown() {
isFaceUp = false
}
} | Go-fish/app/src/main/java/com/example/gofish/Card.kt | 3179310334 |
package com.example.gofish
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
class HomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
val oceanImage1 = findViewById<ImageView>(R.id.oceanImage1)
val welcomeTextView = findViewById<TextView>(R.id.welcomeTextView)
val cardGameTextView = findViewById<TextView>(R.id.cardGameTextView)
val fishImage = findViewById<ImageView>(R.id.fishImage)
val howButton = findViewById<Button>(R.id.howButton)
val playButton = findViewById<Button>(R.id.playButton)
val animation = Animations()
playButton.setOnClickListener {
val intent = Intent(this, GameActivity::class.java)
startActivity(intent)
}
howButton.setOnClickListener {
val intent = Intent(this,RulesActivity::class.java)
startActivity(intent)
}
fishImage.setOnClickListener {
animation.fishAnimation(fishImage)
}
}
} | Go-fish/app/src/main/java/com/example/gofish/HomeActivity.kt | 4042635860 |
package com.example.gofish
import android.widget.TextView
import java.util.Random
open class Player (val name:String) {
var hand = mutableListOf<Card>()
var score = 0
fun addCardToHand(card: Card) {
hand.add(card)
}
fun removeCardFromHand(card: Card) {
hand.remove(card)
}
fun giveCard(otherPlayer : Player, card: Card): Card?{
val card = hand.find { it.value == card.value }
if(card!=null){
removeCardFromHand(card)
otherPlayer.addCardToHand(card)
return card
}
return null
}
fun showScore():String{
return "Score : $score"
}
fun selectCardToChoose(cardList: List<Card>):Card?{
if(cardList.isNotEmpty()) {
val random = Random()
val randomCardIndex = random.nextInt(cardList.size)
return cardList[randomCardIndex]
}
return null
}
} | Go-fish/app/src/main/java/com/example/gofish/Player.kt | 721668637 |
package com.example.gofish
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
class RulesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rules)
var titleTextView : TextView = findViewById(R.id.theRulesText)
var fishRulesImage = findViewById<ImageView>(R.id.fishRulesImage)
var rulesTextView1 : TextView = findViewById(R.id.rulesTextView1)
var rulesTextView2 : TextView = findViewById(R.id.rulesTextView2)
var rulesTextView3 : TextView = findViewById(R.id.rulesTextView3)
var rulesText4 : TextView = findViewById(R.id.rulesText4)
var rulesText5: TextView = findViewById(R.id.rulesText5)
var rulesText6 : TextView = findViewById(R.id.rulesText6)
var goBackButton : Button = findViewById(R.id.goBackButton)
goBackButton.setOnClickListener {
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
}
} | Go-fish/app/src/main/java/com/example/gofish/RulesActivity.kt | 3787529596 |
package com.example.gofish
interface CardClickListener {
fun onCardClick( card: Card)
} | Go-fish/app/src/main/java/com/example/gofish/CardClickListener.kt | 3929057776 |
package com.example.gofish
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.media.Image
import android.view.View
import android.widget.ImageView
class Animations {
fun seaCardAnimations(view : View){
val moveUpAnimator = ObjectAnimator.ofFloat(view, "translationY", -100f, 0f)
moveUpAnimator.duration = 1000
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", -0f, -50f)
moveDownAnimator.duration = 1000
val animatorSet = AnimatorSet()
animatorSet.playSequentially(moveUpAnimator, moveDownAnimator)
animatorSet.start()
}
fun fishAnimation(view : ImageView){
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", -0f, 700f)
moveDownAnimator.duration = 2000
val moveUpAnimator = ObjectAnimator.ofFloat(view, "translationY", 500f, 300f)
moveUpAnimator.duration = 1000
val moveLeftAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f,-400f)
moveLeftAnimator.duration=1000
val bigXAnimator= ObjectAnimator.ofFloat(view,"scaleX",1.0f,3.0f)
val bigYAnimator= ObjectAnimator.ofFloat(view,"scaleY",1.0f,3.0f)
bigXAnimator.duration=2000
bigYAnimator.duration=2000
val animatorSet = AnimatorSet()
val animatorSet2 = AnimatorSet()
view.setImageResource(R.drawable.redfish2)
animatorSet.playTogether(moveDownAnimator,moveUpAnimator,moveLeftAnimator,moveUpAnimator)
animatorSet2.playTogether(bigXAnimator,bigYAnimator)
animatorSet.start()
animatorSet2.start()
}
fun cardFromSeaHuman(view : ImageView){
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", 200f, 900f)
val moveRightAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f, 350f)
moveDownAnimator.duration = 1500
val animatorSet = AnimatorSet()
moveRightAnimator.duration = 1000
animatorSet.playTogether(moveDownAnimator, moveRightAnimator)
animatorSet.start()
}
fun cardFromSeaComputer(view : ImageView){
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", 400f, -100f)
val moveRightAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f, 350f)
moveDownAnimator.duration = 1500
val animatorSet = AnimatorSet()
moveRightAnimator.duration = 1000
animatorSet.playTogether(moveDownAnimator, moveRightAnimator)
animatorSet.start()
}
fun givenCardHuman(view : ImageView){
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", -0f, 800f)
val moveRightAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f, 350f)
moveDownAnimator.duration = 1000
val animatorSet = AnimatorSet()
moveRightAnimator.duration = 1000
animatorSet.playTogether(moveDownAnimator, moveRightAnimator)
animatorSet.start()
}
fun givenCardComputer(view:ImageView){
val moveUpAnimator = ObjectAnimator.ofFloat(view, "translationY", 800f, 0f)
moveUpAnimator.duration = 1000
val moveRightAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f, 350f)
moveRightAnimator.duration = 1000
val animatorSet = AnimatorSet()
animatorSet.playTogether(moveUpAnimator, moveRightAnimator)
animatorSet.start()
}
fun goFish(view:ImageView){
val moveUpAnimator = ObjectAnimator.ofFloat(view, "translationY", -100f, 0f)
moveUpAnimator.duration = 500
val moveDownAnimator = ObjectAnimator.ofFloat(view, "translationY", -0f, -50f)
moveDownAnimator.duration = 500
val animatorSet = AnimatorSet()
animatorSet.playSequentially(moveUpAnimator, moveDownAnimator)
animatorSet.start()
}
}
| Go-fish/app/src/main/java/com/example/gofish/Animations.kt | 3818182977 |
package com.example.gofish
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
class CardAdapter(val context: Context,
var handCards: MutableList<Card>,
val cardClickListener: CardClickListener,
val isClickable: Boolean
):
RecyclerView.Adapter<CardAdapter.ViewHolder>() {
val layoutInflater = LayoutInflater.from(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardAdapter.ViewHolder {
val itemView = layoutInflater.inflate(R.layout.card_item,parent,false)
return ViewHolder(itemView)
}
override fun getItemCount(): Int {
return handCards.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val card = handCards[position]
Log.d("CardAdapter", "Binding card at position $position. Card: $card")
if(card.isFaceUp){
holder.cardImage.setImageResource(card.faceUpImage)
}
else{
holder.cardImage.setImageResource(card.faceDownImage)
}
if(isClickable) {
holder.cardImage.setOnClickListener {
cardClickListener.onCardClick(card)
}
}
}
fun removeItem(position: Int): Card {
val removedCard = handCards.removeAt(position)
notifyItemRemoved(position)
return removedCard
}
fun addItem(card: Card, position: Int = handCards.size) {
handCards.add(position, card)
notifyItemInserted(position)
}
inner class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
val cardImage: ImageView = itemView.findViewById<ImageView>(R.id.cardImage)
}
}
| Go-fish/app/src/main/java/com/example/gofish/CardAdapter.kt | 2558242652 |
package com.example.gofish
import java.util.Random
class Computer(name: String) : Player(name) {
}
fun selectCardToChoose(cardList: List<Card>):Card?{
if(cardList.isNotEmpty()) {
val random = Random()
val randomCardIndex = random.nextInt(cardList.size)
return cardList[randomCardIndex]
}
return null
} | Go-fish/app/src/main/java/com/example/gofish/Computer.kt | 800739291 |
package com.example.gofish
class Human(name :String) : Player(name) {
} | Go-fish/app/src/main/java/com/example/gofish/Human.kt | 2154038045 |
package com.demo.DroneMed
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DroneMedApplicationTests {
@Test
fun contextLoads() {
}
}
| DroneMedApplication/src/test/kotlin/com/demo/DroneMed/DroneMedApplicationTests.kt | 1756430646 |
package com.demo.DroneMed
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DroneMedApplication
fun main(args: Array<String>) {
runApplication<DroneMedApplication>(*args)
}
| DroneMedApplication/src/main/kotlin/com/demo/DroneMed/DroneMedApplication.kt | 4202065951 |
package org.kreier.wificar23
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("org.kreier.wificar23", appContext.packageName)
}
} | Wificar23/app/src/androidTest/java/org/kreier/wificar23/ExampleInstrumentedTest.kt | 1251156699 |
package org.kreier.wificar23
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)
}
} | Wificar23/app/src/test/java/org/kreier/wificar23/ExampleUnitTest.kt | 3314531724 |
package org.kreier.wificar23
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
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
}
}
} | Wificar23/app/src/main/java/org/kreier/wificar23/MainActivity.kt | 2337307569 |
package fr.totolastro.pricetracker
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class PriceTrackerApplicationTests {
@Test
fun contextLoads() {
}
}
| price-tracker/src/test/kotlin/fr/totolastro/pricetracker/PriceTrackerApplicationTests.kt | 1113126016 |
package fr.totolastro.pricetracker
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class PriceTrackerApplication
fun main(args: Array<String>) {
runApplication<PriceTrackerApplication>(*args)
}
| price-tracker/src/main/kotlin/fr/totolastro/pricetracker/PriceTrackerApplication.kt | 4142217483 |
package com.example.myapplication
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | Proyecto-Integrador-Android/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Proyecto-Integrador-Android/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Proyecto-Integrador-Android/app/src/main/java/com/example/myapplication/ui/theme/Color.kt | 2513741509 |
package com.example.myapplication.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MyApplicationTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Proyecto-Integrador-Android/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt | 196007232 |
package com.example.myapplication.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Proyecto-Integrador-Android/app/src/main/java/com/example/myapplication/ui/theme/Type.kt | 3481532690 |
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
Greeting("Android")
}
} | Proyecto-Integrador-Android/app/src/main/java/com/example/myapplication/MainActivity.kt | 1231236054 |
package com.example.geminichat
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.geminichat", appContext.packageName)
}
} | Gemini-Demo/app/src/androidTest/java/com/example/geminichat/ExampleInstrumentedTest.kt | 2809754424 |
package com.example.geminichat
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)
}
} | Gemini-Demo/app/src/test/java/com/example/geminichat/ExampleUnitTest.kt | 764788558 |
package com.example.geminichat.ui.component
import androidx.compose.foundation.gestures.GestureCancellationException
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.AwaitPointerEventScope
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventTimeoutCancellationException
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.changedToDown
import androidx.compose.ui.input.pointer.changedToDownIgnoreConsumed
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.input.pointer.isOutOfBounds
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.unit.Density
import androidx.compose.ui.util.fastAll
import androidx.compose.ui.util.fastAny
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
/**
* Receiver scope for [myDetectTapGestures]'s `onPress` lambda. This offers
* two methods to allow waiting for the press to be released.
*/
interface PressGestureScope : Density {
/**
* Waits for the press to be released before returning. If the gesture was canceled by
* motion being consumed by another gesture, [GestureCancellationException] will be
* thrown.
*/
suspend fun awaitRelease()
/**
* Waits for the press to be released before returning. If the press was released,
* `true` is returned, or if the gesture was canceled by motion being consumed by
* another gesture, `false` is returned .
*/
suspend fun tryAwaitRelease(): Boolean
}
private val NoPressGesture: suspend PressGestureScope.(Offset) -> Unit = { }
/**
* Detects tap, double-tap, and long press gestures and calls [onTap], [onDoubleTap], and
* [onLongPress], respectively, when detected. [onPress] is called when the press is detected
* and the [PressGestureScope.tryAwaitRelease] and [PressGestureScope.awaitRelease] can be
* used to detect when pointers have released or the gesture was canceled.
* The first pointer down and final pointer up are consumed, and in the
* case of long press, all changes after the long press is detected are consumed.
*
* Each function parameter receives an [Offset] representing the position relative to the containing
* element. The [Offset] can be outside the actual bounds of the element itself meaning the numbers
* can be negative or larger than the element bounds if the touch target is smaller than the
* [ViewConfiguration.minimumTouchTargetSize].
*
* When [onDoubleTap] is provided, the tap gesture is detected only after
* the [ViewConfiguration.doubleTapMinTimeMillis] has passed and [onDoubleTap] is called if the
* second tap is started before [ViewConfiguration.doubleTapTimeoutMillis]. If [onDoubleTap] is not
* provided, then [onTap] is called when the pointer up has been received.
*
* After the initial [onPress], if the pointer moves out of the input area, the position change
* is consumed, or another gesture consumes the down or up events, the gestures are considered
* canceled. That means [onDoubleTap], [onLongPress], and [onTap] will not be called after a
* gesture has been canceled.
*
* If the first down event is consumed somewhere else, the entire gesture will be skipped,
* including [onPress].
*/
suspend fun PointerInputScope.myDetectTapGestures(
onDoubleTap: ((Offset) -> Unit)? = null,
onLongPress: ((Offset) -> Unit)? = null,
onPress: suspend PressGestureScope.(Offset) -> Unit = NoPressGesture,
onTap: ((Offset) -> Unit)? = null
) = coroutineScope {
// special signal to indicate to the sending side that it shouldn't intercept and consume
// cancel/up events as we're only require down events
val pressScope = PressGestureScopeImpl(this@myDetectTapGestures)
awaitEachGesture {
val down = awaitFirstDown()
//down.consume()
launch {
pressScope.reset()
}
if (onPress !== NoPressGesture) launch {
pressScope.onPress(down.position)
}
val longPressTimeout = onLongPress?.let {
viewConfiguration.longPressTimeoutMillis
} ?: (Long.MAX_VALUE / 2)
var upOrCancel: PointerInputChange? = null
try {
// wait for first tap up or long press
upOrCancel = withTimeout(longPressTimeout) {
waitForUpOrCancellation()
}
if (upOrCancel == null) {
launch {
pressScope.cancel() // tap-up was canceled
}
} else {
//upOrCancel.consume()
launch {
pressScope.release()
}
}
} catch (_: PointerEventTimeoutCancellationException) {
onLongPress?.invoke(down.position)
//consumeUntilUp()
launch {
pressScope.release()
}
}
if (upOrCancel != null) {
// tap was successful.
if (onDoubleTap == null) {
onTap?.invoke(upOrCancel.position) // no need to check for double-tap.
} else {
// check for second tap
val secondDown = awaitSecondDown(upOrCancel)
if (secondDown == null) {
onTap?.invoke(upOrCancel.position) // no valid second tap started
} else {
// Second tap down detected
launch {
pressScope.reset()
}
if (onPress !== NoPressGesture) {
launch { pressScope.onPress(secondDown.position) }
}
try {
// Might have a long second press as the second tap
withTimeout(longPressTimeout) {
val secondUp = waitForUpOrCancellation()
if (secondUp != null) {
//secondUp.consume()
launch {
pressScope.release()
}
onDoubleTap(secondUp.position)
} else {
launch {
pressScope.cancel()
}
onTap?.invoke(upOrCancel.position)
}
}
} catch (e: PointerEventTimeoutCancellationException) {
// The first tap was valid, but the second tap is a long press.
// notify for the first tap
onTap?.invoke(upOrCancel.position)
// notify for the long press
onLongPress?.invoke(secondDown.position)
//consumeUntilUp()
launch {
pressScope.release()
}
}
}
}
}
}
}
/**
* Waits for [ViewConfiguration.doubleTapTimeoutMillis] for a second press event. If a
* second press event is received before the time out, it is returned or `null` is returned
* if no second press is received.
*/
private suspend fun AwaitPointerEventScope.awaitSecondDown(
firstUp: PointerInputChange
): PointerInputChange? = withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) {
val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis
var change: PointerInputChange
// The second tap doesn't count if it happens before DoubleTapMinTime of the first tap
do {
change = awaitFirstDown()
} while (change.uptimeMillis < minUptime)
change
}
/**
* Reads events until the first down is received in the given [pass]. If [requireUnconsumed] is
* `true` and the first down is already consumed in the pass, that gesture is ignored.
*/
suspend fun AwaitPointerEventScope.awaitFirstDown(
requireUnconsumed: Boolean = true,
pass: PointerEventPass = PointerEventPass.Main,
): PointerInputChange {
var event: PointerEvent
do {
event = awaitPointerEvent(pass)
} while (
!event.changes.fastAll {
if (requireUnconsumed) it.changedToDown() else it.changedToDownIgnoreConsumed()
}
)
return event.changes[0]
}
/**
* Reads events in the given [pass] until all pointers are up or the gesture was canceled.
* The gesture is considered canceled when a pointer leaves the event region, a position
* change has been consumed or a pointer down change event was already consumed in the given
* pass. If the gesture was not canceled, the final up change is returned or `null` if the
* event was canceled.
*/
suspend fun AwaitPointerEventScope.waitForUpOrCancellation(
pass: PointerEventPass = PointerEventPass.Main
): PointerInputChange? {
while (true) {
val event = awaitPointerEvent(pass)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
return event.changes[0]
}
if (event.changes.fastAny {
it.isConsumed || it.isOutOfBounds(size, extendedTouchPadding)
}
) {
return null // Canceled
}
// Check for cancel by position consumption. We can look on the Final pass of the
// existing pointer event because it comes after the pass we checked above.
val consumeCheck = awaitPointerEvent(PointerEventPass.Final)
if (consumeCheck.changes.fastAny { it.isConsumed }) {
return null
}
}
}
/**
* [myDetectTapGestures]'s implementation of [PressGestureScope].
*/
private class PressGestureScopeImpl(
density: Density
) : PressGestureScope, Density by density {
private var isReleased = false
private var isCanceled = false
private val mutex = Mutex(locked = false)
/**
* Called when a gesture has been canceled.
*/
fun cancel() {
isCanceled = true
mutex.unlock()
}
/**
* Called when all pointers are up.
*/
fun release() {
isReleased = true
mutex.unlock()
}
/**
* Called when a new gesture has started.
*/
suspend fun reset() {
mutex.lock()
isReleased = false
isCanceled = false
}
override suspend fun awaitRelease() {
if (!tryAwaitRelease()) {
throw GestureCancellationException("The press gesture was canceled.")
}
}
override suspend fun tryAwaitRelease(): Boolean {
if (!isReleased && !isCanceled) {
mutex.lock()
mutex.unlock()
}
return isReleased
}
}
| Gemini-Demo/app/src/main/java/com/example/geminichat/ui/component/MyTapGestureDetector.kt | 3927443526 |
package com.example.geminichat.ui.component
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.awaitLongPressOrCancellation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
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.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.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.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.PointerType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import com.example.geminichat.R
import com.example.geminichat.ui.data.Conversation
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.time.withTimeout
import kotlinx.coroutines.withTimeout
private const val TAG = "ChatField"
@Preview
@Composable
fun ChatField(
modifier: Modifier = Modifier,
mutableConversationFlowList: MutableList<MutableStateFlow<Conversation>> = mutableListOf()
) {
LazyColumn(modifier = modifier.fillMaxWidth()) {
for (conversation in mutableConversationFlowList) {
item {
ChatItem(
name = conversation.collectAsState().value.role,
message = conversation.collectAsState().value.message
)
}
}
}
}
@Preview
@Composable
fun ChatItem(
name: String = "YOU",
message: String = "Message"
) {
var isExpanded by remember { mutableStateOf(false) }
var offset by remember { mutableStateOf(DpOffset(0.dp, 0.dp)) }
Surface {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { }
.pointerInput(Unit) {
myDetectTapGestures(
onLongPress = {
offset = DpOffset(it.x.toDp(), it.y.toDp())
isExpanded = true
}
)
},
verticalArrangement = Arrangement.Center
) {
Row(verticalAlignment = Alignment.CenterVertically) {
when (name) {
"YOU" -> Icon(
imageVector = Icons.Default.Person,
contentDescription = null,
modifier = Modifier
.padding(horizontal = 5.dp)
.width(20.dp)
)
else -> Image(
painter = painterResource(id = R.drawable.gemini_icon),
contentDescription = null,
modifier = Modifier
.padding(horizontal = 5.dp)
.width(20.dp)
)
}
Text(text = name)
}
Text(
text = message,
modifier = Modifier.padding(start = 30.dp, end = 10.dp, bottom = 10.dp),
style = MaterialTheme.typography.bodyLarge
)
}
Box(modifier = Modifier.offset(offset.x, offset.y)) {
DropdownMenu(
expanded = isExpanded,
onDismissRequest = { isExpanded = false }
) {
val clipboardManager = LocalClipboardManager.current
DropdownMenuItem(
leadingIcon = {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = null
)
},
text = { Text(text = "Copy") },
onClick = {
clipboardManager.setText(AnnotatedString(message))
isExpanded = false
}
)
DropdownMenuItem(
leadingIcon = {
Icon(
imageVector = Icons.Default.SelectAll,
contentDescription = null
)
},
text = { Text(text = "Select Text") },
onClick = {
}
)
}
}
}
}
suspend fun PointerInputScope.interceptTap(
pass: PointerEventPass = PointerEventPass.Initial,
onTap: ((Offset) -> Unit)? = null,
) = coroutineScope {
if (onTap == null) return@coroutineScope
awaitEachGesture {
val down = awaitFirstDown(pass = pass)
val downTime = System.currentTimeMillis()
val tapTimeout = viewConfiguration.longPressTimeoutMillis
val tapPosition = down.position
do {
val event = awaitPointerEvent(pass)
val currentTime = System.currentTimeMillis()
if (event.changes.size != 1) break // More than one event: not a tap
if (currentTime - downTime >= tapTimeout) break // Too slow: not a tap
val change = event.changes[0]
// Too much movement: not a tap
if ((change.position - tapPosition).getDistance() > viewConfiguration.touchSlop) break
if (change.id == down.id && !change.pressed) {
change.consume()
onTap(change.position)
}
} while (event.changes.any { it.id == down.id && it.pressed })
}
} | Gemini-Demo/app/src/main/java/com/example/geminichat/ui/component/ChatField.kt | 1066329194 |
package com.example.geminichat.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)
val Navy = Color(0xFF073042)
val Blue = Color(0xFF4285F4)
val LightBlue = Color(0xFFD7EFFE)
val Chartreuse = Color(0xFFEFF7CF)
| Gemini-Demo/app/src/main/java/com/example/geminichat/ui/theme/Color.kt | 3542017880 |
package com.example.geminichat.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.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
//private val DarkColorScheme = darkColorScheme(
// primary = Purple80,
// secondary = PurpleGrey80,
// tertiary = Pink80
//)
//
//private val LightColorScheme = lightColorScheme(
// primary = Purple40,
// secondary = PurpleGrey40,
// tertiary = Pink40
//)
private val LightColorScheme = lightColorScheme(
surface = Blue,
onSurface = Color.White,
primary = LightBlue,
onPrimary = Navy
)
private val DarkColorScheme = darkColorScheme(
surface = Blue,
onSurface = Navy,
primary = Navy,
onPrimary = Chartreuse
)
/* 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 GeminiChatTheme(
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
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Gemini-Demo/app/src/main/java/com/example/geminichat/ui/theme/Theme.kt | 866373831 |
package com.example.geminichat.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
)
*/
) | Gemini-Demo/app/src/main/java/com/example/geminichat/ui/theme/Type.kt | 332489818 |
package com.example.geminichat.ui.screen
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Sort
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
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.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.geminichat.R
import com.example.geminichat.ui.component.ChatField
import com.example.geminichat.ui.data.Conversation
import com.example.geminichat.ui.data.MainScreenViewModel
import com.example.geminichat.ui.theme.GeminiChatTheme
import kotlinx.coroutines.launch
private const val TAG = "MainScreen"
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun MainScreen(
mainScreenViewModel: MainScreenViewModel = viewModel()
) {
val context = LocalContext.current
val mutableConversationFlowList = mainScreenViewModel.mutableConversationsFlowList
val updatedIndex by mainScreenViewModel.updateIndex.collectAsState()
val isGenerating by mainScreenViewModel.isGenerating.collectAsState()
var message by remember { mutableStateOf("") }
GeminiChatTheme {
Surface(
modifier = Modifier
.fillMaxSize()
) {
Column {
TopAppBar(
title = {
Row {
Text(
"Gemini",
modifier = Modifier.padding(vertical = 10.dp, horizontal = 5.dp)
)
Text(
text = "Demo",
modifier = Modifier.padding(vertical = 10.dp),
color = MaterialTheme.colorScheme.primary
)
}
},
navigationIcon = {
Icon(
imageVector = Icons.AutoMirrored.Filled.Sort,
contentDescription = null
)
},
actions = {
Icon(imageVector = Icons.Default.Edit, contentDescription = null)
Spacer(modifier = Modifier.width(20.dp))
Icon(imageVector = Icons.Default.MoreVert, contentDescription = null)
}
)
ChatField(
modifier = Modifier.weight(1f),
mutableConversationFlowList = mutableConversationFlowList
)
Row(verticalAlignment = Alignment.CenterVertically) {
TextField(
value = message,
onValueChange = { message = it },
placeholder = {
Text(
"Message"
)
},
modifier = Modifier
.padding(start = 10.dp)
.padding(10.dp)
.clip(MaterialTheme.shapes.extraLarge)
.weight(1f),
colors = TextFieldDefaults.colors(
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
)
Box(
modifier = Modifier
.padding(end = 20.dp),
contentAlignment = Alignment.Center
) {
val focusManager = LocalFocusManager.current
Icon(
imageVector = if (!isGenerating) Icons.Default.ArrowUpward
else Icons.Default.Stop,
tint = if (isGenerating) MaterialTheme.colorScheme.surfaceVariant
else MaterialTheme.colorScheme.onSurfaceVariant,
contentDescription = null,
modifier = Modifier
.clip(MaterialTheme.shapes.extraLarge)
.background(
if (!isGenerating) MaterialTheme.colorScheme.surfaceVariant
else MaterialTheme.colorScheme.onSurfaceVariant,
MaterialTheme.shapes.small
)
.padding(10.dp)
.clickable(
enabled = !isGenerating,
onClick = {
focusManager.clearFocus()
mainScreenViewModel.changeGenerateState()
val tempMessage = message
message = ""
mainScreenViewModel.addConversation(
Conversation(
"YOU",
tempMessage
)
)
mainScreenViewModel.updateScreen()
mainScreenViewModel.viewModelScope.launch {
mainScreenViewModel.sendMessage(tempMessage,context)
}
},
indication = null,
interactionSource = remember {
MutableInteractionSource()
}
)
)
}
}
}
}
}
if (updatedIndex == 0) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.gemini_background),
contentDescription = null,
modifier = Modifier.scale(0.4f)
)
}
}
} | Gemini-Demo/app/src/main/java/com/example/geminichat/ui/screen/MainScreen.kt | 2160111374 |
package com.example.geminichat.ui.data
import android.content.Context
import android.widget.Toast
import androidx.lifecycle.ViewModel
import com.example.geminichat.BuildConfig
import com.google.ai.client.generativeai.GenerativeModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlin.coroutines.coroutineContext
private const val TAG = "MainScreenViewModel"
class MainScreenViewModel : ViewModel() {
private val generativeModel by lazy {
GenerativeModel(
modelName = "gemini-pro",
apiKey = BuildConfig.apiKey
)
}
private val chat by lazy {
generativeModel.startChat()
}
val mutableConversationsFlowList: MutableList<MutableStateFlow<Conversation>> = mutableListOf()
val updateIndex: MutableStateFlow<Int> = MutableStateFlow(0)
val isGenerating: MutableStateFlow<Boolean> = MutableStateFlow(false)
suspend fun sendMessage(message: String, context: Context) {
try {
val response = chat.sendMessage(message).text ?: "Something go wrong."
addConversation(Conversation("GEMINI", response))
} catch (e: Exception) {
Toast.makeText(context, "Error: ${e.message}", Toast.LENGTH_LONG).show()
}
changeGenerateState()
}
fun addConversation(conversation: Conversation) {
mutableConversationsFlowList.add(MutableStateFlow(conversation))
updateScreen()
}
fun updateScreen() {
updateIndex.update { it + 1 }
}
fun changeGenerateState() {
isGenerating.update { !it }
}
}
| Gemini-Demo/app/src/main/java/com/example/geminichat/ui/data/MainScreenViewModel.kt | 2549901535 |
package com.example.geminichat.ui.data
data class Conversation(val role: String, val message: String) | Gemini-Demo/app/src/main/java/com/example/geminichat/ui/data/Conversation.kt | 3129289247 |
package com.example.geminichat
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.os.BuildCompat
import com.example.geminichat.ui.screen.MainScreen
import com.example.geminichat.ui.theme.GeminiChatTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MainScreen()
}
}
} | Gemini-Demo/app/src/main/java/com/example/geminichat/MainActivity.kt | 43714191 |
class Pedido {
} | 1dam-restaurante-poo-lnarote777/Restaurante/src/main/kotlin/Pedido.kt | 2046343521 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.