content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.town360 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.town360", appContext.packageName) } }
Town360/androidTest/java/com/example/town360/ExampleInstrumentedTest.kt
4238441056
package com.example.town360 import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.example.town360.databinding.ActivityAddUserBinding import com.google.firebase.FirebaseApp import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference class AddUser : AppCompatActivity() { private lateinit var binding: ActivityAddUserBinding private val database = FirebaseDatabase.getInstance() private val storage = FirebaseStorage.getInstance() private val imageRef: StorageReference by lazy { storage.reference.child("images") // You can customize the storage path } private var selectedImageUri: Uri? = null private val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> uri?.let { // Image selected from the gallery selectedImageUri = it // Display the selected image in your ImageView binding.imgUser.setImageURI(selectedImageUri) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) FirebaseApp.initializeApp(this) binding = ActivityAddUserBinding.inflate(layoutInflater) setContentView(binding.root) val btnAddUser: Button = findViewById(R.id.btnAddUser) val etName: EditText = findViewById(R.id.etName) val etNumber: EditText = findViewById(R.id.etNumber) val etDetails: EditText = findViewById(R.id.etDetails) val tvJobDetails: TextView = findViewById(R.id.tvJobDetails) binding.tvJob.text = intent.getStringExtra("ITEM_NAME").toString() val imgUser: ImageView = findViewById(R.id.imgUser) binding.btnSelectImage.setOnClickListener { // Call the image picker pickImage.launch("image/*") } btnAddUser.setOnClickListener { val name = etName.text.toString() val number = etNumber.text.toString() val details = etDetails.text.toString() val job = intent.getStringExtra("ITEM_NAME").toString() // Check if any of the fields are empty if (name.isEmpty() || number.isEmpty() || details.isEmpty()) { showToast("Please fill in all fields") return@setOnClickListener } // Create a User object val user = User(id=null,name, number, details, job) // Upload the image and save user data uploadImageAndSaveUser(job, user) // Clear all EditText fields etName.text.clear() etNumber.text.clear() etDetails.text.clear() // Show a toast showToast("User added successfully!") } } private fun uploadImageAndSaveUser(collectionName: String, user: User) { selectedImageUri?.let { uri -> // Create a reference to the image file val imageFileName = "${System.currentTimeMillis()}.jpg" val imageRef = imageRef.child(imageFileName) // Upload the image to Firebase Storage imageRef.putFile(uri) .addOnSuccessListener { taskSnapshot -> // Image upload successful, get the download URL imageRef.downloadUrl.addOnSuccessListener { imageUrl -> // Save the user with the image URL to Firebase Realtime Database user.image = imageUrl.toString() saveUserToFirebase(collectionName, user) } } .addOnFailureListener { exception -> // Image upload failed showToast("Failed to upload image. ${exception.message}") } } } private fun saveUserToFirebase(collectionName: String, user: User) { val usersReference = database.getReference(collectionName) val userId = usersReference.push().key // Generate a unique key for the user userId?.let { val userReference = usersReference.child(it) user.id = it // Set the ID userReference.setValue(user) .addOnSuccessListener { showToast("User added successfully!") finish() // Close the activity after successful addition } .addOnFailureListener { exception -> showToast("Failed to add user. ${exception.message}") } } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
Town360/java/com/example/town360/AddUser.kt
1517940249
package com.example.town360 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.GridView import androidx.fragment.app.Fragment import com.google.firebase.FirebaseApp import com.example.town360.databinding.ActivityHealthBinding import com.example.town360.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) FirebaseApp.initializeApp(this) replaceFragment(Home()) binding.bottomNavigationView.setOnItemSelectedListener { when(it.itemId){ R.id.home -> replaceFragment(Home()) R.id.emergency -> replaceFragment(emergency()) R.id.aboutus -> replaceFragment(about_us()) else ->{ } } true } // // val gridView: GridView = findViewById(R.id.gridView) // // val dashboardItems = listOf( // DashboardItem(R.drawable.farmer, "ખેતી"), // DashboardItem(R.drawable.mechanic, "ગાડી રેપઈરિનગ"), // DashboardItem(R.drawable.handyman, "કારીગરો"), // DashboardItem(R.drawable.apartment, "પ્રોપરટી"), // DashboardItem(R.drawable.housebuy, "મકાન"), // DashboardItem(R.drawable.homerent, "ભાડે મકાન"), // DashboardItem(R.drawable.vegfruit, "શાક ભાજી"), // DashboardItem(R.drawable.mechanic, "Car Repair"), // DashboardItem(R.drawable.handyman, "Repair"), // // Add more items as needed // ) // // val adapter = DashboardAdapter(this, dashboardItems) // gridView.adapter = adapter } private fun replaceFragment(fragment: Fragment){ val fragmentManeger = supportFragmentManager val fragmentTrancection = fragmentManeger.beginTransaction() fragmentTrancection.replace(R.id.frame_layout,fragment) fragmentTrancection.commit() } }
Town360/java/com/example/town360/MainActivity.kt
4117882933
// ServiceDetailsActivity.kt package com.example.town360 import android.content.Intent import android.os.Bundle import android.view.ContextMenu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.GridView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.textview.MaterialTextView import com.google.firebase.database.* class ServiceDetailsActivity : AppCompatActivity() { private lateinit var serviceNameTextView: MaterialTextView private lateinit var gridView: GridView private lateinit var fabAddService: FloatingActionButton private lateinit var parentServiceName: String private lateinit var subServices: MutableList<SubService> private lateinit var subServiceAdapter: SubServiceAdapter private val databaseReference = FirebaseDatabase.getInstance().reference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_service_details) serviceNameTextView = findViewById(R.id.serviceNameTextView) gridView = findViewById(R.id.gridView1) fabAddService = findViewById(R.id.fabAddService1) parentServiceName = intent.getStringExtra("SERVICE_NAME").toString() serviceNameTextView.text = parentServiceName subServices = mutableListOf() subServiceAdapter = SubServiceAdapter(this, subServices) gridView.adapter = subServiceAdapter registerForContextMenu(gridView) retrieveSubServicesFromFirebase() fabAddService.setOnClickListener { val i = Intent(this, AddSubServiceActivity::class.java).apply { putExtra("SERVICE_NAME", parentServiceName) } startActivity(i) } gridView.setOnItemLongClickListener { _, view, position, _ -> showBottomSheetOptions(subServices[position]) true } gridView.setOnItemClickListener { _, _, position, _ -> val selectedSubService = subServices[position] val i = Intent(this, Health::class.java).apply { putExtra("ITEM_NAME", selectedSubService.name) } startActivity(i) } } private fun retrieveSubServicesFromFirebase() { val subServicesReference = databaseReference.child("sub_services").child(parentServiceName) subServicesReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { subServices.clear() for (childSnapshot in snapshot.children) { val subService = childSnapshot.getValue(SubService::class.java) subService?.let { subServices.add(it) } } subServiceAdapter.notifyDataSetChanged() } override fun onCancelled(error: DatabaseError) { showToast("Database error: ${error.message}") } }) } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun showBottomSheetOptions(subService: SubService) { val bottomSheetFragment = BottomSheetOptionsDialogFragment() bottomSheetFragment.setOnDeleteClickListener { showDeleteConfirmationDialog(subService) } bottomSheetFragment.show(supportFragmentManager, bottomSheetFragment.tag) } private fun showDeleteConfirmationDialog(subService: SubService) { AlertDialog.Builder(this) .setTitle("Delete Sub-Service") .setMessage("Are you sure you want to delete ${subService.name}?") .setPositiveButton("Delete") { _, _ -> deleteSubService(subService) } .setNegativeButton("Cancel", null) .show() } private fun deleteSubService(subService: SubService) { val subServiceReference = databaseReference.child("sub_services").child(parentServiceName) .child(subService.name) subServiceReference.removeValue() .addOnSuccessListener { showToast("Sub-Service deleted successfully") } .addOnFailureListener { showToast("Error deleting sub-service") } } }
Town360/java/com/example/town360/ServiceDetailsActivity.kt
910251705
package com.example.town360 import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView class EmergencyAdapter(private val context: Context, private val items: List<DashboardItem>) : BaseAdapter() { private val activityClasses = arrayOf( bloodtype::class.java, Health::class.java, Health::class.java, Health::class.java, Health::class.java, Health::class.java, // Add more activities as needed ) override fun getCount(): Int = items.size override fun getItem(position: Int): Any = items[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val viewHolder: ViewHolder val view: View if (convertView == null) { // Inflate the view for each item if it's not recycled view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false) // Create a ViewHolder and store references to the children views viewHolder = ViewHolder(view) view.tag = viewHolder } else { // Reuse the recycled view view = convertView // Retrieve the ViewHolder from the recycled view viewHolder = view.tag as ViewHolder } val item = getItem(position) as DashboardItem viewHolder.imageView.setImageResource(item.imageResId) viewHolder.textView.text = item.text // Handle item click view.setOnClickListener { // Create an Intent to start the corresponding activity val intent = Intent(context, activityClasses[position]) // Pass information to the next activity intent.putExtra("ITEM_NAME", item.text) intent.putExtra("ITEM_IMAGE_RES_ID", item.imageResId) context.startActivity(intent) } return view } private class ViewHolder(view: View) { val imageView: ImageView = view.findViewById(R.id.imageView) val textView: TextView = view.findViewById(R.id.textView) } }
Town360/java/com/example/town360/EmergencyAdapter.kt
2106318808
package com.example.town360 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.GridView import androidx.fragment.app.Fragment private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" class emergency : Fragment() { private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_emergency, container, false) // Move GridView setup to onViewCreated return view } // Move GridView setup to onViewCreated override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val gridView: GridView = view.findViewById(R.id.gridView) val dashboardItems = listOf( DashboardItem(R.drawable.blood, "બ્લડ ડોનર"), DashboardItem(R.drawable.hospital, "હોસ્પિટલ"), DashboardItem(R.drawable.med, "દવાઓ"), DashboardItem(R.drawable.ambulance, "એમ્બુલન્સ"), DashboardItem(R.drawable.firestation, "ફાયર સ્ટેશન"), DashboardItem(R.drawable.police, "પોલીસ"), // Add more items as needed ) val adapter = EmergencyAdapter(requireContext(), dashboardItems) gridView.adapter = adapter } companion object { @JvmStatic fun newInstance(param1: String, param2: String) = Home().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Town360/java/com/example/town360/emergency.kt
786543731
package com.example.town360 import android.content.DialogInterface import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.* import com.squareup.picasso.Picasso class UserDetailsActivity : AppCompatActivity() { private lateinit var userImageView: ImageView private lateinit var userNameTextView: TextView private lateinit var userNumberTextView: TextView private lateinit var userJobTextView: TextView private lateinit var userDetailsTextView: TextView private lateinit var userReference: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_details) // Initialize UI components userImageView = findViewById(R.id.userImageView) userNameTextView = findViewById(R.id.userNameTextView) userNumberTextView = findViewById(R.id.userNumberTextView) userJobTextView = findViewById(R.id.userJobTextView) userDetailsTextView = findViewById(R.id.userDetailsTextView) // Retrieve user information from intent val collection = intent.getStringExtra("ITEM_NAME") val userId = intent.getStringExtra("USER_ID").toString() // Initialize Firebase Database reference userReference = FirebaseDatabase.getInstance().getReference(collection.toString()).child(userId) // Add a ValueEventListener to listen for changes in user data userReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { if (snapshot.exists()) { // User data found, update UI val user = snapshot.getValue(User::class.java) user?.let { // Load image using Picasso library if (!user.image.isNullOrBlank()) { Picasso.get().load(user.image).into(userImageView) } else { // If the image URL is empty or null, set a default image resource userImageView.setImageResource(R.drawable.wp) } // Display user details userNameTextView.text = user.name userNumberTextView.text = user.number userJobTextView.text = user.job userDetailsTextView.text = user.details // Set click listener for the call button val callButton = findViewById<Button>(R.id.callButton) callButton.setOnClickListener { // Call the user's phone number val dialIntent = Intent(Intent.ACTION_DIAL) dialIntent.data = Uri.parse("tel:${user.number}") startActivity(dialIntent) } // Set click listener for the update button val updateButton = findViewById<Button>(R.id.btnUpdate) updateButton.setOnClickListener { // Navigate to the UpdateUserActivity with necessary information val intent = Intent(this@UserDetailsActivity, UserUpdateActivity::class.java) intent.putExtra("ITEM_NAME", collection) intent.putExtra("USER_ID", userId) intent.putExtra("USER_NAME", user.name) intent.putExtra("USER_JOB", user.job) intent.putExtra("USER_NUMBER", user.number) intent.putExtra("USER_IMG_LINK", user.image) intent.putExtra("USER_DETAILS", user.details) startActivity(intent) } // Set click listener for the delete button val deleteButton = findViewById<Button>(R.id.btnDelete) deleteButton.setOnClickListener { // Show a confirmation dialog before deleting the user showConfirmationDialog(userId, collection.toString()) } } } } override fun onCancelled(error: DatabaseError) { // Handle error } }) } private fun showConfirmationDialog(userId: String, collection: String) { val builder = AlertDialog.Builder(this) builder.setTitle("Confirm Deletion") builder.setMessage("Are you sure you want to delete this user?") builder.setPositiveButton("Yes") { _, _ -> // User clicked Yes, delete the user deleteUser(userId, collection) } builder.setNegativeButton("No") { _, _ -> // User clicked No, do nothing or provide feedback } val dialog: AlertDialog = builder.create() dialog.show() } private fun deleteUser(userId: String, collection: String) { // Implement the deleteUser function to delete the user from Firebase userReference.removeValue() // Optionally, you can add a completion listener to handle the result // Provide appropriate feedback to the user // For example, display a Toast or navigate back to the previous screen finish() } }
Town360/java/com/example/town360/UserDetailsActivity.kt
4133156947
// BottomSheetOptionsDialogFragment.kt package com.example.town360 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.fragment.app.DialogFragment class BottomSheetOptionsDialogFragment : DialogFragment() { private var onDeleteClickListener: (() -> Unit)? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.bottom_sheet_options, container, false) val btnDelete = view.findViewById<LinearLayout>(R.id.btnDelete) btnDelete.setOnClickListener { onDeleteClickListener?.invoke() dismiss() } return view } fun setOnDeleteClickListener(listener: () -> Unit) { onDeleteClickListener = listener } }
Town360/java/com/example/town360/BottomSheetOptionsDialogFragment.kt
1025840494
// AddServiceActivity.kt package com.example.town360 import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.widget.Button import android.widget.ImageView import android.widget.RadioButton import android.widget.RadioGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.material.textfield.TextInputEditText import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import java.io.IOException class AddServiceActivity : AppCompatActivity() { private lateinit var serviceImageView: ImageView private lateinit var chooseImageButton: Button private lateinit var serviceNameEditText: TextInputEditText private lateinit var subServiceRadioGroup: RadioGroup private lateinit var yesRadioButton: RadioButton private lateinit var noRadioButton: RadioButton private lateinit var addButton: Button private var selectedImageUri: Uri? = null companion object { private const val PICK_IMAGE_REQUEST = 1 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_service) // Initialize UI components serviceImageView = findViewById(R.id.serviceImageView) chooseImageButton = findViewById(R.id.chooseImageButton) serviceNameEditText = findViewById(R.id.serviceNameEditText) subServiceRadioGroup = findViewById(R.id.subServiceRadioGroup) yesRadioButton = findViewById(R.id.yesRadioButton) noRadioButton = findViewById(R.id.noRadioButton) addButton = findViewById(R.id.addButton) // Set click listeners chooseImageButton.setOnClickListener { openGallery() } addButton.setOnClickListener { addServiceToRealtimeDatabase() } } private fun openGallery() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null) { // Get the selected image URI selectedImageUri = data.data try { // Set the selected image to the ImageView serviceImageView.setImageURI(selectedImageUri) } catch (e: IOException) { e.printStackTrace() } } } private fun addServiceToRealtimeDatabase() { val serviceName = serviceNameEditText.text.toString().trim() val hasSubService = yesRadioButton.isChecked if (serviceName.isNotEmpty() && selectedImageUri != null) { val storageReference = FirebaseStorage.getInstance().reference.child("service_images") val imageFileName = "${System.currentTimeMillis()}.jpg" val imageReference = storageReference.child(imageFileName) // Upload image to Firebase Storage imageReference.putFile(selectedImageUri!!) .addOnSuccessListener { taskSnapshot -> // Get the download URL of the uploaded image imageReference.downloadUrl.addOnSuccessListener { uri -> // Save the service data with the image URL to Realtime Database val db = FirebaseDatabase.getInstance().reference.child("services").child(serviceName) val newService = hashMapOf( "name" to serviceName, "image" to uri.toString(), // Store the download URL "hasSubService" to hasSubService ) db.setValue(newService) .addOnSuccessListener { // Handle success, e.g., show a toast Toast.makeText(this, "Service added successfully", Toast.LENGTH_SHORT).show() // Clear UI components serviceNameEditText.text = null serviceImageView.setImageURI(null) subServiceRadioGroup.clearCheck() // Finish the activity finish() } .addOnFailureListener { e -> // Handle errors, e.g., show an error message Toast.makeText(this, "Error adding service", Toast.LENGTH_SHORT).show() } } } .addOnFailureListener { e -> // Handle errors during image upload Toast.makeText(this, "Error uploading image", Toast.LENGTH_SHORT).show() } } else { // Show an error message if required fields are not filled Toast.makeText(this, "Please fill in all the fields", Toast.LENGTH_SHORT).show() } } }
Town360/java/com/example/town360/AddServiceActivity.kt
105906237
// UpdateServiceActivity.kt package com.example.town360 import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText import com.google.firebase.database.* class UpdateServiceActivity : AppCompatActivity() { private lateinit var serviceNameEditText: TextInputEditText private lateinit var updateButton: MaterialButton private lateinit var parentServiceName: String private lateinit var subServiceName: String private val databaseReference = FirebaseDatabase.getInstance().reference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_update_service) serviceNameEditText = findViewById(R.id.serviceNameEditText) updateButton = findViewById(R.id.updateButton) // Retrieve data from intent parentServiceName = intent.getStringExtra("SERVICE_NAME").toString() subServiceName = intent.getStringExtra("SUB_SERVICE_NAME").toString() // Set the existing sub-service name in the edit text serviceNameEditText.setText(subServiceName) updateButton.setOnClickListener { updateSubService() } } private fun updateSubService() { val updatedSubServiceName = serviceNameEditText.text.toString().trim() if (updatedSubServiceName.isEmpty()) { // Handle empty input serviceNameEditText.error = "Sub-Service name cannot be empty" return } // Check if the sub-service name is unchanged if (subServiceName == updatedSubServiceName) { showToast("Sub-Service name unchanged") finish() return } // Update the sub-service name in Firebase val subServiceReference = databaseReference.child("sub_services").child(parentServiceName) .child(subServiceName) subServiceReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { // Check if the sub-service exists if (snapshot.exists()) { // Remove the existing sub-service subServiceReference.removeValue() // Add the updated sub-service with the new name val updatedSubServiceReference = databaseReference.child("sub_services").child(parentServiceName) .child(updatedSubServiceName) updatedSubServiceReference.setValue(true) .addOnSuccessListener { showToast("Sub-Service updated successfully") finish() } .addOnFailureListener { showToast("Error updating sub-service") } } else { showToast("Sub-Service not found") finish() } } override fun onCancelled(error: DatabaseError) { // Handle errors } }) } private fun showToast(message: String) { // Implement showToast method based on your project's implementation } }
Town360/java/com/example/town360/UpdateServiceActivity.kt
3585014228
package com.example.town360 data class SubService( val name: String = "", val image: String = "" ) { // Add a no-argument constructor for Firebase constructor() : this("", "") }
Town360/java/com/example/town360/SubService.kt
3315568256
package com.example.town360 import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.fragment.app.Fragment private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" class about_us : Fragment() { private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { val view = inflater.inflate(R.layout.fragment_about_us, container, false) val callButton = view.findViewById<Button>(R.id.callButton1) callButton?.setOnClickListener { // Call the user's phone number val dialIntent = Intent(Intent.ACTION_DIAL) dialIntent.data = Uri.parse("tel:+91 9265273298") startActivity(dialIntent) } val openLinkButton = view.findViewById<Button>(R.id.openInMapButton) openLinkButton?.setOnClickListener { // Open the specified link val linkIntent = Intent(Intent.ACTION_VIEW) linkIntent.data = Uri.parse("wa.link/h5339o8") startActivity(linkIntent) } return view } companion object { @JvmStatic fun newInstance(param1: String, param2: String) = about_us().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Town360/java/com/example/town360/about_us.kt
3937952899
package com.example.town360 import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.example.town360.User import com.example.town360.databinding.ActivityUpdateUserBinding import com.google.firebase.FirebaseApp import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageReference import com.squareup.picasso.Picasso class UserUpdateActivity : AppCompatActivity() { private lateinit var binding: ActivityUpdateUserBinding private val database = FirebaseDatabase.getInstance() private val storage = FirebaseStorage.getInstance() private val imageRef: StorageReference by lazy { storage.reference.child("images") // You can customize the storage path } private var selectedImageUri: Uri? = null private val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> uri?.let { // Image selected from the gallery selectedImageUri = it // Display the selected image in your ImageView binding.imgUserUpdate.setImageURI(selectedImageUri) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) FirebaseApp.initializeApp(this) binding = ActivityUpdateUserBinding.inflate(layoutInflater) setContentView(binding.root) val btnUpdateUser: Button = findViewById(R.id.btnUpdateUser) val etName: EditText = findViewById(R.id.etNameUpdate) val etNumber: EditText = findViewById(R.id.etNumberUpdate) val etDetails: EditText = findViewById(R.id.etDetailsUpdate) val tvJobDetails: TextView = findViewById(R.id.tvJobUpdate) val imgUser: ImageView = findViewById(R.id.imgUserUpdate) // Load user data from intent val userId = intent.getStringExtra("USER_ID") val userName = intent.getStringExtra("USER_NAME") val userNumber = intent.getStringExtra("USER_NUMBER") val userGoogleMapLink = intent.getStringExtra("USER_MAP_LINK") val userDetails = intent.getStringExtra("USER_DETAILS") val userJob = intent.getStringExtra("USER_JOB") val userProfileImage = intent.getStringExtra("USER_IMG_LINK") // Set user data to UI elements etName.setText(userName) etNumber.setText(userNumber) etDetails.setText(userDetails) tvJobDetails.text = userJob Picasso.get().load(userProfileImage).into(/* target = */ imgUser) binding.btnSelectImageUpdate.setOnClickListener { // Call the image picker pickImage.launch("image/*") } btnUpdateUser.setOnClickListener { val name = etName.text.toString() val number = etNumber.text.toString() val details = etDetails.text.toString() // Check if any of the fields are empty if (name.isEmpty() || number.isEmpty() || details.isEmpty()) { showToast("Please fill in all fields") return@setOnClickListener } // Create a User object val updatedUser = User(id = userId, name, number, details, userJob) // Upload the image and update user data uploadImageAndUpdateUser(userJob.toString(), updatedUser) // Show a toast showToast("User updated successfully!") } } private fun uploadImageAndUpdateUser(collectionName: String, user: User) { selectedImageUri?.let { uri -> // Create a reference to the image file val imageFileName = "${System.currentTimeMillis()}.jpg" val imageRef = imageRef.child(imageFileName) // Upload the image to Firebase Storage imageRef.putFile(uri) .addOnSuccessListener { taskSnapshot -> // Image upload successful, get the download URL imageRef.downloadUrl.addOnSuccessListener { imageUrl -> // Save the user with the updated image URL to Firebase Realtime Database user.image = imageUrl.toString() updateUserInFirebase(collectionName, user) } } .addOnFailureListener { exception -> // Image upload failed showToast("Failed to upload image. ${exception.message}") } } } private fun updateUserInFirebase(collectionName: String, user: User) { val usersReference = database.getReference(collectionName) val userReference = usersReference.child(user.id!!) userReference.setValue(user) .addOnSuccessListener { showToast("User updated successfully!") finish() // Close the activity after successful update } .addOnFailureListener { exception -> showToast("Failed to update user. ${exception.message}") } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
Town360/java/com/example/town360/update_user.kt
353396589
package com.example.town360 import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView class khedutadapter(private val context: Context, private val items: List<DashboardItem>) : BaseAdapter() { override fun getCount(): Int = items.size override fun getItem(position: Int): Any = items[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val viewHolder: ViewHolder val view: View if (convertView == null) { // Inflate the view for each item if it's not recycled view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false) // Create a ViewHolder and store references to the children views viewHolder = ViewHolder(view) view.tag = viewHolder } else { // Reuse the recycled view view = convertView // Retrieve the ViewHolder from the recycled view viewHolder = view.tag as ViewHolder } val item = getItem(position) as DashboardItem viewHolder.imageView.setImageResource(item.imageResId) viewHolder.textView.text = item.text // Handle item click view.setOnClickListener { // Create an Intent to start the Health activity val intent = Intent(context, Health::class.java) // Pass information to the Health activity intent.putExtra("ITEM_NAME", item.text) intent.putExtra("ITEM_IMAGE_RES_ID", item.imageResId) context.startActivity(intent) } return view } private class ViewHolder(view: View) { val imageView: ImageView = view.findViewById(R.id.imageView) val textView: TextView = view.findViewById(R.id.textView) } }
Town360/java/com/example/town360/Khedutadapter.kt
79118588
package com.example.town360 // SubServiceAdapter.kt import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.example.town360.R class SubServiceAdapter(private val context: Context, private val subServices: List<SubService>) : BaseAdapter() { override fun getCount(): Int { return subServices.size } override fun getItem(position: Int): Any { return subServices[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view = convertView val viewHolder: ViewHolder if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false) viewHolder = ViewHolder(view) view.tag = viewHolder } else { viewHolder = view.tag as ViewHolder } // Set data to views val subService = getItem(position) as SubService viewHolder.bind(subService) return view!! } private class ViewHolder(view: View) { private val imageView: ImageView = view.findViewById(R.id.imageView) private val textView: TextView = view.findViewById(R.id.textView) fun bind(subService: SubService) { // Load image using Glide or your preferred image loading library Glide.with(imageView.context) .load(subService.image) .into(imageView) textView.text = subService.name } } }
Town360/java/com/example/town360/SubServiceAdapter.kt
359860530
package com.example.town360 import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Bundle import android.view.ContextMenu import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.GridView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.firebase.database.* class Home : Fragment() { private lateinit var gridView: GridView private lateinit var fabAddService: FloatingActionButton override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home, container, false) gridView = view.findViewById(R.id.gridView) fabAddService = view.findViewById(R.id.fabAddService) setupFab() if (!isInternetAvailable()) { showToast("Internet not available") } // Register for context menu for long-press registerForContextMenu(gridView) return view } private fun setupFab() { fabAddService.setOnClickListener { // Check for internet connectivity before navigating to AddServiceActivity if (isInternetAvailable()) { navigateToAddService() } else { showToast("Internet not available") } } } private fun isInternetAvailable(): Boolean { val connectivityManager = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } private fun navigateToAddService() { val intent = Intent(requireContext(), AddServiceActivity::class.java) startActivity(intent) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Fetch service data from Firebase val databaseReference = FirebaseDatabase.getInstance().reference.child("services") val services = mutableListOf<Service>() databaseReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { services.clear() for (childSnapshot in snapshot.children) { val service = childSnapshot.getValue(Service::class.java) service?.let { services.add(it) } } try { // Update the GridView with the new data val adapter = ServiceAdapter(requireContext(), services) gridView.adapter = adapter // Set item click listener gridView.setOnItemClickListener { _, _, position, _ -> // Handle item click, if needed val selectedService = services[position] if (!selectedService.hasSubService) { navigateToHealth(selectedService) } else { navigateToServiceDetails(selectedService) } } } catch (e: Exception) { if (isAdded) { // Check if the fragment is added before showing the toast showToast("Error updating UI: ${e.message}") } } } override fun onCancelled(error: DatabaseError) { if (isAdded) { // Check if the fragment is added before showing the toast showToast("Database error: ${error.message}") } } }) } private fun showToast(message: String) { Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show() } private fun navigateToHealth(selectedService: Service) { val intent = Intent(requireContext(), Health::class.java).apply { putExtra("ITEM_NAME", selectedService.name) // Add more data as needed } startActivity(intent) } private fun navigateToServiceDetails(selectedService: Service) { val intent = Intent(requireContext(), ServiceDetailsActivity::class.java).apply { putExtra("SERVICE_NAME", selectedService.name) putExtra("SERVICE_IMAGE", selectedService.image) // Add more data as needed } startActivity(intent) } override fun onCreateContextMenu( menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo? ) { super.onCreateContextMenu(menu, v, menuInfo) if (v.id == R.id.gridView) { requireActivity().menuInflater.inflate(R.menu.context_menu, menu) } } override fun onContextItemSelected(item: MenuItem): Boolean { val info = item.menuInfo as AdapterView.AdapterContextMenuInfo // Assuming you have a Service model in your adapter val selectedService = gridView.adapter.getItem(info.position) as Service when (item.itemId) { R.id.action_delete -> { showDeleteConfirmationDialog(selectedService) return true } else -> return super.onContextItemSelected(item) } } private fun showDeleteConfirmationDialog(selectedService: Service) { AlertDialog.Builder(requireContext()) .setTitle("Delete Service") .setMessage("Are you sure you want to delete ${selectedService.name}?") .setPositiveButton("Delete") { _, _ -> deleteService(selectedService) } .setNegativeButton("Cancel", null) .show() } private fun deleteService(selectedService: Service) { // Implement the logic to delete the service from Firebase val databaseReference = FirebaseDatabase.getInstance().reference.child("services") val serviceReference = databaseReference.child(selectedService.name) val databaseRef = FirebaseDatabase.getInstance().reference.child("sub_services") val serviceRef = databaseRef.child(selectedService.name) serviceReference.removeValue() serviceRef.removeValue() .addOnSuccessListener { showToast("Service deleted successfully") } .addOnFailureListener { showToast("Error deleting service") } } }
Town360/java/com/example/town360/Home.kt
1451426955
package com.example.town360 data class DashboardItem(val imageResId: Int, val text: String)
Town360/java/com/example/town360/DashboardItem.kt
393184450
// ServiceAdapter.kt package com.example.town360 import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions class ServiceAdapter(private val context: Context, private val services: List<Service>) : BaseAdapter() { override fun getCount(): Int = services.size override fun getItem(position: Int): Any = services[position] override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val viewHolder: ViewHolder val view: View if (convertView == null) { // Inflate the view for each item if it's not recycled view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false) // Create a ViewHolder and store references to the children views viewHolder = ViewHolder(view) view.tag = viewHolder } else { // Reuse the recycled view view = convertView // Retrieve the ViewHolder from the recycled view viewHolder = view.tag as ViewHolder } val service = getItem(position) as Service // Load image using Glide or your preferred image loading library Glide.with(context) .load(service.image) .apply( RequestOptions() .placeholder(R.drawable.baseline_info_24) // optional placeholder image .error(R.drawable.w) // optional error image .diskCacheStrategy(DiskCacheStrategy.ALL) // optional caching strategy ) .into(viewHolder.imageView) viewHolder.textView.text = service.name return view } private class ViewHolder(view: View) { val imageView: ImageView = view.findViewById(R.id.imageView) val textView: TextView = view.findViewById(R.id.textView) } }
Town360/java/com/example/town360/ServiceAdapter.kt
4067057270
package com.example.town360 import android.annotation.SuppressLint import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.GridView import com.example.town360.R class bloodtype : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bloodtype) val gridView: GridView = findViewById(R.id.gridView) val dashboardItems = listOf( DashboardItem(R.drawable.bloodtypea, "A+"), DashboardItem(R.drawable.bloodtypeaneg, "A-"), DashboardItem(R.drawable.bloodtypebpos, "B+"), DashboardItem(R.drawable.bloodtypebneg, "B-"), DashboardItem(R.drawable.bloodtypeabpos, "AB+"), DashboardItem(R.drawable.bloodtypeabneg, "AB-"), DashboardItem(R.drawable.bloodtypeopos, "O+"), DashboardItem(R.drawable.bloodtypeoneg, "O-"), // Add more items as needed ) val adapter = khedutadapter(this, dashboardItems) gridView.adapter = adapter } }
Town360/java/com/example/town360/bloodtype.kt
2339665546
// AddSubServiceActivity.kt package com.example.town360 import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.material.textfield.TextInputEditText import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import java.io.IOException class AddSubServiceActivity : AppCompatActivity() { private lateinit var serviceImageView: ImageView private lateinit var chooseImageButton: Button private lateinit var serviceNameEditText: TextInputEditText private lateinit var addButton: Button // Service name passed from the previous activity private lateinit var serviceName: String private var selectedImageUri: Uri? = null companion object { private const val PICK_IMAGE_REQUEST = 1 } @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_addsubservice) // Initialize UI components serviceImageView = findViewById(R.id.serviceImageView) chooseImageButton = findViewById(R.id.chooseImageButton) serviceNameEditText = findViewById(R.id.serviceNameEditText) addButton = findViewById(R.id.addsubButton) // Get service name from the intent serviceName = intent.getStringExtra("SERVICE_NAME") ?: "" // Set click listeners chooseImageButton.setOnClickListener { openGallery() } addButton.setOnClickListener { addSubServiceToRealtimeDatabase() } } private fun openGallery() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) { // Get the selected image URI selectedImageUri = data.data try { // Set the selected image to the ImageView serviceImageView.setImageURI(selectedImageUri) } catch (e: IOException) { e.printStackTrace() } } } private fun addSubServiceToRealtimeDatabase() { val subServiceName = serviceNameEditText.text.toString().trim() if (subServiceName.isNotEmpty() && selectedImageUri != null) { val storageReference = FirebaseStorage.getInstance().reference.child("sub_service_images") val imageFileName = "${System.currentTimeMillis()}.jpg" val imageReference = storageReference.child(imageFileName) // Upload image to Firebase Storage imageReference.putFile(selectedImageUri!!) .addOnSuccessListener { taskSnapshot -> // Get the download URL of the uploaded image imageReference.downloadUrl.addOnSuccessListener { uri -> // Save the sub-service data with the image URL to Realtime Database val db = FirebaseDatabase.getInstance().reference.child("sub_services").child(serviceName).child(subServiceName) val newSubService = hashMapOf( "name" to subServiceName, "image" to uri.toString(), // Store the download URL "parent_service" to serviceName ) db.setValue(newSubService) .addOnSuccessListener { // Handle success, e.g., show a toast Toast.makeText(this, "Sub-Service added successfully", Toast.LENGTH_SHORT).show() // Clear UI components serviceNameEditText.text = null serviceImageView.setImageURI(null) } .addOnFailureListener { e -> // Handle errors, e.g., show an error message Toast.makeText(this, "Error adding sub-service", Toast.LENGTH_SHORT).show() } } } .addOnFailureListener { e -> // Handle errors during image upload Toast.makeText(this, "Error uploading image", Toast.LENGTH_SHORT).show() } } else { // Show an error message if required fields are not filled Toast.makeText(this, "Please fill in all the fields", Toast.LENGTH_SHORT).show() } } }
Town360/java/com/example/town360/addsubservice.kt
2068259469
package com.example.town360 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide class UserAdapter(private var userList: List<User>, private val onItemClick: (User) -> Unit) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() { inner class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val imageView: ImageView = itemView.findViewById(R.id.imageView2) val nameTextView: TextView = itemView.findViewById(R.id.textView3) val numberTextView: TextView = itemView.findViewById(R.id.textView4) val jobTextView: TextView = itemView.findViewById(R.id.textView5) init { // Set an OnClickListener for the entire itemView itemView.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { onItemClick(userList[position]) } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.user_item, parent, false) return UserViewHolder(itemView) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { val currentUser = userList[position] // Load the image using Glide (replace "currentUser.image" with the actual image property) Glide.with(holder.imageView.context) .load(currentUser.image) .placeholder(R.drawable.ic_launcher_foreground) // Placeholder image .into(holder.imageView) holder.nameTextView.text = currentUser.name holder.numberTextView.text = currentUser.number holder.jobTextView.text = currentUser.job } override fun getItemCount(): Int { return userList.size } // Update the user list and refresh the adapter fun updateUserList(newList: List<User>) { userList = newList notifyDataSetChanged() } }
Town360/java/com/example/town360/UserAdapter.kt
2935821687
package com.example.town360 import android.os.Parcel import android.os.Parcelable data class User( var id: String? = "", // Firebase ID val name: String? = "", val number: String? = "", val details: String? = "", val job: String? = "", var image: String? = "" ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(id) parcel.writeString(name) parcel.writeString(number) parcel.writeString(details) parcel.writeString(job) parcel.writeString(image) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<User> { override fun createFromParcel(parcel: Parcel): User { return User(parcel) } override fun newArray(size: Int): Array<User?> { return arrayOfNulls(size) } } }
Town360/java/com/example/town360/User.kt
878372583
package com.example.town360 // Service.kt data class Service( val name: String = "", val image: String = "", val hasSubService: Boolean = false )
Town360/java/com/example/town360/Service.kt
20621745
package com.example.town360 import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.town360.databinding.ActivityHealthBinding import com.google.firebase.database.* class Health : AppCompatActivity() { private lateinit var binding: ActivityHealthBinding private lateinit var userAdapter: UserAdapter private lateinit var recyclerView: RecyclerView private lateinit var database: FirebaseDatabase private lateinit var usersReference: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHealthBinding.inflate(layoutInflater) setContentView(binding.root) // Initialize Firebase database = FirebaseDatabase.getInstance() // Retrieve extra data from the Intent val itemName = intent.getStringExtra("ITEM_NAME") supportActionBar?.title = itemName // Initialize RecyclerView and UserAdapter recyclerView = findViewById(R.id.recycleview) userAdapter = UserAdapter(ArrayList()) { clickedUser -> // Handle item click here using 'clickedUser' // 'clickedUser' is the user that was clicked // For example, you can launch a new activity with the user details val intent = Intent(this@Health, UserDetailsActivity::class.java) intent.putExtra("USER_ID", clickedUser.id) intent.putExtra("ITEM_NAME", itemName) startActivity(intent) } recyclerView.adapter = userAdapter recyclerView.layoutManager = LinearLayoutManager(this) // Set the TextView to display the retrieved name binding.textView2.text = itemName // Set up Firebase reference with the collection name as itemName usersReference = database.getReference(itemName.toString()) val btn: Button = findViewById(R.id.button2) btn.setOnClickListener { val intent = Intent(this, AddUser::class.java) intent.putExtra("ITEM_NAME", itemName) startActivity(intent) } // Retrieve and display data from Firebase retrieveDataFromFirebase() } private fun retrieveDataFromFirebase() { usersReference.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val userList = mutableListOf<User>() for (snapshot in dataSnapshot.children) { val user = snapshot.getValue(User::class.java) user?.let { userList.add(it) } } userAdapter.updateUserList(userList) } override fun onCancelled(error: DatabaseError) { // Handle the error val errorMessage = "Firebase Data Retrieval Error: ${error.message}" // Display a Toast message or log the error } }) } }
Town360/java/com/example/town360/Health.kt
695912160
package io.github.kamo.ktor.springboot.test import io.github.kamo.ktor.springboot.router.KtorRouter import io.github.kamo.ktor.springboot.router.KtorRouterFun import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.pipeline.* import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.stereotype.Controller fun main() { runApplication<TestConfig>() } @EnableAutoConfiguration @ComponentScan class TestConfig { @Bean fun c(): KtorRouterFun = { get("/c") { call.respondText { "c" } } } @Bean fun d(): KtorRouterFun = { get("/d") { call.respondText { "d" } } } } @Controller class TestController : KtorRouter { override fun Routing.register() { get("/a") { a() } get("/b") { b() } } suspend fun PipelineContext<Unit, ApplicationCall>.a() { call.respondText { "a" } } suspend fun PipelineContext<Unit, ApplicationCall>.b() { call.respondText { "b" } } fun Routing.e() { get("/e") { call.respondText { "e" } } } }
ktor-spring-boot-starter/src/test/kotlin/KtorSpringTest.kt
1051979144
package io.github.kamo.ktor.springboot import io.github.kamo.ktor.springboot.modules.KtorFunctionAdapterModule import io.github.kamo.ktor.springboot.modules.KtorModule import io.github.kamo.ktor.springboot.router.KtorFunctionAdapterRouter import io.github.kamo.ktor.springboot.router.KtorRouter import io.ktor.util.reflect.* import org.springframework.beans.factory.config.BeanPostProcessor import org.springframework.beans.factory.config.ConfigurableListableBeanFactory import org.springframework.beans.factory.support.BeanDefinitionBuilder import org.springframework.beans.factory.support.BeanDefinitionRegistry import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor import org.springframework.core.ResolvableType import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.full.declaredMemberExtensionFunctions import kotlin.reflect.full.extensionReceiverParameter class KtorFunctionBeanPostProcessor : BeanPostProcessor, BeanDefinitionRegistryPostProcessor { companion object { private const val MODULE_ADAPTER_BEAN_NAME: String = "extensionBeanPostProcessorModuleAdapter" private const val ROUTER_ADAPTER_BEAN_NAME: String = "extensionBeanPostProcessorRouterAdapter" private const val APPLICATION_TYPE_NAME = "io.ktor.server.application.Application" private const val ROUTING_TYPE_NAME = "io.ktor.server.routing.Routing" private val defaultFunNameMaps = mapOf( KtorModule::class to "install", KtorRouter::class to "register" ) } private val moduleAdapter: KtorFunctionAdapterModule = KtorFunctionAdapterModule() private val routerAdapter: KtorFunctionAdapterRouter = KtorFunctionAdapterRouter() override fun postProcessBeforeInitialization(bean: Any, beanName: String): Any { if (beanName == MODULE_ADAPTER_BEAN_NAME || beanName == ROUTER_ADAPTER_BEAN_NAME) { return bean } if (bean is KtorModule) { moduleAdapter.addModule(bean) } else if (bean is KtorRouter) { routerAdapter.addRouter(bean) } val extFunctions = runCatching { bean::class.declaredMemberExtensionFunctions }.getOrNull() ?: return bean extFunctions.filter { it.parameters.size == 2 } .forEach { if (isExtensionFunBy(bean, it, APPLICATION_TYPE_NAME, KtorModule::class)) { moduleAdapter.addModule { it.call(bean, this) } } else if (isExtensionFunBy(bean, it, ROUTING_TYPE_NAME, KtorRouter::class)) { routerAdapter.addRouter { it.call(bean, this) } } } return bean } private fun isExtensionFunBy(bean: Any, function: KFunction<*>, typeName: String, type: KClass<*>): Boolean = function.extensionReceiverParameter?.type?.toString() == typeName && (!bean.instanceOf(type) || defaultFunNameMaps[type] != function.name) override fun postProcessBeanDefinitionRegistry(registry: BeanDefinitionRegistry) { val moduleAdapterType = ResolvableType.forInstance(moduleAdapter) val extensionModuleAdapterBD = BeanDefinitionBuilder .rootBeanDefinition(moduleAdapterType) { moduleAdapter }.beanDefinition val routerAdapterType = ResolvableType.forInstance(routerAdapter) val extensionRouterAdapterBD = BeanDefinitionBuilder .rootBeanDefinition(routerAdapterType) { routerAdapter }.beanDefinition registry.registerBeanDefinition(MODULE_ADAPTER_BEAN_NAME, extensionModuleAdapterBD) registry.registerBeanDefinition(ROUTER_ADAPTER_BEAN_NAME, extensionRouterAdapterBD) } override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) = Unit }
ktor-spring-boot-starter/src/main/kotlin/KtorFunctionBeanPostProcessor.kt
1283808884
package io.github.kamo.ktor.springboot import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(prefix = "ktor.server", ignoreUnknownFields = true) data class KtorServerProperties( var port: Int = 8080, var host: String = "0.0.0.0", var path: String = "/" )
ktor-spring-boot-starter/src/main/kotlin/KtorServerProperties.kt
1641109375
package io.github.kamo.ktor.springboot import io.ktor.server.engine.* import org.springframework.context.SmartLifecycle class KtorServerStartStopLifecycle(private val engine: ApplicationEngine) : SmartLifecycle { private var running = false override fun start() { engine.start(true) running = true } override fun stop() { this.running = false engine.stop() } override fun isRunning(): Boolean = running }
ktor-spring-boot-starter/src/main/kotlin/KtorServerStartStopLifecycle.kt
2460551985
package io.github.kamo.ktor.springboot import io.github.kamo.ktor.springboot.modules.KtorModuleFun import io.github.kamo.ktor.springboot.router.KtorRouterFun import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.routing.* import io.ktor.util.logging.* import org.springframework.boot.autoconfigure.AutoConfiguration import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.core.env.Environment @AutoConfiguration @EnableConfigurationProperties(KtorServerProperties::class) @ConditionalOnClass(ApplicationEngine::class) @Import(KtorServerStartStopLifecycle::class, KtorFunctionBeanPostProcessor::class) class KtorServerAutoConfiguration( private val properties: KtorServerProperties, private val environment: Environment ) { @Bean fun engine( engineFactory: ApplicationEngineFactory<ApplicationEngine, out ApplicationEngine.Configuration>, environment: ApplicationEngineEnvironment ): ApplicationEngine { return embeddedServer( factory = engineFactory, environment = environment ) } @Bean @ConditionalOnMissingBean fun engineFactory(): ApplicationEngineFactory<ApplicationEngine, out ApplicationEngine.Configuration> = Netty @Bean @ConditionalOnMissingBean fun defaultEnvironment( modules: List<KtorModuleFun>, connectors: List<EngineConnectorConfig> ): ApplicationEngineEnvironment = applicationEngineEnvironment { this.log = KtorSimpleLogger(environment.getProperty("spring.application.name") ?: "ktor.application") this.rootPath = properties.path this.modules.addAll(modules) this.connectors.addAll(connectors) } @Bean fun routeModules( routeFunList: List<KtorRouterFun> ): KtorModuleFun = { routing { routeFunList.forEach { it() } } } @Bean fun defaultEngineConnectorConfig(): EngineConnectorConfig { return EngineConnectorBuilder().apply { this.port = properties.port this.host = properties.host } } }
ktor-spring-boot-starter/src/main/kotlin/KtorServerAutoConfiguration.kt
1134748709
package io.github.kamo.ktor.springboot.modules import io.ktor.server.application.* interface KtorModule { fun Application.install() } typealias KtorModuleFun = Application.() -> Unit
ktor-spring-boot-starter/src/main/kotlin/modules/KtorModule.kt
765364915
package io.github.kamo.ktor.springboot.modules import io.ktor.server.application.* class KtorFunctionAdapterModule : (Application) -> Unit { private val modules: MutableList<KtorModuleFun> = mutableListOf() fun addModule(function: KtorModuleFun) { modules.add(function) } fun addModule(module: KtorModule) { modules.add { module.apply { install() } } } override fun invoke(application: Application) { modules.forEach { it(application) } } }
ktor-spring-boot-starter/src/main/kotlin/modules/KtorFunctionAdapterModule.kt
2230977199
package io.github.kamo.ktor.springboot.modules import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware abstract class KtorSpringModule : KtorModule, ApplicationContextAware { protected lateinit var context: ApplicationContext override fun setApplicationContext(context: ApplicationContext) { this.context = context } }
ktor-spring-boot-starter/src/main/kotlin/modules/KtorSpringModule.kt
3794039067
package io.github.kamo.ktor.springboot.router import io.ktor.server.routing.* interface KtorRouter { fun Routing.register() } typealias KtorRouterFun = Routing.() -> Unit
ktor-spring-boot-starter/src/main/kotlin/router/KtorRouter.kt
470354840
package io.github.kamo.ktor.springboot.router import io.ktor.server.routing.* class KtorFunctionAdapterRouter : (Routing) -> Unit { private val routers: MutableList<KtorRouterFun> = mutableListOf() fun addRouter(function: KtorRouterFun) { routers.add(function) } fun addRouter(router: KtorRouter) { routers.add { router.apply { register() } } } override fun invoke(router: Routing) { routers.forEach { it(router) } } }
ktor-spring-boot-starter/src/main/kotlin/router/KtorFunctionAdapterRouter.kt
1472242525
package com.rodrigo.signinexamples 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.rodrigo.signinexamples", appContext.packageName) } }
SignInSamples/app/src/androidTest/java/com/rodrigo/signinexamples/ExampleInstrumentedTest.kt
1687219805
package com.rodrigo.signinexamples 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) } }
SignInSamples/app/src/test/java/com/rodrigo/signinexamples/ExampleUnitTest.kt
155782116
package com.rodrigo.signinexamples.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)
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/ui/theme/Color.kt
2689969826
package com.rodrigo.signinexamples.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80, onPrimary = Color.White ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40, onPrimary = Color.Black /* 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 SignInExamplesTheme( 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 ) }
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/ui/theme/Theme.kt
2249173867
package com.rodrigo.signinexamples.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 ) */ )
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/ui/theme/Type.kt
782005969
package com.rodrigo.signinexamples.sign_in_samples import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField 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.draw.alpha import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.rodrigo.signinexamples.R import com.rodrigo.signinexamples.utils.rememberImeState @Composable fun SignIn1() { val appName = "AppName" val highlightColor = Color(red = 224, green = 96, blue = 63, alpha = 255) val buttonHeight = 50.dp val shapeSizeValue = 30.dp val imeState = rememberImeState() val scrollState = rememberScrollState() LaunchedEffect(key1 = imeState.value) { if (imeState.value) { scrollState.animateScrollTo(scrollState.maxValue, tween(300)) } } Box(modifier = Modifier.fillMaxSize()) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(R.drawable.background), contentDescription = "", contentScale = ContentScale.Crop, alpha = 1f ) Box( modifier = Modifier .fillMaxSize() .alpha(0.7f) .background( if (isSystemInDarkTheme()) Color.Black else Color.White ) ) Column( modifier = Modifier .padding(32.dp) .fillMaxSize() .verticalScroll(state = scrollState), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.weight(0.5f)) HeadLineText(appName) Spacer(modifier = Modifier.size(16.dp)) Row( modifier = Modifier .fillMaxWidth() .align(Alignment.Start), verticalAlignment = Alignment.CenterVertically ) { BasicText(textValue = "New to $appName? ") ClickableTextSample( textValue = "Sign Up", colorValue = highlightColor, onTextClick = {/*TODO*/ }) BasicText(textValue = " now") } Spacer(modifier = Modifier.size(16.dp)) OutsideSignInButton( textValue = "Apple", iconPath = R.drawable.apple_icon, onButtonClicked = {/*TODO*/ }, backgroundColor = Color.White, buttonHeight = buttonHeight, shapeSize = shapeSizeValue ) Spacer(modifier = Modifier.size(16.dp)) OutsideSignInButton( textValue = "Google", iconPath = R.drawable.google_icon, onButtonClicked = {/*TODO*/ }, backgroundColor = Color.Black, buttonHeight = buttonHeight, shapeSize = shapeSizeValue ) Spacer(modifier = Modifier.size(16.dp)) SignDivider() Spacer(modifier = Modifier.size(8.dp)) InputDataComposable( textValue = "Email", placeholder = "Enter your email", KeyboardType.Email ) Spacer(modifier = Modifier.size(8.dp)) InputDataComposable( textValue = "Password", placeholder = "Enter your password", KeyboardType.Password ) Spacer(modifier = Modifier.size(16.dp)) Box( modifier = Modifier .wrapContentHeight() .fillMaxWidth(), contentAlignment = Alignment.CenterEnd ) { ClickableTextSample( textValue = "Forgot Password?", colorValue = highlightColor, onTextClick = {/*TODO*/ }) } Spacer(modifier = Modifier.size(16.dp)) Button( modifier = Modifier .fillMaxWidth() .height(buttonHeight), onClick = { /*TODO*/ }, colors = ButtonDefaults.buttonColors(containerColor = highlightColor) ) { Text(text = "Sign in",color = MaterialTheme.colorScheme.onSurface) } Spacer(modifier = Modifier.weight(1f)) if (!imeState.value) { RRSSButtons(shapeSizeValue) } } } } @Composable fun RRSSButtons(shapeSize: Dp) { Row { RoundBottom( size = 50, imageIconPath = R.drawable.instagram_icon, onButtonClick = { /*TODO*/ }, shapeSize = shapeSize ) Spacer(modifier = Modifier.size(8.dp)) RoundBottom( size = 50, imageIconPath = R.drawable.facebook_icon, onButtonClick = { /*TODO*/ }, shapeSize = shapeSize ) Spacer(modifier = Modifier.size(8.dp)) RoundBottom( size = 50, imageIconPath = R.drawable.youtube_icon, onButtonClick = { /*TODO*/ }, shapeSize = shapeSize ) Spacer(modifier = Modifier.size(8.dp)) RoundBottom( size = 50, imageIconPath = R.drawable.twitterx_icon, onButtonClick = { /*TODO*/ }, shapeSize = shapeSize ) Spacer(modifier = Modifier.size(8.dp)) RoundBottom( size = 50, imageIconPath = R.drawable.spotify_icon, onButtonClick = { /*TODO*/ }, shapeSize = shapeSize ) } } @Composable fun RoundBottom(size: Int, imageIconPath: Int, onButtonClick: () -> Unit, shapeSize: Dp) { Box(contentAlignment = Alignment.Center) { Button( modifier = Modifier .size(size.dp) .border( width = 0.5.dp, color = Color.Black, shape = RoundedCornerShape(shapeSize) ), shape = RoundedCornerShape(size.dp), onClick = onButtonClick, colors = ButtonDefaults.buttonColors( containerColor = if (isSystemInDarkTheme()) Color.Black else Color.White ) ) {} Image( modifier = Modifier.size(size.dp / 2), painter = painterResource(imageIconPath), contentDescription = "" ) } } @Composable fun InputDataComposable(textValue: String, placeholder: String, keyboardType: KeyboardType) { var value by remember { mutableStateOf("") } Column(modifier = Modifier.fillMaxWidth()) { Text( text = textValue, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface ) Spacer(modifier = Modifier.size(8.dp)) OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = value, onValueChange = { value = it }, shape = RoundedCornerShape(30.dp), placeholder = { Text(placeholder) }, keyboardOptions = KeyboardOptions(keyboardType = keyboardType), singleLine = true ) } } @Composable fun SignDivider() { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { HorizontalDivider(modifier = Modifier.weight(1f), thickness = 1.dp, color = MaterialTheme.colorScheme.onSurface) Spacer(modifier = Modifier.size(8.dp)) Text(text = "Or",color = MaterialTheme.colorScheme.onSurface) Spacer(modifier = Modifier.size(8.dp)) HorizontalDivider(modifier = Modifier.weight(1f), thickness = 1.dp, color = MaterialTheme.colorScheme.onSurface) } } @Composable fun OutsideSignInButton( textValue: String, iconPath: Int, onButtonClicked: () -> Unit, backgroundColor: Color, buttonHeight: Dp, shapeSize: Dp ) { Button( modifier = Modifier .border( width = 1.dp, color = Color.Black, shape = RoundedCornerShape(shapeSize) ) .height(buttonHeight), onClick = onButtonClicked, colors = ButtonDefaults.buttonColors(containerColor = backgroundColor), shape = RoundedCornerShape(shapeSize) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Image( modifier = Modifier.scale(0.9f), painter = painterResource(iconPath), contentDescription = "", ) Spacer(Modifier.size(8.dp)) Text( text = "Sign in with $textValue", color = if (backgroundColor == Color.White) Color.Black else Color.White ) } } } @Composable fun HeadLineText(appName: String) { Text( modifier = Modifier.fillMaxWidth(), text = "Sign to $appName", fontWeight = FontWeight.W900, fontSize = 30.sp, color = MaterialTheme.colorScheme.onSurface ) } @Composable fun BasicText(textValue: String) { Text(text = textValue, color = MaterialTheme.colorScheme.onSurface) } @Composable fun ClickableTextSample(textValue: String, colorValue: Color, onTextClick: (Int) -> Unit) { ClickableText( text = AnnotatedString(textValue), onClick = onTextClick, style = TextStyle( color = colorValue, fontWeight = FontWeight.Medium ) ) } @Composable @Preview(showSystemUi = true) fun SignIn1Preview() { SignIn1() }
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/sign_in_samples/SignIn_1.kt
2782821216
package com.rodrigo.signinexamples import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.rodrigo.signinexamples.sign_in_samples.SignIn1 import com.rodrigo.signinexamples.ui.theme.SignInExamplesTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { SignInExamplesTheme { SignIn1() } } } }
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/MainActivity.kt
3642382295
package com.rodrigo.signinexamples.utils import android.view.ViewTreeObserver import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalView import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat @Composable fun rememberImeState(): State<Boolean> { val imeState = remember { mutableStateOf(false) } val view = LocalView.current DisposableEffect(view) { val listener = ViewTreeObserver.OnGlobalLayoutListener { val isKeyboardOpen = ViewCompat.getRootWindowInsets(view) ?.isVisible(WindowInsetsCompat.Type.ime()) ?: true imeState.value = isKeyboardOpen } view.viewTreeObserver.addOnGlobalLayoutListener(listener) onDispose { view.viewTreeObserver.removeOnGlobalLayoutListener(listener) } } return imeState }
SignInSamples/app/src/main/java/com/rodrigo/signinexamples/utils/ImeListener.kt
1132103263
package com.example.foodies import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class FoodiesApp : Application()
FoodiesApp/app/src/main/java/com/example/foodies/FoodiesApp.kt
1997735527
package com.example.foodies.ui import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.foodies.R import com.example.foodies.model.Product import com.example.foodies.model.fakeProduct import com.example.foodies.navigation.NavigationDestination import com.example.foodies.ui.parts.Counter import com.example.foodies.ui.parts.FoodiesBotAppBar import com.example.foodies.ui.theme.FoodiesTheme import com.example.foodies.ui.theme.Orange import java.text.NumberFormat object CartScreenDestination : NavigationDestination { override val route = "cart_screen" } @Composable fun CartScreen( catalogScreenUiState: CatalogScreenUiState, onBackClick: () -> Unit, modifier: Modifier = Modifier ) { when (catalogScreenUiState) { is CatalogScreenUiState.Success -> SuccessCartScreen( cart = catalogScreenUiState.cart.value.filter { it.value != 0 }, onBackClick = onBackClick, modifier = modifier ) else -> {} } } @Composable fun SuccessCartScreen( cart: Map<Product, Int>, onBackClick: () -> Unit, modifier: Modifier = Modifier ) { Scaffold( topBar = { SuccessCartScreenTopAppBar(onBackClick = onBackClick) }, bottomBar = { FoodiesBotAppBar( onButtonClick = { /*TODO*/ }, cart = cart, currentDestination = CartScreenDestination, currentProduct = fakeProduct ) } ) { paddingValues -> LazyColumn(modifier = modifier.padding(paddingValues)) { item { Divider(thickness = 1.dp) } for (pair in cart) { item { CartItem( product = pair.key, counter = pair.value, onAddClick = { /*TODO*/ }, onRemoveClick = { /*TODO*/ }) Divider(thickness = 1.dp) } } } } } @Composable fun CartItem( product: Product, counter: Int, onAddClick: () -> Unit, onRemoveClick: () -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier.padding(dimensionResource(id = R.dimen.padding_large)), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(id = R.drawable.photo), contentDescription = stringResource(R.string.photo, product.name), modifier = Modifier.size(96.dp), contentScale = ContentScale.Crop ) Column( modifier = Modifier .height(98.dp) .padding(start = dimensionResource(id = R.dimen.padding_large)) ) { Text( text = product.name, style = MaterialTheme.typography.bodySmall, minLines = 2 ) Spacer(modifier = Modifier.weight(1f)) Row { Counter( counter = counter, onAddClick = onAddClick, onRemoveClick = onRemoveClick, modifier = Modifier.width(135.dp) ) Spacer(modifier = Modifier.weight(1f)) Column { Text( text = "${product.priceCurrent / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.titleSmall ) if (product.priceOld != null) Text( text = "${product.priceOld / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.bodyMedium, textDecoration = TextDecoration.LineThrough ) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SuccessCartScreenTopAppBar(onBackClick: () -> Unit) { TopAppBar( title = { Text( text = stringResource(R.string.cart), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(start = dimensionResource(id = R.dimen.padding_large)) ) }, navigationIcon = { IconButton(onClick = onBackClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(R.string.go_back), modifier = Modifier.size(24.dp), tint = Orange ) } } ) } @Preview @Composable fun SuccessCartScreenPreview() { FoodiesTheme { SuccessCartScreen(cart = mapOf(fakeProduct to 1), onBackClick = {}) } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/CartScreen.kt
943893310
package com.example.foodies.ui import androidx.compose.runtime.MutableState 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.example.foodies.data.FoodiesRepository import com.example.foodies.model.Product import com.example.foodies.model.ProductCategory import com.example.foodies.model.ProductTag import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import retrofit2.HttpException import java.io.IOException import javax.inject.Inject @HiltViewModel class FoodiesAppViewModel @Inject constructor(private val foodiesRepository: FoodiesRepository) : ViewModel() { var catalogScreenUiState: CatalogScreenUiState by mutableStateOf(CatalogScreenUiState.Loading) private set init { loadCategories() } private fun loadCategories() { viewModelScope.launch { catalogScreenUiState = CatalogScreenUiState.Loading catalogScreenUiState = try { val productsList = foodiesRepository.getProducts() val categoriesOfProduct = foodiesRepository.getCategories() CatalogScreenUiState.Success( categoriesOfProduct = categoriesOfProduct, productsList = productsList, listOfTags = foodiesRepository.getTags(), cart = mutableStateOf(productsList.associateWith { 0 }), currentCategory = mutableStateOf(categoriesOfProduct[0]) ) } catch (e: IOException) { CatalogScreenUiState.Error } catch (e: HttpException) { CatalogScreenUiState.Error } } } } sealed interface CatalogScreenUiState { class Success( val categoriesOfProduct: List<ProductCategory>, val productsList: List<Product>, val listOfTags: List<ProductTag>, var cart: MutableState<Map<Product, Int>>, var currentCategory: MutableState<ProductCategory> ) : CatalogScreenUiState { fun changeCategory(category: ProductCategory) { currentCategory.value = category } fun increaseCounter(product: Product) { val currentCounter = cart.value[product]!! val newMap = cart.value.toMutableMap() newMap[product] = currentCounter + 1 cart.value = newMap } fun decreaseCounter(product: Product) { val currentCounter = cart.value[product]!! val newMap = cart.value.toMutableMap() newMap[product] = currentCounter - 1 cart.value = newMap } } data object Error : CatalogScreenUiState data object Loading : CatalogScreenUiState }
FoodiesApp/app/src/main/java/com/example/foodies/ui/FoodiesAppViewModel.kt
430326311
package com.example.foodies.ui import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.example.foodies.R import com.example.foodies.model.Product import com.example.foodies.model.ProductTag import com.example.foodies.navigation.NavigationDestination import com.example.foodies.ui.parts.FoodiesBotAppBar import com.example.foodies.ui.parts.ProductImageWithTag object ProductCardDestination : NavigationDestination { override val route = "product_card" } @Composable fun ProductCardScreen( catalogScreenUiState: CatalogScreenUiState, product: Product, navigateBack: () -> Unit, modifier: Modifier = Modifier ) { when (catalogScreenUiState) { is CatalogScreenUiState.Success -> { SuccessProductCardScreen( product = product, listOfTags = catalogScreenUiState.listOfTags, navigateBack = navigateBack, cart = catalogScreenUiState.cart.value, addToCart = { catalogScreenUiState.increaseCounter(product) }, modifier = modifier ) } else -> {} } } @Composable fun SuccessProductCardScreen( product: Product, listOfTags: List<ProductTag>, navigateBack: () -> Unit, cart: Map<Product, Int>, addToCart: (Product) -> Unit, modifier: Modifier = Modifier ) { Scaffold( bottomBar = { FoodiesBotAppBar( onButtonClick = { addToCart(product) }, cart = cart, currentDestination = ProductCardDestination, currentProduct = product ) } ) { paddingValues -> LazyColumn(modifier = modifier.padding(paddingValues)) { item { ProductImageWithTag( product = product, listOfTags = listOfTags, currentDestination = ProductCardDestination, onBackClick = navigateBack ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.padding_medium) * 2)) Text( text = product.name, style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.padding_large)) ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.padding_small))) Text( text = product.description, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.padding_large)) ) Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.padding_medium) * 2)) Divider(thickness = 1.dp) ProductInfo( info = stringResource(R.string.weight), value = product.measure.toDouble(), measureUnit = product.measureUnit ) Divider(thickness = 1.dp) ProductInfo( info = stringResource(R.string.energy), value = product.energy, measureUnit = stringResource(id = R.string.kilo_calories) ) Divider(thickness = 1.dp) ProductInfo( info = stringResource(R.string.proteins), value = product.proteins, measureUnit = product.measureUnit ) Divider(thickness = 1.dp) ProductInfo( info = stringResource(R.string.fats), value = product.fats, measureUnit = product.measureUnit ) Divider(thickness = 1.dp) ProductInfo( info = stringResource(R.string.carbohydrates), value = product.energy, measureUnit = product.measureUnit ) Divider(thickness = 1.dp) } } } } @Composable fun ProductInfo(info: String, value: Double, measureUnit: String, modifier: Modifier = Modifier) { Row( modifier = modifier.padding( horizontal = dimensionResource(id = R.dimen.padding_large), vertical = dimensionResource(id = R.dimen.padding_medium) ) ) { Text( text = info, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f) ) Text( text = "${value.toString().removeSuffix("0").removeSuffix(".")} $measureUnit", style = MaterialTheme.typography.titleSmall ) } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/ProductCardScreen.kt
184657820
package com.example.foodies.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( medium = RoundedCornerShape(8.dp) )
FoodiesApp/app/src/main/java/com/example/foodies/ui/theme/Shape.kt
176478035
package com.example.foodies.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFFFB59D) val PurpleGrey80 = Color(0xFF4FD8EB) val Pink80 = Color(0xFFFFB597) val Orange = Color(0xFFF15412) val DarkOrange = Color(0xFF99461E)
FoodiesApp/app/src/main/java/com/example/foodies/ui/theme/Color.kt
1492982937
package com.example.foodies.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Orange, secondary = Color.White, tertiary = DarkOrange, /* 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 FoodiesTheme( 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 -> 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, shapes = Shapes, typography = Typography, content = content ) }
FoodiesApp/app/src/main/java/com/example/foodies/ui/theme/Theme.kt
2033861128
package com.example.foodies.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.foodies.R val Roboto = FontFamily( Font(R.font.roboto_regular), Font(R.font.roboto_bold, FontWeight.Bold) ) // Set of Material typography styles to start with val Typography = Typography( titleSmall = TextStyle( fontFamily = Roboto, fontWeight = FontWeight.Bold, fontSize = 16.sp ), titleMedium = TextStyle( fontFamily = Roboto, fontWeight = FontWeight.Bold, fontSize = 23.sp ), titleLarge = TextStyle( fontFamily = Roboto, fontWeight = FontWeight.Bold, fontSize = 36.sp ), bodyMedium = TextStyle( fontFamily = Roboto, fontWeight = FontWeight.Normal, fontSize = 16.sp ), bodySmall = TextStyle( fontFamily = Roboto, fontWeight = FontWeight.Normal, fontSize = 14.sp ) )
FoodiesApp/app/src/main/java/com/example/foodies/ui/theme/Type.kt
1911727284
package com.example.foodies.ui.parts import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme 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.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.foodies.R import com.example.foodies.ui.theme.FoodiesTheme import com.example.foodies.ui.theme.Orange @Composable fun Counter( counter: Int, onAddClick: () -> Unit, onRemoveClick: () -> Unit, modifier: Modifier = Modifier ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = modifier ) { ButtonForCounter( onButtonClick = onRemoveClick, icon = painterResource(id = R.drawable.baseline_remove_24), iconDescription = "Remove one", backgroundColor = MaterialTheme.colorScheme.primary, ) Text( text = "$counter", modifier = Modifier.weight(1f), fontSize = 16.sp, textAlign = TextAlign.Center ) ButtonForCounter( onButtonClick = onAddClick, icon = painterResource(id = R.drawable.baseline_add_24), iconDescription = "Add one", backgroundColor = MaterialTheme.colorScheme.primary, ) } } @Composable fun ButtonForCounter( onButtonClick: () -> Unit, icon: Painter, iconDescription: String, backgroundColor: Color, modifier: Modifier = Modifier ) { Button( onClick = onButtonClick, shape = MaterialTheme.shapes.medium, colors = ButtonDefaults.buttonColors( containerColor = if (backgroundColor == MaterialTheme.colorScheme.primary) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.primary ), contentPadding = PaddingValues(all = 0.dp), modifier = modifier.size(40.dp) ) { Icon( painter = icon, contentDescription = iconDescription, tint = Orange, modifier = Modifier.size(16.dp) ) } } @Preview @Composable fun CounterPreview() { FoodiesTheme { Counter(counter = 100, onAddClick = { /*TODO*/ }, onRemoveClick = { /*TODO*/ }) } } @Preview @Composable fun ButtonForCounterPreview() { FoodiesTheme { ButtonForCounter( onButtonClick = {}, icon = painterResource(id = R.drawable.baseline_remove_24), iconDescription = "", backgroundColor = MaterialTheme.colorScheme.primary ) } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/parts/Counter.kt
143710388
package com.example.foodies.ui.parts import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material3.BottomAppBar import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.foodies.R import com.example.foodies.model.Product import com.example.foodies.navigation.NavigationDestination import com.example.foodies.ui.CartScreenDestination import com.example.foodies.ui.CatalogScreenDestination import com.example.foodies.ui.ProductCardDestination import java.text.NumberFormat @Composable fun FoodiesBotAppBar( onButtonClick: () -> Unit, cart: Map<Product, Int>, currentDestination: NavigationDestination, modifier: Modifier = Modifier, currentProduct: Product ) { BottomAppBar { Button( onClick = onButtonClick, modifier = modifier .fillMaxSize() .padding( horizontal = dimensionResource(id = R.dimen.padding_large), vertical = dimensionResource(id = R.dimen.padding_medium) ), shape = MaterialTheme.shapes.medium ) { when(currentDestination) { is CatalogScreenDestination -> Icon( imageVector = Icons.Default.ShoppingCart, contentDescription = stringResource(R.string.buy) ) is ProductCardDestination -> Text( text = stringResource(R.string.add_to_cart_for), style = MaterialTheme.typography.titleSmall ) is CartScreenDestination -> Text( text = stringResource(R.string.order_for), style = MaterialTheme.typography.titleSmall ) } Spacer(modifier = modifier.width(dimensionResource(id = R.dimen.padding_small))) when(currentDestination) { is ProductCardDestination -> Text( text = "${currentProduct.priceCurrent / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.titleSmall ) else -> Text( text = "${cart.filter { it.value != 0 }.map { it.key.priceCurrent * it.value } .sumOf { it } / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.titleSmall ) } } } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/parts/FoodiesBotAppBar.kt
327764361
package com.example.foodies.ui.parts import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size 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.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.foodies.R import com.example.foodies.model.Product import com.example.foodies.model.ProductTag import com.example.foodies.model.fakeProduct import com.example.foodies.model.fakeTag import com.example.foodies.navigation.NavigationDestination import com.example.foodies.ui.CatalogScreenDestination import com.example.foodies.ui.ProductCardDestination import com.example.foodies.ui.theme.FoodiesTheme @Composable fun ProductImageWithTag( product: Product, listOfTags: List<ProductTag>, currentDestination: NavigationDestination, onBackClick: () -> Unit, modifier: Modifier = Modifier ) { Box { ProductTags( product = product, listOfTags = listOfTags, currentDestination = currentDestination, onBackClick = onBackClick, modifier = Modifier .size(if (currentDestination == ProductCardDestination) 44.dp else 24.dp) .padding( start = dimensionResource(id = R.dimen.padding_small), top = dimensionResource(id = R.dimen.padding_small) ) ) Image( painter = painterResource(id = R.drawable.photo), contentDescription = stringResource(R.string.photo, product.name), modifier = modifier, contentScale = ContentScale.Crop ) } } @Composable fun ProductTags( product: Product, listOfTags: List<ProductTag>, currentDestination: NavigationDestination, onBackClick: () -> Unit, modifier: Modifier = Modifier ) { Row { if (currentDestination == ProductCardDestination) IconButton(onClick = onBackClick) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(R.string.go_back), modifier = modifier ) } for (tagId in product.tagIds) { Image( painter = painterResource( id = when (tagId) { 2 -> R.drawable.tag_without_meat 4 -> R.drawable.tag_spicy else -> R.drawable.tag_discount } ), contentDescription = listOfTags.find { it.id == tagId }!!.name, modifier = modifier ) } } } @Preview @Composable fun ProductImageWithTagOnProductScreenPreview() { FoodiesTheme { ProductImageWithTag( product = fakeProduct, listOfTags = listOf(fakeTag, fakeTag), currentDestination = ProductCardDestination, onBackClick = {}, modifier = Modifier.fillMaxWidth() ) } } @Preview @Composable fun ProductImageWithTagOnCatalogPreview() { FoodiesTheme { ProductImageWithTag( product = fakeProduct, listOfTags = listOf(fakeTag, fakeTag), currentDestination = CatalogScreenDestination, onBackClick = {}, modifier = Modifier.fillMaxWidth() ) } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/parts/ProductImageWithTag.kt
4087164164
package com.example.foodies.ui import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues 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.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow 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.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.foodies.R import com.example.foodies.model.Product import com.example.foodies.model.ProductCategory import com.example.foodies.model.ProductTag import com.example.foodies.model.fakeCategory import com.example.foodies.model.fakeProduct import com.example.foodies.model.fakeTag import com.example.foodies.navigation.NavigationDestination import com.example.foodies.ui.parts.Counter import com.example.foodies.ui.parts.FoodiesBotAppBar import com.example.foodies.ui.parts.ProductImageWithTag import com.example.foodies.ui.theme.FoodiesTheme import java.text.NumberFormat object CatalogScreenDestination : NavigationDestination { override val route = "catalog_screen" } @Composable fun CatalogScreen( catalogScreenUiState: CatalogScreenUiState, goToCartScreen: () -> Unit, onCardClick: (Product) -> Unit, modifier: Modifier = Modifier ) { when (catalogScreenUiState) { is CatalogScreenUiState.Loading -> {} is CatalogScreenUiState.Success -> { SuccessCatalogScreen( currentCategory = catalogScreenUiState.currentCategory.value, categoriesOfProduct = catalogScreenUiState.categoriesOfProduct, changeCategory = { catalogScreenUiState.changeCategory(it) }, productsList = catalogScreenUiState.productsList, cart = catalogScreenUiState.cart.value, listOfTags = catalogScreenUiState.listOfTags, increaseCounter = { catalogScreenUiState.increaseCounter(it) }, decreaseCounter = { catalogScreenUiState.decreaseCounter(it) }, goToCartScreen = goToCartScreen, onCardClick = onCardClick, modifier = modifier ) } is CatalogScreenUiState.Error -> {} } } @Composable fun SuccessCatalogScreen( currentCategory: ProductCategory, categoriesOfProduct: List<ProductCategory>, changeCategory: (ProductCategory) -> Unit, productsList: List<Product>, cart: Map<Product, Int>, listOfTags: List<ProductTag>, increaseCounter: (Product) -> Unit, decreaseCounter: (Product) -> Unit, goToCartScreen: () -> Unit, onCardClick: (Product) -> Unit, modifier: Modifier = Modifier ) { Scaffold( topBar = { CatalogScreenTopAppBar(onFilterClick = {}, onSearchClick = {}) }, bottomBar = { if (cart.filter { it.value != 0 }.isNotEmpty()) { FoodiesBotAppBar( onButtonClick = goToCartScreen, cart = cart, currentDestination = CatalogScreenDestination, currentProduct = fakeProduct ) } } ) { paddingValues -> Column(modifier = modifier.padding(paddingValues)) { ListOfProductCategories( currentCategory = currentCategory, productCategories = categoriesOfProduct, changeCurrentCategory = { changeCategory(it) } ) GridOfProducts( productsList = productsList.filter { it.categoryId == currentCategory.id }, cart = cart, listOfTags = listOfTags, increaseCounter = increaseCounter, decreaseCounter = decreaseCounter, onCardClick = onCardClick, modifier = Modifier.padding(all = dimensionResource(id = R.dimen.padding_large)) ) } } } @Composable @OptIn(ExperimentalMaterial3Api::class) fun CatalogScreenTopAppBar( onFilterClick: () -> Unit, onSearchClick: () -> Unit ) { CenterAlignedTopAppBar(title = { Image( painter = painterResource(id = R.drawable.logo), contentDescription = stringResource(R.string.logo), modifier = Modifier.height(60.dp), contentScale = ContentScale.Crop ) }, navigationIcon = { IconButton(onClick = onFilterClick) { Icon( painter = painterResource(id = R.drawable.filter), contentDescription = stringResource(R.string.menu), modifier = Modifier.size(24.dp) ) } }, actions = { IconButton(onClick = onSearchClick) { Icon( imageVector = Icons.Default.Search, contentDescription = stringResource(R.string.search), modifier = Modifier.size(24.dp) ) } }) } @Composable fun ListOfProductCategories( currentCategory: ProductCategory, productCategories: List<ProductCategory>, changeCurrentCategory: (ProductCategory) -> Unit, modifier: Modifier = Modifier ) { LazyRow( modifier = modifier, contentPadding = PaddingValues( start = dimensionResource(id = R.dimen.padding_large), end = dimensionResource(id = R.dimen.padding_large) ), horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_small)) ) { items(productCategories) { productCategory -> Button( onClick = { changeCurrentCategory(productCategory) }, modifier = Modifier.height(40.dp), shape = MaterialTheme.shapes.medium, colors = if (productCategory == currentCategory) ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.primary ) else ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.secondary ) ) { Text( text = productCategory.name, style = MaterialTheme.typography.titleSmall, color = if (productCategory == currentCategory) Color.White else Color.Black ) } } } } @Composable fun GridOfProducts( productsList: List<Product>, cart: Map<Product, Int>, listOfTags: List<ProductTag>, increaseCounter: (Product) -> Unit, decreaseCounter: (Product) -> Unit, onCardClick: (Product) -> Unit, modifier: Modifier = Modifier ) { LazyVerticalGrid( columns = GridCells.Fixed(2), modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_small)), horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_small)) ) { items(productsList) { product -> GridProductCard( product = product, productCount = cart[product]!!, listOfTags = listOfTags, increaseCounter = { increaseCounter(product) }, decreaseCounter = { decreaseCounter(product) }, onCardClick = { onCardClick(product) } ) } } } @Composable fun GridProductCard( product: Product, productCount: Int, listOfTags: List<ProductTag>, increaseCounter: () -> Unit, decreaseCounter: () -> Unit, onCardClick: () -> Unit, modifier: Modifier = Modifier ) { Card(modifier = modifier .fillMaxWidth() .clickable { onCardClick() } ) { Column( verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.heightIn(min = 290.dp) ) { ProductImageWithTag( product = product, listOfTags = listOfTags, currentDestination = CatalogScreenDestination, onBackClick = { }, modifier = Modifier.height(170.dp) ) Text( text = product.name, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.padding_medium), end = dimensionResource(id = R.dimen.padding_medium) ), minLines = 3 ) Text( text = "${product.measure} ${product.measureUnit}", style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding( start = dimensionResource(id = R.dimen.padding_medium) ) ) Box(contentAlignment = Alignment.Center) { if (productCount == 0) { Button( onClick = increaseCounter, shape = MaterialTheme.shapes.medium, modifier = Modifier .padding( start = dimensionResource(id = R.dimen.padding_medium), bottom = dimensionResource(id = R.dimen.padding_medium), end = dimensionResource(id = R.dimen.padding_medium) ) .fillMaxWidth(), contentPadding = PaddingValues(0.dp) ) { Row { Text( text = "${product.priceCurrent / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.titleSmall ) if (product.priceOld != null) { Spacer(modifier = Modifier.width(dimensionResource(id = R.dimen.padding_small))) Text( text = "${product.priceOld / 100} ${NumberFormat.getCurrencyInstance().currency!!.symbol}", style = MaterialTheme.typography.bodyMedium, textDecoration = TextDecoration.LineThrough ) } } } } else { Counter( counter = productCount, onAddClick = increaseCounter, onRemoveClick = decreaseCounter, modifier = Modifier .padding( start = dimensionResource(id = R.dimen.padding_medium), bottom = dimensionResource(id = R.dimen.padding_medium), end = dimensionResource(id = R.dimen.padding_medium) ) .fillMaxWidth() ) } } } } } @Preview @Composable fun SuccessCatalogScreenPreview() { FoodiesTheme { SuccessCatalogScreen( currentCategory = fakeCategory, categoriesOfProduct = listOf(fakeCategory, fakeCategory, fakeCategory), changeCategory = {}, productsList = listOf(fakeProduct, fakeProduct, fakeProduct, fakeProduct), cart = mutableMapOf(fakeProduct to 1), increaseCounter = {}, decreaseCounter = {}, goToCartScreen = {}, onCardClick = {}, listOfTags = listOf(fakeTag) ) } } @Preview @Composable fun GridProductCardPreview() { FoodiesTheme { GridProductCard( product = fakeProduct, productCount = 0, listOfTags = listOf(ProductTag(2, "Вегетарианское блюдо")), increaseCounter = {}, decreaseCounter = {}, onCardClick = {} ) } } @Preview @Composable fun CatalogScreenTopAppBarPreview() { FoodiesTheme { CatalogScreenTopAppBar(onFilterClick = {}, onSearchClick = {}) } } @Preview @Composable fun CatalogScreenBottomAppBarPreview() { FoodiesTheme { FoodiesBotAppBar( onButtonClick = {}, cart = mapOf(fakeProduct to 1), currentDestination = CatalogScreenDestination, currentProduct = fakeProduct ) } }
FoodiesApp/app/src/main/java/com/example/foodies/ui/CatalogScreen.kt
3724964309
package com.example.foodies 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 com.example.foodies.navigation.FoodiesAppNavHost import com.example.foodies.ui.theme.FoodiesTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FoodiesTheme { FoodiesAppNavHost() } } } }
FoodiesApp/app/src/main/java/com/example/foodies/MainActivity.kt
2456830585
package com.example.foodies.di import com.example.foodies.data.FoodiesRepository import com.example.foodies.network.FoodiesApiService import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import retrofit2.Retrofit import retrofit2.create import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object Injection { private const val baseUrl = "https://anika1d.github.io/WorkTestServer/" @Provides @Singleton fun provideApi(): Retrofit = Retrofit.Builder() .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .baseUrl(baseUrl) .build() @Provides @Singleton fun provideFoodiesApiService(retrofit: Retrofit): FoodiesApiService = retrofit.create(FoodiesApiService::class.java) @Provides @Singleton fun provideFoodiesRepository(foodiesApiService: FoodiesApiService): FoodiesRepository = FoodiesRepository(foodiesApiService) }
FoodiesApp/app/src/main/java/com/example/foodies/di/Injection.kt
3007421525
package com.example.foodies.network import com.example.foodies.model.Product import com.example.foodies.model.ProductCategory import com.example.foodies.model.ProductTag import retrofit2.http.GET interface FoodiesApiService { @GET("Categories.json") suspend fun getCategories(): List<ProductCategory> @GET("Tags.json") suspend fun getTags(): List<ProductTag> @GET("Products.json") suspend fun getProducts(): List<Product> }
FoodiesApp/app/src/main/java/com/example/foodies/network/FoodiesApiService.kt
448920407
package com.example.foodies.navigation import android.provider.ContactsContract.Profile import androidx.compose.runtime.Composable import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavType import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.example.foodies.model.fakeProduct import com.example.foodies.ui.CartScreen import com.example.foodies.ui.CartScreenDestination import com.example.foodies.ui.CatalogScreen import com.example.foodies.ui.CatalogScreenDestination import com.example.foodies.ui.CatalogScreenUiState import com.example.foodies.ui.FoodiesAppViewModel import com.example.foodies.ui.ProductCardDestination import com.example.foodies.ui.ProductCardScreen @Composable fun FoodiesAppNavHost() { val navController = rememberNavController() val foodiesAppViewModel = hiltViewModel<FoodiesAppViewModel>() val catalogScreenUiState = foodiesAppViewModel.catalogScreenUiState NavHost( navController = navController, startDestination = CatalogScreenDestination.route ) { composable( route = CatalogScreenDestination.route ) { CatalogScreen( catalogScreenUiState = catalogScreenUiState, goToCartScreen = { navController.navigate(CartScreenDestination.route) }, onCardClick = { product -> navController.navigate(ProductCardDestination.route + "/${product.id}") } ) } composable( route = ProductCardDestination.route + "/{productId}", arguments = listOf(navArgument("productId") { type = NavType.StringType }) ) { backStackEntry -> val productId = backStackEntry.arguments?.getString("productId")!!.toInt() val product = if (foodiesAppViewModel.catalogScreenUiState is CatalogScreenUiState.Success) (foodiesAppViewModel.catalogScreenUiState as CatalogScreenUiState.Success).productsList.find { it.id == productId } else fakeProduct ProductCardScreen( catalogScreenUiState = catalogScreenUiState, product = product!!, navigateBack = { navController.navigateUp() } ) } composable(route = CartScreenDestination.route) { CartScreen( catalogScreenUiState = catalogScreenUiState, onBackClick = { navController.navigateUp() }) } } }
FoodiesApp/app/src/main/java/com/example/foodies/navigation/FoodiesAppNavHost.kt
2195693255
package com.example.foodies.navigation interface NavigationDestination { val route: String }
FoodiesApp/app/src/main/java/com/example/foodies/navigation/NavigationDestination.kt
506664930
package com.example.foodies.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Product( val id: Int, @SerialName("category_id") val categoryId: Int, val name: String, val description: String, val image: String, @SerialName("price_current") val priceCurrent: Int, @SerialName("price_old") val priceOld: Int?, val measure: Int, @SerialName("measure_unit") val measureUnit: String, @SerialName("energy_per_100_grams") val energy: Double, @SerialName("proteins_per_100_grams") val proteins: Double, @SerialName("fats_per_100_grams") val fats: Double, @SerialName("carbohydrates_per_100_grams") val carbohydrates: Double, @SerialName("tag_ids") val tagIds: List<Int> ) val fakeProduct: Product = Product( id = 1, categoryId = 676153, name = "Авокадо Кранч Маки 8шт", description = "Ролл с нежным мясом камчатского краба, копченой курицей и авокадо.Украшается соусом\"Унаги\" и легким майонезом Комплектуется бесплатным набором для роллов (Соевый соус Лайт 35г., васаби 6г., имбирь 15г.). +1 набор за каждые 600 рублей в заказе", image = "1.jpg", priceCurrent = 47000, priceOld = null, measure = 250, measureUnit = "г", energy = 307.8, proteins = 6.1, fats = 11.4, carbohydrates = 45.1, tagIds = listOf(2) )
FoodiesApp/app/src/main/java/com/example/foodies/model/Product.kt
2707968215
package com.example.foodies.model import kotlinx.serialization.Serializable @Serializable data class ProductCategory( val id: Int, val name: String ) val fakeCategory = ProductCategory( id = 676153, name = "Горячие блюда" )
FoodiesApp/app/src/main/java/com/example/foodies/model/ProductCategory.kt
2607338278
package com.example.foodies.model import kotlinx.serialization.Serializable @Serializable data class ProductTag( val id: Int, val name: String ) val fakeTag = ProductTag( id = 2, name = "Вегетарианское блюдо" )
FoodiesApp/app/src/main/java/com/example/foodies/model/ProductTag.kt
4228076667
package com.example.foodies.data import com.example.foodies.model.Product import com.example.foodies.model.ProductCategory import com.example.foodies.model.ProductTag import com.example.foodies.network.FoodiesApiService import javax.inject.Inject class FoodiesRepository @Inject constructor(private val foodiesApiService: FoodiesApiService) { suspend fun getCategories(): List<ProductCategory> = foodiesApiService.getCategories() suspend fun getTags(): List<ProductTag> = foodiesApiService.getTags() suspend fun getProducts(): List<Product> = foodiesApiService.getProducts() }
FoodiesApp/app/src/main/java/com/example/foodies/data/FoodiesRepository.kt
1622907088
package com.example.myrecipeapp 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.myrecipeapp", appContext.packageName) } }
recipe-app-jetpack-compose-kotlin/app/src/androidTest/java/com/example/myrecipeapp/ExampleInstrumentedTest.kt
4105126126
package com.example.myrecipeapp 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) } }
recipe-app-jetpack-compose-kotlin/app/src/test/java/com/example/myrecipeapp/ExampleUnitTest.kt
3953524014
package com.example.myrecipeapp import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch class MainViewModel: ViewModel(){ private val _categorieState = mutableStateOf(RecipeState()) // i got an error when i wrote it like categoriesState = State<RecipeState> val categoriesState : State<RecipeState> = _categorieState init { fetchCategories() } private fun fetchCategories(){ viewModelScope.launch{ try{ val response = recipeService.getCategories() _categorieState.value = _categorieState.value.copy( list = response.categories, // Update the list loading = false, // Reset the loading error = null // Reset the error ) } catch (e: Exception) { _categorieState.value = _categorieState.value.copy( loading = false, // Reset the loading error = "Error fetching Categories ${e.message}" // Update the error ) } } } data class RecipeState( val loading : Boolean = true, val list : List<Category> = emptyList(), // string is nullable and can be null val error : String? = null ) }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/MainViewModel.kt
3910066208
package com.example.myrecipeapp.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)
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/ui/theme/Color.kt
3732476451
package com.example.myrecipeapp.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 MyrecipeAppTheme( 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 ) }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/ui/theme/Theme.kt
3977748713
package com.example.myrecipeapp.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 ) */ )
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/ui/theme/Type.kt
32801975
package com.example.myrecipeapp import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.navigation.compose.rememberNavController import com.example.myrecipeapp.ui.theme.MyrecipeAppTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val navController = rememberNavController() MyrecipeAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { } RecipeApp(navController = navController ) } } } }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/MainActivity.kt
4110272870
package com.example.myrecipeapp import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Category( val idCategory : String, val strCategory : String, val strCategoryThumb : String, val strCategoryDescription : String ): Parcelable data class CategoriesResponse (val categories : List<Category>)
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/Category.kt
1727660838
package com.example.myrecipeapp import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable @Composable fun RecipeApp(navController: NavHostController){ val recipeViewModel : MainViewModel = viewModel() val viewstate by recipeViewModel.categoriesState NavHost(navController = navController , startDestination = Screen.RecipeScreen.route ) { composable(route = Screen.RecipeScreen.route) { RecipeScreen(viewstate = viewstate, navigateToDetail = { navController.currentBackStackEntry?.savedStateHandle?.set("cat", it) navController.navigate(Screen.DetailScreen.route) }) } composable(route = Screen.DetailScreen.route) { val category = navController.previousBackStackEntry?.savedStateHandle?.get<Category>("cat") ?: Category("", "", "", "") CategoryScreenDetails(category = category) } } }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/RecipeApp.kt
535966635
package com.example.myrecipeapp sealed class Screen(val route : String) { object RecipeScreen: Screen ("recipescreen") object DetailScreen: Screen ("detailscreen") }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/Screen.kt
1589189624
package com.example.myrecipeapp import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET private val retrofit = Retrofit.Builder() .baseUrl("https://www.themealdb.com/api/json/v1/1/") // Corrected baseUrl .addConverterFactory(GsonConverterFactory.create()) .build() val recipeService = retrofit.create(ApiService::class.java) interface ApiService { @GET("categories.php") suspend fun getCategories(): CategoriesResponse }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/ApiService.kt
2581442069
package com.example.myrecipeapp import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import coil.compose.rememberAsyncImagePainter @Composable fun CategoryScreenDetails( category : Category ){ Column( modifier = Modifier .fillMaxSize() .padding(18.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text(text = category.strCategory , modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, fontWeight = FontWeight.Bold ) Image( painter = rememberAsyncImagePainter(category.strCategoryThumb), contentDescription = null, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) ) Spacer(modifier = Modifier.padding(8.dp)) Text(text = category.strCategoryDescription, modifier = Modifier .fillMaxWidth() .verticalScroll(rememberScrollState())) } }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/CategoryScreenDetails.kt
1962473717
package com.example.myrecipeapp import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio 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.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.rememberAsyncImagePainter @Composable fun RecipeScreen( modifier: Modifier = Modifier, viewstate : MainViewModel.RecipeState, navigateToDetail : (Category) -> Unit ) { Box(modifier = Modifier.fillMaxSize()) { when{ viewstate.loading -> { CircularProgressIndicator(modifier = Modifier.align(Alignment.Center)) } viewstate.error != null -> { Text("Error Occurred !") } else -> { // Display Categories CategoryScreen(categories = viewstate.list,navigateToDetail) } } } } @Composable fun CategoryScreen(categories: List<Category> , navigateToDetail : (Category) -> Unit ){ LazyVerticalGrid(GridCells.Fixed(2) , modifier = Modifier.fillMaxSize() ) { items(categories){ category -> CategoryItem(category = category, navigateToDetail) } } } // How each item looks like @Composable fun CategoryItem(category: Category , navigateToDetail : (Category) -> Unit ) { Column( modifier = Modifier .padding(8.dp) .fillMaxSize() .clickable { navigateToDetail (category) }, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = rememberAsyncImagePainter(category.strCategoryThumb), contentDescription = null, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) ) Text( text = category.strCategory.orEmpty(), color = Color.Black, style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 20.sp ), modifier = Modifier.padding(top = 4.dp) ) } }
recipe-app-jetpack-compose-kotlin/app/src/main/java/com/example/myrecipeapp/RecipeScreen.kt
3054892420
package com.example.activityexample 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.activityexample", appContext.packageName) } }
ActivityExample/app/src/androidTest/java/com/example/activityexample/ExampleInstrumentedTest.kt
1511704786
package com.example.activityexample 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) } }
ActivityExample/app/src/test/java/com/example/activityexample/ExampleUnitTest.kt
3087422512
package com.example.activityexample.model import android.os.Parcelable import androidx.annotation.DrawableRes import com.google.android.material.progressindicator.DeterminateDrawable import kotlinx.parcelize.Parcelize @Parcelize data class Person( val name : String, @DrawableRes val imgResDrawable: Int, val jobDesc : String, val shortDesc : String ) : Parcelable
ActivityExample/app/src/main/java/com/example/activityexample/model/Person.kt
4152424995
package com.example.activityexample.feature.home import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.example.activityexample.R import com.example.activityexample.databinding.FragmentAboutBinding import com.example.activityexample.databinding.FragmentHomeBinding import com.example.activityexample.feature.detail.DetailActivity import com.example.activityexample.model.Person class HomeFragment : Fragment() { private lateinit var binding : FragmentHomeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //todo : inflate data } }
ActivityExample/app/src/main/java/com/example/activityexample/feature/home/HomeFragment.kt
3396837724
package com.example.activityexample.feature.about import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.activityexample.R import com.example.activityexample.databinding.FragmentAboutBinding import com.example.activityexample.feature.detail.DetailActivity import com.example.activityexample.model.Person class AboutFragment : Fragment() { private lateinit var binding : FragmentAboutBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentAboutBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setClickAction() // Call setClickAction here } private fun setClickAction() { binding.btnProfile.setOnClickListener { navigateToProfile() } } private fun navigateToProfile() { DetailActivity.startActivity( requireContext(), Person( "Rohit", R.drawable.ic_profil, "Priciple Android", "Lorem ipsum set dolot almet" ) ) //Toast.makeText(this, "Navigate to Profile", Toast.LENGTH_LONG).show() } }
ActivityExample/app/src/main/java/com/example/activityexample/feature/about/AboutFragment.kt
1571411082
package com.example.activityexample.feature.detail import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.activityexample.databinding.ActivityDetailBinding import com.example.activityexample.model.Person class DetailActivity : AppCompatActivity() { companion object { const val EXTRAS_DETAIL_DATA = "EXTRAS_DETAIL_DATA" fun startActivity(context: Context, person: Person) { val intent = Intent(context, DetailActivity::class.java) intent.putExtra(EXTRAS_DETAIL_DATA, person) context.startActivity(intent) } } private lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) getIntentData() } private fun getIntentData() { val person = intent.getParcelableExtra<Person>(EXTRAS_DETAIL_DATA) person?.let { setProfileImage(it.imgResDrawable) setProfileData(it) } } private fun setProfileData(person: Person) { binding.tvName.text = person.name binding.tvJobDesc.text = person.jobDesc binding.tvMoreDetails.text = person.shortDesc } private fun setProfileImage(imgResDrawable: Int) { imgResDrawable?.let {binding.ivProvile.setImageResource(imgResDrawable) } } }
ActivityExample/app/src/main/java/com/example/activityexample/feature/detail/DetailActivity.kt
1779161872
package com.example.activityexample.feature.main import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.example.activityexample.feature.detail.DetailActivity import com.example.activityexample.R import com.example.activityexample.databinding.ActivityMainBinding import com.example.activityexample.model.Person class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.java.simpleName private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate: Activity Created") binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) //setClickAction() setBottomNavigation() } private fun setBottomNavigation() { val navController = findNavController(R.id.main_nav_host) binding.btnMain.setupWithNavController(navController) } /* *//* private fun setClickAction() { binding.btnProfile.setOnClickListener { navigateToProfile() } }*/ /* private fun navigateToProfile() { DetailActivity.startActivity( this, Person( "Rohit", R.drawable.ic_profil, "Priciple Android", "Lorem ipsum set dolot almet" ) ) Toast.makeText(this, "Navigate to Profile", Toast.LENGTH_LONG).show() }*/ override fun onStart() { super.onStart() Log.d(TAG, "onStart: Activity Started") } override fun onResume() { super.onResume() Log.d(TAG, "onResume: Activity Resume") } override fun onPause() { super.onPause() Log.d(TAG, "onPause: Activity Pause") } override fun onStop() { super.onStop() Log.d(TAG, "onStop: Activity Stop") } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy: Activity Destroy") } }
ActivityExample/app/src/main/java/com/example/activityexample/feature/main/MainActivity.kt
3943695466
package com.android.feedme.test.ui import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.Profile import com.android.feedme.model.data.ProfileRepository import com.android.feedme.model.viewmodel.ProfileViewModel import com.android.feedme.screen.EditProfileTestScreen import com.android.feedme.ui.navigation.NavigationActions import com.android.feedme.ui.profile.EditProfileScreen import com.google.android.gms.tasks.Tasks import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.every import io.mockk.mockk import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class EditProfileTest { @get:Rule val composeTestRule = createComposeRule() private val mockNavActions = mockk<NavigationActions>(relaxed = true) private val mockFirestore = mockk<FirebaseFirestore>(relaxed = true) private val mockDocumentReference = mockk<DocumentReference>(relaxed = true) private val mockCollectionReference = mockk<CollectionReference>(relaxed = true) private var mockDocumentSnapshot = mockk<DocumentSnapshot>(relaxed = true) // Avoid re-creating a viewModel for every test private lateinit var profileViewModel: ProfileViewModel private lateinit var profileRepository: ProfileRepository @Before fun setUpMocks() { ProfileRepository.initialize(mockFirestore) profileRepository = ProfileRepository.instance every { mockFirestore.collection("profiles") } returns mockCollectionReference every { mockCollectionReference.document(any()) } returns mockDocumentReference val profile = Profile() every { mockDocumentReference.get() } returns Tasks.forResult(mockDocumentSnapshot) every { mockDocumentSnapshot.toObject(Profile::class.java) } returns profile every { mockDocumentReference.set(any()) } returns Tasks.forResult(null) profileViewModel = ProfileViewModel() } @Test fun testIsDisplayed() { goToEditProfileScreen() ComposeScreen.onComposeScreen<EditProfileTestScreen>(composeTestRule) { composeTestRule.waitForIdle() editProfileContent.assertIsDisplayed() editPicture.assertIsDisplayed() nameInput.assertIsDisplayed() usernameInput.assertIsDisplayed() bioInput.assertIsDisplayed() saveButton.assertIsDisplayed() } } @Test fun testIllegalModification() { goToEditProfileScreen() ComposeScreen.onComposeScreen<EditProfileTestScreen>(composeTestRule) { composeTestRule.waitForIdle() nameInput.performTextClearance() nameInput.performTextInput("Jn") usernameInput.performTextClearance() usernameInput.performTextInput("J#123") bioInput.performTextClearance() bioInput.performTextInput("This is a sample bio repeated several times for testing") bioInput.performTextInput("This is a sample bio repeated several times for testing") composeTestRule.waitForIdle() // Check error messages nameError.assertIsDisplayed() nameError.assertTextEquals("Name must be at least 3 characters") usernameError.assertIsDisplayed() usernameError.assertTextEquals("Username must be alphanumeric or underscores") bioError.assertIsDisplayed() bioError.assertTextEquals("Bio must be no more than 100 characters") saveButton.assertIsNotEnabled() // Clear inputs again to re-enter new values nameInput.performTextClearance() usernameInput.performTextClearance() bioInput.performTextClearance() usernameInput.performTextInput("johnjohnjohnjohnjohn") usernameError.assertTextEquals("Username must be no more than 15 characters") usernameInput.performTextClearance() // Re-entering text to test updated values nameInput.performTextInput("John") usernameInput.performTextInput("john") bioInput.performTextInput("This is a sample bio.") composeTestRule.waitForIdle() // Ensuring Save button functionality saveButton.assertIsDisplayed() saveButton.assertTextEquals("Save") saveButton.assertHasClickAction() saveButton.assertIsEnabled() composeTestRule.waitForIdle() } } @Test fun testSaveButton() { goToEditProfileScreen() ComposeScreen.onComposeScreen<EditProfileTestScreen>(composeTestRule) { composeTestRule.waitForIdle() nameInput.performTextClearance() usernameInput.performTextClearance() bioInput.performTextClearance() nameInput.performTextInput("John") usernameInput.performTextInput("john") bioInput.performTextInput("This is a sample bio.") composeTestRule.waitForIdle() saveButton { assertIsEnabled() assertTextEquals("Save") performClick() } composeTestRule.waitForIdle() } } @Test fun testProfilePicture() { goToEditProfileScreen() ComposeScreen.onComposeScreen<EditProfileTestScreen>(composeTestRule) { editPicture.assertIsDisplayed() editPicture.assertHasClickAction() editPicture.performClick() } } private fun goToEditProfileScreen() { composeTestRule.setContent { EditProfileScreen(mockNavActions, profileViewModel) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/ui/EditProfileTest.kt
1678765174
package com.android.feedme.test.ui import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.Profile import com.android.feedme.model.data.ProfileRepository import com.android.feedme.model.viewmodel.ProfileViewModel import com.android.feedme.screen.ProfileScreen import com.android.feedme.ui.navigation.NavigationActions import com.android.feedme.ui.profile.ProfileScreen import com.google.firebase.firestore.FirebaseFirestore import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.every import io.mockk.mockk import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ProfileTest { @get:Rule val composeTestRule = createComposeRule() private val mockFirestore = mockk<FirebaseFirestore>(relaxed = true) @Before fun init() { ProfileRepository.initialize(mockFirestore) } @Test fun profileBoxAndComponentsCorrectlyDisplayed() { ComposeScreen.onComposeScreen<ProfileScreen>(composeTestRule) { val mockProfileViewModel = mockk<ProfileViewModel>() val profile = Profile( // Sample profile data name = "John Doe", username = "johndoe", followers = listOf("follower1", "follower2"), following = listOf("following1", "following2"), description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." // Add any other required fields for Profile ) every { mockProfileViewModel.currentUserId } returns "ID_DEFAULT" every { mockProfileViewModel.viewingUserId } returns null every { mockProfileViewModel.isViewingProfile() } returns false every { mockProfileViewModel.profileToShow() } returns profile every { mockProfileViewModel.fetchCurrentUserProfile() } returns Unit composeTestRule.setContent { ProfileScreen(mockk<NavigationActions>(), mockProfileViewModel) } topBarProfile { assertIsDisplayed() } bottomBarProfile { assertIsDisplayed() } profileBox { assertIsDisplayed() } profileName { assertIsDisplayed() } profileIcon { assertIsDisplayed() } profileBio { assertIsDisplayed() } followerDisplayButton { assertIsDisplayed() assertHasClickAction() } followingDisplayButton { assertIsDisplayed() assertHasClickAction() } editButton { assertIsDisplayed() assertHasClickAction() } shareButton { assertIsDisplayed() assertHasClickAction() } } } @Test fun viewingDisplayedProfileIsCorrectAndFollowButtonWorks() { ComposeScreen.onComposeScreen<ProfileScreen>(composeTestRule) { val mockProfileViewModel = mockk<ProfileViewModel>() val profile = Profile( // Sample profile data name = "John Doe", username = "johndoe", followers = listOf("follower1", "follower2"), following = listOf("following1", "following2"), description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." // Add any other required fields for Profile ) every { mockProfileViewModel.currentUserId } returns "ID_DEFAULT_1" every { mockProfileViewModel.viewingUserId } returns "ID_DEFAULT_2" every { mockProfileViewModel.isViewingProfile() } returns true every { mockProfileViewModel.profileToShow() } returns profile every { mockProfileViewModel.fetchCurrentUserProfile() } returns Unit composeTestRule.setContent { ProfileScreen(mockk<NavigationActions>(), mockProfileViewModel) } topBarProfile { assertIsDisplayed() } bottomBarProfile { assertIsDisplayed() } profileBox { assertIsDisplayed() } profileName { assertIsDisplayed() } profileIcon { assertIsDisplayed() } profileBio { assertIsDisplayed() } followerDisplayButton { assertIsDisplayed() assertHasClickAction() } followingDisplayButton { assertIsDisplayed() assertHasClickAction() } editButton { assertIsNotDisplayed() } shareButton { assertIsDisplayed() assertHasClickAction() } followerButton { assertIsDisplayed() assertHasClickAction() performClick() } followingButton { assertIsDisplayed() assertHasClickAction() } } } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/ui/ProfileTest.kt
871513613
package com.android.feedme.test.ui import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.ProfileRepository import com.android.feedme.screen.FriendsScreen import com.android.feedme.ui.navigation.NavigationActions import com.google.firebase.FirebaseApp import com.google.firebase.firestore.FirebaseFirestore import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.mockk import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FriendsTest { @get:Rule val composeTestRule = createComposeRule() private val mockNavActions = mockk<NavigationActions>(relaxed = true) private val mockFirestore = mockk<FirebaseFirestore>(relaxed = true) @Before fun setupMocks() { if (FirebaseApp.getApps(ApplicationProvider.getApplicationContext()).isEmpty()) { FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext()) } ProfileRepository.initialize(mockFirestore) } @Test fun tabsAndComponentsCorrectlyDisplayed() { goToFriendsScreen() ComposeScreen.onComposeScreen<FriendsScreen>(composeTestRule) { tabFollowers { assertIsDisplayed() assertHasClickAction() performClick() } followersList { assertIsDisplayed() } followerCard { assertIsDisplayed() } tabFollowing { assertIsDisplayed() assertHasClickAction() performClick() } followingList.assertIsDisplayed() followerCard { assertIsDisplayed() } } } private fun goToFriendsScreen() { val mockNavActions = mockk<NavigationActions>(relaxed = true) // Make the mock relaxed composeTestRule.setContent { com.android.feedme.ui.profile.FriendsScreen(mockNavActions, mode = 4242) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/ui/FriendsTest.kt
552269666
package com.android.feedme.test.ui import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.Ingredient import com.android.feedme.model.data.IngredientMetaData import com.android.feedme.model.data.MeasureUnit import com.android.feedme.model.data.Recipe import com.android.feedme.model.data.RecipeRepository import com.android.feedme.model.data.Step import com.android.feedme.model.viewmodel.RecipeViewModel import com.android.feedme.ui.home.RecipeFullDisplay import com.android.feedme.ui.navigation.NavigationActions import com.google.android.gms.tasks.Tasks import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import io.mockk.every import io.mockk.mockk import junit.framework.TestCase import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FullRecipeTest : TestCase() { private val recipe = Recipe( recipeId = "lasagna1", title = "Tasty Lasagna", description = "Description of the recipe, writing a longer one to see if it fills up the whole space available. Still writing with no particular aim lol", ingredients = listOf( IngredientMetaData( quantity = 2.0, measure = MeasureUnit.ML, ingredient = Ingredient("Tomato", "Vegetables", "tomatoID"))), steps = listOf( Step( 1, "In a large, heavy pot, put the olive oil, garlic and parsley over medium high heat. When the garlic begins to brown, increase the heat and add the ground beef. Break up the beef, but keep it rather chunky. Sprinkle with about 1/2 tsp of salt. \n" + "\n" + "When the beef is beginning to dry up, add the tomatoes and stir well. Add more salt, then lower the heat and allow to simmer for about an hour, stirring from time to time. Taste for salt and add pepper.", "Make the Meat Sauce")), tags = listOf("Meat"), time = 1.15, rating = 4.5, userid = "@PasDavid", difficulty = "Intermediate", "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.mamablip.com%2Fstorage%2FLasagna%2520with%2520Meat%2520and%2520Tomato%2520Sauce_3481612355355.jpg&f=1&nofb=1&ipt=8e887ba99ce20a85fb867dabbe0206c1146ebf2f13548b5653a2778e3ea18c54&ipo=images") @get:Rule val composeTestRule = createComposeRule() private val mockNavActions = mockk<NavigationActions>(relaxed = true) private val mockFirestore = mockk<FirebaseFirestore>(relaxed = true) private val mockDocumentReference = mockk<DocumentReference>(relaxed = true) private val mockCollectionReference = mockk<CollectionReference>(relaxed = true) private var mockDocumentSnapshot = mockk<DocumentSnapshot>(relaxed = true) // Avoid re-creating a viewModel for every test private lateinit var recipeViewModel: RecipeViewModel private lateinit var recipeRepository: RecipeRepository @Before fun setUpMocks() { every { mockNavActions.canGoBack() } returns true RecipeRepository.initialize(mockFirestore) recipeRepository = RecipeRepository.instance every { mockFirestore.collection("recipes") } returns mockCollectionReference every { mockCollectionReference.document("lasagna1") } returns mockDocumentReference every { mockDocumentReference.get() } returns Tasks.forResult(mockDocumentSnapshot) every { mockDocumentSnapshot.toObject(Recipe::class.java) } returns recipe every { mockDocumentReference.set(any()) } returns Tasks.forResult(null) recipeViewModel = RecipeViewModel() recipeViewModel.setRecipe(recipe) recipeViewModel.selectRecipe(recipe) } @Test fun checkFullRecipeDisplay() { goToFullRecipeScreen() // Check whether the Image or the warning message is displayed try { composeTestRule.onNodeWithTag("Recipe Image").assertIsDisplayed() } catch (e: AssertionError) { composeTestRule.onNodeWithText("Fail Image Download") } composeTestRule.onNodeWithTag("General Infos Row").assertIsDisplayed() composeTestRule.onNodeWithTag("Time Icon").assertIsDisplayed() composeTestRule.onNodeWithTag("Text Time").assertIsDisplayed() composeTestRule.onNodeWithTag("Rating Icon").assertIsDisplayed() composeTestRule.onNodeWithTag("Text Rating").assertIsDisplayed() composeTestRule.onNodeWithTag("Horizontal Divider 1").assertIsDisplayed() composeTestRule.onNodeWithTag("Ingredient Title").assertIsDisplayed() composeTestRule.onNodeWithTag("Ingredient Description").assertIsDisplayed() composeTestRule.onNodeWithTag("Horizontal Divider 2").assertIsDisplayed() composeTestRule.onNodeWithTag("Step Title").assertIsDisplayed() composeTestRule.onNodeWithTag("Step Description").assertIsDisplayed() } private fun goToFullRecipeScreen() { composeTestRule.setContent { RecipeFullDisplay(mockNavActions, recipeViewModel) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/ui/FullRecipeTest.kt
1895868821
package com.android.feedme.test import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.screen.NotImplementedScreen import com.android.feedme.ui.NotImplementedScreen import com.android.feedme.ui.navigation.NavigationActions import com.android.feedme.ui.navigation.Route import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.mockk import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NotImplementedTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() @Test fun mainComponentsAreDisplayed() { goToCreateScreen() ComposeScreen.onComposeScreen<NotImplementedScreen>(composeTestRule) { topBarLanding { assertIsDisplayed() } bottomBarLanding { assertIsDisplayed() } middleText { assertIsDisplayed() } } } private fun goToCreateScreen() { composeTestRule.setContent { NotImplementedScreen(mockk<NavigationActions>(), Route.SETTINGS) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/NotImplementedTest.kt
3370783748
package com.android.feedme.test.auth import com.google.android.gms.auth.api.signin.GoogleSignInAccount import io.mockk.every import io.mockk.mockk fun mockGoogleSignInAccount(): GoogleSignInAccount { val account = mockk<GoogleSignInAccount>(relaxed = true) // Mock necessary methods of GoogleSignInAccount as needed for the test every { account.id } returns "ID_DEFAULT" every { account.displayName } returns "NAME_DEFAULT" every { account.email } returns "EMAIL_DEFAULT" return account }
feedme-android/app/src/androidTest/java/com/android/feedme/test/auth/LoginMock.kt
156161760
package com.android.feedme.test.auth import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.espresso.intent.rule.IntentsTestRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.MainActivity import com.android.feedme.screen.LoginScreen import com.android.feedme.ui.auth.LoginScreen import com.android.feedme.ui.navigation.NavigationActions import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.mockk import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LoginTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() // The IntentsTestRule simply calls Intents.init() before the @Test block // and Intents.release() after the @Test block is completed. IntentsTestRule // is deprecated, but it was MUCH faster than using IntentsRule in our tests @get:Rule val intentsTestRule = IntentsTestRule(MainActivity::class.java) @Test fun titleAndButtonAreCorrectlyDisplayed() { goToLoginScreen() ComposeScreen.onComposeScreen<LoginScreen>(composeTestRule) { // Test the UI elements loginTitle { assertIsDisplayed() assertTextEquals("Welcome") } loginButton { assertIsDisplayed() assertHasClickAction() } } } /* This Test make the CI fail, as no response of the Intent is received @Test fun googleSignInReturnsValidActivityResult() { goToLoginScreen() ComposeScreen.onComposeScreen<LoginScreen>(composeTestRule) { loginButton { assertIsDisplayed() performClick() } // assert that an Intent resolving to Google Mobile Services has been sent (for sign-in) intended(toPackage("com.google.android.gms")) } } */ private fun goToLoginScreen() { composeTestRule.setContent { LoginScreen(mockk<NavigationActions>()) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/auth/LoginTest.kt
3900281828
package com.android.feedme.test.camera import android.Manifest import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.isDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.GrantPermissionRule import com.android.feedme.screen.CameraScreen import com.android.feedme.ui.camera.CameraScreen import com.android.feedme.ui.navigation.NavigationActions import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.every import io.mockk.mockk import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CameraTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() // Grant camera permission for tests @get:Rule val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(Manifest.permission.CAMERA) @Test fun buttonsAndCameraCorrectlyDisplayed() { goToCameraScreen() ComposeScreen.onComposeScreen<CameraScreen>(composeTestRule) { cameraPreview { assertIsDisplayed() } photoButton { assertIsDisplayed() assertHasClickAction() } galleryButton { assertIsDisplayed() assertHasClickAction() } } } @Test fun galleryButtonDisplayGalleryWhenEmpty() { goToCameraScreen() ComposeScreen.onComposeScreen<CameraScreen>(composeTestRule) { cameraPreview { assertIsDisplayed() } photoButton { assertIsDisplayed() } galleryButton { assertIsDisplayed() performClick() } // Wait for the gallery to be displayed composeTestRule.waitForIdle() // Assert that the empty gallery text is displayed after clicking composeTestRule .onNodeWithText("There are no photos yet", useUnmergedTree = true) .assertIsDisplayed() } } @Test fun galleryButtonDisplayGalleryAfterTakingPhoto() { goToCameraScreen() ComposeScreen.onComposeScreen<CameraScreen>(composeTestRule) { cameraPreview { assertIsDisplayed() } photoButton { assertIsDisplayed() performClick() } // Wait until the "Photo saved" text appears on the UI. composeTestRule.waitUntil(timeoutMillis = 5000) { composeTestRule.onNodeWithText("Photo saved", useUnmergedTree = true).isDisplayed() } galleryButton { assertIsDisplayed() performClick() } // Wait for the gallery to be displayed composeTestRule.waitForIdle() // Assert that the photos are displayed after clicking composeTestRule .onNodeWithContentDescription("Photo", useUnmergedTree = true) .assertIsDisplayed() } } private fun goToCameraScreen() { val navActions = mockk<NavigationActions>() every { navActions.canGoBack() } returns true composeTestRule.setContent { CameraScreen(navActions) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/camera/CameraTest.kt
2110940381
package com.android.feedme.test.navigation import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.SaveAlt import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.ui.navigation.NavigationActions import com.android.feedme.ui.navigation.TopBarNavigation import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TopBarNavigationTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() @Test fun testTopBarNavigationEverythingDisplayed() { // Create NavigationActions instance with the mock NavController val navActions = mockk<NavigationActions>() every { navActions.canGoBack() } returns true every { navActions.goBack() } returns composeTestRule.setContent { TopBarNavigation( title = "Test", navAction = navActions, rightIcon = Icons.Default.SaveAlt, rightIconOnClickAction = {}) } composeTestRule.onNodeWithTag("TopBarNavigation").assertIsDisplayed() composeTestRule.onNodeWithTag("LeftIconBox").assertIsDisplayed() composeTestRule .onNodeWithTag("LeftIconButton") .assertIsDisplayed() .assertHasClickAction() .performClick() composeTestRule.onNodeWithTag("TitleBox").assertIsDisplayed() composeTestRule.onNodeWithTag("TitleText").assertIsDisplayed() composeTestRule.onNodeWithTag("RightIconBox").assertIsDisplayed() composeTestRule.onNodeWithTag("RightIconButton").assertIsDisplayed().assertHasClickAction() coVerify { navActions.goBack() } } @Test fun testTopBarNavigationRightIconDoesNotAppear() { // Create NavigationActions instance with the mock NavController val navActions = mockk<NavigationActions>() every { navActions.canGoBack() } returns true composeTestRule.setContent { TopBarNavigation( title = "Test", navAction = navActions, rightIcon = null, rightIconOnClickAction = {}) } composeTestRule.onNodeWithTag("TopBarNavigation").assertIsDisplayed() composeTestRule.onNodeWithTag("LeftIconBox").assertIsDisplayed() composeTestRule.onNodeWithTag("LeftIconButton").assertIsDisplayed().assertHasClickAction() composeTestRule.onNodeWithTag("TitleBox").assertIsDisplayed() composeTestRule.onNodeWithTag("TitleText").assertIsDisplayed() composeTestRule.onNodeWithTag("RightIconBox").assertIsNotDisplayed() composeTestRule.onNodeWithTag("RightIconButton").assertIsNotDisplayed() } @Test fun testTopBarNavigationLeftIconDoesNotAppear() { // Create NavigationActions instance with the mock NavController val navActions = mockk<NavigationActions>() every { navActions.canGoBack() } returns true composeTestRule.setContent { TopBarNavigation( title = "Test", navAction = null, rightIcon = Icons.Default.SaveAlt, rightIconOnClickAction = {}) } composeTestRule.onNodeWithTag("TopBarNavigation").assertIsDisplayed() composeTestRule.onNodeWithTag("LeftIconBox").assertIsNotDisplayed() composeTestRule.onNodeWithTag("LeftIconButton").assertIsNotDisplayed() composeTestRule.onNodeWithTag("TitleBox").assertIsDisplayed() composeTestRule.onNodeWithTag("TitleText").assertIsDisplayed() composeTestRule.onNodeWithTag("RightIconBox").assertIsDisplayed() composeTestRule.onNodeWithTag("RightIconButton").assertIsDisplayed().assertHasClickAction() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/navigation/TopBarNavigationTest.kt
4198516620
package com.android.feedme.test.navigation import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.ui.navigation.BottomNavigationMenu import com.android.feedme.ui.navigation.TOP_LEVEL_DESTINATIONS import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class BottomNavigationMenuTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() @Test fun bottomNavigationMenuCorrectlyDisplayed() { composeTestRule.setContent { BottomNavigationMenu( selectedItem = "Home", onTabSelect = {}, tabList = TOP_LEVEL_DESTINATIONS) } composeTestRule.onNodeWithTag("BottomNavigationMenu").assertIsDisplayed() TOP_LEVEL_DESTINATIONS.forEach { destination -> composeTestRule.onNodeWithTag(destination.textId).assertIsDisplayed().assertHasClickAction() composeTestRule.onNodeWithText(destination.textId).assertIsDisplayed() } } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/navigation/BottomNavigationMenuTest.kt
3166552633
package com.android.feedme.test.component import androidx.compose.ui.test.assertHasClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.ui.component.IngredientList import junit.framework.TestCase import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class IngredientListTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() @Test fun testIngredientListTestEverythingDisplayed() { composeTestRule.setContent { IngredientList() } composeTestRule.onNodeWithTag("LazyList").assertIsDisplayed() composeTestRule.onNodeWithTag("IngredientsBox").assertIsDisplayed() composeTestRule.onNodeWithTag("QuantityInput").assertIsDisplayed() composeTestRule.onNodeWithTag("DoseBox").assertIsDisplayed() composeTestRule.onNodeWithTag("DoseInput").assertIsDisplayed() } @Test fun testIngredientDropDownMenuWorksAndHasClickableItem() { composeTestRule.setContent { IngredientList() } composeTestRule.onNodeWithTag("LazyList").assertIsDisplayed() composeTestRule.onNodeWithTag("IngredientsBox").assertIsDisplayed() composeTestRule.onNodeWithTag("IngredientsInput").assertIsDisplayed().performTextInput("Item 1") composeTestRule .onNodeWithText("Item 1") .assertIsDisplayed() .assertHasClickAction() .performClick() composeTestRule .onNodeWithTag("DeleteIconButton") .assertIsDisplayed() .assertHasClickAction() .performClick() composeTestRule.onNodeWithTag("DeleteIconButton").assertIsNotDisplayed() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/component/IngredientListTest.kt
2539900548
package com.android.feedme.test.component import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.ui.component.SearchBarFun import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SearchBarTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() @Test fun checkSearchBarDisplayed() { composeTestRule.setContent { SearchBarFun() } composeTestRule.waitForIdle() composeTestRule.onNodeWithTag("SearchBar").assertIsDisplayed() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/component/SearchBarTest.kt
1179910076
package com.android.feedme.test.component import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.Ingredient import com.android.feedme.model.data.IngredientMetaData import com.android.feedme.model.data.MeasureUnit import com.android.feedme.model.data.Recipe import com.android.feedme.model.data.Step import com.android.feedme.ui.component.SmallThumbnailsDisplay import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SmallThumbnailsDisplayTest { @get:Rule val composeTestRule = createComposeRule() @Test fun checkThumbnailsDisplay() { val recipe1 = Recipe( recipeId = "lasagna1", title = "Tasty Lasagna", description = "a", ingredients = listOf( IngredientMetaData( quantity = 2.0, measure = MeasureUnit.ML, ingredient = Ingredient("Tomato", "Vegetables", "tomatoID"))), steps = listOf(Step(1, "a", "Step1")), tags = listOf("Meat"), time = 1.15, rating = 4.5, userid = "PasDavid", difficulty = "Intermediate", "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.mamablip.com%2Fstorage%2FLasagna%2520with%2520Meat%2520and%2520Tomato%2520Sauce_3481612355355.jpg&f=1&nofb=1&ipt=8e887ba99ce20a85fb867dabbe0206c1146ebf2f13548b5653a2778e3ea18c54&ipo=images") composeTestRule.setContent { SmallThumbnailsDisplay(listRecipe = listOf(recipe1)) } // Check whether the Image or the warning message is displayed try { composeTestRule.onNodeWithTag("Recipe Image").assertIsDisplayed() } catch (e: AssertionError) { composeTestRule.onNodeWithText("Fail Image Download") } // Thread.sleep(30000) composeTestRule.onNodeWithContentDescription("Star Icon").assertIsDisplayed() composeTestRule.onNodeWithText(recipe1.rating.toString()).assertIsDisplayed() composeTestRule.onNodeWithContentDescription("Info Icon").assertIsDisplayed() composeTestRule.onNodeWithText(recipe1.time.toString()).assertIsDisplayed() composeTestRule.waitForIdle() /*composeTestRule .onNodeWithContentDescription("Save Icon", useUnmergedTree = true) .assertIsDisplayed()*/ composeTestRule.onNodeWithText(recipe1.title).assertIsDisplayed() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/component/SmallThumbnailsDisplayTest.kt
2704770081
package com.android.feedme.test.component import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.Comment import com.android.feedme.ui.component.SmallCommentsDisplay import java.util.Date import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SmallCommentsTest { @get:Rule val composeTestRule = createComposeRule() @Test fun checkCommentsDisplay() { val comment1 = Comment( "@author", "@author", "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.mamablip.com%2Fstorage%2FLasagna%2520with%2520Meat%2520and%2520Tomato%2520Sauce_3481612355355.jpg&f=1&nofb=1&ipt=8e887ba99ce20a85fb867dabbe0206c1146ebf2f13548b5653a2778e3ea18c54&ipo=images", 3.5, 1.15, "Was uncooked", "I respected instruction, but the result wasn't great", Date()) composeTestRule.setContent { SmallCommentsDisplay(listComment = listOf(comment1)) } // Recipe Image composeTestRule.onNodeWithContentDescription("Recipe Image").assertIsDisplayed() // Author name composeTestRule.onNodeWithText(comment1.authorId).assertIsDisplayed() // Title composeTestRule.onNodeWithText(comment1.title).assertIsDisplayed() // Description composeTestRule.onNodeWithText(comment1.content).assertIsDisplayed() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/component/SmallCommentsTest.kt
1581486077
package com.android.feedme.test import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.isDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.GrantPermissionRule import com.android.feedme.MainActivity import com.android.feedme.screen.CameraScreen import com.android.feedme.screen.CreateScreen import com.android.feedme.screen.LandingScreen import com.android.feedme.screen.LoginScreen import com.android.feedme.test.auth.mockGoogleSignInAccount import com.android.feedme.ui.auth.setLoginMockingForTests import com.android.feedme.ui.auth.setTestMode import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class UserFlowTest : TestCase() { @get:Rule val composeTestRule = createAndroidComposeRule<MainActivity>() // Grant camera permission for tests @get:Rule val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(android.Manifest.permission.CAMERA) @Before fun setup() { // Set up the test environment for Login mocking setTestMode(true) setLoginMockingForTests(::mockGoogleSignInAccount) } @After fun teardown() { // Reset the test environment after the test setTestMode(false) } @Test fun userFlowFromLoginPageThroughAllTopLevelDestinations() { ComposeScreen.onComposeScreen<LoginScreen>(composeTestRule) { // Click on the "Sign in with Google" button loginButton { assertIsDisplayed() performClick() } // Wait for the login to complete composeTestRule.waitForIdle() } // From HOME Page go to EXPLORE page composeTestRule.onNodeWithText("Explore").assertIsDisplayed().performClick() // Wait for the EXPLORE page to load composeTestRule.waitForIdle() // From EXPLORE Page go to CREATE page composeTestRule.onNodeWithText("Create").assertIsDisplayed().performClick() // Wait for the CREATE page to load composeTestRule.waitForIdle() // From CREATE Page go to PROFILE page // TODO We got to Mockk Firebase another issue // composeTestRule.onNodeWithText("Profile").assertIsDisplayed().performClick() // Wait for the PROFILE page to load composeTestRule.waitForIdle() // From PROFILE Page go to SETTINGS page composeTestRule.onNodeWithText("Settings").assertIsDisplayed().performClick() // Wait for the SETTINGS page to load composeTestRule.waitForIdle() // From SETTINGS Page go to HOME page composeTestRule.onNodeWithText("Home").assertIsDisplayed().performClick() // Wait for the HOME page to load composeTestRule.waitForIdle() } @Test fun userFlowFromLoginPageToCameraAndTakePhoto() { ComposeScreen.onComposeScreen<LoginScreen>(composeTestRule) { // Click on the "Sign in with Google" button loginButton { assertIsDisplayed() performClick() } // Wait for the login to complete composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<LandingScreen>(composeTestRule) { // From Home Page go to CREATE page composeTestRule.onNodeWithText("Create").assertIsDisplayed().performClick() // Wait for the CREATE page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<CreateScreen>(composeTestRule) { cameraButton { assertIsDisplayed() performClick() } // Wait for the CAMERA page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<CameraScreen>(composeTestRule) { cameraPreview { assertIsDisplayed() } photoButton { assertIsDisplayed() performClick() } // Wait until the "Photo saved" text appears on the UI. composeTestRule.waitUntil(timeoutMillis = 5000) { composeTestRule.onNodeWithText("Photo saved", useUnmergedTree = true).isDisplayed() } // Click on the gallery button galleryButton { assertIsDisplayed() performClick() } // Wait for the gallery to be displayed composeTestRule.waitForIdle() // Assert that the photos are displayed after clicking composeTestRule .onNodeWithContentDescription("Photo", useUnmergedTree = true) .assertIsDisplayed() } } /* // TODO We got to Mockk Firebase another issue @Test fun userFlowFromLoginPageToProfileAndNavigateThroughSubScreens() { ComposeScreen.onComposeScreen<LoginScreen>(composeTestRule) { // Click on the "Sign in with Google" button loginButton { assertIsDisplayed() performClick() } // Wait for the login to complete composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<LandingScreen>(composeTestRule) { // From Home Page go to PROFILE page composeTestRule.onNodeWithText("Profile").assertIsDisplayed().performClick() // Wait for the PROFILE page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<ProfileScreen>(composeTestRule) { followerDisplayButton { assertIsDisplayed() performClick() } // Wait for the FRIENDS page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<FriendsScreen>(composeTestRule) { tabFollowing { assertIsDisplayed() performClick() } // Wait for the FOLLOWING list to load composeTestRule.waitForIdle() followingList { assertIsDisplayed() } tabFollowers { assertIsDisplayed() performClick() } // Wait for the FOLLOWERS list to load composeTestRule.waitForIdle() followersList { assertIsDisplayed() } composeTestRule .onNodeWithTag("LeftIconButton") .assertIsDisplayed() .assertHasClickAction() .performClick() // Wait for the PROFILE page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<ProfileScreen>(composeTestRule) { editButton { assertIsDisplayed() performClick() } // Wait for the EDIT PROFILE page to load composeTestRule.waitForIdle() } ComposeScreen.onComposeScreen<EditProfileTestScreen>(composeTestRule) { // Wait for the EDIT PROFILE page to load composeTestRule.waitForIdle() composeTestRule .onNodeWithTag("LeftIconButton") .assertIsDisplayed() .assertHasClickAction() .performClick() } } */ }
feedme-android/app/src/androidTest/java/com/android/feedme/test/UserFlowTest.kt
3453453690
package com.android.feedme.test import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.screen.CreateScreen import com.android.feedme.ui.CreateScreen import com.android.feedme.ui.navigation.NavigationActions import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.mockk import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CreateTest : TestCase() { // @get:Rule val composeTestRule = createAndroidComposeRule<MainActivity>() @get:Rule val composeTestRule = createComposeRule() @Test fun mainComponentsAreDisplayed() { goToCreateScreen() ComposeScreen.onComposeScreen<CreateScreen>(composeTestRule) { topBarLanding { assertIsDisplayed() } bottomBarLanding { assertIsDisplayed() } cameraButton { assertIsDisplayed() assertHasClickAction() } } } private fun goToCreateScreen() { composeTestRule.setContent { CreateScreen(mockk<NavigationActions>()) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/CreateTest.kt
66988060
package com.android.feedme.test import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.feedme.model.data.RecipeRepository import com.android.feedme.screen.LandingScreen import com.android.feedme.ui.home.LandingPage import com.android.feedme.ui.navigation.NavigationActions import com.google.firebase.firestore.FirebaseFirestore import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import io.github.kakaocup.compose.node.element.ComposeScreen import io.mockk.mockk import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LandingTest : TestCase() { @get:Rule val composeTestRule = createComposeRule() private val mockFirestore = mockk<FirebaseFirestore>(relaxed = true) @Before fun init() { RecipeRepository.initialize(mockFirestore) } @Test fun mainComponentsAreDisplayed() { goToLandingScreen() ComposeScreen.onComposeScreen<LandingScreen>(composeTestRule) { composeTestRule.waitForIdle() completeScreen.assertIsDisplayed() topBarLanding { assertIsDisplayed() } bottomBarLanding { assertIsDisplayed() } recipeList { assertIsDisplayed() } recipeCard { assertIsDisplayed() assertHasClickAction() } saveIcon { assertIsDisplayed() assertHasClickAction() } userName { assertIsDisplayed() assertHasClickAction() } shareIcon { assertIsDisplayed() } ratingButton { assertIsDisplayed() assertHasClickAction() } filterClick { assertIsDisplayed() assertHasClickAction() } completeScreen { assertIsDisplayed() } } } private fun goToLandingScreen() { composeTestRule.setContent { LandingPage(mockk<NavigationActions>(relaxed = true)) } composeTestRule.waitForIdle() } }
feedme-android/app/src/androidTest/java/com/android/feedme/test/LandingTest.kt
74275030