content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.journalapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.databinding.DataBindingUtil import com.example.journalapp.databinding.ActivitySigninBinding import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.auth class SigninActivity : AppCompatActivity() { lateinit var binding: ActivitySigninBinding private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this,R.layout.activity_signin) auth = Firebase.auth binding.signinbtn.setOnClickListener { createUser() } } private fun createUser() { val email = binding.crateemail.text.toString() val password = binding.createpassword.text.toString() auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d("TAGY", "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w("TAGY", "createUserWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } } } private fun updateUI(user: FirebaseUser?) { } public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if (currentUser != null) { reload() } } public fun reload() { } }
Journal_App/app/src/main/java/com/example/journalapp/SigninActivity.kt
2998866699
package com.example.journalapp import android.app.Application class JournalUser: Application() { var username:String? = null var userId: String?= null companion object{ var instance: JournalUser? = null get() { if(field == null){ field = JournalUser() } return field } private set } }
Journal_App/app/src/main/java/com/example/journalapp/JournalUser.kt
1465068673
package com.example.journalapp import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.TextView import android.widget.Toast import androidx.annotation.RequiresApi import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.journalapp.databinding.ActivityJournalListBinding import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.auth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.StorageReference import java.sql.Timestamp import kotlin.collections.ArrayList class Journal_list : AppCompatActivity() { //retrive data lateinit var dbb: DatabaseReference private lateinit var itemrecyclerview: RecyclerView private lateinit var itemarraylist: ArrayList<Journal> lateinit var binding: ActivityJournalListBinding lateinit var journalList: MutableList<Journal> lateinit var adapter: JournalRecyclerAdapter var eventListener:ValueEventListener? = null //Firebase Refrences lateinit var firebaseAuth: FirebaseAuth lateinit var user: FirebaseUser var db = FirebaseFirestore.getInstance() lateinit var storageReference: StorageReference var collectionReference: CollectionReference = db.collection("Journals") lateinit var nopostTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_journal_list) itemrecyclerview = findViewById(R.id.recyclerView) itemrecyclerview.layoutManager = LinearLayoutManager(this) itemrecyclerview.hasFixedSize() // itemarraylist = arrayListOf<Journal>() // getitemData() //Firebase Auth firebaseAuth = Firebase.auth user = firebaseAuth.currentUser!! //Recyclerview binding.recyclerView.setHasFixedSize(true) binding.recyclerView.layoutManager = LinearLayoutManager(this) //Post araylist journalList = arrayListOf<Journal>() } /* private fun getitemData() { dbb = FirebaseDatabase.getInstance().getReference("Journals") dbb.addValueEventListener(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { if(snapshot.exists()){ for(itmsnapshot in snapshot.children){ val item = itmsnapshot.getValue(Journal::class.java) itemarraylist.add(item!!) } itemrecyclerview.adapter = JournalRecyclerAdapter(itemarraylist) } } override fun onCancelled(error: DatabaseError) { } }) }*/ override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_add -> if (user != null && firebaseAuth != null) { val intent = Intent(this, AddJournalActivity::class.java) startActivity(intent) } R.id.action_signout -> { if (user != null && firebaseAuth != null) { firebaseAuth.signOut() val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } } return super.onOptionsItemSelected(item) } //Getting all post override fun onStart(){ super.onStart() collectionReference.whereEqualTo("userId", user.uid) .get() .addOnSuccessListener { Log.i("TAGY","sizey:${it.size()}") if (!it.isEmpty) { Log.i("TAGY","Elements: ${it}") for(document in it){ var journals = Journal( document.data["title"].toString(), document.data.get("thoughts").toString(), document.data.get("imageUri").toString(), document.data.get("userId").toString(), document.data.get("timestamp") as com.google.firebase.Timestamp, document.data.get("userName").toString(), ) journalList.add(journals) } //Recyclerview binding.recyclerView.setAdapter(adapter) adapter.notifyDataSetChanged() } }.addOnFailureListener { Toast.makeText( this, "Opps! Something went wrong!", Toast.LENGTH_SHORT ).show() } } @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) override fun onBackPressed() { super.onBackPressed() finishAffinity() // Finish the current activity and all parent activities } }
Journal_App/app/src/main/java/com/example/journalapp/Journal_list.kt
1559136576
package com.example.myocrapp 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.myocrapp", appContext.packageName) } }
OCR_app/app/src/androidTest/java/com/example/myocrapp/ExampleInstrumentedTest.kt
1293787906
package com.example.myocrapp 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) } }
OCR_app/app/src/test/java/com/example/myocrapp/ExampleUnitTest.kt
1662558209
package com.example.myocrapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
OCR_app/app/src/main/java/com/example/myocrapp/MainActivity.kt
3021800444
package com.cloffygames.gpacalculator 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.cloffygames.gpacalculator", appContext.packageName) } }
GPA_Calculator/app/src/androidTest/java/com/cloffygames/gpacalculator/ExampleInstrumentedTest.kt
745569687
package com.cloffygames.gpacalculator 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) } }
GPA_Calculator/app/src/test/java/com/cloffygames/gpacalculator/ExampleUnitTest.kt
4049095780
package com.cloffygames.gpacalculator.ui.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.cloffygames.gpacalculator.data.entity.Department import com.cloffygames.gpacalculator.databinding.CardDepartmentBinding class DepartmentAdapter(var dContext: Context, var departmentList : List<Department>) : RecyclerView.Adapter<DepartmentAdapter.CardDesignHolder>(){ inner class CardDesignHolder(var design : CardDepartmentBinding) : RecyclerView.ViewHolder(design.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardDesignHolder { val binding = CardDepartmentBinding.inflate(LayoutInflater.from(dContext), parent, false) return CardDesignHolder(binding) } override fun onBindViewHolder(holder: CardDesignHolder, position: Int) { val department = departmentList.get(position) val d = holder.design d.departmentName.text = department.name d.GPAText.text = department.gpa.toString() } override fun getItemCount(): Int { return departmentList.size } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/adapter/DepartmentAdapter.kt
1995074844
package com.cloffygames.gpacalculator.ui.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.recyclerview.widget.RecyclerView import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.ItemSemesterBinding class SemesterAdapter(var sContext: Context, var lessonCount : Int) : RecyclerView.Adapter<SemesterAdapter.ItemDesignHolder>() { inner class ItemDesignHolder(var item : ItemSemesterBinding) : RecyclerView.ViewHolder(item.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemDesignHolder { val binding = ItemSemesterBinding.inflate(LayoutInflater.from(sContext), parent, false) return ItemDesignHolder(binding) } override fun onBindViewHolder(holder: ItemDesignHolder, position: Int) { val binding = holder.item // Bir ArrayAdapter oluşturur ve kaynak olarak bir string-array verir val creditAdapter = ArrayAdapter.createFromResource( sContext, R.array.credit_array, R.layout.spinner_item ) // Bir ArrayAdapter oluşturur ve kaynak olarak bir string-array verir val scoreAdapter = ArrayAdapter.createFromResource( sContext, R.array.score_array_1, R.layout.spinner_item ) // Bir ArrayAdapter oluşturur ve kaynak olarak bir string-array verir val adapter = ArrayAdapter.createFromResource( sContext, R.array.semester_array, R.layout.spinner_item ) // Spinner'ın açılır menüsü için bir düzen belirler adapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item) // Spinner'a adapter'ı uygular binding.spinnerCredit.adapter = creditAdapter binding.spinnerScore.adapter = scoreAdapter // Spinner'dan seçilen değeri tutmak için bir değişken tanımlar var selectedCredit = "0" var selectedScore = "0" binding.spinnerCredit.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Adapter'dan seçilen değeri alır ve değişkene atar selectedCredit = creditAdapter.getItem(position).toString() } // Spinner'da hiçbir seçim yapılmadığında bu metod çalışır override fun onNothingSelected(parent: AdapterView<*>?) { // Hiçbir şey yapmaz } } // Spinner'a bir seçim dinleyicisi atar binding.spinnerScore.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Adapter'dan seçilen değeri alır ve değişkene atar selectedScore = scoreAdapter.getItem(position).toString() } // Spinner'da hiçbir seçim yapılmadığında bu metod çalışır override fun onNothingSelected(parent: AdapterView<*>?) { // Hiçbir şey yapmaz } } } override fun getItemCount(): Int { return lessonCount } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/adapter/SemesterAdapter.kt
1415165110
package com.cloffygames.gpacalculator.ui.fragment import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.Navigation import com.cloffygames.gpacalculator.databinding.FragmentSplashBinding class SplashFragment : Fragment() { private lateinit var binding: FragmentSplashBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentSplashBinding.inflate(inflater, container, false) // SharedPreferences'a bağlan. val preferences = requireActivity().getSharedPreferences("com.cloffygames.gpacalculator", Context.MODE_PRIVATE) // İlk defa açılma bilgisini al. val checkFirstOpen = preferences.getBoolean("check_first_open", true) binding.apply { // ImageView'ın alpha değerini sıfıra ayarla. imageView.alpha = 0f // ImageView'ın alpha değerini 1'e animasyonlu bir şekilde artır. imageView.animate().setDuration(1500).alpha(1f).withEndAction { if (checkFirstOpen) { // İlk defa açılma bilgisini güncelle. preferences.edit().putBoolean("check_first_open", false).apply() // Uygulama ilk defa açıldıysa .... ekranına git. } else { // Ana ekrana git. goHomeActivity() } // Geçiş efektini uygula. activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) // Aktiviteyi kapat. activity?.finish() } // TextView'ın alpha değerini sıfıra ayarla. textView2.alpha = 0f // TextView'ın alpha değerini 1'e animasyonlu bir şekilde artır. textView2.animate().setDuration(1500).alpha(1f) } return binding.root } // Ana erkana gidiş fonksiyonu. fun goHomeActivity() { val transition = SplashFragmentDirections.actionSplashFragmentToMainActivity() Navigation.findNavController(requireView()).navigate(transition) } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/SplashFragment.kt
1267289951
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentLoginBinding import com.cloffygames.gpacalculator.databinding.FragmentMainBinding class LoginFragment : Fragment() { private lateinit var binding: FragmentLoginBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/LoginFragment.kt
125872977
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentSemesterBinding import com.cloffygames.gpacalculator.ui.adapter.SemesterAdapter class SemesterFragment : Fragment() { private lateinit var binding: FragmentSemesterBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentSemesterBinding.inflate(inflater, container, false) binding.recyclerView.layoutManager = LinearLayoutManager(requireContext()) val semesterAdapter = SemesterAdapter(requireContext(), binding.spinner.count) binding.recyclerView.adapter = semesterAdapter // Bir ArrayAdapter oluşturur ve kaynak olarak bir string-array verir val adapter = ArrayAdapter.createFromResource( requireContext(), R.array.semester_array, R.layout.spinner_item ) // Spinner'ın açılır menüsü için bir düzen belirler adapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item) // Spinner'a adapter'ı uygular binding.spinner.adapter = adapter // Spinner'dan seçilen değeri tutmak için bir değişken tanımlar var selectedSemester = "0" // Spinner'a bir seçim dinleyicisi atar binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Adapter'dan seçilen değeri alır ve değişkene atar selectedSemester = adapter.getItem(position).toString() val semesterAdapter = SemesterAdapter(requireContext(), selectedSemester.toInt()) binding.recyclerView.adapter = semesterAdapter } // Spinner'da hiçbir seçim yapılmadığında bu metod çalışır override fun onNothingSelected(parent: AdapterView<*>?) { // Hiçbir şey yapmaz } } return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/SemesterFragment.kt
2849522272
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentDepartmentBinding class DepartmentFragment : Fragment() { private lateinit var binding: FragmentDepartmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentDepartmentBinding.inflate(inflater, container, false) return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/DepartmentFragment.kt
2652773350
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentAddDepartmentBinding class AddDepartmentFragment : Fragment() { private lateinit var binding: FragmentAddDepartmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentAddDepartmentBinding.inflate(inflater, container, false) // Bir ArrayAdapter oluşturur ve kaynak olarak bir string-array verir val adapter = ArrayAdapter.createFromResource( requireContext(), R.array.semester_array, R.layout.spinner_item ) // Spinner'ın açılır menüsü için bir düzen belirler adapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item) // Spinner'a adapter'ı uygular binding.spinner.adapter = adapter // Spinner'dan seçilen değeri tutmak için bir değişken tanımlar var selectedSemester = "0" // Spinner'a bir seçim dinleyicisi atar binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Adapter'dan seçilen değeri alır ve değişkene atar selectedSemester = adapter.getItem(position).toString() } // Spinner'da hiçbir seçim yapılmadığında bu metod çalışır override fun onNothingSelected(parent: AdapterView<*>?) { // Hiçbir şey yapmaz } } return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/AddDepartmentFragment.kt
3752148614
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentRegisterBinding class RegisterFragment : Fragment() { private lateinit var binding: FragmentRegisterBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/RegisterFragment.kt
161238836
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.SearchView.OnQueryTextListener import androidx.fragment.app.Fragment import androidx.navigation.Navigation import androidx.recyclerview.widget.LinearLayoutManager import com.cloffygames.gpacalculator.data.entity.Department import com.cloffygames.gpacalculator.databinding.FragmentMainBinding import com.cloffygames.gpacalculator.ui.adapter.DepartmentAdapter class MainFragment : Fragment() { private lateinit var binding: FragmentMainBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentMainBinding.inflate(inflater, container, false) binding.departmentsView.layoutManager = LinearLayoutManager(requireContext()) val departmentList = ArrayList<Department>() val d1 = Department(1,"Bilgisayar Mühendisliği", 2.85) val d2 = Department(1,"Makine Mühendisliği", 2.35) val d3 = Department(1,"Elektronik Mühendisliği", 3.85) val d4 = Department(1,"Endüstri Mühendisliği", 2.65) val d5 = Department(1,"Mekatronik Mühendisliği", 1.85) val d6 = Department(1,"Orman Mühendisliği", 4.00) departmentList.add(d1) departmentList.add(d2) departmentList.add(d3) departmentList.add(d4) departmentList.add(d5) departmentList.add(d6) val departmentAdapter = DepartmentAdapter(requireContext(), departmentList) binding.departmentsView.adapter = departmentAdapter // binding.addDepartmentButton tıklandığında bir işlem yapmak için bir tıklama dinleyicisi eklenir. binding.addDepartmentButton.setOnClickListener{ // Ana fragmentten Departman Ekleme fragmentine geçişi sağlayan bir action oluşturulur. val transfer = MainFragmentDirections.actionMainFragmentToAddDepartmentFragment() // Oluşturulan action kullanılarak fragment geçişi gerçekleştirilir. Navigation.findNavController(it).navigate(transfer) } // binding.fastCalculateButton tıklandığında bir işlem yapmak için bir tıklama dinleyicisi eklenir. binding.fastCalculateButton.setOnClickListener{ // Ana fragmentten Dönem fragmentine geçişi sağlayan bir action oluşturulur. val transfer = MainFragmentDirections.actionMainFragmentToSemesterFragment() // Oluşturulan action kullanılarak fragment geçişi gerçekleştirilir. Navigation.findNavController(it).navigate(transfer) } // binding.searchView üzerinde arama yapıldığında bu metot çağrılır. binding.searchView.setOnQueryTextListener(object : OnQueryTextListener{ // Yeni metin girildiğinde çağrılır. override fun onQueryTextChange(newText: String): Boolean { // Yeni metinle birlikte departman araması yapılır. searchDepartment(newText) return true } // Arama butonuna tıklandığında çağrılır. override fun onQueryTextSubmit(query: String): Boolean { // Girilen sorguyla birlikte departman araması yapılır. searchDepartment(query) return true } }) return binding.root } // Verilen arama sorgusunu kullanarak departman araması yapar. fun searchDepartment(searchQuery : String){ // Logcat'e arama sorgusu yazdırılır. Log.e("Kişi ara", searchQuery) } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/MainFragment.kt
792088764
package com.cloffygames.gpacalculator.ui.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cloffygames.gpacalculator.R import com.cloffygames.gpacalculator.databinding.FragmentProfileBinding class ProfileFragment : Fragment() { private lateinit var binding: FragmentProfileBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { binding = FragmentProfileBinding.inflate(inflater, container, false) return binding.root } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/ui/fragment/ProfileFragment.kt
931140169
package com.cloffygames.gpacalculator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.NavigationUI import com.cloffygames.gpacalculator.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // NavHostFragment'i bul val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment // BottomNavigationView'i NavController ile bağla NavigationUI.setupWithNavController(binding.bottomNavigationView, navHostFragment.navController) // Navigasyon kontrolcüsüne bir hedef değişikliği dinleyicisi ekleme navHostFragment.navController.addOnDestinationChangedListener { _, destination, _ -> // Eğer hedefin değiştiği durumdaysak ve hedef fragmentlar 'addDepartmentFragment' veya 'semesterFragment' ise, if (destination.id == R.id.addDepartmentFragment || destination.id == R.id.semesterFragment || destination.id == R.id.departmentFragment) { // BottomNavigationView'ı gizle binding.bottomNavigationView.visibility = View.GONE } else { // Diğer durumlarda BottomNavigationView'ı görünür yap binding.bottomNavigationView.visibility = View.VISIBLE } } } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/MainActivity.kt
3607268467
package com.cloffygames.gpacalculator import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.cloffygames.gpacalculator.databinding.ActivityMainBinding import com.cloffygames.gpacalculator.databinding.ActivityStartBinding class StartActivity : AppCompatActivity() { private lateinit var binding: ActivityStartBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityStartBinding.inflate(layoutInflater) setContentView(binding.root) // SharedPreferences'a bağlan. val sharedPreferences = getSharedPreferences("com.cloffygames.gpacalculator", Context.MODE_PRIVATE) // SharedPreferences üzerinde düzenleme yapmak için bir editor oluştur. val editor = sharedPreferences.edit() } }
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/StartActivity.kt
2181025081
package com.cloffygames.gpacalculator.data.entity //@Entity(tableName = "courses") data class Department( // @PrimaryKey(autoGenerate = true) val id: Int, val name: String, val gpa : Double, )
GPA_Calculator/app/src/main/java/com/cloffygames/gpacalculator/data/entity/Department.kt
3452500727
package com.example.myfood 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.myfood", appContext.packageName) } }
MyFood/app/src/androidTest/java/com/example/myfood/ExampleInstrumentedTest.kt
591959578
package com.example.myfood.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)
MyFood/app/src/main/java/com/example/myfood/ui/theme/Color.kt
3088721561
package com.example.myfood.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 = Color(0xFFFF6B00), secondary = PurpleGrey80, tertiary = Pink80, ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40, background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), ) @Composable fun MyFoodTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = false, 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 -> DarkColorScheme } 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 ) }
MyFood/app/src/main/java/com/example/myfood/ui/theme/Theme.kt
1936027700
package com.example.myfood.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.myfood.R val urbanistFontFamily = FontFamily( Font(R.font.lora_regular, FontWeight.Normal), Font(R.font.lora_medium, FontWeight.Medium), Font(R.font.lora_semibold, FontWeight.SemiBold), Font(R.font.lora_bold, FontWeight.Bold), ) val Typography = Typography( displayLarge = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Light, fontSize = 57.sp, lineHeight = 64.sp, letterSpacing = 0.sp ), displayMedium = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Light, fontSize = 45.sp, lineHeight = 52.sp, letterSpacing = 0.sp ), displaySmall = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Normal, fontSize = 36.sp, lineHeight = 44.sp, letterSpacing = 0.sp ), headlineLarge = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 32.sp, lineHeight = 40.sp, letterSpacing = 0.sp ), headlineMedium = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 28.sp, lineHeight = 36.sp, letterSpacing = 0.sp ), headlineSmall = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 24.sp, lineHeight = 32.sp, letterSpacing = 0.sp ), titleLarge = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), titleMedium = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp ), titleSmall = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Bold, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp ), bodyLarge = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp ), bodyMedium = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp ), bodySmall = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.Bold, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.4.sp ), labelLarge = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp ), labelMedium = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ), labelSmall = TextStyle( fontFamily = urbanistFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) )
MyFood/app/src/main/java/com/example/myfood/ui/theme/Type.kt
3690312490
package com.example.myfood import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Food( val foodId: Int, val foodTitle: String, val foodDescription: String, val foodTime: Int, val foodServings: Int, val foodYoutubeLink: String, val foodIngredientImages: List<Int>, val foodMeal: String, val foodCourse: String, val foodImage: Int ): Parcelable val myFoodList = listOf( Food( foodId = 1, foodTitle = "Scrambled Eggs", foodDescription = "For a perfect scrambled eggs breakfast, crack the eggs into a bowl and whisk them with a splash of milk. Melt butter in a non-stick skillet over medium-low heat. Pour the eggs into the skillet and let them sit for a moment until they start to set. Gently stir the eggs with a spatula, allowing them to cook evenly and form soft curds. Remove from heat just before they're fully set to prevent overcooking. Serve immediately for a delicious, fluffy breakfast!", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=7goNbTdFwNM", foodIngredientImages = listOf(R.drawable.egg, R.drawable.butter, R.drawable.milk), foodCourse = "Breakfast", foodMeal = "Main Dish", foodImage = R.drawable.scrambledegg ), Food( foodId = 2, foodTitle = "Tomato Pasta", foodDescription = "Start by boiling pasta in salted water until al dente. In a separate pan, sauté minced garlic and chopped onions in olive oil until translucent. Add diced tomatoes and let them simmer until they break down into a sauce. Season with salt and pepper to taste. Toss the cooked pasta into the tomato sauce, ensuring the pasta is coated evenly. Garnish with fresh basil and grated cheese before serving.", foodTime = 20, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=Svk1SwdL1eg", foodIngredientImages = listOf(R.drawable.pasta, R.drawable.tomato, R.drawable.garlic, R.drawable.oil), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.tomatopasta ), Food( foodId = 3, foodTitle = "Banana Bread", foodDescription = "Preheat the oven and grease a loaf pan. Mash ripe bananas in a bowl and mix in melted butter, honey, and flour until well combined. Pour the batter into the loaf pan and bake until a toothpick inserted into the center comes out clean. Allow the banana bread to cool before slicing. Enjoy this moist and flavorful treat for breakfast or as a snack!", foodTime = 10, foodServings = 1, foodYoutubeLink = "https://www.youtube.com/watch?v=vPUuY-bEK2w", foodIngredientImages = listOf(R.drawable.banana, R.drawable.flour, R.drawable.butter, R.drawable.honey), foodCourse = "Breakfast", foodMeal = "Dessert", foodImage = R.drawable.bananabread ), Food( foodId = 4, foodTitle = "Cheese Omelette", foodDescription = "Whisk eggs in a bowl and season with salt and pepper. Melt butter in a non-stick skillet over medium heat. Pour in the eggs and let them cook until the edges start to set. Sprinkle grated cheese over one half of the omelette and let it melt slightly. Fold the other half over the cheese and cook for a minute until the cheese is fully melted. Slide the omelette onto a plate and serve with toast or a side salad.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=-ZnK6OgRqqY", foodIngredientImages = listOf(R.drawable.egg, R.drawable.cheese, R.drawable.butter), foodCourse = "Breakfast", foodMeal = "Main Dish", foodImage = R.drawable.cheeseomelette ), Food( foodId = 5, foodTitle = "Tomato Soup", foodDescription = "In a pot, melt butter and sauté minced garlic and diced onions until soft. Add chopped tomatoes and water, bringing the mixture to a simmer. Let it cook until the tomatoes break down and the flavors meld together. Use an immersion blender to blend the soup until smooth. Season with salt and pepper, and garnish with fresh herbs before serving this comforting soup.", foodTime = 30, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=szjZ3vqwyXE", foodIngredientImages = listOf(R.drawable.tomato, R.drawable.garlic, R.drawable.onion, R.drawable.butter, R.drawable.water), foodCourse = "Dinner", foodMeal = "Soup", foodImage = R.drawable.tomatosoup ), Food( foodId = 6, foodTitle = "Potato Pancakes", foodDescription = "Grate potatoes and mix them with flour, beaten eggs, and a pinch of salt. Heat butter in a skillet over medium heat. Spoon the potato mixture into the skillet, flattening them with a spatula. Cook until golden brown on both sides. Serve these crispy pancakes as a side dish or a tasty snack with sour cream or applesauce.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://youtu.be/5ocdVtv5-bA?si=MeT0PuGbFR3vluXV", foodIngredientImages = listOf(R.drawable.egg, R.drawable.butter, R.drawable.potato, R.drawable.flour), foodCourse = "Breakfast", foodMeal = "Main Dish", foodImage = R.drawable.potatopancake ), Food( foodId = 7, foodTitle = "Berry Smoothie", foodDescription = "Blend mixed berries, a ripe banana, milk, and a drizzle of honey until smooth and creamy. Adjust the sweetness to your liking by adding more honey if desired. Pour into glasses and enjoy this refreshing and nutritious smoothie for a quick breakfast or a satisfying snack.", foodTime = 10, foodServings = 1, foodYoutubeLink = "https://youtu.be/J83nEr7sg3c?si=htLT-7dYZQoYWJqK", foodIngredientImages = listOf(R.drawable.berry, R.drawable.banana, R.drawable.milk, R.drawable.honey), foodCourse = "Breakfast", foodMeal = "Appetizer", foodImage = R.drawable.berrysmoothie ), Food( foodId = 8, foodTitle = "Chicken Sandwich", foodDescription = "Marinate chicken breasts in your preferred seasoning and cook them until fully done. Toast slices of bread and spread mayonnaise on one side. Layer the bread with lettuce, sliced tomatoes, cooked chicken, and cheese. Top with another slice of bread and serve this hearty sandwich with a side of chips or a fresh salad.", foodTime = 50, foodServings = 1, foodYoutubeLink = "https://www.youtube.com/watch?v=NqJtUVhAdNw", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.bread, R.drawable.lettuce, R.drawable.tomato, R.drawable.cheese), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.chickensandwich ), Food( foodId = 9, foodTitle = "Garlic Butter Shrimp", foodDescription = "Peel and devein shrimp, then pat them dry. In a skillet, melt butter and sauté minced garlic until fragrant. Add the shrimp and cook until they turn pink and opaque. Sprinkle chopped parsley over the shrimp and toss to coat. Serve this flavorful garlic butter shrimp over rice or pasta for a delightful meal.", foodTime = 40, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=f8wO2wsaUz0", foodIngredientImages = listOf(R.drawable.shrimp, R.drawable.butter, R.drawable.garlic, R.drawable.parsley), foodCourse = "Dinner", foodMeal = "Main Dish", foodImage = R.drawable.garlicbuttershrimp ), Food( foodId = 10, foodTitle = "Cheeseburger", foodDescription = "Form ground beef into patties and season them generously with salt and pepper. Cook the patties on a grill or in a skillet until they reach your preferred doneness. Toast burger buns and assemble the cheeseburgers with lettuce, tomato slices, onion, and cheese. Add condiments of your choice and enjoy this classic comfort food!", foodTime = 55, foodServings = 6, foodYoutubeLink = "https://www.youtube.com/watch?v=-B6FvKbq2Uw", foodIngredientImages = listOf(R.drawable.groundbeef, R.drawable.cheese, R.drawable.tomato, R.drawable.lettuce, R.drawable.onion, R.drawable.bread), foodCourse = "Breakfast", foodMeal = "Main Dish", foodImage = R.drawable.cheeseburger ), Food( foodId = 11, foodTitle = "Vegetable Stir-Fry", foodDescription = "Heat oil in a wok or skillet and add chopped onions, peppers, garlic, corn, and peas. Stir-fry the vegetables until they're tender yet crisp. Season with soy sauce or your favorite stir-fry sauce. Serve this colorful medley of veggies over steamed rice for a quick and nutritious meal.", foodTime = 30, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=h8IXBipqYgs", foodIngredientImages = listOf(R.drawable.onion, R.drawable.pepper, R.drawable.garlic, R.drawable.tomato, R.drawable.corn, R.drawable.peas), foodCourse = "Dinner", foodMeal = "Side", foodImage = R.drawable.vegetablestirfry ), Food( foodId = 12, foodTitle = "Honey Glazed Carrots", foodDescription = "Steam or boil carrots until they're tender. In a skillet, melt butter and add honey. Toss the cooked carrots in the honey-butter mixture until they're coated evenly. Sprinkle a pinch of salt and serve these glazed carrots as a delightful side dish.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=qYfoARhooHE", foodIngredientImages = listOf(R.drawable.carrot, R.drawable.honey, R.drawable.butter), foodCourse = "Dinner", foodMeal = "Appetizer", foodImage = R.drawable.honeyglazedcarrots ), Food( foodId = 13, foodTitle = "Lentil Soup", foodDescription = "Rinse lentils and boil them in water until they soften. In another pot, sauté chopped onions and garlic until golden brown. Add the cooked lentils to the pot along with diced tomatoes and simmer until flavors meld. Season with salt, pepper, and chopped parsley. Enjoy this hearty lentil soup with a slice of bread.", foodTime = 55, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=hfL7CPhku2I", foodIngredientImages = listOf(R.drawable.lentil, R.drawable.onion, R.drawable.garlic, R.drawable.tomato, R.drawable.parsley), foodCourse = "Lunch", foodMeal = "Soup", foodImage = R.drawable.lentilsoup ), Food( foodId = 14, foodTitle = "Spinach Salad", foodDescription = "Toss fresh spinach leaves with sliced tomatoes and crumbled cheese of your choice. Drizzle with your preferred vinaigrette or a simple olive oil and vinegar dressing. Add some freshly ground black pepper for a burst of flavor and serve this refreshing salad as a side or a light meal.", foodTime = 15, foodServings = 1, foodYoutubeLink = "https://www.youtube.com/watch?v=zHToir532B4", foodIngredientImages = listOf(R.drawable.spinach, R.drawable.tomato, R.drawable.cheese), foodCourse = "Lunch", foodMeal = "Side", foodImage = R.drawable.spinachsalad ), Food( foodId = 15, foodTitle = "Chicken Curry", foodDescription = "Sauté diced onions and minced garlic in oil until golden. Add cubed chicken and cook until browned. Stir in diced tomatoes and spices like curry powder, cumin, and paprika. Simmer until the chicken is cooked through and the sauce thickens. Serve this aromatic chicken curry over steamed rice or with naan bread.", foodTime = 30, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=WRYOVVexMhU", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.tomato, R.drawable.onion, R.drawable.garlic), foodCourse = "Dinner", foodMeal = "Main Dish", foodImage = R.drawable.chickencurry ), Food( foodId = 16, foodTitle = "Garlic Bread", foodDescription = "Preheat the oven. Slice a baguette lengthwise and spread a mixture of butter, minced garlic, and chopped parsley on each half. Sprinkle grated cheese over the top. Bake until the bread is crispy and the cheese is melted. Serve this fragrant garlic bread as a side to complement pasta dishes or soups.", foodTime = 20, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=wBFrmiDDIek", foodIngredientImages = listOf(R.drawable.bread, R.drawable.butter, R.drawable.garlic), foodCourse = "Breakfast", foodMeal = "Appetizer", foodImage = R.drawable.garlicbread ), Food( foodId = 17, foodTitle = "Cheesy Potato Casserole", foodDescription = "Thinly slice potatoes and layer them in a baking dish. Mix melted butter and grated cheese, then pour it over the potatoes. Bake until the potatoes are tender and the cheese is golden and bubbly. Garnish with chopped parsley before serving this comforting casserole.", foodTime = 30, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=eqgLQhXokJY", foodIngredientImages = listOf(R.drawable.potato, R.drawable.butter, R.drawable.cheese), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.cheesypotatocasserole ), Food( foodId = 18, foodTitle = "Pepper Steak", foodDescription = "Slice beef into strips and marinate in soy sauce. Sauté sliced onions and peppers in oil until softened. Add the marinated beef and cook until it's browned. Season with black pepper and a splash of soy sauce. Serve this savory pepper steak with rice or noodles.", foodTime = 45, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=IM6wXmo0gQw", foodIngredientImages = listOf(R.drawable.groundbeef, R.drawable.pepper, R.drawable.onion), foodCourse = "Dinner", foodMeal = "Main Dish", foodImage = R.drawable.peppersteak ), Food( foodId = 19, foodTitle = "Tomato Basil Bruschetta", foodDescription = "Dice tomatoes and mix them with minced garlic, chopped basil, olive oil, salt, and pepper. Toast slices of bread until golden and crisp. Top the bread with the tomato mixture and a drizzle of balsamic glaze. Serve this fresh and vibrant bruschetta as an appetizer.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=Q3xg35pcLyo", foodIngredientImages = listOf(R.drawable.tomato, R.drawable.garlic, R.drawable.bread, R.drawable.basil), foodCourse = "Lunch", foodMeal = "Side", foodImage = R.drawable.tomatobasilbruschetta ), Food( foodId = 20, foodTitle = "Banana Pancakes", foodDescription = "Mash ripe bananas in a bowl and mix in flour, beaten egg, and a splash of milk to create a pancake batter. Heat a skillet and pour the batter to make pancakes. Cook until bubbles form, then flip and cook until golden brown. Serve these fluffy banana pancakes with a drizzle of honey or maple syrup.", foodTime = 25, foodServings = 3, foodYoutubeLink = "https://www.youtube.com/watch?v=NbGPOTDf6Jc", foodIngredientImages = listOf(R.drawable.banana, R.drawable.flour, R.drawable.milk, R.drawable.egg), foodCourse = "Breakfast", foodMeal = "Side", foodImage = R.drawable.bananapancakes ), Food( foodId = 21, foodTitle = "Chicken Caesar Salad", foodDescription = "Grill or cook chicken until fully cooked, then slice it. Toss chopped romaine lettuce with Caesar dressing until well coated. Add the sliced chicken, croutons, and grated cheese. Toss everything together and serve this classic salad as a delicious and satisfying meal.", foodTime = 25, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=AGwfmY60FOM", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.lettuce, R.drawable.cheese), foodCourse = "Lunch", foodMeal = "Side", foodImage = R.drawable.chickencaesarsalad ), Food( foodId = 22, foodTitle = "Corn Chowder", foodDescription = "Sauté diced onions and minced garlic in butter until soft. Add corn kernels and diced potatoes, then pour in broth and bring to a simmer. Cook until the potatoes are tender. Add a splash of cream, season with salt and pepper, and garnish with chopped parsley. Serve this creamy corn chowder for a comforting meal.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=XjBBqQqT5DA", foodIngredientImages = listOf(R.drawable.corn, R.drawable.potato, R.drawable.onion, R.drawable.garlic), foodCourse = "Lunch", foodMeal = "Soup", foodImage = R.drawable.cornchowder ), Food( foodId = 23, foodTitle = "Berry Salad", foodDescription = "Combine mixed berries with fresh spinach leaves in a bowl. Add crumbled cheese of your choice and toss gently. Drizzle honey over the salad for a touch of sweetness. Serve this vibrant and flavorful berry salad as a refreshing side dish.", foodTime = 10, foodServings = 1, foodYoutubeLink = "https://www.youtube.com/watch?v=K-JgAopLnZo", foodIngredientImages = listOf(R.drawable.berry, R.drawable.spinach, R.drawable.cheese), foodCourse = "Breakfast", foodMeal = "Appetizer", foodImage = R.drawable.berrysalad ), Food( foodId = 24, foodTitle = "Cheese Quesadilla", foodDescription = "Sprinkle cheese on a tortilla and fold it in half. Heat a skillet and cook the quesadilla on both sides until the cheese melts and the tortilla turns golden brown. Cut into wedges and serve this simple and delicious snack.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=YbaTzT7PNTg", foodIngredientImages = listOf(R.drawable.cheese, R.drawable.bread, R.drawable.tomato), foodCourse = "Breakfast", foodMeal = "Side", foodImage = R.drawable.cheesequesadilla ), Food( foodId = 25, foodTitle = "Pasta Primavera", foodDescription = "Boil pasta until al dente, then set it aside. Sauté diced onions and minced garlic in olive oil until translucent. Add chopped tomatoes, peas, and carrots, cooking until the vegetables soften. Toss the cooked pasta with the vegetable mixture, season with salt and pepper, and drizzle with a bit of olive oil before serving.", foodTime = 25, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=eza6eFm5ioQ", foodIngredientImages = listOf(R.drawable.pasta, R.drawable.tomato, R.drawable.garlic, R.drawable.onion, R.drawable.oil, R.drawable.peas), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.pastaprimavera ), Food( foodId = 26, foodTitle = "Onion Rings", foodDescription = "Slice onions into rings and separate them. Dip the rings in a mixture of beaten egg and flour or breadcrumbs. Heat oil in a skillet and fry the onion rings until golden and crispy. Drain excess oil on paper towels and serve these crunchy onion rings as a delicious side dish or snack.", foodTime = 20, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=dcB5VU93AII", foodIngredientImages = listOf(R.drawable.onion, R.drawable.flour, R.drawable.egg), foodCourse = "Lunch", foodMeal = "Appetizer", foodImage = R.drawable.onionrings ), Food( foodId = 27, foodTitle = "Honey Mustard Chicken", foodDescription = "Mix honey and mustard to create a marinade. Coat chicken pieces in the marinade and let them sit for a while. Grill or bake the chicken until fully cooked and glazed. Garnish with a sprinkle of chopped parsley and serve this sweet and tangy chicken with your favorite sides.", foodTime = 35, foodServings = 3, foodYoutubeLink = "https://www.youtube.com/watch?v=duYwAwG3zIc", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.honey, R.drawable.butter, R.drawable.mustard), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.honeymustardchicken ), Food( foodId = 28, foodTitle = "Spinach and Cheese Stuffed Chicken", foodDescription = "Flatten chicken breasts and stuff them with a mixture of spinach and cheese. Secure with toothpicks. Sear the stuffed chicken in a skillet until browned, then bake until the chicken is cooked through. Remove the toothpicks before serving this flavorful stuffed chicken.", foodTime = 45, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=zUeSdsJYQxs", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.spinach, R.drawable.cheese, R.drawable.garlic, R.drawable.butter), foodCourse = "Dinner", foodMeal = "Main Dish", foodImage = R.drawable.spinachandcheesestuffedchicken ), Food( foodId = 29, foodTitle = "Lentil Curry", foodDescription = "Cook lentils until tender, then set them aside. Sauté diced onions and minced garlic until fragrant. Add diced tomatoes and spices like curry powder, cumin, and turmeric. Stir in the cooked lentils and let the flavors meld together. Garnish with chopped cilantro and serve this aromatic lentil curry with rice or naan.", foodTime = 15, foodServings = 3, foodYoutubeLink = "https://www.youtube.com/watch?v=3C-DQrS5L2Y", foodIngredientImages = listOf(R.drawable.lentil, R.drawable.onion, R.drawable.garlic), foodCourse = "Dinner", foodMeal = "Appetizer", foodImage = R.drawable.lentilcurry ), Food( foodId = 30, foodTitle = "Garlic Parmesan Roasted Potatoes", foodDescription = "Cut potatoes into wedges and toss them with minced garlic, grated Parmesan cheese, olive oil, salt, and pepper. Spread the seasoned potatoes on a baking sheet and roast until crispy and golden brown. Garnish with chopped parsley before serving these flavorful roasted potatoes.", foodTime = 25, foodServings = 4, foodYoutubeLink = "https://www.youtube.com/watch?v=L1lUQiIsCdE", foodIngredientImages = listOf(R.drawable.potato, R.drawable.garlic, R.drawable.cheese, R.drawable.oil), foodCourse = "Lunch", foodMeal = "Side", foodImage = R.drawable.garlicparmesanroastedpotatoes ), Food( foodId = 31, foodTitle = "Cheesy Garlic Breadsticks", foodDescription = "Mix grated cheese, minced garlic, and melted butter in a bowl. Spread the mixture on pre-made breadsticks or sliced baguette. Bake until the cheese is melted and bubbly. Serve these cheesy garlic breadsticks as a delightful appetizer or side dish.", foodTime = 15, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=qdAObPqiA0Y", foodIngredientImages = listOf(R.drawable.egg, R.drawable.butter, R.drawable.milk), foodCourse = "Dinner", foodMeal = "Appetizer", foodImage = R.drawable.cheesygarlicbreadsticks ), Food( foodId = 32, foodTitle = "Chicken Alfredo", foodDescription = "Cook pasta until al dente, then drain and set aside. Sauté diced chicken in butter until cooked through. Add cream and grated Parmesan cheese, stirring until the cheese melts and the sauce thickens. Toss the cooked pasta in the Alfredo sauce, garnish with parsley, and serve this creamy chicken Alfredo.", foodTime = 35, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=LPPcNPdq_j4", foodIngredientImages = listOf(R.drawable.chicken, R.drawable.butter, R.drawable.pasta, R.drawable.cheese), foodCourse = "Lunch", foodMeal = "Main Dish", foodImage = R.drawable.chickenalfredo ), Food( foodId = 33, foodTitle = "Berry Parfait", foodDescription = "Layer mixed berries, yogurt, and granola in a glass or bowl. Repeat the layers until the container is filled. Drizzle honey over the top for extra sweetness. Serve this colorful and nutritious berry parfait as a wholesome breakfast or a satisfying dessert.", foodTime = 15, foodServings = 1, foodYoutubeLink = "https://www.youtube.com/watch?v=aYwkYRm12QM", foodIngredientImages = listOf(R.drawable.berry, R.drawable.butter, R.drawable.milk), foodCourse = "Breakfast", foodMeal = "Appetizer", foodImage = R.drawable.berryparfait ), Food( foodId = 34, foodTitle = "Tomato Basil Pizza", foodDescription = "Roll out pizza dough into a circle. Spread a thin layer of tomato paste over the dough and sprinkle chopped tomatoes and basil leaves. Add grated cheese on top and bake until the crust is golden and the cheese melts. Slice and serve this homemade tomato basil pizza for a delicious meal.", foodTime = 55, foodServings = 6, foodYoutubeLink = "https://www.youtube.com/watch?v=--bv0V6ZjWI", foodIngredientImages = listOf(R.drawable.tomato, R.drawable.basil, R.drawable.cheese, R.drawable.flour), foodCourse = "Dinner", foodMeal = "Main Dish", foodImage = R.drawable.tomatobasilpizza ), Food( foodId = 35, foodTitle = "Potato Salad", foodDescription = "Boil potatoes until tender, then chop them into cubes. Mix the potatoes with boiled eggs, chopped onions, and a dressing made from mayonnaise, mustard, salt, and pepper. Chill the potato salad before serving this classic side dish at picnics or barbecues.", foodTime = 35, foodServings = 2, foodYoutubeLink = "https://www.youtube.com/watch?v=2Qzf0gyu6Qo", foodIngredientImages = listOf(R.drawable.potato, R.drawable.egg, R.drawable.onion), foodCourse = "Breakfast", foodMeal = "Side", foodImage = R.drawable.potatosalad ) )
MyFood/app/src/main/java/com/example/myfood/FoodList.kt
557247498
package com.example.myfood import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.compose.rememberNavController import com.example.myfood.filter.FilterScreen import com.example.myfood.fooddetail.FoodDetailScreen import com.example.myfood.ui.theme.MyFoodTheme import com.example.myfood.welcome.WelcomeScreen import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyFoodTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ScreensNavigation() } } } } }
MyFood/app/src/main/java/com/example/myfood/MainActivity.kt
3804544599
package com.example.myfood import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MyApp: Application()
MyFood/app/src/main/java/com/example/myfood/MyApp.kt
1812127290
package com.example.myfood.room import kotlinx.coroutines.flow.Flow interface FoodRepository { fun getAllHistory(): Flow<List<HistoryEntity>> suspend fun insertHistory(historyEntity: HistoryEntity): Long suspend fun loginUser(username: String, password: String): UserEntity? suspend fun signUpUser(user: UserEntity) suspend fun getUserByUsername(username: String): UserEntity? }
MyFood/app/src/main/java/com/example/myfood/room/FoodRepository.kt
4046743307
package com.example.myfood.room import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [HistoryEntity::class, UserEntity::class], version = 1) abstract class FoodDatabase: RoomDatabase() { abstract val dao: FoodDao }
MyFood/app/src/main/java/com/example/myfood/room/FoodDatabase.kt
2324107399
package com.example.myfood.room import android.content.Context import android.content.SharedPreferences import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun provideRecipeDatabase(@ApplicationContext context: Context) = Room.databaseBuilder( context, FoodDatabase::class.java, "recipe_db" ).build() @Provides @Singleton fun provideRecipeRepository(recipeDao: FoodDao): FoodRepository = FoodRepositoryImpl(dao = recipeDao) @Provides @Singleton fun provideRecipeDao(recipeDatabase: FoodDatabase) = recipeDatabase.dao @Provides @Singleton fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences { return context.getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) } }
MyFood/app/src/main/java/com/example/myfood/room/AppModule.kt
2478917086
package com.example.myfood.room import kotlinx.coroutines.flow.Flow class FoodRepositoryImpl(private val dao: FoodDao) : FoodRepository { override fun getAllHistory(): Flow<List<HistoryEntity>> { return dao.getAllHistory() } override suspend fun insertHistory(historyEntity: HistoryEntity): Long { return dao.insertHistory(historyEntity) } override suspend fun loginUser(username: String, password: String): UserEntity? { return dao.loginUser(username, password) } override suspend fun signUpUser(user: UserEntity) { return dao.signUpUser(user) } override suspend fun getUserByUsername(username: String): UserEntity? { return dao.getUserByUsername(username) } }
MyFood/app/src/main/java/com/example/myfood/room/FoodRepositoryImpl.kt
3642877619
package com.example.myfood.room import androidx.room.Entity import androidx.room.PrimaryKey @Entity("history") data class HistoryEntity( @PrimaryKey(autoGenerate = true) val historyId: Long, val foodId: Int )
MyFood/app/src/main/java/com/example/myfood/room/HistoryEntity.kt
2225917704
package com.example.myfood.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow @Dao interface FoodDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertHistory(historyEntity: HistoryEntity): Long @Query("SELECT * FROM history") fun getAllHistory(): Flow<List<HistoryEntity>> @Query("SELECT * FROM users WHERE username = :username AND password = :password") suspend fun loginUser(username: String, password: String): UserEntity? @Insert suspend fun signUpUser(user: UserEntity) @Query("SELECT * FROM users WHERE username = :username") suspend fun getUserByUsername(username: String): UserEntity? }
MyFood/app/src/main/java/com/example/myfood/room/FoodDao.kt
2484122053
package com.example.myfood.room import androidx.room.Entity import androidx.room.PrimaryKey @Entity("users") data class UserEntity( @PrimaryKey(autoGenerate = true) val userId: Long, val username: String, val password: String )
MyFood/app/src/main/java/com/example/myfood/room/UserEntity.kt
2876586351
package com.example.myfood.fooddetail import android.content.Intent import android.net.Uri import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Notifications import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat.startActivity import androidx.navigation.NavController import com.example.myfood.Food import com.example.myfood.R import com.example.myfood.commonui.RatingBar import com.example.myfood.myFoodList @Composable fun FoodDetailScreen( navController: NavController, food: Food ) { Surface { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(8.dp) ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, null) } IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Notifications, null) } } Text(text = food.foodMeal, color = Color(0xFF128FAE), fontSize = 16.sp) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = food.foodTitle, Modifier.align(Alignment.CenterVertically), fontWeight = FontWeight.Bold, fontSize = 20.sp ) IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Favorite, null) } } RatingBar(rating = 4.5f, Modifier.height(16.dp)) Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Column( modifier = Modifier .height(150.dp) .weight(1f) ) { Row(Modifier.padding(top = 20.dp)) { Icon(painter = painterResource(id = R.drawable.timer), null) Text("10 minutes", Modifier.align(Alignment.CenterVertically).padding(start = 6.dp)) } Row { Icon(painter = painterResource(id = R.drawable.serving), null) Text("2 servings", Modifier.align(Alignment.CenterVertically).padding(start = 6.dp)) } } Image( painter = painterResource(food.foodImage), null, modifier = Modifier .weight(1f) .size(170.dp) .clip(CircleShape), contentScale = ContentScale.Crop, ) } LazyRow( content = { items(food.foodIngredientImages) { image -> Image( painter = painterResource(id = image), null, modifier = Modifier .size(60.dp) .clip(RoundedCornerShape(25.dp)), contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.padding(4.dp)) } }, modifier = Modifier .padding() .fillMaxWidth() ) Spacer(Modifier.height(50.dp)) YouTubeVideoButton( youtubeLink = food.foodYoutubeLink, modifier = Modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp) ) Button( onClick = { /*TODO*/ }, modifier = Modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp) ) { Text("Recipe") } } } } } @Composable fun YouTubeVideoButton( modifier: Modifier = Modifier, youtubeLink: String) { val context = LocalContext.current var launcher: ActivityResultLauncher<Intent>? = null Button( modifier = modifier, onClick = { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(youtubeLink)) startActivity(context, intent, null) }) { Text("Tutorial") } }
MyFood/app/src/main/java/com/example/myfood/fooddetail/FoodDetailScreen.kt
883220618
package com.example.myfood.auth import android.content.SharedPreferences import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.myfood.DbConstants.SHARED_PREF_USER_NAME import com.example.myfood.room.FoodRepository import com.example.myfood.room.UserEntity import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AuthViewModel @Inject constructor( private val repository: FoodRepository, private val sharedPreferences: SharedPreferences ) : ViewModel() { private val editor = sharedPreferences.edit() private val _state = mutableStateOf(AuthState()) val state: State<AuthState> = _state private suspend fun performSignUp(userName: String, password: String) { val userEntity = UserEntity(0L, userName, password) repository.signUpUser(userEntity) editor.putString(SHARED_PREF_USER_NAME, userEntity.username) editor.apply() } private fun performLogin(userName: String, password: String) = viewModelScope.launch { val user = repository.loginUser(userName, password) user?.let { _state.value = AuthState(isLoginSuccessful = true) Log.i("usercredentials", _state.value.isLoginSuccessful.toString()) } } private fun performLogout() { editor.putString(SHARED_PREF_USER_NAME, null) editor.apply() } fun onEvent(event: AuthEvent) { when (event) { is AuthEvent.LoginEvent -> { viewModelScope.launch { performLogin(event.userName, event.password) } } is AuthEvent.SignUpEvent -> { viewModelScope.launch { performSignUp(event.userName, event.password) } } is AuthEvent.LogoutEvent -> { viewModelScope.launch { performLogout() } } } } }
MyFood/app/src/main/java/com/example/myfood/auth/AuthViewModel.kt
2496003388
package com.example.myfood.auth sealed class AuthEvent { data class LoginEvent(val userName: String, val password: String): AuthEvent() data class SignUpEvent(val userName: String, val password: String): AuthEvent() data class LogoutEvent(val dummy: String): AuthEvent() }
MyFood/app/src/main/java/com/example/myfood/auth/AuthEvent.kt
858462748
package com.example.myfood.auth import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.text.ClickableText import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.intl.Locale import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.rememberNavController import com.example.myfood.Screen import com.example.myfood.ui.theme.urbanistFontFamily @Composable fun SignUpScreen( navController: NavController, viewModel: AuthViewModel = hiltViewModel() ) { var username by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } var passwordConfirmation by remember { mutableStateOf("") } val context = LocalContext.current Surface(modifier = Modifier.fillMaxSize()) { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues), verticalArrangement = Arrangement.Center ) { Text( "Sign Up", Modifier.align(Alignment.CenterHorizontally), fontSize = 32.sp ) Spacer(Modifier.size(38.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = username, onValueChange = { username = it }) Spacer(Modifier.size(8.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = password, onValueChange = { password = it }) Spacer(Modifier.size(8.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = passwordConfirmation, onValueChange = { passwordConfirmation = it }) Spacer(Modifier.size(8.dp)) Spacer(Modifier.size(8.dp)) Button( onClick = { if (password == passwordConfirmation) { viewModel.onEvent(AuthEvent.SignUpEvent(username, password)) navController.navigate(Screen.HomeScreen.route) { popUpTo(navController.graph.findStartDestination().id) { inclusive = true } } } else { Toast.makeText( context, "Passwords Are not Matching", Toast.LENGTH_SHORT ).show() } }, Modifier.fillMaxWidth() ) { Text(text = "Sign Up") } ClickableText( text = AnnotatedString(text = "I have an account"), onClick = { navController.navigate(Screen.LoginScreen.route) }, style = TextStyle( color = Color(0xFFF55A00), fontSize = 18.sp, fontFamily = urbanistFontFamily ) ) } } } }
MyFood/app/src/main/java/com/example/myfood/auth/SignUpScreen.kt
837775703
package com.example.myfood.auth import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.text.ClickableText import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface 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.Color import androidx.compose.ui.graphics.Color.Companion.Blue import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import com.example.myfood.Screen import com.example.myfood.ui.theme.urbanistFontFamily @Composable fun LoginScreen( navController: NavController, viewModel: AuthViewModel = hiltViewModel() ) { val state = viewModel.state.value LaunchedEffect(state.isLoginSuccessful) { state.isLoginSuccessful.let { if (state.isLoginSuccessful == true) { navController.navigate(Screen.HomeScreen.route) { popUpTo(navController.graph.findStartDestination().id) { inclusive = true } } } } } var userName by remember { mutableStateOf("") } var password by remember { mutableStateOf("") } Surface(modifier = Modifier.fillMaxSize()) { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues), verticalArrangement = Arrangement.Center ) { Text( text = "Login Screen", fontSize = 32.sp, modifier = Modifier.align(Alignment.CenterHorizontally) ) Spacer(Modifier.size(38.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = userName, onValueChange = { userName = it } ) Spacer(Modifier.size(16.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = password, onValueChange = { password = it } ) Spacer(Modifier.size(8.dp)) Button( onClick = { viewModel.onEvent(AuthEvent.LoginEvent(userName, password)) }, Modifier.fillMaxWidth(), ) { Text("Login") } ClickableText( text = AnnotatedString(text = "I don't have an account"), onClick = { navController.navigate(Screen.SignUpScreen.route) }, style = TextStyle( color = Color(0xFFF55A00), fontSize = 18.sp, fontFamily = urbanistFontFamily ) ) } } } }
MyFood/app/src/main/java/com/example/myfood/auth/LoginScreen.kt
3666393358
package com.example.myfood.auth data class AuthState( val isLoginSuccessful: Boolean? = null )
MyFood/app/src/main/java/com/example/myfood/auth/AuthState.kt
2232255253
package com.example.myfood object DbConstants { const val SHARED_PREF_USER_NAME = "userName" }
MyFood/app/src/main/java/com/example/myfood/AppConstants.kt
3535159620
package com.example.myfood import android.content.Context import android.content.SharedPreferences import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.myfood.DbConstants.SHARED_PREF_USER_NAME import com.example.myfood.about.AboutScreen import com.example.myfood.auth.LoginScreen import com.example.myfood.auth.SignUpScreen import com.example.myfood.favourite.FavouriteScreen import com.example.myfood.filter.FilterScreen import com.example.myfood.fooddetail.FoodDetailScreen import com.example.myfood.history.HistoryScreen import com.example.myfood.welcome.WelcomeScreen @Composable fun ScreensNavigation() { val context = LocalContext.current val navController = rememberNavController() val sharedPreferences: SharedPreferences = context.getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) val userId = sharedPreferences.getString(SHARED_PREF_USER_NAME, null) var startDestination = "" if (userId == null) { startDestination = Screen.LoginScreen.route } else { startDestination = Screen.HomeScreen.route } NavHost(navController = navController, startDestination = startDestination) { composable(route = Screen.HomeScreen.route) { WelcomeScreen(navController = navController) } composable(route = Screen.FilterScreen.route) { FilterScreen(navController = navController) } composable(route = Screen.LoginScreen.route) { LoginScreen(navController = navController) } composable(route = Screen.SignUpScreen.route) { SignUpScreen(navController = navController) } composable(route = Screen.FoodDetail.route + "/{foodId}") { navBackStackEntry -> val foodId = navBackStackEntry.arguments?.getString("foodId") val food = myFoodList.find { it.foodId.toString() == foodId } FoodDetailScreen(navController = navController, food!!) } composable(route = Screen.HistoryScreen.route) { HistoryScreen(navController = navController) } composable(route = Screen.AboutScreen.route) { AboutScreen(navController = navController) } composable(route = Screen.FavouriteScreen.route) { FavouriteScreen(navController = navController) } } } sealed class Screen(val route: String) { data object HomeScreen : Screen(route = "home_screen") data object FilterScreen : Screen(route = "filter_screen") data object HistoryScreen : Screen(route = "history_screen") data object AboutScreen : Screen(route = "about_screen") data object FoodDetail : Screen(route = "food_detail") data object FavouriteScreen : Screen(route = "favourite_screen") data object LoginScreen : Screen(route = "login_screen") data object SignUpScreen : Screen(route = "signup_screen") }
MyFood/app/src/main/java/com/example/myfood/Navigation.kt
1766404014
package com.example.myfood.about import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Notifications import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import androidx.navigation.compose.rememberNavController @Composable fun AboutScreen(navController: NavController) { Surface(modifier = Modifier.fillMaxSize()) { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column(modifier = Modifier .padding(paddingValues) .padding(8.dp)) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, null) } Text("ABOUT") IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.Notifications, null) } } Text(text = aboutText) } } } } @Preview @Composable fun AboutScreenPreview() { AboutScreen(navController = rememberNavController()) } val aboutText = "Welcome to MyFood App, where cooking becomes an adventure!\n" + "\n" + "\uD83C\uDF73 Explore a diverse collection of recipes curated for every skill level and taste.\n" + "\n" + "\uD83D\uDCF1 Easy-to-follow instructions make cooking a breeze.\n" + "\n" + "\uD83D\uDCA1 Personalize your experience, save favorites, and discover new culinary delights.\n" + "\n" + "Join us and transform your kitchen into a place of creativity and deliciousness!"
MyFood/app/src/main/java/com/example/myfood/about/AboutScreen.kt
931735916
package com.example.myfood.welcome import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Notifications import androidx.compose.material3.Divider import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MediumTopAppBar import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.OutlinedIconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight.Companion.Bold import androidx.compose.ui.text.font.FontWeight.Companion.Light import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.example.myfood.Food import com.example.myfood.filter.FoodCard import com.example.myfood.R import com.example.myfood.Screen import com.example.myfood.auth.AuthEvent import com.example.myfood.auth.AuthViewModel import com.example.myfood.history.HistoryEvent import com.example.myfood.history.HistoryViewModel import com.example.myfood.myFoodList import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun WelcomeScreen( navController: NavController, authViewModel: AuthViewModel = hiltViewModel(), historyViewModel: HistoryViewModel = hiltViewModel() ) { var searchQuery by remember { mutableStateOf("") } val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() var filteredFoods by remember { mutableStateOf(myFoodList) } Surface(modifier = Modifier.fillMaxSize()) { ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet { Text( text = "Welcome Again!", modifier = Modifier.padding(25.dp), fontWeight = Bold, fontSize = 30.sp ) Divider() NavigationDrawerItem( label = { Text( text = "Home", fontWeight = Bold, fontSize = 24.sp ) }, selected = false, onClick = { scope.launch { drawerState.apply { if (isClosed) open() else close() } } } ) NavigationDrawerItem( label = { Text(text = "Favourite", fontWeight = Bold, fontSize = 24.sp) }, selected = false, onClick = { navController.navigate(Screen.FavouriteScreen.route) } ) NavigationDrawerItem( label = { Text(text = "History", fontWeight = Bold, fontSize = 24.sp) }, selected = false, onClick = { navController.navigate(Screen.HistoryScreen.route) } ) NavigationDrawerItem( label = { Text(text = "About", fontWeight = Bold, fontSize = 24.sp) }, selected = false, onClick = { navController.navigate(Screen.AboutScreen.route) } ) NavigationDrawerItem( label = { Text(text = "Log Out", fontWeight = Bold, fontSize = 24.sp) }, selected = false, onClick = { authViewModel.onEvent(AuthEvent.LogoutEvent("")) navController.navigate(Screen.LoginScreen.route) } ) } }) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { MediumTopAppBar( title = { Text("Welcome Chef!") }, navigationIcon = { IconButton(onClick = { scope.launch { drawerState.apply { if (isClosed) open() else close() } } }) { Icon(Icons.Filled.Menu, null) } }, actions = { IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Filled.Notifications, null) } } ) }, ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) .padding(16.dp) ) { Text( text = "What Would You Like to Cook Today?", fontSize = 28.sp, lineHeight = 26.sp, modifier = Modifier.padding(bottom = 10.dp) ) Row(modifier = Modifier.fillMaxWidth()) { OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it filteredFoods = searchFood(searchQuery) } ) Spacer(modifier = Modifier.padding(8.dp)) OutlinedIconButton( onClick = { navController.navigate("filter_screen") }, shape = RoundedCornerShape(50) //modifier = Modifier.border(BorderStroke(1.dp, Color.Black)), ) { Icon(painter = painterResource(id = R.drawable.filter), null) } } if (searchQuery.isBlank()) { Spacer(modifier = Modifier.padding(top = 15.dp)) Text( text = "As You Type, the Results Will Appear Here", modifier = Modifier.align(Alignment.CenterHorizontally), fontSize = 20.sp, fontWeight = Light ) } else { LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), contentPadding = PaddingValues(bottom = 150.dp), content = { items(filteredFoods) { food -> FoodCard( food = food, onRecipeItemClick = { historyViewModel.onEvent(HistoryEvent.AddHistory(food.foodId)) navController.navigate(Screen.FoodDetail.route + "/" + food.foodId.toString()) }) } } ) } } } } } } fun searchFood(query: String): List<Food> { val lowerCaseQuery = query.toLowerCase() return myFoodList.filter { food -> food.foodTitle.toLowerCase().contains(lowerCaseQuery) || food.foodDescription.toLowerCase().contains(lowerCaseQuery) } }
MyFood/app/src/main/java/com/example/myfood/welcome/WelcomeScreen.kt
2100990498
package com.example.myfood.commonui import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.GenericShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import kotlin.math.cos import kotlin.math.sin @Composable fun RatingBar( rating: Float, modifier: Modifier = Modifier, color: Color = Color(0xFFF55A00) ) { Row(modifier = modifier.wrapContentSize()) { (1..5).forEach { step -> val stepRating = when { rating > step -> 1f step.rem(rating) < 1 -> rating - (step - 1f) else -> 0f } RatingStar(stepRating, color) } } } @Composable private fun RatingStar( rating: Float, ratingColor: Color = Color.Yellow, backgroundColor: Color = Color.Gray ) { BoxWithConstraints( modifier = Modifier .fillMaxHeight() .aspectRatio(1f) .clip(starShape) ) { Canvas(modifier = Modifier.size(maxHeight)) { drawRect( brush = SolidColor(backgroundColor), size = Size( height = size.height * 1.4f, width = size.width * 1.4f ), topLeft = Offset( x = -(size.width * 0.1f), y = -(size.height * 0.1f) ) ) if (rating > 0) { drawRect( brush = SolidColor(ratingColor), size = Size( height = size.height * 1.1f, width = size.width * rating ) ) } } } } private val starShape = GenericShape { size, _ -> addPath(starPath(size.height)) } private val starPath = { size: Float -> Path().apply { val outerRadius: Float = size / 1.8f val innerRadius: Double = outerRadius / 2.5 var rot: Double = Math.PI / 2 * 3 val cx: Float = size / 2 val cy: Float = size / 20 * 11 var x: Float = cx var y: Float = cy val step = Math.PI / 5 moveTo(cx, cy - outerRadius) repeat(5) { x = (cx + cos(rot) * outerRadius).toFloat() y = (cy + sin(rot) * outerRadius).toFloat() lineTo(x, y) rot += step x = (cx + cos(rot) * innerRadius).toFloat() y = (cy + sin(rot) * innerRadius).toFloat() lineTo(x, y) rot += step } close() } } @Preview @Composable fun RatingBarPreview() { Column( Modifier.fillMaxSize().background(Color.White) ) { RatingBar( 2.5f, modifier = Modifier.height(20.dp) ) } }
MyFood/app/src/main/java/com/example/myfood/commonui/RatingBar.kt
3440542947
package com.example.myfood.history import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.example.myfood.Food import com.example.myfood.favourite.pickRandomFoods import com.example.myfood.myFoodList @Composable fun HistoryScreen( navController: NavController, viewModel: HistoryViewModel = hiltViewModel() ) { val viewModelData = viewModel.state.value val historyFoods = viewModel.getFilteredFoods(viewModelData.historyList.map { it.foodId }) Surface(modifier = Modifier.fillMaxSize()) { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .padding(8.dp) ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, null) } } Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text(text = "History", fontWeight = FontWeight.Bold, fontSize = 30.sp) } LazyColumn(modifier = Modifier.fillMaxWidth()) { items(historyFoods) { food -> HistoryItem(food = food) } } } } } }
MyFood/app/src/main/java/com/example/myfood/history/HistoryScreen.kt
123395142
package com.example.myfood.history import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.myfood.Food import com.example.myfood.R import com.example.myfood.commonui.RatingBar import com.example.myfood.myFoodList @Composable fun HistoryItem(food: Food) { ElevatedCard { Row(modifier = Modifier .fillMaxWidth() .padding(8.dp)) { Column(modifier = Modifier.weight(1f)) { Image( painter = painterResource(id = food.foodImage), null, contentScale = ContentScale.FillHeight, modifier = Modifier .size(90.dp) .clip(CircleShape) ) } Spacer(Modifier.padding(end = 8.dp)) Column(modifier = Modifier.weight(3f)) { Text(text = food.foodCourse, color = Color(0xFF128FAE)) Text(text = food.foodTitle, fontSize = 22.sp) RatingBar(rating = 4.6f, modifier = Modifier.height(14.dp)) Row(Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.SpaceBetween) { Icon(painter = painterResource(id = R.drawable.timer), null) Text( text = food.foodTime.toString() + " mins", Modifier.align(Alignment.CenterVertically), color = Color(0xFF7B7B7B) ) Spacer(Modifier.padding(end = 8.dp)) Icon(painter = painterResource(id = R.drawable.serving), null) Text( text = food.foodServings.toString() + " servings", Modifier.align(Alignment.CenterVertically), color = Color(0xFF7B7B7B) ) } } } } } @Preview @Composable fun HistoryItemPreview() { HistoryItem(food = myFoodList[12]) }
MyFood/app/src/main/java/com/example/myfood/history/HistoryItem.kt
2160453841
package com.example.myfood.history sealed class HistoryEvent { data class AddHistory(val foodId: Int): HistoryEvent() }
MyFood/app/src/main/java/com/example/myfood/history/HistoryEvent.kt
3079225516
package com.example.myfood.history import com.example.myfood.room.HistoryEntity data class HistoryState( val historyList: List<HistoryEntity> = listOf(), val historyEmptyMessage: String = "" )
MyFood/app/src/main/java/com/example/myfood/history/HistoryState.kt
2329622662
package com.example.myfood.history import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.myfood.Food import com.example.myfood.myFoodList import com.example.myfood.room.FoodRepository import com.example.myfood.room.HistoryEntity import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HistoryViewModel @Inject constructor( private val repository: FoodRepository ) : ViewModel() { private val _state = mutableStateOf(HistoryState()) val state: State<HistoryState> = _state init { getHistory() } private fun getHistory() = viewModelScope.launch { repository.getAllHistory().onEach { _state.value = HistoryState(historyList = it) }.launchIn(viewModelScope) } private fun addHistory(foodId: Int) = viewModelScope.launch { val historyEntity = HistoryEntity(0L, foodId) repository.insertHistory(historyEntity) } private fun filterFoodIdsFromHistory(foodIds: List<Int>): List<Food> { val historyList = state.value.historyList return myFoodList.filter { food -> historyList.any { it.foodId == food.foodId && foodIds.contains(it.foodId) } } } fun getFilteredFoods(foodIds: List<Int>): List<Food> { return filterFoodIdsFromHistory(foodIds) } fun onEvent(event: HistoryEvent) { when (event) { is HistoryEvent.AddHistory -> { addHistory(event.foodId) } } } }
MyFood/app/src/main/java/com/example/myfood/history/HistoryViewModel.kt
2200121128
package com.example.myfood.favourite import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.example.myfood.Food import com.example.myfood.filter.FoodCard import com.example.myfood.myFoodList @Composable fun FavouriteScreen(navController: NavController) { Surface(modifier = Modifier.fillMaxSize()) { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .padding(8.dp) .fillMaxSize() ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Filled.ArrowBack, null) } } LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), content = { items(pickRandomFoods(5)) { food -> FoodCard(food = food, onRecipeItemClick = {}) } } ) } } } } fun pickRandomFoods(count: Int): List<Food> { return myFoodList.shuffled().take(count) }
MyFood/app/src/main/java/com/example/myfood/favourite/FavouriteScreen.kt
2414981733
package com.example.myfood.filter import android.util.Log import androidx.compose.foundation.* import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.example.myfood.Food import com.example.myfood.Screen import com.example.myfood.history.HistoryEvent import com.example.myfood.history.HistoryViewModel import com.example.myfood.myFoodList import kotlinx.coroutines.launch import kotlin.math.roundToInt @OptIn(ExperimentalMaterial3Api::class) @Composable fun FilterScreen( navController: NavController, viewModel: HistoryViewModel = hiltViewModel() ) { val sheetState = rememberBottomSheetScaffoldState() val scope = rememberCoroutineScope() var showBottomSheet by remember { mutableStateOf(true) } var filterCourseSet by remember { mutableStateOf(mutableSetOf<String>()) } var filterMealSet by remember { mutableStateOf(mutableSetOf<String>()) } var servingSliderPosition by remember { mutableFloatStateOf(1f) } var timeSliderPosition by remember { mutableFloatStateOf(15f) } var filteredFoods by remember { mutableStateOf(myFoodList) } Surface(modifier = Modifier.fillMaxSize()) { Scaffold( modifier = Modifier.fillMaxSize() ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { if (showBottomSheet) { BottomSheetScaffold( scaffoldState = sheetState, topBar = { MediumTopAppBar(title = { Text("Filter Foods") }) }, sheetPeekHeight = 150.dp, sheetContent = { Column { Row( modifier = Modifier .fillMaxWidth() .padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text("Filter") Text( text = "Reset", modifier = Modifier.clickable { scope.launch { filteredFoods = myFoodList } }, color = Color(0xFFF55A00) ) } Row( modifier = Modifier .fillMaxWidth() .padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text("Meal", fontWeight = FontWeight.Bold) Text(text = "") } Row( modifier = Modifier .fillMaxWidth() .padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { SelectableButton( text = "Breakfast", onToggle = { filterMealSet.add("Breakfast") filteredFoods = filterFoodsByMeal(filterMealSet) } ) SelectableButton( text = "Lunch", onToggle = { filterMealSet.add("Lunch") filteredFoods = filterFoodsByMeal(filterMealSet) } ) SelectableButton( text = "Dinner", onToggle = { filterMealSet.add("Dinner") filteredFoods = filterFoodsByMeal(filterMealSet) } ) } Divider() LazyVerticalGrid( columns = GridCells.Adaptive(100.dp), contentPadding = PaddingValues( top = 16.dp, bottom = 16.dp, start = 8.dp, end = 8.dp ), content = { items(courseSelections) { course -> SelectableButton( modifier = Modifier.padding( bottom = 8.dp, start = 4.dp, end = 4.dp ), text = course, onToggle = { filterCourseSet.add(course) filteredFoods = filterFoodsByMealCourse(filterCourseSet) Log.i("filterSet", filterCourseSet.toString()) } ) } } ) Row( modifier = Modifier .fillMaxWidth() .padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text("Serving (min)") Text( text = "Set Manually", modifier = Modifier.clickable { // TODO: RESET FILTER }, color = Color(0xFFF55A00) ) } Slider( value = servingSliderPosition, onValueChange = { servingSliderPosition = it filteredFoods = filterServing(servingSliderPosition.roundToInt()) }, steps = 7, valueRange = 0f..7f ) Text( text = servingSliderPosition.roundToInt() .toString() + " servings" ) Spacer(Modifier.padding(6.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text("Preparation Time (max)") Text( text = "Set Manually", modifier = Modifier.clickable { // TODO: RESET FILTER }, color = Color(0xFFF55A00) ) } Slider( value = timeSliderPosition, onValueChange = { timeSliderPosition = it filteredFoods = filterTime(timeSliderPosition.roundToInt()) }, valueRange = 5f..65f ) Text(text = (timeSliderPosition.roundToInt()).toString() + " minutes") Spacer(Modifier.padding(6.dp)) Button( onClick = { scope.launch { sheetState.bottomSheetState.partialExpand() } }, Modifier.fillMaxWidth() ) { Text("Apply") } } } ) { Column(modifier = Modifier.fillMaxSize()) { LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), contentPadding = PaddingValues(bottom = 150.dp), content = { items(filteredFoods) { food -> FoodCard(food = food, onRecipeItemClick = { viewModel.onEvent(HistoryEvent.AddHistory(food.foodId)) navController.navigate(Screen.FoodDetail.route + "/" + food.foodId.toString()) }) } } ) } } } } } } } fun filterServing(serving: Int): List<Food> { return myFoodList.filter { food -> food.foodServings > serving } } fun filterTime(time: Int): List<Food> { return myFoodList.filter { food -> food.foodTime < time } } fun filterFoodsByMealCourse(selectedMealTypes: Set<String>): List<Food> { return if (selectedMealTypes.isEmpty()) { // If no meal types are selected, return the original list myFoodList } else { // Filter the list by selected meal types myFoodList.filter { food -> food.foodMeal in selectedMealTypes } } } fun filterFoodsByMeal(selectedMealCourses: Set<String>): List<Food> { return if (selectedMealCourses.isEmpty()) { // If no meal types are selected, return the original list myFoodList } else { // Filter the list by selected meal types myFoodList.filter { food -> food.foodCourse in selectedMealCourses } } } fun removeFromSet(keyWord: String, keySet: Set<String>) { keySet.toMutableSet().remove(keyWord) } @Composable fun SelectableButton( modifier: Modifier = Modifier, text: String, selectedColor: Color = Color(0xFFF55A00).copy(alpha = 0.25f), unselectedColor: Color = Color.Transparent, onToggle: () -> Unit ) { var isSelected by remember { mutableStateOf(false) } OutlinedButton( modifier = modifier, onClick = { if (!isSelected) { onToggle() } isSelected = !isSelected }, colors = ButtonDefaults.outlinedButtonColors( containerColor = if (isSelected) selectedColor else unselectedColor, contentColor = Color(0xFFF55A00), disabledContainerColor = unselectedColor, disabledContentColor = Color.Gray ), border = BorderStroke( width = ButtonDefaults.outlinedButtonBorder.width, color = if (isSelected) Color(0xFFF55A00) else Color.Gray ), content = { Text(text = text) } ) } val courseSelections = listOf( "Soup", "Appetizer", "Starter", "Main Dish", "Side", "Dessert" )
MyFood/app/src/main/java/com/example/myfood/filter/FilteringPage.kt
3411662339
package com.example.myfood.filter import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Favorite import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.myfood.Food import com.example.myfood.R import com.example.myfood.commonui.RatingBar import com.example.myfood.myFoodList @OptIn(ExperimentalMaterial3Api::class) @Composable fun FoodCard( food: Food, onRecipeItemClick: (Food) -> Unit ) { ElevatedCard(modifier = Modifier .fillMaxWidth() .background(color = Color.DarkGray) .padding(4.dp), onClick = { onRecipeItemClick(food) } ) { Column( modifier = Modifier .fillMaxSize() .padding(4.dp) ) { Row( modifier = Modifier .fillMaxWidth() .height(150.dp), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { addFavorite(food.foodId.toString()) }) { Icon(Icons.Outlined.Favorite, contentDescription = null) } Image( painter = painterResource(id = food.foodImage), contentDescription = null, contentScale = ContentScale.FillHeight, modifier = Modifier .clip(CircleShape) .size(130.dp) ) } Text(text = food.foodCourse, color = Color.Blue) Text(text = food.foodTitle) Spacer(Modifier.padding(8.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Start) { Icon(painter = painterResource(id = R.drawable.timer), null) Spacer(Modifier.padding(2.dp)) Text(text = food.foodTime.toString(), Modifier.align(Alignment.CenterVertically)) } if (food.foodTitle.length > 11) { RatingBar(4.5f, Modifier.height(15.dp)) } else { RatingBar(5.0f, Modifier.height(15.dp)) } Spacer(Modifier.padding(bottom = 8.dp)) } } } fun addFavorite(foodId: String) { } @Preview(showBackground = true, showSystemUi = true) @Composable fun PreviewFoodCard() { FoodCard(food = myFoodList[3], onRecipeItemClick = {}) }
MyFood/app/src/main/java/com/example/myfood/filter/FoodCard.kt
4242983518
package com.gabrielsanchez.ac603 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.gabrielsanchez.ac603", appContext.packageName) } }
AC603/app/src/androidTest/java/com/gabrielsanchez/ac603/ExampleInstrumentedTest.kt
3886973576
package com.gabrielsanchez.ac603 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) } }
AC603/app/src/test/java/com/gabrielsanchez/ac603/ExampleUnitTest.kt
2449938149
package com.gabrielsanchez.ac603.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)
AC603/app/src/main/java/com/gabrielsanchez/ac603/ui/theme/Color.kt
2589576345
package com.gabrielsanchez.ac603.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 AC603Theme( 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 ) }
AC603/app/src/main/java/com/gabrielsanchez/ac603/ui/theme/Theme.kt
1892725261
package com.gabrielsanchez.ac603.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 ) */ )
AC603/app/src/main/java/com/gabrielsanchez/ac603/ui/theme/Type.kt
3405130506
package com.gabrielsanchez.ac603.viewmodels import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.gabrielsanchez.ac603.models.Articulos import com.gabrielsanchez.ac603.room.ArticulosDatabaseDao import com.gabrielsanchez.ac603.states.ArticulosState import kotlinx.coroutines.async import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class ArticulosViewModel( private val dao: ArticulosDatabaseDao ): ViewModel() { var state by mutableStateOf(ArticulosState()) private set init { viewModelScope.launch { dao.getAllArticulos().collectLatest { state = state.copy( articulosList = it ) } } } fun insertArticulo(articulo: Articulos) = viewModelScope.launch { dao.insertArticulo(articulo) } fun updateArticulo(articulo: Articulos) = viewModelScope.launch { dao.updateArticulo(articulo) } suspend fun getArticuloByCodigo(codigo: Int): Articulos? { return viewModelScope.async { dao.getArticuloByCodigo(codigo) }.await() } suspend fun getArticulosByPrecio(precioMin: Float, precioMax: Float) { val articulos = viewModelScope.async { dao.getArticulosByPrecio(precioMin, precioMax) }.await() state = state.copy(articulosList = articulos) } fun deleteArticuloByCodigo(codigo: Int) = viewModelScope.launch { dao.deleteArticuloByCodigo(codigo) } }
AC603/app/src/main/java/com/gabrielsanchez/ac603/viewmodels/ArticulosViewModel.kt
1089240459
package com.gabrielsanchez.ac603 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.room.Room import com.gabrielsanchez.ac603.navigation.NavManager import com.gabrielsanchez.ac603.room.ArticulosDatabase import com.gabrielsanchez.ac603.ui.theme.AC603Theme import com.gabrielsanchez.ac603.viewmodels.ArticulosViewModel class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AC603Theme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val database = Room.databaseBuilder(this, ArticulosDatabase::class.java, "db_articulos").build() val dao = database.articulosDao() val viewModel = ArticulosViewModel(dao) NavManager(viewModel = viewModel) } } } } }
AC603/app/src/main/java/com/gabrielsanchez/ac603/MainActivity.kt
1019822181
package com.gabrielsanchez.ac603.room import androidx.room.Database import androidx.room.RoomDatabase import com.gabrielsanchez.ac603.models.Articulos @Database( entities = [Articulos::class], version = 1, exportSchema = false ) abstract class ArticulosDatabase: RoomDatabase() { abstract fun articulosDao(): ArticulosDatabaseDao }
AC603/app/src/main/java/com/gabrielsanchez/ac603/room/ArticulosDatabase.kt
624903714
package com.gabrielsanchez.ac603.room import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update import com.gabrielsanchez.ac603.models.Articulos import kotlinx.coroutines.flow.Flow @Dao interface ArticulosDatabaseDao { @Query("SELECT * FROM articulos") fun getAllArticulos(): Flow<List<Articulos>> @Query("SELECT * FROM articulos WHERE codigo = :codigo") fun getArticulobyCodigo(codigo: Int): Flow<Articulos> @Insert suspend fun insertArticulo(articulo: Articulos) @Update suspend fun updateArticulo(articulo: Articulos) @Query("SELECT * FROM articulos WHERE codigo = :codigo") suspend fun getArticuloByCodigo(codigo: Int): Articulos @Query("SELECT * FROM articulos WHERE precio BETWEEN :precioMin AND :precioMax") suspend fun getArticulosByPrecio(precioMin: Float, precioMax: Float): List<Articulos> @Query("DELETE FROM articulos WHERE codigo = :codigo") suspend fun deleteArticuloByCodigo(codigo: Int) @Delete suspend fun deleteArticulo(articulo: Articulos) }
AC603/app/src/main/java/com/gabrielsanchez/ac603/room/ArticulosDatabaseDao.kt
1665951247
package com.gabrielsanchez.ac603.navigation sealed class AppScreens(val route: String) { object Articulos : AppScreens("home") object NewArticulo : AppScreens("newArticulo") object EditArticulo : AppScreens("editArticulo") }
AC603/app/src/main/java/com/gabrielsanchez/ac603/navigation/AppScreens.kt
4278755630
package com.gabrielsanchez.ac603.navigation import androidx.compose.runtime.Composable import androidx.lifecycle.ViewModel import androidx.navigation.NavController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.gabrielsanchez.ac603.models.Articulos import com.gabrielsanchez.ac603.viewmodels.ArticulosViewModel import com.gabrielsanchez.ac603.views.ArticulosHomeView import com.gabrielsanchez.ac603.views.EditArticuloView import com.gabrielsanchez.ac603.views.NewArticuloView @Composable fun NavManager(viewModel: ArticulosViewModel) { val navController = rememberNavController() NavHost(navController = navController, startDestination = AppScreens.Articulos.route) { composable(AppScreens.Articulos.route) { ArticulosHomeView(navController, viewModel) } composable(AppScreens.NewArticulo.route) { NewArticuloView(navController, viewModel) } composable(AppScreens.EditArticulo.route + "/{codigo}", arguments = listOf( navArgument("codigo") { type = NavType.IntType } )) { EditArticuloView( navController, viewModel, it.arguments!!.getInt("codigo"), ) } } }
AC603/app/src/main/java/com/gabrielsanchez/ac603/navigation/NavManager.kt
2629993360
package com.gabrielsanchez.ac603.models import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "articulos") data class Articulos( @PrimaryKey(autoGenerate = false) val codigo: Int = 0, @ColumnInfo("descripcion") val descripcion: String, @ColumnInfo("precio") val precio: Float )
AC603/app/src/main/java/com/gabrielsanchez/ac603/models/Articulos.kt
2720983005
package com.gabrielsanchez.ac603.states import com.gabrielsanchez.ac603.models.Articulos data class ArticulosState( val articulosList: List<Articulos> = emptyList() )
AC603/app/src/main/java/com/gabrielsanchez/ac603/states/ArticulosState.kt
4247727052
package com.gabrielsanchez.ac603.views import android.annotation.SuppressLint import android.widget.Toast import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.viewModelScope import androidx.navigation.NavController import com.gabrielsanchez.ac603.models.Articulos import com.gabrielsanchez.ac603.navigation.AppScreens import com.gabrielsanchez.ac603.viewmodels.ArticulosViewModel import kotlinx.coroutines.launch @SuppressLint("CoroutineCreationDuringComposition") @OptIn(ExperimentalMaterial3Api::class) @Composable fun EditArticuloView(navController: NavController, viewModel: ArticulosViewModel, codigo: Int) { var descripcion = remember { mutableStateOf<String?>(null) } var precio = remember { mutableStateOf<Float?>(null) } viewModel.viewModelScope.launch { val articulo = viewModel.getArticuloByCodigo(codigo) if (articulo != null) { descripcion.value = articulo.descripcion precio.value = articulo.precio } } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text(text = "Editar Artículo #${codigo}", color = Color.White, fontWeight = FontWeight.Bold) }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = MaterialTheme.colorScheme.primary ), navigationIcon = { IconButton( onClick = { navController.popBackStack() } ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Regresar", tint = Color.White ) } } ) }, floatingActionButton = { FloatingActionButton( onClick = { if (descripcion.value.toString().isEmpty() || precio.value.toString().isEmpty()) { Toast.makeText(navController.context, "Tienes que llenar todos los campos", Toast.LENGTH_SHORT).show() return@FloatingActionButton } val articulo = Articulos(codigo = codigo, descripcion = descripcion.value!!, precio = precio.value!!) viewModel.updateArticulo(articulo) navController.popBackStack() }, containerColor = MaterialTheme.colorScheme.primary, contentColor = Color.White, shape = CircleShape, ) { Icon(imageVector = Icons.Default.Check, contentDescription = "Agregar") } } ) { ContentEditArticuloView(it, descripcion, precio) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ContentEditArticuloView( it: PaddingValues, descripcion: MutableState<String?>, precio: MutableState<Float?> ) { Column( modifier = Modifier .padding(it) .padding(top = 30.dp) .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { OutlinedTextField( value = descripcion.value ?: "", onValueChange = { descripcion.value = it }, label = { Text(text = "Descripcion") }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 30.dp) .padding(bottom = 15.dp), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Next ), ) OutlinedTextField( value = precio.value?.toString() ?: "", onValueChange = { if (it.isNotEmpty()) precio.value = it.toFloat() }, label = { Text(text = "Precio") }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 30.dp) .padding(bottom = 15.dp), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done, keyboardType = KeyboardType.Number ), ) } }
AC603/app/src/main/java/com/gabrielsanchez/ac603/views/EditArticuloView.kt
2025896802
package com.gabrielsanchez.ac603.views import android.widget.Toast import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.gabrielsanchez.ac603.models.Articulos import com.gabrielsanchez.ac603.viewmodels.ArticulosViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun NewArticuloView(navController: NavController, viewModel: ArticulosViewModel) { var codigo = remember { mutableStateOf("") } var descripcion = remember { mutableStateOf("") } var precio = remember { mutableStateOf("") } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text(text = "Nuevo Artículo", color = Color.White, fontWeight = FontWeight.Bold) }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = MaterialTheme.colorScheme.primary ), navigationIcon = { IconButton( onClick = { navController.popBackStack() } ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "Regresar", tint = Color.White ) } } ) }, floatingActionButton = { FloatingActionButton( onClick = { if (codigo.value.isEmpty() || descripcion.value.isEmpty() || precio.value.isEmpty()) { Toast.makeText(navController.context, "Todos los campos son requeridos", Toast.LENGTH_SHORT).show() return@FloatingActionButton } val articulo = Articulos(codigo = codigo.value.toInt(), descripcion = descripcion.value, precio = precio.value.toFloat()) viewModel.insertArticulo(articulo) navController.popBackStack() }, containerColor = MaterialTheme.colorScheme.primary, contentColor = Color.White, shape = CircleShape, ) { Icon(imageVector = Icons.Default.Check, contentDescription = "Agregar") } } ) { ContentNewArticuloView(it, codigo, descripcion, precio) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ContentNewArticuloView( it: PaddingValues, codigo: MutableState<String>, descripcion: MutableState<String>, precio: MutableState<String> ) { Column( modifier = Modifier .padding(it) .padding(top = 30.dp) .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { OutlinedTextField( value = codigo.value, onValueChange = { codigo.value = it }, label = { Text(text = "Código") }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 30.dp) .padding(bottom = 15.dp), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Next, keyboardType = KeyboardType.Number ), ) OutlinedTextField( value = descripcion.value, onValueChange = { descripcion.value = it }, label = { Text(text = "Descripcion") }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 30.dp) .padding(bottom = 15.dp), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Next ), ) OutlinedTextField( value = precio.value, onValueChange = { precio.value = it }, label = { Text(text = "Precio") }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 30.dp) .padding(bottom = 15.dp), keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done, keyboardType = KeyboardType.Number ), ) } }
AC603/app/src/main/java/com/gabrielsanchez/ac603/views/NewArticuloView.kt
1017778963
package com.gabrielsanchez.ac603.views import android.annotation.SuppressLint import android.content.Context import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RangeSlider import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import kotlinx.coroutines.launch import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewModelScope import androidx.navigation.NavController import com.gabrielsanchez.ac603.models.Articulos import com.gabrielsanchez.ac603.navigation.AppScreens import com.gabrielsanchez.ac603.viewmodels.ArticulosViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun ArticulosHomeView(navController: NavController, viewModel: ArticulosViewModel) { var isMenuOpen by rememberSaveable { mutableStateOf(false) } val menuItems = listOf("Consulta por código", "Consulta por precio", "Borrar artículo por código") val showDialogConsultaPorCodigo = rememberSaveable { mutableStateOf(false) } val showDialogConsultaPorPrecio = rememberSaveable { mutableStateOf(false) } val showDialogDelete = rememberSaveable { mutableStateOf(false) } var precioMin = remember { mutableStateOf("") } var precioMax = remember { mutableStateOf("") } if (showDialogConsultaPorCodigo.value) { ConsultaPorCodigo( onDismissRequest = { showDialogConsultaPorCodigo.value = false }, onConfirmation = { showDialogConsultaPorCodigo.value = false }, dialogTitle = "Consulta por código", viewModel = viewModel, navController = navController ) } if (showDialogDelete.value) { DeletePorCodigo( onDismissRequest = { showDialogDelete.value = false }, onConfirmation = { showDialogDelete.value = false }, dialogTitle = "Borrar artículo por código", viewModel = viewModel ) } if (showDialogConsultaPorPrecio.value) { ConsultaPorPrecio( onDismissRequest = { showDialogConsultaPorPrecio.value = false }, onConfirmation = { showDialogConsultaPorPrecio.value = false }, dialogTitle = "Consulta por precio", viewModel = viewModel, precioMin, precioMax ) } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text(text = "Artículos", color = Color.White, fontWeight = FontWeight.Bold) }, actions = { IconButton(onClick = { isMenuOpen = true }) { Icon( imageVector = Icons.Default.MoreVert, contentDescription = "Menú", tint = Color.White ) } DropdownMenu( expanded = isMenuOpen, onDismissRequest = { isMenuOpen = false } ) { menuItems.forEachIndexed { index, s -> DropdownMenuItem(text = { Text(text = s) }, onClick = { isMenuOpen = false when (index) { 0 -> showDialogConsultaPorCodigo.value = true 1 -> showDialogConsultaPorPrecio.value = true 2 -> showDialogDelete.value = true } }) } } }, colors = TopAppBarDefaults.centerAlignedTopAppBarColors( containerColor = MaterialTheme.colorScheme.primary ), ) }, floatingActionButton = { FloatingActionButton( onClick = { navController.navigate(AppScreens.NewArticulo.route) }, containerColor = MaterialTheme.colorScheme.primary, contentColor = Color.White ) { Icon(imageVector = Icons.Default.Add, contentDescription = "Agregar") } } ) { ContentInicioView(it, navController, viewModel) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ContentInicioView( it: PaddingValues, navController: NavController, viewModel: ArticulosViewModel ) { var state = viewModel.state LaunchedEffect(state.articulosList) { // Este bloque se ejecutará cada vez que state.articulosList cambie state = state.copy() } Column( modifier = Modifier.padding(it) ) { LazyColumn { if (state.articulosList.isEmpty()) { item { Text( text = "No hay articulos", fontSize = 20.sp, modifier = Modifier .fillMaxWidth() .padding(8.dp), textAlign = TextAlign.Center ) } } else { items(state.articulosList) { Card( elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ), modifier = Modifier .fillMaxWidth() .padding(8.dp), onClick = { navController.navigate(AppScreens.EditArticulo.route + "/${it.codigo}") } ) { Box( modifier = Modifier .fillMaxWidth() .padding(15.dp) ) { Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Text( text = "#${it.codigo} - ${it.descripcion}", textAlign = TextAlign.Start, fontSize = 20.sp, fontWeight = FontWeight.Bold, // Aumenta el grosor del texto modifier = Modifier .weight(1f), ) Text( text = "${it.precio}€", textAlign = TextAlign.End, fontSize = 20.sp, fontWeight = FontWeight.Bold, // Aumenta el grosor del texto modifier = Modifier .weight(1f), ) } } } } } } } } @Composable fun ConsultaPorCodigo( onDismissRequest: () -> Unit, onConfirmation: () -> Unit, dialogTitle: String, viewModel: ArticulosViewModel, navController: NavController, context: Context = LocalContext.current ) { var codigo by remember { mutableStateOf("") } AlertDialog( icon = { Icon(Icons.Default.Edit, contentDescription = "Example Icon") }, title = { Text(text = dialogTitle) }, text = { OutlinedTextField( value = codigo, onValueChange = { codigo = it }, label = { Text("Código del artículo") }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done, ) ) }, onDismissRequest = { onDismissRequest() }, confirmButton = { TextButton( onClick = { // Lanzamos una corrutina para obtener el articulo viewModel.viewModelScope.launch { val articulo = viewModel.getArticuloByCodigo(codigo.toInt()) if (articulo != null) { navController.navigate(AppScreens.EditArticulo.route + "/${articulo.codigo}") } else { Toast.makeText( context, "El artículo no existe", Toast.LENGTH_SHORT ).show() } } onConfirmation() } ) { Text("Confirmar") } }, dismissButton = { TextButton( onClick = { onDismissRequest() } ) { Text("Cancelar") } } ) } @SuppressLint("UnrememberedMutableState") @Composable fun ConsultaPorPrecio( onDismissRequest: () -> Unit, onConfirmation: () -> Unit, dialogTitle: String, viewModel: ArticulosViewModel, precioMin: MutableState<String>, // Recibir precioMin y precioMax como argumentos precioMax: MutableState<String>, ) { AlertDialog( icon = { Icon(Icons.Default.Edit, contentDescription = "Example Icon") }, title = { Text(text = dialogTitle) }, text = { RangeSliderPrecio(precioMin, precioMax) }, onDismissRequest = { onDismissRequest() }, confirmButton = { TextButton( onClick = { // Lanzamos una corrutina para obtener el articulo viewModel.viewModelScope.launch { viewModel.getArticulosByPrecio(precioMin.value.toFloat(), precioMax.value.toFloat()) } onConfirmation() } ) { Text("Confirmar") } }, dismissButton = { TextButton( onClick = { onDismissRequest() } ) { Text("Cancelar") } } ) } @SuppressLint("CoroutineCreationDuringComposition") @Composable fun RangeSliderPrecio(precioMin: MutableState<String>, precioMax: MutableState<String>) { Column { // Precio Minimo OutlinedTextField( value = precioMin.value, onValueChange = { precioMin.value = it }, label = { Text("Precio mínimo") }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done, ) ) // Precio Maximo OutlinedTextField( value = precioMax.value.toString(), onValueChange = { precioMax.value = it }, label = { Text("Precio máximo") }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done, ) ) } } @Composable fun DeletePorCodigo( onDismissRequest: () -> Unit, onConfirmation: () -> Unit, dialogTitle: String, viewModel: ArticulosViewModel, context: Context = LocalContext.current ) { var codigo by remember { mutableStateOf("") } AlertDialog( icon = { Icon(Icons.Default.Delete, contentDescription = "Example Icon") }, title = { Text(text = dialogTitle) }, text = { OutlinedTextField( value = codigo, onValueChange = { codigo = it }, label = { Text("Código del artículo") }, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ) ) }, onDismissRequest = { onDismissRequest() }, confirmButton = { TextButton( onClick = { // Comprobamos que el articulo existe viewModel.viewModelScope.launch { val articulo = viewModel.getArticuloByCodigo(codigo.toInt()) if (articulo == null) { Toast.makeText( context, "El artículo no existe", Toast.LENGTH_SHORT ).show() } else { viewModel.deleteArticuloByCodigo(codigo.toInt()) Toast.makeText( context, "Artículo borrado correctamente", Toast.LENGTH_SHORT ).show() } } onConfirmation() } ) { Text("Eliminar") } }, dismissButton = { TextButton( onClick = { onDismissRequest() } ) { Text("Cancelar") } } ) }
AC603/app/src/main/java/com/gabrielsanchez/ac603/views/ArticulosHomeView.kt
933144627
package dev.silverandro.ee_boom enum class State(val message: String) { // Startup ACQUIRE_LOG("Getting log file"), // Loop WAITING("Waiting for update"), PARSING("Parsing lines"), PLAYING("Playing audio clip") }
ee-boom/src/main/kotlin/dev/silverandro/ee_boom/State.kt
1724073655
package dev.silverandro.ee_boom import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.Column import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowState import androidx.compose.ui.window.application import dev.silverandro.ee_boom.log.LogWatcher import java.time.Instant @Composable @Preview fun App() { var applicationState by remember { mutableStateOf(State.ACQUIRE_LOG) } var averageUpdateRate by remember { mutableStateOf(0.0) } val updates = mutableListOf<Instant>() val updater: (State)->Unit = { if (it != applicationState) { println(it) } applicationState = it } val ping: ()->Unit = { updates.add(Instant.now()) if (updates.size > 20) { updates.removeFirst() } val result = updates.mapIndexedNotNull { i, inst -> if (i+1 > updates.lastIndex) return@mapIndexedNotNull null return@mapIndexedNotNull updates[i + 1].toEpochMilli() - inst.toEpochMilli() }.average() averageUpdateRate = result } MaterialTheme { Column { Text(applicationState.message) Text("Mills between updates: $averageUpdateRate") } } LogWatcher.start(updater, ping) } fun main() = application { Window( title = "ee-boom", resizable = false, state = WindowState(width = 400.dp, height = 200.dp), onCloseRequest = { LogWatcher.shutdown(); exitApplication(); } ) { App() } }
ee-boom/src/main/kotlin/dev/silverandro/ee_boom/Main.kt
2478783207
package dev.silverandro.ee_boom.audio import kotlinx.coroutines.* import javax.sound.sampled.* import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds object ClipPlayer : LineListener { val scope = CoroutineScope(Dispatchers.IO) private var donePlaying = false suspend fun playClip() { scope.launch { val inputStream = javaClass.classLoader.getResourceAsStream("vine_boom.wav")?.buffered() val audioStream = AudioSystem.getAudioInputStream(inputStream) val clip = AudioSystem.getClip() clip.open(audioStream) clip.addLineListener(this@ClipPlayer) clip.start() launch { delay(2.seconds) while (isActive && !donePlaying) { delay(100.milliseconds) } }.join() donePlaying = false clip.close() audioStream.close() }.join() } override fun update(event: LineEvent) { if (LineEvent.Type.START == event.type) { println("playback start") } else if (LineEvent.Type.STOP == event.type) { println("playback stop") donePlaying = true } } }
ee-boom/src/main/kotlin/dev/silverandro/ee_boom/audio/ClipPlayer.kt
4043009869
package dev.silverandro.ee_boom.log import dev.silverandro.ee_boom.State import dev.silverandro.ee_boom.audio.ClipPlayer import kotlinx.coroutines.* import java.io.File import java.nio.file.FileSystems import java.nio.file.Path import java.nio.file.StandardWatchEventKinds import java.time.Instant import kotlin.io.path.Path import kotlin.io.path.exists import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds object LogWatcher { val logFile = File("${System.getenv("LOCALAPPDATA")}/Warframe/EE.log") val scope = CoroutineScope(Dispatchers.IO) var watch = Instant.now().toEpochMilli() val fileBuffer = logFile.bufferedReader() var fragment: String? = null var shouldPlay = false fun start(update: (State) -> Unit, ping: () -> Unit) { // Disruption: Boss Killed for artifact 2 scope.launch { while (isActive) { delay(25.milliseconds) val new = logFile.lastModified() if (new > watch) { watch = new update.invoke(State.PARSING) ping.invoke() fragment = fileBuffer.readLine() while (true) { val next = fileBuffer.readLine() if (next != null) { processLine(fragment!!) fragment = next } else { break } } } if (shouldPlay) { update.invoke(State.PLAYING) ClipPlayer.playClip() shouldPlay = false } update.invoke(State.WAITING) } } } fun processLine(line: String) { if ( line.contains("Disruption: Boss Killed for artifact") || line.contains("Disruption: Completed defense for artifact") ) { shouldPlay = true println("FOUND LINE!") } } fun shutdown() { scope.cancel("Shutting down application") fileBuffer.close() } }
ee-boom/src/main/kotlin/dev/silverandro/ee_boom/log/LogWatcher.kt
640002989
package com.example.todoapp import android.content.Intent import android.graphics.* import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.lifecycle.Observer import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val list = arrayListOf<TodoModel>() var adapter = TodoAdapter(list) val db by lazy { AppDatabase.getDatabase(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) todoRv.apply { layoutManager = LinearLayoutManager(this@MainActivity) adapter = [email protected] } initSwipe() db.todoDao().getTask().observe(this, Observer { if (!it.isNullOrEmpty()) { list.clear() list.addAll(it) adapter.notifyDataSetChanged() }else{ list.clear() adapter.notifyDataSetChanged() } }) } fun initSwipe() { val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition if (direction == ItemTouchHelper.LEFT) { GlobalScope.launch(Dispatchers.IO) { db.todoDao().deleteTask(adapter.getItemId(position)) } } else if (direction == ItemTouchHelper.RIGHT) { GlobalScope.launch(Dispatchers.IO) { db.todoDao().finishTask(adapter.getItemId(position)) } } } override fun onChildDraw( canvas: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val itemView = viewHolder.itemView val paint = Paint() val icon: Bitmap if (dX > 0) { icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_check_white_png) paint.color = Color.parseColor("#388E3C") canvas.drawRect( itemView.left.toFloat(), itemView.top.toFloat(), itemView.left.toFloat() + dX, itemView.bottom.toFloat(), paint ) canvas.drawBitmap( icon, itemView.left.toFloat(), itemView.top.toFloat() + (itemView.bottom.toFloat() - itemView.top.toFloat() - icon.height.toFloat()) / 2, paint ) } else { icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_delete_white_png) paint.color = Color.parseColor("#D32F2F") canvas.drawRect( itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat(), paint ) canvas.drawBitmap( icon, itemView.right.toFloat() - icon.width, itemView.top.toFloat() + (itemView.bottom.toFloat() - itemView.top.toFloat() - icon.height.toFloat()) / 2, paint ) } viewHolder.itemView.translationX = dX } else { super.onChildDraw( canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive ) } } } val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback) itemTouchHelper.attachToRecyclerView(todoRv) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) val item = menu.findItem(R.id.search) val searchView = item.actionView as SearchView item.setOnActionExpandListener(object :MenuItem.OnActionExpandListener{ override fun onMenuItemActionExpand(item: MenuItem?): Boolean { displayTodo() return true } override fun onMenuItemActionCollapse(item: MenuItem?): Boolean { displayTodo() return true } }) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { if(!newText.isNullOrEmpty()){ displayTodo(newText) } return true } }) return super.onCreateOptionsMenu(menu) } fun displayTodo(newText: String = "") { db.todoDao().getTask().observe(this, Observer { if(it.isNotEmpty()){ list.clear() list.addAll( it.filter { todo -> todo.title.contains(newText,true) } ) adapter.notifyDataSetChanged() } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.history -> { startActivity(Intent(this, HistoryActivity::class.java)) } } return super.onOptionsItemSelected(item) } fun openNewTask(view: View) { startActivity(Intent(this, TaskActivity::class.java)) } }
MobileApplication/MainActivity.kt
1330864296
package com.example.todoapp 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.todoapp", appContext.packageName) } }
MobileApplication/ExampleInstrumentedTest.kt
1645281313
package com.example.todoapp 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) } }
MobileApplication/ExampleUnitTest.kt
3779751093
package com.example.todoapp import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [TodoModel::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun todoDao(): TodoDao companion object { // Singleton prevents multiple instances of database opening at the // same time. @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, DB_NAME ).build() INSTANCE = instance return instance } } } }
MobileApplication/AppDatabase.kt
3836948247
package com.example.todoapp import androidx.room.Entity import androidx.room.PrimaryKey // we are making list for each task @Entity data class TodoModel( var title:String, var description:String, var category: String, var date:Long, var time:Long, var isFinished : Int = 0, @PrimaryKey(autoGenerate = true) var id:Long = 0 )
MobileApplication/TodoModel.kt
3374681082
package com.example.todoapp import android.app.DatePickerDialog import android.app.TimePickerDialog import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.DatePicker import android.widget.TimePicker import androidx.appcompat.app.AppCompatActivity import androidx.room.Room import kotlinx.android.synthetic.main.activity_task.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.SimpleDateFormat import java.util.* const val DB_NAME = "todo.db" class TaskActivity : AppCompatActivity(), View.OnClickListener { lateinit var myCalendar: Calendar lateinit var dateSetListener: DatePickerDialog.OnDateSetListener lateinit var timeSetListener: TimePickerDialog.OnTimeSetListener var finalDate = 0L var finalTime = 0L private val labels = arrayListOf("Personal", "Business", "Insurance", "Shopping", "Banking") val db by lazy { AppDatabase.getDatabase(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_task) dateEdt.setOnClickListener(this) timeEdt.setOnClickListener(this) saveBtn.setOnClickListener(this) setUpSpinner() } private fun setUpSpinner() { val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, labels) labels.sort() spinnerCategory.adapter = adapter } override fun onClick(v: View) { when (v.id) { R.id.dateEdt -> { setListener() } R.id.timeEdt -> { setTimeListener() } R.id.saveBtn -> { saveTodo() } } } private fun saveTodo() { val category = spinnerCategory.selectedItem.toString() val title = titleInpLay.editText?.text.toString() val description = taskInpLay.editText?.text.toString() GlobalScope.launch(Dispatchers.Main) { val id = withContext(Dispatchers.IO) { return@withContext db.todoDao().insertTask( TodoModel( title, description, category, finalDate, finalTime ) ) } finish() } } private fun setTimeListener() { myCalendar = Calendar.getInstance() timeSetListener = TimePickerDialog.OnTimeSetListener() { _: TimePicker, hourOfDay: Int, min: Int -> myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay) myCalendar.set(Calendar.MINUTE, min) updateTime() } val timePickerDialog = TimePickerDialog( this, timeSetListener, myCalendar.get(Calendar.HOUR_OF_DAY), myCalendar.get(Calendar.MINUTE), false ) timePickerDialog.show() } private fun updateTime() { //Mon, 5 Jan 2020 val myformat = "h:mm a" val sdf = SimpleDateFormat(myformat) finalTime = myCalendar.time.time timeEdt.setText(sdf.format(myCalendar.time)) } private fun setListener() { myCalendar = Calendar.getInstance() dateSetListener = DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, month: Int, dayOfMonth: Int -> myCalendar.set(Calendar.YEAR, year) myCalendar.set(Calendar.MONTH, month) myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) updateDate() } val datePickerDialog = DatePickerDialog( this, dateSetListener, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH) ) datePickerDialog.datePicker.minDate = System.currentTimeMillis() datePickerDialog.show() } private fun updateDate() { //Mon, 5 Jan 2020 val myformat = "EEE, d MMM yyyy" val sdf = SimpleDateFormat(myformat) finalDate = myCalendar.time.time dateEdt.setText(sdf.format(myCalendar.time)) timeInptLay.visibility = View.VISIBLE } }
MobileApplication/TaskActivity.kt
3184034091
package com.example.todoapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class HistoryActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_history) } }
MobileApplication/HistoryActivity.kt
508418990
package com.example.todoapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.activity_task.* import kotlinx.android.synthetic.main.item_todo.view.* import java.text.SimpleDateFormat import java.util.* // first create adapter class. This inherits recycler view. Recycler view now requires view holder class TodoAdapter(val list: List<TodoModel>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() { // 3 functions of the view holder // 1st func // In this Layout inflatter is called which converts view in such a form that adapter can consume it override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder { return TodoViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_todo, parent, false) ) } override fun getItemCount() = list.size // 2nd func // this will set data in each card override fun onBindViewHolder(holder: TodoViewHolder, position: Int) { holder.bind(list[position]) // we are passing the object of the list that we made in the ToDoModel.kt } // 3rd func override fun getItemId(position: Int): Long { return list[position].id } // view holder is present inside the recycler view class TodoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(todoModel: TodoModel) { with(itemView) { val colors = resources.getIntArray(R.array.random_color) val randomColor = colors[Random().nextInt(colors.size)] viewColorTag.setBackgroundColor(randomColor) txtShowTitle.text = todoModel.title txtShowTask.text = todoModel.description txtShowCategory.text = todoModel.category updateTime(todoModel.time) updateDate(todoModel.date) } } private fun updateTime(time: Long) { //Mon, 5 Jan 2020 val myformat = "h:mm a" val sdf = SimpleDateFormat(myformat) itemView.txtShowTime.text = sdf.format(Date(time)) } private fun updateDate(time: Long) { //Mon, 5 Jan 2020 val myformat = "EEE, d MMM yyyy" val sdf = SimpleDateFormat(myformat) itemView.txtShowDate.text = sdf.format(Date(time)) } } }
MobileApplication/TodoAdapter.kt
1845334418
package com.example.todoapp import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query @Dao interface TodoDao { @Insert() suspend fun insertTask(todoModel: TodoModel):Long @Query("Select * from TodoModel where isFinished == 0") fun getTask():LiveData<List<TodoModel>> @Query("Update TodoModel Set isFinished = 1 where id=:uid") fun finishTask(uid:Long) @Query("Delete from TodoModel where id=:uid") fun deleteTask(uid:Long) }
MobileApplication/TodoDao.kt
3511300464
package com.example.socialm 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.socialm", appContext.packageName) } }
Money-Management-Android-App/app/src/androidTest/java/com/example/socialm/ExampleInstrumentedTest.kt
2901896263
package com.example.socialm 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) } }
Money-Management-Android-App/app/src/test/java/com/example/socialm/ExampleUnitTest.kt
574320850
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class addFund : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_fund) val add_btn = findViewById<Button>(R.id.add_btn) add_btn.setOnClickListener { val homeIntent = Intent(this, home ::class.java) startActivity(homeIntent) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/addFund.kt
2181627479
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val loginPageButton = findViewById<Button>(R.id.loginPagebutton) loginPageButton.setOnClickListener { val loginIntent = Intent(this, login::class.java) startActivity(loginIntent) finish() } val activityHomeButton = findViewById<Button>(R.id.signUp) activityHomeButton.setOnClickListener { val homeIntent = Intent(this, home ::class.java) startActivity(homeIntent) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/MainActivity.kt
3578062243
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.ImageView import android.widget.Spinner import android.widget.Toast class transfer : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_transfer) class TransferActivity : AppCompatActivity() { // val banks = arrayOf("Commercial Bank", "Sampath Bank", "BOC") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_transfer) val home5 = findViewById<Button>(R.id.home5) home5.setOnClickListener { val home5_btb = Intent(this, profile::class.java) startActivity(home5_btb) finish() } // val imageView7 = findViewById<ImageView>(R.id.imageView7) // imageView7.setOnClickListener { // val home5_btb = Intent(this, home::class.java) // startActivity(home5_btb) // finish() // } // val spinner = findViewById<Spinner>(R.id.spinner) // if (spinner != null) { // val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, banks) // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // spinner.adapter = adapter // // spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { // override fun onItemSelected( // parent: AdapterView<*>, // view: View, // position: Int, // id: Long // ) { // Toast.makeText( // this@TransferActivity, // getString(R.string.selected_item) + " " + banks[position], // Toast.LENGTH_SHORT // ).show() // } // override fun onNothingSelected(parent: AdapterView<*>) { // write code to perform some action } } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/transfer.kt
3950340495
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Button import android.widget.ImageView import android.widget.ListView import android.widget.Toast class history : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_history) val homerr = findViewById<ImageView>(R.id.homerr) homerr.setOnClickListener { val actadd_fund_btn = Intent(this, home::class.java) startActivity(actadd_fund_btn) finish() } val historyDataa = arrayOf("LKR 2500 Expence for Class Fee", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath","LKR 2500 Expence for Class Fee", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath","LKR 2500 Expence for Class Fee", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath") // Get the ListView reference val historyListVieww = findViewById<ListView>(R.id.hislist) // Create an ArrayAdapter to populate data into the ListView val adapterr = ArrayAdapter(this, android.R.layout.simple_list_item_1, historyDataa) // Set the adapter to the ListView historyListVieww.adapter = adapterr // Optionally, handle item click events historyListVieww.setOnItemClickListener { _, _, position, _ -> val selectedItem = historyDataa[position] Toast.makeText(this, "Clicked on: $selectedItem", Toast.LENGTH_SHORT).show() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/history.kt
2332648047
package com.example.socialm import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class addaccount : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_addaccount) } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/addaccount.kt
660972989
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class login : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val loginButton = findViewById<Button>(R.id.loginButton) loginButton.setOnClickListener { val homeIntent = Intent(this, home::class.java) startActivity(homeIntent) finish() } val forget = findViewById<Button>(R.id.forget) forget.setOnClickListener { val reset = Intent(this, resetpassword::class.java) startActivity(reset) finish() } val signUp = findViewById<Button>(R.id.signUp) signUp.setOnClickListener { val actsignUp = Intent(this, MainActivity::class.java) startActivity(actsignUp) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/login.kt
1733422165
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class resetpassword : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_resetpassword) val newAccount = findViewById<Button>(R.id.newAccount) newAccount.setOnClickListener { val actnewAccount = Intent(this, MainActivity::class.java) startActivity(actnewAccount) finish() } val backToLogin = findViewById<Button>(R.id.backToLogin) backToLogin.setOnClickListener { val actbackToLogin = Intent(this, login::class.java) startActivity(actbackToLogin) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/resetpassword.kt
953085613
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class CurrencyCalculator : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_currency_calculator) val buttonConvert = findViewById<Button>(R.id.buttonConvert) buttonConvert.setOnClickListener { val home5_btb = Intent(this, home::class.java) startActivity(home5_btb) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/CurrencyCalculator.kt
244746735
package com.example.socialm import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Button import android.widget.ImageButton import android.widget.ImageView import android.widget.ListView import android.widget.Toast class home : AppCompatActivity() { @SuppressLint("WrongViewCast") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val add_fund_btn = findViewById<Button>(R.id.add_fund_btn) add_fund_btn.setOnClickListener { val actadd_fund_btn = Intent(this, addFund::class.java) startActivity(actadd_fund_btn) finish() } val expencess_btn = findViewById<Button>(R.id.expencess_btn) expencess_btn.setOnClickListener { val actexpencess_btn = Intent(this, expencess::class.java) startActivity(actexpencess_btn) finish() } val Pro_btn = findViewById<ImageView>(R.id.Pro_btn) Pro_btn.setOnClickListener { val Pro_btn1 = Intent(this, profile::class.java) startActivity(Pro_btn1) finish() } val calbtn = findViewById<ImageView>(R.id.calbtn) calbtn.setOnClickListener { val Pro_calbtn = Intent(this, CurrencyCalculator::class.java) startActivity(Pro_calbtn) finish() } val sendm = findViewById<ImageButton>(R.id.sendm) sendm.setOnClickListener { val Pro_sendm = Intent(this, transfer::class.java) startActivity(Pro_sendm) finish() } val sendbtn3 = findViewById<ImageView>(R.id.sendbtn3) sendbtn3.setOnClickListener { val Pro_sendm = Intent(this, transfer::class.java) startActivity(Pro_sendm) finish() } val historybtn = findViewById<ImageView>(R.id.historybtn) historybtn.setOnClickListener { val history_btn14 = Intent(this, history::class.java) startActivity(history_btn14) finish() } val historyData = arrayOf("LKR 2500 Expence for Class Fee", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath","LKR 2500 Expence for Class Fee", "LKR 5000 Expence for Helth", "LKR 50 000 Add Fund from March salary", "LKR 6500 Expence for car service", "LKR 10 000 Add Fund from Kasun herath") // Get the ListView reference val historyListView = findViewById<ListView>(R.id.hislist) // Create an ArrayAdapter to populate data into the ListView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, historyData) // Set the adapter to the ListView historyListView.adapter = adapter // Optionally, handle item click events historyListView.setOnItemClickListener { _, _, position, _ -> val selectedItem = historyData[position] Toast.makeText(this, "Clicked on: $selectedItem", Toast.LENGTH_SHORT).show() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/home.kt
4000676246
package com.example.socialm import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class expencess : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_expencess) val expen_btn = findViewById<Button>(R.id.expen_btn) expen_btn.setOnClickListener { val homeexpen_btn = Intent(this, home::class.java) startActivity(homeexpen_btn) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/expencess.kt
900831752
package com.example.socialm import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity class profile : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_profile) val logout = findViewById<Button>(R.id.logout) logout.setOnClickListener { val logout_btb = Intent(this, login::class.java) startActivity(logout_btb) finish() } val button2 = findViewById<Button>(R.id.button2) button2.setOnClickListener { val addacc_btb = Intent(this, addaccount::class.java) startActivity(addacc_btb) finish() } val options_view = findViewById<ImageView>(R.id.options_view) options_view.setOnClickListener { val options_view_btb = Intent(this, home::class.java) startActivity(options_view_btb) finish() } } }
Money-Management-Android-App/app/src/main/java/com/example/socialm/profile.kt
4143872090
package com.example.testecompose 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.testecompose", appContext.packageName) } }
TesteCompose/app/src/androidTest/java/com/example/testecompose/ExampleInstrumentedTest.kt
2562760055
package com.example.testecompose 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) } }
TesteCompose/app/src/test/java/com/example/testecompose/ExampleUnitTest.kt
2316930971
package com.example.testecompose.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)
TesteCompose/app/src/main/java/com/example/testecompose/ui/theme/Color.kt
2705594236
package com.example.testecompose.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 TesteComposeTheme( 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 ) }
TesteCompose/app/src/main/java/com/example/testecompose/ui/theme/Theme.kt
698296399