content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.otsembo.farmersfirst.data.repository import com.otsembo.farmersfirst.common.AppResource import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map /** * Base repository class for performing database transactions. * This class utilizes Kotlin coroutines and flows to handle asynchronous operations. */ abstract class BaseRepository { /** * Executes a database transaction asynchronously and emits the result as a flow of AppResource. * @param flow The flow representing the database transaction. * @return A flow of AppResource representing the transaction result. */ suspend fun <T> dbTransact(flow: Flow<T>) = flow { // Emit loading state emit(AppResource.Loading()) // Collect the flow and emit success state with the result emitAll(flow.map { AppResource.Success(result = it) }) }.catch { error -> // Catch any errors during the transaction and emit error state emit(AppResource.Error(info = error.message ?: "An error occurred!")) } }
FarmersFirst/app/src/main/java/com/otsembo/farmersfirst/data/repository/BaseRepository.kt
631584331
package com.otsembo.farmersfirst.data.repository import android.content.Context import androidx.credentials.CredentialManager import androidx.credentials.GetCredentialRequest import androidx.credentials.exceptions.NoCredentialException import com.google.android.libraries.identity.googleid.GetGoogleIdOption import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential import com.otsembo.farmersfirst.BuildConfig import com.otsembo.farmersfirst.common.AppResource import com.otsembo.farmersfirst.common.coerceTo import com.otsembo.farmersfirst.data.database.AppDatabaseHelper import com.otsembo.farmersfirst.data.database.dao.UserDao import com.otsembo.farmersfirst.data.model.Basket import com.otsembo.farmersfirst.data.model.User import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.last import kotlinx.coroutines.flow.map import java.security.MessageDigest import java.util.UUID /** * Interface for the authentication repository, defining methods for signing in and signing out users. */ interface IAuthRepository { /** * Signs in the user with the specified Google ID option. * @param googleIdOption The optional Google ID option for signing in. Defaults to null. * @return A flow of AppResource representing the result of the sign-in operation. * The flow emits a nullable String which represents the user's unique identifier upon successful sign-in, * or null if the sign-in operation fails. */ suspend fun signInUser(googleIdOption: GetGoogleIdOption? = null): Flow<AppResource<String?>> /** * Signs out the currently signed-in user. * @return A flow of AppResource representing the result of the sign-out operation. * The flow emits a Boolean value indicating whether the sign-out operation was successful (true) or not (false). */ suspend fun signOutUser(): Flow<AppResource<Boolean>> /** * Checks if a user is currently signed in. * @return A flow of AppResource representing the result of the check. * The flow emits a Boolean value indicating whether a user is currently signed in (true) or not (false). */ suspend fun checkIfSignedIn(): Flow<AppResource<Boolean>> } /** * Repository class responsible for handling authentication-related operations, * such as signing in and signing out users using Google OAuth. * Implements the [IAuthRepository] interface. * * @param activityContext The context of the activity or application. * @param oAuthClient The OAuth client identifier. * @param userPrefRepository The repository for user preferences. */ class AuthRepository( private val activityContext: Context, private val oAuthClient: String, private val userPrefRepository: IUserPrefRepository, private val basketRepository: IBasketRepository, ) : IAuthRepository { private val credentialManager = CredentialManager.create(activityContext) private val userDao: UserDao = UserDao(AppDatabaseHelper(activityContext).writableDatabase) /** * Signs in the user with the specified Google ID option. * If no option is provided, a default option is constructed. * Emits [AppResource] objects representing the result of the sign-in operation. * * @param googleIdOption The optional Google ID option for signing in. Defaults to null. * @return A flow of [AppResource] representing the result of the sign-in operation. */ override suspend fun signInUser(googleIdOption: GetGoogleIdOption?): Flow<AppResource<String?>> = flow { emit(AppResource.Loading()) val googleId: GetGoogleIdOption = googleIdOption ?: buildGoogleId(true) val request: GetCredentialRequest = GetCredentialRequest.Builder() .addCredentialOption(googleId) .build() val result = credentialManager.getCredential( request = request, context = activityContext, ) val tokenCredential = GoogleIdTokenCredential .createFrom(result.credential.data) val userEmail = tokenCredential.data.getString(EMAIL_KEY) val signInToken = tokenCredential.idToken userEmail?.let { val user = userDao.queryWhere("${AppDatabaseHelper.USER_EMAIL} = ?", arrayOf(it)).last() val userId: Int = if (user.isEmpty()) { // if no existing user, create one then throw exception if error occurs val createdUser = userDao.create(User(id = 0, it)).last() ?: throw Exception( "Could not create your account!", ) // create their initial basket basketRepository.createBasket( Basket( id = 0, user = User(id = createdUser.id, email = ""), status = AppDatabaseHelper.BasketStatusPending, ), ).last() createdUser.id } else { user.first().id } emitAll( userPrefRepository.addUserToStore(signInToken, userId).map { tokenStoreResult -> tokenStoreResult.coerceTo { res -> when (res) { is AppResource.Success -> signInToken else -> null } } }, ) } }.catch { cause: Throwable -> if (cause is NoCredentialException) { signInUser(googleIdOption = buildGoogleId(false)) } else { emit(AppResource.Error(info = cause.message ?: "An unexpected error occurred")) } } /** * Signs out the currently signed-in user. * Emits [AppResource] objects representing the result of the sign-out operation. * * @return A flow of [AppResource] representing the result of the sign-out operation. */ override suspend fun signOutUser(): Flow<AppResource<Boolean>> = flow { emit(AppResource.Loading()) val logout = userPrefRepository.removeUserFromStore().last() if (logout.data == true) { emit(AppResource.Success(true)) } else { emit(AppResource.Error("Something went wrong")) } }.catch { emit(AppResource.Error(it.message ?: "Something went wrong")) } override suspend fun checkIfSignedIn(): Flow<AppResource<Boolean>> = flow { emit(AppResource.Loading()) emitAll( userPrefRepository.fetchToken().map { res -> res.coerceTo { when (it) { is AppResource.Error -> false is AppResource.Loading -> false is AppResource.Success -> true } } }, ) } /** * Builds a Google ID option for signing in based on the provided authorized filter. * * @param authorizedFilter Boolean indicating whether to filter by authorized accounts. * @return A constructed [GetGoogleIdOption] object for signing in. */ private fun buildGoogleId(authorizedFilter: Boolean): GetGoogleIdOption = GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(authorizedFilter) .setNonce(buildNonce()) .setServerClientId(BuildConfig.googleOAuthKey) .build() /** * Generates a unique nonce string for authentication purposes. * * @return The generated nonce string. */ private fun buildNonce(): String { val rawNonce = UUID.randomUUID().toString() val bytes = rawNonce.toByteArray() val mDigest = MessageDigest.getInstance("SHA-512") val digest = mDigest.digest(bytes) return digest.fold("") { hash, it -> hash + "%02x".format(it) } } companion object { private const val EMAIL_KEY = "com.google.android.libraries.identity.googleid.BUNDLE_KEY_ID" } }
FarmersFirst/app/src/main/java/com/otsembo/farmersfirst/data/repository/AuthRepository.kt
3070365185
package com.otsembo.farmersfirst.data.work import android.annotation.SuppressLint import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.otsembo.farmersfirst.data.database.AppDatabaseHelper import com.otsembo.farmersfirst.data.database.ProductsSeed import com.otsembo.farmersfirst.data.database.dao.ProductDao import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * Worker class for seeding the database with initial data. * @param context The application context. * @param workerParams The parameters for the worker. */ class DbSeedWorker( private val context: Context, workerParams: WorkerParameters, ) : CoroutineWorker(context, workerParams) { /** * Performs the work of seeding the database with initial data. * @return The result of the work. */ @SuppressLint("RestrictedApi") override suspend fun doWork(): Result { return withContext(Dispatchers.IO) { try { val appDB = AppDatabaseHelper(context) val productDao = ProductDao(appDB.writableDatabase) val dbSeeder = ProductsSeed(appDB, productDao) dbSeeder.addProducts() Result.success() } catch (e: Exception) { Result.retry() } } } }
FarmersFirst/app/src/main/java/com/otsembo/farmersfirst/data/work/DbSeedWorker.kt
78808245
package com.otsembo.farmersfirst.data.model /** * Data class representing a user entity. * @property id The unique identifier of the user (default value: 0). * @property email The email address of the user. */ data class User( var id: Int = 0, val email: String, ) /** * Data class representing a product entity. * @property id The unique identifier of the product (default value: 0). * @property name The name of the product. * @property description The description of the product. * @property stock The stock quantity of the product. * @property price The price of an individual product * @property image The image URL of an individual product */ data class Product( var id: Int = 0, val name: String, val description: String, val stock: Int, val price: Float, val image: String, ) /** * Data class representing a basket entity. * @property id The unique identifier of the basket (default value: 0). * @property user The user associated with the basket. * @property status The status of the basket. */ data class Basket( var id: Int = 0, val user: User, val status: String, ) /** * Data class representing a basket item entity. * @property id The unique identifier of the basket item (default value: 0). * @property basket The basket associated with the item. * @property product The product associated with the item. * @property quantity The quantity of the product in the basket. */ data class BasketItem( var id: Int = 0, val basket: Basket, val product: Product, val quantity: Int, )
FarmersFirst/app/src/main/java/com/otsembo/farmersfirst/data/model/entities.kt
1363191809
package com.example.mobileproject 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.mobileproject", appContext.packageName) } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/androidTest/java/com/example/mobileproject/ExampleInstrumentedTest.kt
1950208751
package com.example.mobileproject 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) } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/test/java/com/example/mobileproject/ExampleUnitTest.kt
4097285190
package adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.mobileproject.databinding.OrderItemBinding import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.ValueEventListener import com.google.firebase.database.database class OrderAdapter(private val orderSummary:MutableList<String>,private val total:MutableList<Int>,): RecyclerView.Adapter<OrderAdapter.OrderViewHolder>() { private val auth = FirebaseAuth.getInstance() init{ val database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference val userId = auth.currentUser?.uid?:"" orderReference = database.child("user").child(userId).child("Order") } companion object{ private lateinit var orderReference : DatabaseReference } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderAdapter.OrderViewHolder { val binding = OrderItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return OrderViewHolder(binding) } override fun onBindViewHolder(holder: OrderAdapter.OrderViewHolder, position: Int) { holder.bind(position) } override fun getItemCount(): Int = total.size inner class OrderViewHolder(private val binding: OrderItemBinding):RecyclerView.ViewHolder(binding.root) { fun bind(position: Int) { binding.summary.text = orderSummary[position] binding.total.text = "Total : RM "+total[position].toString() binding.btnDelete.setOnClickListener { val itemPosition = adapterPosition if (itemPosition != RecyclerView.NO_POSITION) { deleteItem(itemPosition) } } } private fun deleteItem(position: Int){ val positionRetrive = position getUniqueKeyAtPosition(positionRetrive){uniqueKey -> if (uniqueKey != null){ removeItem(position,uniqueKey) } } } private fun removeItem(position: Int ,uniqueKey: String){ if (uniqueKey != null){ orderReference.child(uniqueKey).removeValue().addOnSuccessListener { orderSummary.removeAt(position) total.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position,total.size) } } } private fun getUniqueKeyAtPosition(positionRetrieve: Int, onComplete:(String?) -> Unit) { orderReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot){ var uniqueKey:String? = null snapshot.children.forEachIndexed { index, dataSnapshot -> if (index == positionRetrieve){ uniqueKey = dataSnapshot.key return@forEachIndexed } } onComplete(uniqueKey) } override fun onCancelled(error: DatabaseError){ } }) } } } //private val auth = FirebaseAuth.getInstance() //init{ // val database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference // val userId = auth.currentUser?.uid?:"" // val oderItemNumber = total.size // orderReference = database.child("user").child(userId).child("Order") //} // //companion object{ // private lateinit var orderReference : DatabaseReference //} // //override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OrderViewHolder { // val binding = OrderItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) // return OrderViewHolder(binding) //} // //override fun onBindViewHolder(holder: OrderViewHolder, position: Int) { // holder.bind(position) //} // //override fun getItemCount(): Int = total.size // // //inner class OrderViewHolder (private val binding: OrderItemBinding) : RecyclerView.ViewHolder(binding.root){ // fun bind(position: Int){ // binding.summary.text = orderSummary[position] // binding.total.text = total[position].toString() // } //} // // //private fun getUniqueKeyAtPosition(positionRetrieve: Int, onComplete:(String?) -> Unit) { // orderReference.addListenerForSingleValueEvent(object : ValueEventListener { // override fun onDataChange(snapshot: DataSnapshot){ // var uniqueKey:String? = null // snapshot.children.forEachIndexed { index, dataSnapshot -> // if (index == positionRetrieve){ // uniqueKey = dataSnapshot.key // return@forEachIndexed // } // } // onComplete(uniqueKey) // } // override fun onCancelled(error: DatabaseError){ // // } // }) //}
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/adapter/OrderAdapter.kt
3164974979
package adapter import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageButton import android.widget.Toast import androidx.core.content.ContextCompat.startActivity import androidx.recyclerview.widget.RecyclerView import com.example.mobileproject.R import com.example.mobileproject.databinding.CartItemBinding import com.example.mobileproject.models.Cart import com.example.mobileproject.nav import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.firebase.database.core.Context import com.google.firebase.database.database class CartAdapter( private val cartItems:MutableList<String>, private val cartPrices:MutableList<Int>, private val cartImages:MutableList<Int>, private val cartQuantities:MutableList<Int>, ): RecyclerView.Adapter<CartAdapter.CartViewHolder>(){ private val auth = FirebaseAuth.getInstance() init{ val database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference val userId = auth.currentUser?.uid?:"" val cartItemNumber = cartItems.size cartReference = database.child("user").child(userId).child("cart") quantities =IntArray(cartItemNumber){1} } companion object{ private var quantities : IntArray = intArrayOf() private lateinit var cartReference :DatabaseReference } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder { val binding = CartItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return CartViewHolder(binding) } override fun onBindViewHolder(holder: CartViewHolder, position: Int) { holder.bind(position) } override fun getItemCount(): Int = cartItems.size fun getUpdatedItemsQuantities() : MutableList<Int>{ val quantity = mutableListOf<Int>() quantity.addAll(cartQuantities) return quantity } inner class CartViewHolder (private val binding: CartItemBinding) : RecyclerView.ViewHolder(binding.root){ fun bind(position: Int){ val quantity = quantities[position] binding.Name.text = cartItems[position] binding.Image.setImageResource(cartImages[position]) binding.Price.text = cartPrices[position].toString() binding.Num.text = quantity.toString() binding.btnMinus.setOnClickListener { decreaseQuantity(position) } binding.btnAdd.setOnClickListener { increaseQuantity(position) } binding.btnDelete.setOnClickListener { val itemPosition = adapterPosition if (itemPosition != RecyclerView.NO_POSITION){ deleteItem(itemPosition) } } } private fun decreaseQuantity(position: Int){ if (quantities[position]>1 ){ quantities[position]-- cartQuantities[position] = quantities[position] binding.Num.text = quantities[position].toString() } } private fun increaseQuantity(position: Int){ if (quantities[position]<10 ){ quantities[position]++ cartQuantities[position] = quantities[position] binding.Num.text = quantities[position].toString() } } private fun deleteItem(position: Int){ // cartItems.removeAt(position) // cartImages.removeAt(position) // cartPrices.removeAt(position) // notifyItemRemoved(position) // notifyItemRangeChanged(position,cartItems.size) val positionRetrive = position getUniqueKeyAtPosition(positionRetrive){uniqueKey -> if (uniqueKey != null){ removeItem(position,uniqueKey) } } } private fun removeItem(position: Int ,uniqueKey: String){ if (uniqueKey != null){ cartReference.child(uniqueKey).removeValue().addOnSuccessListener { cartItems.removeAt(position) cartImages.removeAt(position) cartPrices.removeAt(position) cartQuantities.removeAt(position) quantities = quantities.filterIndexed{ index, i -> index!=position }.toIntArray() notifyItemRemoved(position) notifyItemRangeChanged(position,cartItems.size) } } } private fun getUniqueKeyAtPosition(positionRetrieve: Int, onComplete:(String?) -> Unit) { cartReference.addListenerForSingleValueEvent(object : ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot){ var uniqueKey:String? = null snapshot.children.forEachIndexed { index, dataSnapshot -> if (index == positionRetrieve){ uniqueKey = dataSnapshot.key return@forEachIndexed } } onComplete(uniqueKey) } override fun onCancelled(error: DatabaseError){ } }) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/adapter/CartAdapter.kt
386061133
package adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.mobileproject.databinding.ItemLayoutBinding class ProductAdapter(private val items:List<String>,private val prices:List<Int> ,private val images:List<Int>): RecyclerView.Adapter<ProductAdapter.ProductViewHolder>(){ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder { return ProductViewHolder(ItemLayoutBinding.inflate(LayoutInflater.from(parent.context),parent,false)) } override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { val item = items[position] val price = prices[position] val image = images[position] holder.bind(item,price,image) } override fun getItemCount(): Int { return items.size } class ProductViewHolder (private val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root){ fun bind(item: String, price:Int, image:Int){ binding.productName.text = item binding.ProductImage.setImageResource(image) binding.price.text = price.toString() } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/adapter/ProductAdapter.kt
1136624791
package com.example.mobileproject // manifest import for READ_EXTERNAL_STORAGE import android.content.Intent import android.os.Build import android.os.Bundle import android.text.TextUtils import android.view.WindowInsets import android.view.WindowManager import android.widget.Button import android.widget.EditText import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import android.widget.Toast import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.User import com.example.mobileproject.utils.Constants class UserProfileActivity : BaseActivity() { private lateinit var mUserDetails: User override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_profile) //code to show full screen @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } if (intent.hasExtra(Constants.EXTRA_USER_DETAILS)) { mUserDetails = intent.getParcelableExtra(Constants.EXTRA_USER_DETAILS)!! } // Accessing Views // val iv_user_photo = findViewById<ImageView>(R.id.iv_user_photo) val etName = findViewById<EditText>(R.id.et_name) val etEmail = findViewById<EditText>(R.id.et_email) val etPhone = findViewById<EditText>(R.id.et_phone) val etAddress1 = findViewById<EditText>(R.id.et_address1) val etAddress2 = findViewById<EditText>(R.id.et_address2) val etAddress3 = findViewById<EditText>(R.id.et_address3) val btnSubmit = findViewById<Button>(R.id.btn_submit) val rgGender = findViewById<RadioGroup>(R.id.rg_gender) val rbMale = findViewById<RadioButton>(R.id.rb_male) val rbFemale = findViewById<RadioButton>(R.id.rb_female) val btnBack: TextView = findViewById(R.id.back) etName.isEnabled = false etName.setText(mUserDetails.fullName) etEmail.isEnabled = false etEmail.setText(mUserDetails.email) etPhone.setText(mUserDetails.mobile.toString()) etAddress1.setText(mUserDetails.address1) etAddress2.setText(mUserDetails.address2) etAddress3.setText(mUserDetails.address3) if(mUserDetails.gender == "male"){ rbMale.setChecked(true) }else if(mUserDetails.gender == "female"){ rbFemale.setChecked(true) } // // local storage permission // iv_user_photo.setOnClickListener { // // check permission for access data of phone local storage // if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE // ) == PackageManager.PERMISSION_GRANTED){ // showErrorSnackBar("you already have storage permission", false) // }else{ // ActivityCompat.requestPermissions( // this, // arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), // Constants.READ_STORAGE_PERMISSION_CODE // ) // } // // } btnBack.setOnClickListener { val intent = Intent(this@UserProfileActivity, MainActivity::class.java) //above code like send data startActivity(intent) } btnSubmit.setOnClickListener { if(validateUserProfileDetails()){ val etPhone = findViewById<EditText>(R.id.et_phone).text.toString().trim{ it <= ' '} val rgGender = findViewById<RadioGroup>(R.id.rg_gender) val rbMale = findViewById<RadioButton>(R.id.rb_male) val rbFemale = findViewById<RadioButton>(R.id.rb_female) val etAddress1 = findViewById<EditText>(R.id.et_address1).text.toString() val etAddress2 = findViewById<EditText>(R.id.et_address2).text.toString() val etAddress3 = findViewById<EditText>(R.id.et_address3).text.toString() //key:"" value:"" val userHashMap = HashMap<String,Any>() val gender = if(rbMale.isChecked){ "male" }else if(rbFemale.isChecked){ "female" }else{ "" } if (etPhone.isNotEmpty()){ userHashMap["mobile"] = etPhone.toLong() } userHashMap["gender"] = gender // showErrorSnackBar("your details are valid",false) if (etAddress1.isNotEmpty()) { userHashMap["address1"] = etAddress1 } if (etAddress2.isNotEmpty()) { userHashMap["address2"] = etAddress2 } if (etAddress3.isNotEmpty()) { userHashMap["address3"] = etAddress3 } userHashMap["profileCompleted"] = 1 showProgressDialog() FirestoreClass().updateUserProfileData(this,userHashMap) } } } private fun validateUserProfileDetails():Boolean{ val etPhone = findViewById<EditText>(R.id.et_phone) val etAddress1 = findViewById<EditText>(R.id.et_address1) val etAddress2 = findViewById<EditText>(R.id.et_address2) val etAddress3 = findViewById<EditText>(R.id.et_address3) return when { TextUtils.isEmpty(etPhone.text.toString().trim{ it <= ' '})->{ showErrorSnackBar("Please enter mobile number!",true) false } TextUtils.isEmpty(etAddress1.text.toString().trim{ it <= ' '})->{ showErrorSnackBar("Please enter address 1!",true) false }else -> { true } } } fun userProfileUpdateSuccess(){ hideProgressDialog() Toast.makeText( this@UserProfileActivity, "update success", Toast.LENGTH_SHORT ).show() startActivity(Intent(this@UserProfileActivity,MainActivity::class.java)) finish() } // // local storage permission // override fun onRequestPermissionsResult( // requestCode: Int, // permissions: Array<out String>, // grantResults: IntArray // ) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults) // if (requestCode == Constants.READ_STORAGE_PERMISSION_CODE){ // //if permission is granted // if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){ // showErrorSnackBar("The storage permission is granted", false) // }else{ // //Displaying another toast if permission is not granted // Toast.makeText( // this, // ("Oops,you just denied the permission for storage. You can also allow it from setting."), // Toast.LENGTH_LONG // ).show() // } // } // } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/UserProfileActivity.kt
770715568
package com.example.mobileproject import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.database //, PaymentResultListener class ProceedActivity : AppCompatActivity() { private var database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_proceed) // Checkout.preload(applicationContext) // val co = Checkout() // // apart from setting it in AndroidManifest.xml, keyId can also be set // // programmatically during runtime // co.setKeyID("rzp_live_XXXXXXXXXXXXXX") // Key Id rzp_test_0N8OCe2J5uJ8aG // Key Secret tqY8sPCXyKodICxhQheC9nBj val intent = intent val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@ProceedActivity, CartActivity::class.java) //above code like send data startActivity(intent) } val total: TextView = findViewById(R.id.total) total.setText(calculateTotalAmount().toString()) val summary: TextView = findViewById(R.id.summary) summary.setText(showOrderSummary()) val btnSubmit: Button = findViewById(R.id.btn_submit) btnSubmit.setOnClickListener { // removeItemFromCart() // val order = Order(showOrderSummary(),calculateTotalAmount() ) // FirestoreClass().addItemToOrder(this@ProceedActivity, order) val intent = Intent(this@ProceedActivity,PaymentActivity::class.java) intent.putExtra("summary",showOrderSummary()) intent.putExtra("total",calculateTotalAmount().toString()) startActivity(intent) } } private fun removeItemFromCart() { auth = FirebaseAuth.getInstance() val userId = auth.currentUser?.uid?:"" var cartReference = database.child("user").child(userId).child("cart") cartReference.removeValue() } private fun showOrderSummary():String { val orderName = intent.getStringArrayListExtra("orderName") val orderPrice = intent.getIntegerArrayListExtra("orderPrice") val orderQuantities = intent.getIntegerArrayListExtra("orderQuantities") var summary = "" if (orderPrice != null) { for (i in 0 until orderPrice.size){ var Name = orderName?.get(i) var quantity = orderQuantities?.get(i).toString() summary += "$Name X$quantity\n" } } return summary } private fun calculateTotalAmount():Int { val orderPrice = intent.getIntegerArrayListExtra("orderPrice") val orderQuantities = intent.getIntegerArrayListExtra("orderQuantities") var totalAmount = 0 if (orderPrice != null) { for (i in 0 until orderPrice.size){ var price = orderPrice?.get(i) var quantity = orderQuantities?.get(i) totalAmount += price?.times(quantity!!) ?: 0 } } return totalAmount } // override fun onPaymentSuccess(p0: String?) { // removeItemFromCart() // val order = Order(showOrderSummary(),calculateTotalAmount() ) // FirestoreClass().addItemToOrder(this@ProceedActivity, order) // Toast.makeText(this@ProceedActivity, "payment success", Toast.LENGTH_LONG).show() // } // // override fun onPaymentError(p0: Int, p1: String?) { // Toast.makeText(this@ProceedActivity, "payment fail", Toast.LENGTH_LONG).show() // } // // // private fun startPayment() { // /* // * You need to pass the current activity to let Razorpay create CheckoutActivity // * */ // val activity: Activity = this // val co = Checkout() // // try { // val options = JSONObject() // options.put("name", "Razorpay Corp") // options.put("description", "Demoing Charges") // //You can omit the image option to fetch the image from the dashboard // options.put("image", "https://s3.amazonaws.com/rzp-mobile/images/rzp.jpg") // options.put("theme.color", "#3399cc"); // options.put("currency", "MYR"); //// options.put("order_id", "order_DBJOWzybf0sJbb"); // options.put("amount", "50000")//pass amount in currency subunits // //// val retryObj = JSONObject(); //// retryObj.put("enabled", true); //// retryObj.put("max_count", 4); //// options.put("retry", retryObj); // //// val prefill = JSONObject() //// prefill.put("email","[email protected]") //// prefill.put("contact","9876543210") // // val prefill = JSONObject() // prefill.put("email", "") // prefill.put("contact", "") // // options.put("prefill", prefill) // co.open(activity, options) // } catch (e: Exception) { // Toast.makeText(activity, "Error in payment: " + e.message, Toast.LENGTH_LONG).show() // e.printStackTrace() // } // } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/ProceedActivity.kt
3580963309
package com.example.mobileproject import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Log import android.view.WindowInsets import android.view.WindowManager import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.User import com.example.mobileproject.utils.Constants import com.google.firebase.auth.FirebaseAuth class nav : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nav) @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } val sharedPreferences = //get data from share preferences (everytime should call) like make connection to database getSharedPreferences( //below like table name Constants.MOBILEPROJECT_PREFERENCES, Context.MODE_PRIVATE ) val fullname = sharedPreferences.getString(Constants.LOGGED_IN_USERNAME,"")!! val email = sharedPreferences.getString(Constants.LOGGED_IN_EMAIL,"")!! val tv_name = findViewById<TextView>(R.id.tv_name) val tv_email = findViewById<TextView>(R.id.tv_email) tv_name.text = "$fullname" tv_email.text = "$email" val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@nav, MainActivity::class.java) //above code like send data startActivity(intent) } val btnHome: LinearLayout = findViewById(R.id.home) btnHome.setOnClickListener { val intent = Intent(this@nav, MainActivity::class.java) //above code like send data startActivity(intent) } val btnProfile: LinearLayout = findViewById(R.id.profile) btnProfile.setOnClickListener { FirestoreClass().getUserDetails(this@nav) } val btnCart: LinearLayout = findViewById(R.id.cart) btnCart.setOnClickListener { val intent = Intent(this@nav, CartActivity::class.java) //above code like send data startActivity(intent) } val btnHistory: LinearLayout = findViewById(R.id.history) btnHistory.setOnClickListener { val intent = Intent(this@nav, HistoryActivity::class.java) startActivity(intent) } val btnLogout: Button = findViewById(R.id.btn_logout) btnLogout.setOnClickListener { FirebaseAuth.getInstance().signOut() val intent = Intent(this@nav, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) finish() } } fun navToProfile(user : User){ Log.i("fullName:", user.fullName) Log.i("email:", user.email) val intent = Intent(this@nav, UserProfileActivity::class.java) intent.putExtra(Constants.EXTRA_USER_DETAILS, user) startActivity(intent) finish() } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/nav.kt
4139541435
package com.example.mobileproject import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart class DrinkActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drink) val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@DrinkActivity, nav::class.java) //above code like send data startActivity(intent) } val pasta: LinearLayout = findViewById(R.id.pasta) pasta.setOnClickListener { val intent = Intent(this@DrinkActivity, PastaActivity::class.java) //above code like send data startActivity(intent) } val bread: LinearLayout = findViewById(R.id.bread) bread.setOnClickListener { val intent = Intent(this@DrinkActivity, BreadActivity::class.java) //above code like send data startActivity(intent) } val drink: LinearLayout = findViewById(R.id.Drink) drink.setOnClickListener { val intent = Intent(this@DrinkActivity, DrinkActivity::class.java) //above code like send data startActivity(intent) } val special: LinearLayout = findViewById(R.id.special) special.setOnClickListener { val intent = Intent(this@DrinkActivity, SpecialActivity::class.java) //above code like send data startActivity(intent) } val drink1: Button = findViewById(R.id.drink1) drink1.setOnClickListener { val cart = Cart("Apple & Orange & Carrot Milk Shake", R.drawable.appleorangecarrot, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink2: Button = findViewById(R.id.drink2) drink2.setOnClickListener { val cart = Cart("Dragon Fruit & Banana Milk Shake", R.drawable.dragonfruitbanana, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink3: Button = findViewById(R.id.drink3) drink3.setOnClickListener { val cart = Cart("Kale & Kiwi Banana Milk Shake", R.drawable.kalekiwibanana, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink4: Button = findViewById(R.id.drink4) drink4.setOnClickListener { val cart = Cart("Pineapple & Coconut & Berry Milk Shake", R.drawable.pineapplecoconutberry, 15, 1) FirestoreClass().addItemToCart(this,cart) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/DrinkActivity.kt
3759108658
package com.example.mobileproject import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart import com.example.mobileproject.utils.Constants import com.google.firebase.Firebase import com.google.firebase.database.database class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sharedPreferences = //get data from share preferences (everytime should call) like make connection to database getSharedPreferences( //below like table name Constants.MOBILEPROJECT_PREFERENCES, Context.MODE_PRIVATE ) val username= sharedPreferences.getString(Constants.LOGGED_IN_USERNAME,"")!! val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@MainActivity, nav::class.java) //above code like send data startActivity(intent) } val pasta: LinearLayout = findViewById(R.id.pasta) pasta.setOnClickListener { val intent = Intent(this@MainActivity, PastaActivity::class.java) //above code like send data startActivity(intent) } val bread: LinearLayout = findViewById(R.id.bread) bread.setOnClickListener { val intent = Intent(this@MainActivity, BreadActivity::class.java) //above code like send data startActivity(intent) } val drink: LinearLayout = findViewById(R.id.Drink) drink.setOnClickListener { val intent = Intent(this@MainActivity, DrinkActivity::class.java) //above code like send data startActivity(intent) } val special: LinearLayout = findViewById(R.id.special) special.setOnClickListener { val intent = Intent(this@MainActivity, SpecialActivity::class.java) //above code like send data startActivity(intent) } val bread1:Button = findViewById(R.id.bread1) bread1.setOnClickListener { val cart = Cart("Scramble Egg Sandwich", R.drawable.scramble_egg_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread2:Button = findViewById(R.id.bread2) bread2.setOnClickListener { val cart = Cart("Floss Egg Sandwich", R.drawable.floss_egg_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread3:Button = findViewById(R.id.bread3) bread3.setOnClickListener { val cart = Cart("Crab Willow Sandwich", R.drawable.crab_willow_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread4:Button = findViewById(R.id.bread4) bread4.setOnClickListener { val cart = Cart("Cheese Floss Sandwich", R.drawable.cheese_floss_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink1: Button = findViewById(R.id.drink1) drink1.setOnClickListener { val cart = Cart("Apple & Orange & Carrot Milk Shake", R.drawable.appleorangecarrot, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink2: Button = findViewById(R.id.drink2) drink2.setOnClickListener { val cart = Cart("Dragon Fruit & Banana Milk Shake", R.drawable.dragonfruitbanana, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink3: Button = findViewById(R.id.drink3) drink3.setOnClickListener { val cart = Cart("Kale & Kiwi Banana Milk Shake", R.drawable.kalekiwibanana, 15, 1) FirestoreClass().addItemToCart(this,cart) } val drink4: Button = findViewById(R.id.drink4) drink4.setOnClickListener { val cart = Cart("Pineapple & Coconut & Berry Milk Shake", R.drawable.pineapplecoconutberry, 15, 1) FirestoreClass().addItemToCart(this,cart) } val pasta1: Button = findViewById(R.id.pasta1) pasta1.setOnClickListener { val cart = Cart("Carbonara", R.drawable.pasta1, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta2: Button = findViewById(R.id.pasta2) pasta2.setOnClickListener { val cart = Cart("Bolognese", R.drawable.pasta2, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta3: Button = findViewById(R.id.pasta3) pasta3.setOnClickListener { val cart = Cart("Black Pepper Pasta", R.drawable.pasta3, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta4: Button = findViewById(R.id.pasta4) pasta4.setOnClickListener { val cart = Cart("Curry Pasta", R.drawable.pasta4, 25, 1) FirestoreClass().addItemToCart(this,cart) } val special1: Button = findViewById(R.id.special1) special1.setOnClickListener { val cart = Cart("Avogado Hotdog Set", R.drawable.avogado_hotdog, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special2: Button = findViewById(R.id.special2) special2.setOnClickListener { val cart = Cart("Avogado Shrimp Set", R.drawable.avogado_shrimp_, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special3: Button = findViewById(R.id.special3) special3.setOnClickListener { val cart = Cart("Grill Salmon Set", R.drawable.grill_salmon_set, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special4: Button = findViewById(R.id.special4) special4.setOnClickListener { val cart = Cart("Potato Egg Set", R.drawable.potato_egg, 15, 1) FirestoreClass().addItemToCart(this,cart) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/MainActivity.kt
2678926715
package com.example.mobileproject import android.content.Intent import android.os.Build import android.os.Bundle import android.text.TextUtils import android.view.WindowInsets import android.view.WindowManager import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.User import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser //AppCompatActivity() is replaced by BaseActivity() //because it also inherit by AppCompatActivity() // and we need call baseActivity() //original : class RegisterActivity : AppCompatActivity() { class RegisterActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } // setupActionBar() val tv_signIn:TextView = findViewById<TextView>(R.id.tv_signIn) tv_signIn.setOnClickListener { val intent = Intent(this@RegisterActivity, LoginActivity::class.java) //above code like send data startActivity(intent) } val btnRegister: Button = findViewById(R.id.btn_register) btnRegister.setOnClickListener { registerUser() } } // if u want to create action bar // private fun setupActionBar(){ // val toolbar_register_activity:Toolbar = findViewById<Toolbar>(R.id.) // //toolbar_register_activity id of toolbar // setSupportActionBar(toolbar_register_activity) // val actionBar = supportActionBar // if(actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true) // actionBar.setHomeAsUpIndicator(R.drawable.baseline_arrow_back_ios_24) // } // toolbar_register_activity.setNavigationOnClickListener{ onBackPressed() } // // } private fun validateRegisterDetails(): Boolean{ val et_name:EditText = findViewById<EditText>(R.id.et_name) val et_email:EditText = findViewById<EditText>(R.id.et_email) val et_password:EditText = findViewById<EditText>(R.id.et_password) return when{ TextUtils.isEmpty(et_name.text.toString().trim {it <= ' '}) || et_name.length() <= 3 ->{ showErrorSnackBar("Please enter your full name",true) false } TextUtils.isEmpty(et_email.text.toString().trim {it <= ' '}) || !isValidEmail(et_email.text.toString().trim())->{ showErrorSnackBar("Please enter valid email",true) false } TextUtils.isEmpty(et_password.text.toString().trim {it <= ' '})->{ showErrorSnackBar("Please enter your password",true) false } // !checkBox.isChecked ...... // et_password.text.toString().trim{ it <= ' '} != et_confirm_password.text.toString().trim{ it <= ' '} -> { // showErrorSnackBar("password is not same as confirm password",true) // false // } else -> { // showErrorSnackBar("Thank fot registering",false) true } } } private fun isValidEmail(email: String): Boolean { val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" return email.matches(emailPattern.toRegex()) } private fun registerUser(){ val et_name:EditText = findViewById<EditText>(R.id.et_name) val et_email:EditText = findViewById<EditText>(R.id.et_email) val et_password:EditText = findViewById<EditText>(R.id.et_password) if(validateRegisterDetails()){ showProgressDialog() val email: String = et_email.text.toString().trim{it <= ' '} val password: String = et_password.text.toString().trim{it <= ' '} //this is create of the account of firebase FirebaseAuth.getInstance().createUserWithEmailAndPassword(email,password) .addOnCompleteListener( OnCompleteListener <AuthResult>{task -> // if the register is successfully done if (task.isSuccessful){ //firebase registered user val firebaseUser: FirebaseUser = task.result!!.user!! //make User class assign in user val user = User( firebaseUser.uid, et_name.text.toString().trim{it <= ' '}, et_email.text.toString().trim{it <= ' '} ) //store data FirestoreClass().registerUser(this@RegisterActivity,user) // showErrorSnackBar( // "You are registered successfully. Your user id is ${firebaseUser.uid}", // false // ) //make sign out and close the register page // FirebaseAuth.getInstance().signOut() // finish() }else{ showErrorSnackBar(task.exception!!.message.toString(),true) hideProgressDialog() } } ) } } fun userRegistrationSuccess(){ hideProgressDialog() Toast.makeText( this@RegisterActivity, "You are registered successfully", Toast.LENGTH_SHORT).show() val intent = Intent(this@RegisterActivity, LoginActivity::class.java) //above code like send data startActivity(intent) } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/RegisterActivity.kt
3874202055
package com.example.mobileproject.firestore import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.util.Log import android.widget.Toast import com.example.mobileproject.LoginActivity import com.example.mobileproject.RegisterActivity import com.example.mobileproject.UserProfileActivity import com.example.mobileproject.models.Cart import com.example.mobileproject.models.Order import com.example.mobileproject.models.User import com.example.mobileproject.nav import com.example.mobileproject.utils.Constants import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.database import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.SetOptions class FirestoreClass { //important private val mFireStore = FirebaseFirestore.getInstance() // fun addCart(activity: Activity, cart:Cart) { // // Get reference to the user's cart collection // mFireStore.collection(Constants.CARTS) // .document(getCurrentUserID()) // .set(cart, SetOptions.merge()) // .addOnSuccessListener { // Toast.makeText( // activity, // "Cart added successfully", // Toast.LENGTH_SHORT // ).show() // } // .addOnFailureListener { e -> // Log.e( // activity.javaClass.simpleName, // "Error while adding the cart.", // e // ) // } // } fun registerUser(activity: RegisterActivity , userInfo: User){ mFireStore.collection(Constants.USERS) // mFireStore.collection("users") // set like primary key in id .document(userInfo.id) //merge data by user class data .set(userInfo, SetOptions.merge()) .addOnSuccessListener { activity.userRegistrationSuccess() } .addOnFailureListener {e -> activity.hideProgressDialog() Log.e( activity.javaClass.simpleName, "error while registering the user", e ) } } fun getCurrentUserID(): String { //An instance of currentUser using FirebaseAuth val currentUser = FirebaseAuth.getInstance().currentUser var currentUserID = "" if (currentUser != null){ currentUserID = currentUser.uid } return currentUserID } fun getUserDetails(activity: Activity) { //pass the collection data from which we want data. mFireStore.collection(Constants.USERS) .document(getCurrentUserID()) .get() .addOnSuccessListener { document -> Log.i(activity.javaClass.simpleName, document.toString()) //Here we received the document snapshot which is converted into object val user = document.toObject(User::class.java)!! //store the small data to share preferences like (session storage) val sharedPreferences = //get data from share preferences (everytime should call) like make connection to database activity.getSharedPreferences( //below like table name Constants.MOBILEPROJECT_PREFERENCES, Context.MODE_PRIVATE ) val editor: SharedPreferences.Editor = sharedPreferences.edit() editor.putString( //below like variable name //key: LOGGED_IN_USERNAME //value : Constants.LOGGED_IN_USERNAME, "${user.fullName}" ) editor.putString( //below like variable name //key: LOGGED_IN_USERNAME //value : Constants.LOGGED_IN_EMAIL, "${user.email}" ) //after edit(above code) must apply editor.apply() when (activity) { is LoginActivity -> { activity.userLoggedInSuccess(user) } is nav -> { activity.navToProfile(user) } } } // .addOnFailureListener {e -> // // } } fun updateUserProfileData(activity: Activity, userHashMap: HashMap<String,Any>){ mFireStore.collection(Constants.USERS) .document(getCurrentUserID()) .update(userHashMap) .addOnSuccessListener { when (activity){ is UserProfileActivity ->{ activity.userProfileUpdateSuccess() } } } .addOnFailureListener { e-> when (activity){ is UserProfileActivity ->{ activity.hideProgressDialog() } } Log.e( activity.javaClass.simpleName, "Error while updating the user details.", e ) } } fun addItemToCart(activity: Activity,cart:Cart){ val userId = FirebaseAuth.getInstance().currentUser?.uid?:"" val database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference val cartReference = database.child("user").child(userId).child("cart") cartReference.push().setValue(cart).addOnSuccessListener { Toast.makeText(activity,"Item added into Cart Successfully",Toast.LENGTH_SHORT).show() }.addOnFailureListener { Toast.makeText(activity,"Item Not added",Toast.LENGTH_SHORT).show() } } fun addItemToOrder(activity: Activity,order: Order){ val userId = FirebaseAuth.getInstance().currentUser?.uid?:"" val database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference val cartReference = database.child("user").child(userId).child("Order") cartReference.push().setValue(order).addOnSuccessListener { Toast.makeText(activity,"Order Successfully",Toast.LENGTH_SHORT).show() }.addOnFailureListener { Toast.makeText(activity,"Order Failed",Toast.LENGTH_SHORT).show() } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/firestore/FirestoreClass.kt
1296451885
package com.example.mobileproject import android.content.Intent import android.os.Build import android.os.Bundle import android.view.WindowInsets import android.view.WindowManager import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class ForgotPasswordActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_forgot_password) @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@ForgotPasswordActivity, LoginActivity::class.java) //above code like send data startActivity(intent) } val btnSubmit: Button= findViewById(R.id.btn_submit) btnSubmit.setOnClickListener { val email:String = findViewById<EditText>(R.id.et_email).text.toString().trim() if (email.isEmpty()||!isValidEmail(email)){ showErrorSnackBar("Please enter valid email",true) }else{ showProgressDialog() FirebaseAuth.getInstance().sendPasswordResetEmail(email) .addOnCompleteListener{task -> hideProgressDialog() if(task.isSuccessful){ Toast.makeText( this@ForgotPasswordActivity, "Email sent successfully to reset your password!", Toast.LENGTH_LONG).show() finish() }else{ showErrorSnackBar(task.exception!!.message.toString(),true) } } } } } private fun isValidEmail(email: String): Boolean { val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" return email.matches(emailPattern.toRegex()) } // if u want to create action bar // private fun setupActionBar() { // val toolbar_forgot_passowrd_activity: Toolbar = findViewById<Toolbar>(R.id.toolbar) // //toolbar_register_activity id of toolbar // setSupportActionBar(toolbar_forgot_passowrd_activity) // val actionBar = supportActionBar // if (actionBar != null) { // actionBar.setDisplayHomeAsUpEnabled(true) // actionBar.setHomeAsUpIndicator(R.drawable.baseline_arrow_back_ios_24) // } // toolbar_forgot_passowrd_activity.setNavigationOnClickListener { // val intent = Intent(this@ForgotPasswordActivity, LoginActivity::class.java) // //above code like send data // startActivity(intent) // } // } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/ForgotPasswordActivity.kt
244052634
package com.example.mobileproject import adapter.CartAdapter import adapter.ProductAdapter import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ImageButton import android.widget.TextView import android.widget.Toast import androidx.core.content.ContentProviderCompat.requireContext import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart import com.example.mobileproject.models.User import com.example.mobileproject.utils.Constants import com.google.android.gms.common.util.CollectionUtils import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.google.firebase.database.database class CartActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth private var database =Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference private lateinit var Item: MutableList<String> private lateinit var Price: MutableList<Int> private lateinit var Image: MutableList<Int> private lateinit var Quantities: MutableList<Int> private lateinit var cartAdapter: CartAdapter private lateinit var userId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_cart) // val item = listOf("Burger", "sandwich", "momo", "item") // val price = listOf(10, 20, 30, 40) // val image = listOf( // R.drawable.appleorangecarrot, // R.drawable.avogado_hotdog, // R.drawable.crab_willow_sandwich, // R.drawable.cheese_floss_sandwich // ) auth = FirebaseAuth.getInstance() reteriveCartItems() // val adapter = CartAdapter(ArrayList(item),ArrayList(price),ArrayList(image),ArrayList(image)) // val recyclerView = findViewById<RecyclerView>(R.id.CartRecyclerView) // // recyclerView.layoutManager = LinearLayoutManager(this) // recyclerView.adapter = adapter val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@CartActivity, nav::class.java) //above code like send data startActivity(intent) } val btn: TextView = findViewById(R.id.btn) btn.setOnClickListener { // val intent = Intent(this@CartActivity, nav::class.java) // //above code like send data // FirestoreClass().getUserDetails(this@CartActivity) // startActivity(intent) getOrderItemsDetail() } } private fun getOrderItemsDetail(){ userId = auth.currentUser?.uid?:"" var orderIdReference = database.child("user").child(userId).child("cart") var orderItem :MutableList<String> = mutableListOf() var orderPrice :MutableList<Int> = mutableListOf() var orderImage :MutableList<Int> = mutableListOf() var orderQuantities :MutableList<Int> = cartAdapter.getUpdatedItemsQuantities() orderIdReference.addListenerForSingleValueEvent(object: ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { for (orderSnapshot in snapshot.children){ //get cart object from the child node val order = orderSnapshot.getValue(Cart::class.java) order?.let { it.cartImage?.let { orderImage.add(it) } it.cartName?.let { orderItem.add(it) } it.cartPrice?.let { orderPrice.add(it) } it.cartQuantity?.let { orderQuantities.add(it) } } } val intent = Intent(this@CartActivity,ProceedActivity::class.java) intent.putExtra("orderName",orderItem as ArrayList<String>) intent.putExtra("orderImage",orderImage as ArrayList<Int>) intent.putExtra("orderPrice",orderPrice as ArrayList<Int>) intent.putExtra("orderQuantities",orderQuantities as ArrayList<Int>) startActivity(intent) } override fun onCancelled(error: DatabaseError) { Toast.makeText(this@CartActivity, "Order making Fail. Please try again", Toast.LENGTH_SHORT).show() } }) } private fun reteriveCartItems(){ userId = auth.currentUser?.uid?:"" val cartReference= database.child("user").child(userId).child("cart") Image = mutableListOf() Item = mutableListOf() Price = mutableListOf() Quantities = mutableListOf() cartReference.addListenerForSingleValueEvent(object :ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { for (cartSnapshot in snapshot.children){ //get cart object from the child node val cartItems = cartSnapshot.getValue(Cart::class.java) cartItems?.let { it.cartImage?.let { Image.add(it) } it.cartName?.let { Item.add(it) } it.cartPrice?.let { Price.add(it) } it.cartQuantity?.let { Quantities.add(it) } } } setAdapter() } private fun setAdapter(){ cartAdapter = CartAdapter(Item,Price,Image,Quantities) val recyclerView = findViewById<RecyclerView>(R.id.CartRecyclerView) recyclerView.layoutManager = LinearLayoutManager(this@CartActivity) recyclerView.adapter = cartAdapter } override fun onCancelled(error: DatabaseError) { Log.e("Firebase", "Error fetching data: ${error.message}") Toast.makeText(this@CartActivity, "Error fetching data: ${error.message}", Toast.LENGTH_SHORT).show() } }) } // fun navToProceed(user : User){ // Log.i("fullName:", user.fullName) // Log.i("email:", user.email) // // val intent = Intent(this, UserProfileActivity::class.java) // intent.putExtra(Constants.EXTRA_USER_DETAILS, user) // startActivity(intent) // // finish() // } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/CartActivity.kt
2343784338
package com.example.mobileproject import android.app.Dialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.google.android.material.snackbar.Snackbar //open is added due to need to call open class BaseActivity : AppCompatActivity() { // // above original code example:create on ... is deleted because it is inherit private lateinit var mProgressDialog :Dialog fun showErrorSnackBar(message: String, errorMessage: Boolean) { val snackBar = Snackbar.make(findViewById(android.R.id.content),message,Snackbar.LENGTH_LONG) val snackBarView = snackBar.view if(errorMessage){ snackBarView.setBackgroundColor( ContextCompat.getColor( this@BaseActivity, R.color.colorSnackBarError ) ) }else{ snackBarView.setBackgroundColor( ContextCompat.getColor( this@BaseActivity, R.color.colorSnackBarSuccess ) ) } snackBar.show() } fun showProgressDialog(){ mProgressDialog = Dialog(this) mProgressDialog.setContentView(R.layout.dialog_progress) mProgressDialog.setCancelable(false) mProgressDialog.setCanceledOnTouchOutside(false) mProgressDialog.show() } fun hideProgressDialog(){ mProgressDialog.dismiss() } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/BaseActivity.kt
340920633
package com.example.mobileproject import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart class BreadActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bread) val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@BreadActivity, nav::class.java) //above code like send data startActivity(intent) } val pasta: LinearLayout = findViewById(R.id.pasta) pasta.setOnClickListener { val intent = Intent(this@BreadActivity, PastaActivity::class.java) //above code like send data startActivity(intent) } val bread: LinearLayout = findViewById(R.id.bread) bread.setOnClickListener { val intent = Intent(this@BreadActivity, BreadActivity::class.java) //above code like send data startActivity(intent) } val drink: LinearLayout = findViewById(R.id.Drink) drink.setOnClickListener { val intent = Intent(this@BreadActivity, DrinkActivity::class.java) //above code like send data startActivity(intent) } val special: LinearLayout = findViewById(R.id.special) special.setOnClickListener { val intent = Intent(this@BreadActivity, SpecialActivity::class.java) //above code like send data startActivity(intent) } val bread1:Button = findViewById(R.id.bread1) bread1.setOnClickListener { val cart = Cart("Scramble Egg Sandwich", R.drawable.scramble_egg_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread2:Button = findViewById(R.id.bread2) bread2.setOnClickListener { val cart = Cart("Floss Egg Sandwich", R.drawable.floss_egg_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread3:Button = findViewById(R.id.bread3) bread3.setOnClickListener { val cart = Cart("Crab Willow Sandwich", R.drawable.crab_willow_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } val bread4:Button = findViewById(R.id.bread4) bread4.setOnClickListener { val cart = Cart("Cheese Floss Sandwich", R.drawable.cheese_floss_sandwich, 15, 1) FirestoreClass().addItemToCart(this,cart) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/BreadActivity.kt
2977841561
package com.example.mobileproject.utils object Constants { const val USERS: String = "users" const val CARTS: String = "carts" const val MOBILEPROJECT_PREFERENCES :String = "MobileProjectPrefs" const val LOGGED_IN_USERNAME: String = "logged_in_username" const val LOGGED_IN_EMAIL: String = "logged_in_email" const val EXTRA_USER_DETAILS: String = "extra_user_details" // like a boolean the permission code if get the storage permission it will be two const val READ_STORAGE_PERMISSION_CODE = 2 }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/utils/Constants.kt
3845375389
package com.example.mobileproject.models data class Cart ( val cartName: String ?= null, val cartImage:Int ?= null, val cartPrice: Int ?= null, var cartQuantity: Int ?= null, )
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/models/Cart.kt
3029948435
package com.example.mobileproject.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize class User ( val id: String = "", val fullName: String = "", val email: String = "", val mobile: Long = 0, val gender: String = "", val address1: String = "", val address2: String = "", val address3: String = "", val profileCompleted: Int=0 ): Parcelable
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/models/User.kt
1006933041
package com.example.mobileproject.models data class Order ( val orderSummary: String ?= null, val total:Int ?= null, )
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/models/Order.kt
2587949206
package com.example.mobileproject import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart class PastaActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_pasta) val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@PastaActivity, nav::class.java) //above code like send data startActivity(intent) } val pasta: LinearLayout = findViewById(R.id.pasta) pasta.setOnClickListener { val intent = Intent(this@PastaActivity, PastaActivity::class.java) //above code like send data startActivity(intent) } val bread: LinearLayout = findViewById(R.id.bread) bread.setOnClickListener { val intent = Intent(this@PastaActivity, BreadActivity::class.java) //above code like send data startActivity(intent) } val drink: LinearLayout = findViewById(R.id.Drink) drink.setOnClickListener { val intent = Intent(this@PastaActivity, DrinkActivity::class.java) //above code like send data startActivity(intent) } val special: LinearLayout = findViewById(R.id.special) special.setOnClickListener { val intent = Intent(this@PastaActivity, SpecialActivity::class.java) //above code like send data startActivity(intent) } val pasta1: Button = findViewById(R.id.pasta1) pasta1.setOnClickListener { val cart = Cart("Carbonara", R.drawable.pasta1, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta2: Button = findViewById(R.id.pasta2) pasta2.setOnClickListener { val cart = Cart("Bolognese", R.drawable.pasta2, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta3: Button = findViewById(R.id.pasta3) pasta3.setOnClickListener { val cart = Cart("Black Pepper Pasta", R.drawable.pasta3, 25, 1) FirestoreClass().addItemToCart(this,cart) } val pasta4: Button = findViewById(R.id.pasta4) pasta4.setOnClickListener { val cart = Cart("Curry Pasta", R.drawable.pasta4, 25, 1) FirestoreClass().addItemToCart(this,cart) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/PastaActivity.kt
2144471458
package com.example.mobileproject import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Cart class SpecialActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_special) val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@SpecialActivity, nav::class.java) //above code like send data startActivity(intent) } val pasta: LinearLayout = findViewById(R.id.pasta) pasta.setOnClickListener { val intent = Intent(this@SpecialActivity, PastaActivity::class.java) //above code like send data startActivity(intent) } val bread: LinearLayout = findViewById(R.id.bread) bread.setOnClickListener { val intent = Intent(this@SpecialActivity, BreadActivity::class.java) //above code like send data startActivity(intent) } val drink: LinearLayout = findViewById(R.id.Drink) drink.setOnClickListener { val intent = Intent(this@SpecialActivity, DrinkActivity::class.java) //above code like send data startActivity(intent) } val special: LinearLayout = findViewById(R.id.special) special.setOnClickListener { val intent = Intent(this@SpecialActivity, SpecialActivity::class.java) //above code like send data startActivity(intent) } val special1: Button = findViewById(R.id.special1) special1.setOnClickListener { val cart = Cart("Avogado Hotdog Set", R.drawable.avogado_hotdog, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special2: Button = findViewById(R.id.special2) special2.setOnClickListener { val cart = Cart("Avogado Shrimp Set", R.drawable.avogado_shrimp_, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special3: Button = findViewById(R.id.special3) special3.setOnClickListener { val cart = Cart("Grill Salmon Set", R.drawable.grill_salmon_set, 15, 1) FirestoreClass().addItemToCart(this,cart) } val special4: Button = findViewById(R.id.special4) special4.setOnClickListener { val cart = Cart("Potato Egg Set", R.drawable.potato_egg, 15, 1) FirestoreClass().addItemToCart(this,cart) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/SpecialActivity.kt
954962516
package com.example.mobileproject import android.app.Activity import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.Order import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.database import com.razorpay.Checkout import com.razorpay.ExternalWalletListener import com.razorpay.PaymentData import com.razorpay.PaymentResultWithDataListener import org.json.JSONObject class PaymentActivity: AppCompatActivity(), PaymentResultWithDataListener, ExternalWalletListener, DialogInterface.OnClickListener { private var database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference private lateinit var auth: FirebaseAuth val TAG:String = PaymentActivity::class.toString() private lateinit var alertDialogBuilder: AlertDialog.Builder override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) /* * To ensure faster loading of the Checkout form, * call this method as early as possible in your checkout flow * */ Checkout.preload(applicationContext) alertDialogBuilder = AlertDialog.Builder(this@PaymentActivity) alertDialogBuilder.setTitle("Payment Result") alertDialogBuilder.setCancelable(true) alertDialogBuilder.setPositiveButton("Ok",this) val button: Button = findViewById(R.id.btn_pay) button.setOnClickListener { startPayment() } val summary = intent.getStringExtra("summary") val total = intent.getStringExtra("total") val textTotal: TextView = findViewById(R.id.total) textTotal.setText("MYR "+total) val textsummary: TextView = findViewById(R.id.summary) textsummary.setText(summary) } private fun startPayment() { /* * You need to pass current activity in order to let Razorpay create CheckoutActivity * */ val summary = intent.getStringExtra("summary") val total = intent.getStringExtra("total") val activity: Activity = this val co = Checkout() co.setKeyID("rzp_test_swnNqUFW65XpiM") // val etApiKey = findViewById<EditText>(R.id.et_api_key) // val etCustomOptions = findViewById<EditText>(R.id.et_custom_options) // if (!TextUtils.isEmpty(etApiKey.text.toString())){ // co.setKeyID(etApiKey.text.toString()) // } // if (!TextUtils.isEmpty(etCustomOptions.text.toString())){ // options = JSONObject(etCustomOptions.text.toString()) // }else{ // options.put("name",summary) // options.put("description","Demoing Charges") //You can omit the image option to fetch the image from dashboard // options.put("image","https://s3.amazonaws.com/rzp-mobile/images/rzp.png") // options.put("currency","MYR") // options.put("amount",total) // options.put("send_sms_hash",true); // } try { var options = JSONObject() options.put("name", summary) options.put("description", "Demoing Charges") options.put("currency", "MYR") options.put("amount", total+"00") val prefill = JSONObject() prefill.put("email", "") prefill.put("contact", "") options.put("prefill", prefill) co.open(activity,options) }catch (e: Exception){ Toast.makeText(activity,"Error in payment: "+ e.message,Toast.LENGTH_LONG).show() e.printStackTrace() } } override fun onPaymentSuccess(p0: String?, p1: PaymentData?) { try{ alertDialogBuilder.setMessage("Payment Successful : Payment ID: $p0\nPayment Data: ${p1?.data}") alertDialogBuilder.show() val summary = intent.getStringExtra("summary") val total = intent.getStringExtra("total")?.toInt() val order = Order(summary,total) FirestoreClass().addItemToOrder(this@PaymentActivity, order) val intent = Intent(this@PaymentActivity,nav::class.java) startActivity(intent) removeItemFromCart() }catch (e: Exception){ e.printStackTrace() } } override fun onPaymentError(p0: Int, p1: String?, p2: PaymentData?) { try { alertDialogBuilder.setMessage("Payment Failed : Payment Data: ${p2?.data}") alertDialogBuilder.show() val intent = Intent(this@PaymentActivity, CartActivity::class.java) startActivity(intent) }catch (e: Exception){ e.printStackTrace() } } override fun onExternalWalletSelected(p0: String?, p1: PaymentData?) { try{ alertDialogBuilder.setMessage("External wallet was selected : Payment Data: ${p1?.data}") alertDialogBuilder.show() }catch (e: Exception){ e.printStackTrace() } } override fun onClick(dialog: DialogInterface?, which: Int) { } private fun removeItemFromCart() { auth = FirebaseAuth.getInstance() val userId = auth.currentUser?.uid?:"" var cartReference = database.child("user").child(userId).child("cart") cartReference.removeValue() } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/PaymentActivity.kt
209749909
package com.example.mobileproject import adapter.OrderAdapter import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobileproject.models.Order import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ValueEventListener import com.google.firebase.database.database class HistoryActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth private var database = Firebase.database("https://mobileproject-724df-default-rtdb.asia-southeast1.firebasedatabase.app/").reference private lateinit var orderSummary: MutableList<String> private lateinit var total: MutableList<Int> private lateinit var orderAdapter: OrderAdapter private lateinit var userId: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_history) auth = FirebaseAuth.getInstance() reteriveCartItems() val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@HistoryActivity, nav::class.java) //above code like send data startActivity(intent) } } private fun reteriveCartItems(){ userId = auth.currentUser?.uid?:"" val OrderReference= database.child("user").child(userId).child("Order") orderSummary = mutableListOf() total = mutableListOf() OrderReference.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { for (orderSnapshot in snapshot.children){ //get cart object from the child node val orderItems = orderSnapshot.getValue(Order::class.java) orderItems?.let { it.orderSummary?.let { orderSummary.add(it) } it.total?.let { total.add(it) } } } setAdapter() } private fun setAdapter(){ orderAdapter = OrderAdapter(orderSummary,total) val recyclerView = findViewById<RecyclerView>(R.id.CartRecyclerView) recyclerView.layoutManager = LinearLayoutManager(this@HistoryActivity) recyclerView.adapter = orderAdapter } override fun onCancelled(error: DatabaseError) { Log.e("Firebase", "Error fetching data: ${error.message}") Toast.makeText(this@HistoryActivity, "Error fetching data: ${error.message}", Toast.LENGTH_SHORT).show() } }) } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/HistoryActivity.kt
1624338072
package com.example.mobileproject import android.content.Intent import android.os.Build import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.WindowInsets import android.view.WindowManager import android.widget.Button import android.widget.EditText import android.widget.TextView import com.example.mobileproject.firestore.FirestoreClass import com.example.mobileproject.models.User import com.example.mobileproject.utils.Constants import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth class LoginActivity : BaseActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) //code to show full screen @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } // Accessing Views val etEmail = findViewById<EditText>(R.id.et_email) val etPassword = findViewById<EditText>(R.id.et_password) val btnLogin = findViewById<Button>(R.id.btn_login) val tvForgetPassword = findViewById<TextView>(R.id.tv_forgetPassword) val tvRegister = findViewById<TextView>(R.id.tv_register) // Set onClickListener for your views or perform any other logic here // Example: Set an onClickListener for the login button btnLogin.setOnClickListener { LogInRegisteredUser() } // Example: Set an onClickListener for the "Forget Password?" TextView tvForgetPassword.setOnClickListener { val intent = Intent(this@LoginActivity, ForgotPasswordActivity::class.java) //above code like send data startActivity(intent) } // Example: Set an onClickListener for the "Click Here" TextView tvRegister.setOnClickListener { val intent = Intent(this@LoginActivity, RegisterActivity::class.java) //above code like send data startActivity(intent) } } private fun isValidEmail(email: String): Boolean { val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" return email.matches(emailPattern.toRegex()) } private fun validateLoginDetails(): Boolean{ val et_email:EditText = findViewById<EditText>(R.id.et_email) val et_password:EditText = findViewById<EditText>(R.id.et_password) return when{ TextUtils.isEmpty(et_email.text.toString().trim {it <= ' '}) || !isValidEmail(et_email.text.toString().trim())->{ showErrorSnackBar("Please enter valid email",true) false } TextUtils.isEmpty(et_password.text.toString().trim {it <= ' '}) || et_email.length() <= 3 ->{ showErrorSnackBar("Please enter your password",true) false }else -> { true } } } private fun LogInRegisteredUser(){ val et_email:EditText = findViewById<EditText>(R.id.et_email) val et_password:EditText = findViewById<EditText>(R.id.et_password) if(validateLoginDetails()){ showProgressDialog() val email: String = et_email.text.toString().trim{it <= ' '} val password: String = et_password.text.toString().trim{it <= ' '} //this is check sign in of firebase FirebaseAuth.getInstance().signInWithEmailAndPassword(email,password) .addOnCompleteListener( OnCompleteListener <AuthResult>{ task -> // hideProgressDialog() // if the register is successfully done if (task.isSuccessful){ //firebase registered user // val firebaseUser: FirebaseUser = task.result!!.user!! FirestoreClass().getUserDetails(this@LoginActivity) // showErrorSnackBar("You are login successfully.", false) }else{ hideProgressDialog() showErrorSnackBar(task.exception!!.message.toString(),true) } } ) } } fun userLoggedInSuccess(user : User){ hideProgressDialog() Log.i("fullName:", user.fullName) Log.i("email:", user.email) if( user.profileCompleted == 0){ val intent = Intent(this@LoginActivity, UserProfileActivity::class.java) intent.putExtra(Constants.EXTRA_USER_DETAILS, user) startActivity(intent) } else{ startActivity(Intent(this@LoginActivity, MainActivity::class.java)) } finish() } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/LoginActivity.kt
1778185554
package com.example.mobileproject import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Handler import android.view.WindowInsets import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) //code to show full screen @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } //call a function after delay @Suppress("DEPRECATION") Handler().postDelayed({ //navigation val intent = Intent(this@SplashActivity, LoginActivity::class.java) //intent.putExtra("bmi", calculateBMI(weight,height)) //above code like send data startActivity(intent) finish() }, 2500) //create a font with customise font family 52.24 (end) } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/SplashActivity.kt
1221994037
package com.example.mobileproject import android.content.Intent import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class testActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test) // val item = listOf("Burger", "sandwich","momo","item") // val price = listOf(10,20,30,40) // val image = listOf(R.drawable.appleorangecarrot,R.drawable.avogado_hotdog,R.drawable.crab_willow_sandwich,R.drawable.cheese_floss_sandwich) // // val adapter = ProductAdapter(item,price,image) // val recyclerView = findViewById<RecyclerView>(R.id.ProductRecyclerView) // // recyclerView.layoutManager = LinearLayoutManager(this) // recyclerView.adapter = adapter val btnBack: TextView = findViewById(R.id.back) btnBack.setOnClickListener { val intent = Intent(this@testActivity, nav::class.java) //above code like send data startActivity(intent) } } }
-Healthy-Food-E-Commerce-Application/mobileproject/app/src/main/java/com/example/mobileproject/testActivity.kt
3325240797
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication import android.icu.text.CaseMap.Title import android.view.LayoutInflater import android.view.ViewGroup import android.widget.AdapterView.OnItemClickListener import androidx.recyclerview.widget.RecyclerView import com.example.myapplication.databinding.NotesitemBinding class notesadapter(private val notes: List<notes>,private val itemClickListener:OnItemClickListener): RecyclerView.Adapter<notesadapter.NoteViewHolder>() { interface OnItemClickListener{ fun onDeleteClick(nodeid:String) fun onUpdateClick(nodeid:String,title: String, description:String) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder { val binding=NotesitemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return NoteViewHolder(binding) } override fun onBindViewHolder(holder: NoteViewHolder, position: Int) { val note=notes[position] holder.bind(note) holder.binding.update.setOnClickListener(){ itemClickListener.onUpdateClick(note.noteId,note.title,note.description) } holder.binding.delete.setOnClickListener(){ itemClickListener.onDeleteClick(note.noteId) } } override fun getItemCount(): Int { return notes.size } class NoteViewHolder(val binding:NotesitemBinding):RecyclerView.ViewHolder (binding.root){ fun bind(note: notes) { binding.itemTitle.text=note.title binding.itemDescription.text=note.description } } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/notesadapter.kt
2284224978
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.os.Looper class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Handler(Looper.getMainLooper()).postDelayed({ startActivity(Intent(this,login::class.java)) finish() },3000) } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/MainActivity.kt
1541541919
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.myapplication.databinding.ActivityCreatenotesBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase class createnotes : AppCompatActivity() { private lateinit var databasereference:DatabaseReference private lateinit var auth:FirebaseAuth private val binding:ActivityCreatenotesBinding by lazy{ ActivityCreatenotesBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) databasereference=FirebaseDatabase.getInstance().reference auth=FirebaseAuth.getInstance() binding.addnotes.setOnClickListener(){ val notes_title=binding.noteTitle.text.toString() val notes_description=binding.noteDescription.text.toString() if(notes_title.isEmpty()||notes_description.isEmpty()){ Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show() } else{ var currentUser=auth.currentUser currentUser?.let { user-> val notekey=databasereference.child("Users").child(user.uid).child("notes").push().key val noteitem=notes(notes_title,notes_description,notekey?:"") if(notekey!=null){ databasereference.child("Users").child(user.uid).child("notes").child(notekey).setValue(noteitem) .addOnCompleteListener{task-> if(task.isSuccessful){ Toast.makeText(this, "Note saved successfully", Toast.LENGTH_SHORT).show() finish() } else{ Toast.makeText(this, "Failed to save", Toast.LENGTH_SHORT).show() } } } } } } } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/createnotes.kt
3065725534
package com.example.myapplication import android.app.Activity import android.app.Instrumentation.ActivityResult import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts import com.example.myapplication.databinding.ActivityLoginBinding import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.GoogleAuthProvider class login : AppCompatActivity() { private val binding:ActivityLoginBinding by lazy{ ActivityLoginBinding.inflate(layoutInflater) } private lateinit var auth:FirebaseAuth // private lateinit var googleSignInClient:GoogleSignInClient override fun onStart() { super.onStart() val user:FirebaseUser?=auth.currentUser if(user!=null){ startActivity(Intent(this,home::class.java)) finish() Toast.makeText(this, "Goodie", Toast.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) auth=FirebaseAuth.getInstance() // val gso=GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build() // googleSignInClient= GoogleSignIn.getClient(this,gso) // binding.google.setOnClickListener(){ // Toast.makeText(this, "lesse", Toast.LENGTH_SHORT).show() // val signinclient=googleSignInClient.signInIntent // Toast.makeText(this, "Ajeeb", Toast.LENGTH_SHORT).show() // launcher.launch(signinclient) // } binding.signup.setOnClickListener(){ startActivity(Intent(this,signup::class.java)) finish() } binding.signin.setOnClickListener(){ val username=binding.username.text.toString() val password=binding.password.text.toString() if(username.isEmpty()||password.isEmpty()){ Toast.makeText(this, "Fill all fields", Toast.LENGTH_SHORT).show() } else{ auth.signInWithEmailAndPassword(username,password) .addOnCompleteListener(this){task-> if(task.isSuccessful){ Toast.makeText(this, "Login completed", Toast.LENGTH_SHORT).show() startActivity(Intent(this,home::class.java)) finish() } else{ Toast.makeText(this, "Sign-in Failed", Toast.LENGTH_SHORT).show() } } } } } // private val launcher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()) // { // result-> // if(result.resultCode== Activity.RESULT_OK) // { // val task=GoogleSignIn.getSignedInAccountFromIntent(result.data) // if(task.isSuccessful){ // val account:GoogleSignInAccount?=task.result // val credential=GoogleAuthProvider.getCredential(account?.idToken,null) // auth.signInWithCredential(credential).addOnCompleteListener{ // if(it.isSuccessful){ // startActivity(Intent(this,home::class.java)) // }else{ // Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show() // // } // } // } // else{ // Toast.makeText(this, "ajeeb", Toast.LENGTH_SHORT).show() // } // } // else{ // Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show() // } // } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/login.kt
3280706354
package com.example.myapplication import android.app.Activity import android.app.Instrumentation.ActivityResult import android.content.ContentResolver import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.webkit.MimeTypeMap import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import com.example.myapplication.databinding.ActivityImageuploaderBinding import com.google.firebase.Firebase import com.google.firebase.database.database import com.google.firebase.storage.storage import com.squareup.picasso.Picasso class imageuploader : AppCompatActivity() { private lateinit var binding:ActivityImageuploaderBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityImageuploaderBinding.inflate(layoutInflater) setContentView(binding.root) binding.uploadbutton.setOnClickListener{ Toast.makeText(this@imageuploader, "let's Go", Toast.LENGTH_SHORT).show() val intent= Intent() intent.action=Intent.ACTION_PICK intent.type="image/*" imagelauncher.launch(intent)} } val imagelauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()){it-> Toast.makeText(this, "1", Toast.LENGTH_SHORT).show() if(it.resultCode== Activity.RESULT_OK){ Toast.makeText(this, "2", Toast.LENGTH_SHORT).show() if(it.data!=null){ Toast.makeText(this, "3", Toast.LENGTH_SHORT).show() val ref=Firebase.storage.reference.child("Photo/"+System.currentTimeMillis()+"."+getFileType(it.data!!.data!!)) ref.putFile(it.data!!.data!!).addOnSuccessListener{ ref.downloadUrl.addOnSuccessListener{ Firebase.database.reference.child("Photo").push().setValue(it.toString()) // binding.imageView6.setImageURI(it) Picasso.get().load(it.toString()).into(binding.imageView7); Toast.makeText(this@imageuploader, "success", Toast.LENGTH_SHORT).show() } } } else{ Toast.makeText(this@imageuploader, "null", Toast.LENGTH_SHORT).show() } } else{ Toast.makeText(this@imageuploader, "not working", Toast.LENGTH_SHORT).show() } } private fun getFileType(data: Uri): String? { val mimetype= MimeTypeMap.getSingleton() return mimetype.getMimeTypeFromExtension(contentResolver.getType(data!!)) } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/imageuploader.kt
2067774635
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.Toast import com.example.myapplication.databinding.ActivityHomeBinding import com.google.firebase.auth.FirebaseAuth class home : AppCompatActivity() { private val binding:ActivityHomeBinding by lazy{ ActivityHomeBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.signout.setOnClickListener(){ Toast.makeText(this, "ff", Toast.LENGTH_SHORT).show() FirebaseAuth.getInstance().signOut() startActivity(Intent(this,login::class.java)) } binding.create.setOnClickListener(){ startActivity(Intent(this,createnotes::class.java)) } binding.open.setOnClickListener(){ startActivity(Intent(this,allnotes::class.java)) } } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/home.kt
3769908678
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.myapplication.databinding.ActivitySignupBinding import com.google.firebase.auth.FirebaseAuth class signup : AppCompatActivity() { private val binding:ActivitySignupBinding by lazy{ ActivitySignupBinding.inflate(layoutInflater) } private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) auth=FirebaseAuth.getInstance() binding.login.setOnClickListener(){ startActivity(Intent(this,login::class.java)) finish() } binding.register.setOnClickListener(){ val fullname=binding.fullname.text.toString() val username=binding.username.text.toString() val password=binding.password.text.toString() val confirmpassword=binding.confirmpassword.text.toString() if(fullname.isEmpty()||username.isEmpty()||password.isEmpty()||confirmpassword.isEmpty()){ Toast.makeText(this, "Please fill the empty fields", Toast.LENGTH_SHORT).show() } else{ if(password!=confirmpassword){ Toast.makeText(this, "Passwords are not same", Toast.LENGTH_SHORT).show() } else{ auth.createUserWithEmailAndPassword(username,password) .addOnCompleteListener(this){task-> if(task.isSuccessful){ Toast.makeText(this, "Registration Successful", Toast.LENGTH_SHORT).show() startActivity(Intent(this,login::class.java)) finish() } else{ Toast.makeText(this, "Registration Failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show() } } } } } } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/signup.kt
767562845
package com.example.myapplication import android.app.Activity import android.app.ProgressDialog import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.webkit.MimeTypeMap import android.widget.MediaController import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.view.isVisible import com.example.myapplication.databinding.ActivityVideouploaderBinding import com.google.firebase.Firebase import com.google.firebase.database.database import com.google.firebase.storage.storage import com.squareup.picasso.Picasso class videouploader : AppCompatActivity() { private lateinit var binding: ActivityVideouploaderBinding private lateinit var progressDialog:ProgressDialog override fun onCreate(savedInstanceState: Bundle?) { progressDialog= ProgressDialog(this) super.onCreate(savedInstanceState) binding = ActivityVideouploaderBinding.inflate(layoutInflater) setContentView(binding.root) binding.videoView.isVisible = false binding.videouploader.setOnClickListener { val intent = Intent() intent.action = Intent.ACTION_PICK intent.type = "video/*" videolauncher.launch(intent) } } val videolauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ it-> if(it.resultCode== Activity.RESULT_OK){ if(it.data!=null){ progressDialog.setTitle("Uploading Video...") progressDialog.show() Toast.makeText(this, "3", Toast.LENGTH_SHORT).show() val ref= Firebase.storage.reference.child("Video/"+System.currentTimeMillis()+"."+getFileType(it.data!!.data!!)) ref.putFile(it.data!!.data!!).addOnSuccessListener{ ref.downloadUrl.addOnSuccessListener{ Firebase.database.reference.child("Video").push().setValue(it.toString()) progressDialog.dismiss() // binding.imageView6.setImageURI(it) // Picasso.get().load(it.toString()).into(binding.videoView); Toast.makeText(this, "success", Toast.LENGTH_SHORT).show() binding.videouploader.isVisible=false binding.videoView.isVisible = true val mediaConroller=android.widget.MediaController(this) mediaConroller.setAnchorView(binding.videoView) binding.videoView.setVideoURI(it) binding.videoView.setMediaController((mediaConroller)) binding.videoView.start() binding.videoView.setOnCompletionListener { ref.delete().addOnSuccessListener { Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show() } } } } .addOnProgressListener { val value=(it.bytesTransferred/it.totalByteCount)*100 progressDialog.setTitle("Uploaded "+value.toString()+"%") } } } } private fun getFileType(data: Uri): String? { val mimetype= MimeTypeMap.getSingleton() return mimetype.getMimeTypeFromExtension(contentResolver.getType(data!!)) } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/videouploader.kt
746460499
package com.example.myapplication data class notes(val title: String, val description: String,val noteId:String) { constructor() :this("","","") }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/notes.kt
568789065
package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.myapplication.databinding.ActivityAllnotesBinding import com.example.myapplication.databinding.UpdatenoteBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class allnotes : AppCompatActivity(), notesadapter.OnItemClickListener{ private val binding:ActivityAllnotesBinding by lazy{ ActivityAllnotesBinding.inflate(layoutInflater) } private lateinit var auth:FirebaseAuth private lateinit var dataBaseReference:DatabaseReference private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) recyclerView=binding.notesRecyclerView recyclerView.layoutManager=LinearLayoutManager(this) dataBaseReference=FirebaseDatabase.getInstance().reference auth=FirebaseAuth.getInstance() val currentuser=auth.currentUser currentuser?.let { user-> val noteReference=dataBaseReference.child("Users").child(user.uid).child("notes") noteReference.addValueEventListener(object:ValueEventListener{ override fun onDataChange(snapshot: DataSnapshot) { val notelist= mutableListOf<notes>() for (notesnapshot in snapshot.children){ val note=notesnapshot.getValue(notes::class.java) note?.let{ notelist.add(it) } notelist.reverse() val adapter=notesadapter(notelist,this@allnotes) recyclerView.adapter=adapter } } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } } override fun onDeleteClick(nodeid: String) { val currentuser=auth.currentUser currentuser?.let{user-> val notereference=dataBaseReference.child("Users").child(user.uid).child("notes") notereference.child(nodeid).removeValue() } } override fun onUpdateClick(nodeid: String,title: String, description:String) { val dialogbinding=UpdatenoteBinding.inflate(LayoutInflater.from(this)) val dialog=AlertDialog.Builder(this).setView(dialogbinding.root) .setTitle("Update Notes") .setPositiveButton("Update"){dialog,_-> val title=dialogbinding.updatetitle.text.toString() val description=dialogbinding.updatedescription.text.toString() updateNoteDataBase(nodeid,title,description) dialog.dismiss() } .setNegativeButton("Cancel"){dialog,_-> dialog.dismiss() } .create() dialogbinding.updatetitle.setText(title) dialogbinding.updatedescription.setText(description) dialog.show() } private fun updateNoteDataBase(nodeid: String, title: String, description: String) { val currentuser=auth.currentUser currentuser?.let{user-> val notereference=dataBaseReference.child("Users").child(user.uid).child("notes") val updatenote=notes(title,description,nodeid) notereference.child(nodeid).setValue(updatenote) .addOnCompleteListener{task-> if(task.isSuccessful){ Toast.makeText(this, "Note Updated Successfully", Toast.LENGTH_SHORT).show() } else{ Toast.makeText(this, "Failed to Update", Toast.LENGTH_SHORT).show() } } } } }
FireBaseAuthentication-RealTimeDatabase-StorageofPhotosAndVideos/app/src/main/java/com/example/myapplication/allnotes.kt
2944616299
package com.lxy.responsivelayout 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.lxy.responsivelayout", appContext.packageName) } }
ResponsiveLayoutDemo/app/src/androidTest/java/com/lxy/responsivelayout/ExampleInstrumentedTest.kt
3626944028
package com.lxy.responsivelayout 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) } }
ResponsiveLayoutDemo/app/src/test/java/com/lxy/responsivelayout/ExampleUnitTest.kt
2944093646
package com.lxy.responsivelayout.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)
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/ui/theme/Color.kt
1215316706
package com.lxy.responsivelayout.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 ResponsiveLayoutTheme( 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 ) }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/ui/theme/Theme.kt
834707098
package com.lxy.responsivelayout.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 ) */ )
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/ui/theme/Type.kt
2053616873
package com.lxy.responsivelayout import android.app.Application import android.util.Log import androidx.startup.AppInitializer import me.jessyan.autosize.AutoSize import me.jessyan.autosize.AutoSizeConfig import me.jessyan.autosize.InitProvider import me.jessyan.autosize.utils.AutoSizeUtils /** * * @Author:liuxy * @Date:2024/4/15 9:23 * @Desc: * */ class RLApp : Application() { override fun onCreate() { super.onCreate() // AppInitializer.getInstance(baseContext) // .initializeComponent(InitProvider::class.java) var init = AutoSize.checkInit() Log.d("TAG", "onCreate autosize init: $init") } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/RLApp.kt
2465591693
package com.lxy.responsivelayout import android.content.pm.ActivityInfo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.window.core.layout.WindowSizeClass import androidx.window.core.layout.WindowWidthSizeClass import androidx.window.layout.WindowMetricsCalculator import com.lxy.responsivelayout.databinding.ActivityXmlBinding class XmlActivity : AppCompatActivity() { private val binding: ActivityXmlBinding by lazy { ActivityXmlBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) if (computeWindowSizeClasses() == WindowWidthSizeClass.EXPANDED){ requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE binding.tvExtend?.text = "我是横屏才展示" }else { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } } private fun computeWindowSizeClasses() : WindowWidthSizeClass { val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(this) val width = metrics.bounds.width() val height = metrics.bounds.height() val density = resources.displayMetrics.density // Xml: width = 1080, height = 2340, density = 2.88 // no size: width = 1080, height = 2340, density = 2.625 Log.d("TAG", "Xml: width = $width, height = $height, density = $density") val windowSizeClass = WindowSizeClass(widthDp = (width/density).toInt(), heightDp = (height/density).toInt()) // COMPACT, MEDIUM, or EXPANDED val widthWindowSizeClass = windowSizeClass.windowWidthSizeClass // COMPACT, MEDIUM, or EXPANDED val heightWindowSizeClass = windowSizeClass.windowHeightSizeClass Log.d("TAG", "Xml: ${windowSizeClass}") return widthWindowSizeClass } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/XmlActivity.kt
404312692
package com.lxy.responsivelayout.entity data class Article( val title : String, val url : String, val author : String = "", val date : String = "", )
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/entity/Article.kt
3415893860
package com.lxy.responsivelayout import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt /** * * @Author:liuxy * @Date:2024/4/24 16:09 * @Desc: * */ val list = listOf("index1", "index2", "index3", "index4", "index5", "index6", "index7") val itemHeight = 100 @OptIn(ExperimentalMaterial3Api::class) @Composable fun MainPage() { Scaffold( topBar = { TopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text(stringResource(R.string.drag)) }, actions = { IconButton( onClick = { } //do something ) { Icon(Icons.Filled.Search, null) } Text(text = "编辑") } ) }, ) { innerPadding -> Surface( modifier = Modifier.padding(innerPadding) ) { DragPage(list = list) } } } @Composable fun DragPage( list: List<String> ) { var itemsList by remember { mutableStateOf(list) } LazyColumn( modifier = Modifier .background(colorResource(id = R.color.white)) .padding(top = 12.dp, start = 12.dp, end = 12.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { items(itemsList.size) { val item = itemsList[it] var offsetX by remember { mutableStateOf(0f) } var offsetY by remember { mutableStateOf(0f) } var isDragging by remember { mutableStateOf(false) } var dragOffset by remember { mutableStateOf(IntOffset.Zero) } Row( modifier = Modifier .offset { if (isDragging) dragOffset else IntOffset.Zero // IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) } .padding(4.dp) .fillMaxWidth() .height(itemHeight.dp) .pointerInput(Unit) { detectDragGestures( onDragStart = { down -> isDragging = true dragOffset = IntOffset.Zero }, onDrag = { change, dragAmount -> // change.consume() dragOffset += IntOffset(0, dragAmount.y.roundToInt()) }, onDragEnd = { isDragging = false Log.d("Drag", "移动的项是$it,content = $item") val newIndex = calculateNewIndex(it, dragOffset) Log.d("Drag", "移动后的位置是$newIndex,content = $item") if (newIndex != it) { itemsList = moveItem(itemsList, it, newIndex) } } ) }, verticalAlignment = Alignment.CenterVertically, ) { Image( painter = painterResource(id = R.drawable.login_icon_person), modifier = Modifier .size(width = 48.dp, height = 48.dp) .clip(RoundedCornerShape(6.dp)), contentDescription = "" ) Text( text = "$item", fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(6.dp) ) } } } } fun calculateNewIndex(draggedItemIndex: Int, dragOffset: IntOffset): Int { val draggedItemY = draggedItemIndex * itemHeight // 假设每个子项的高度相等 val draggedItemCenterY = draggedItemY + (itemHeight / 2) val newIndex = (draggedItemCenterY + dragOffset.y) / itemHeight return newIndex.coerceIn(0, list.size - 1) } fun moveItem(list: List<String>, oldIndex: Int, newIndex:Int) : List<String>{ val mutableList = list.toMutableList() mutableList.add(newIndex, mutableList.removeAt(oldIndex)) return mutableList.toList() }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/DragPage.kt
1386246029
package com.lxy.responsivelayout.list import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import com.lxy.responsivelayout.R import com.lxy.responsivelayout.XmlActivity import com.lxy.responsivelayout.databinding.FragmentFirstBinding import com.lxy.responsivelayout.main.MainViewModel class FirstFragment : Fragment() { private val binding : FragmentFirstBinding by lazy { FragmentFirstBinding.inflate(layoutInflater) } private val mViewModel: ListViewModel by lazy { ViewModelProvider(requireActivity())[ListViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() } private fun initView() { mViewModel.select.observe(viewLifecycleOwner){ binding.webView.loadUrl(it.url) } binding.tvButton.setOnClickListener { startActivity(Intent(requireContext(), XmlActivity::class.java)) } binding.tvBack.setOnClickListener { mViewModel.back.value?.let { if (it){ } } } } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/list/FirstFragment.kt
1738405297
package com.lxy.responsivelayout.list import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.lxy.responsivelayout.entity.Article import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow class ListViewModel : ViewModel() { private val _select = MutableLiveData<Article>() val select : LiveData<Article> = _select fun setSelectItem(article: Article){ _select.postValue(article) } private val _back = MutableLiveData<Boolean>() val back : LiveData<Boolean> = _back fun back(back : Boolean){ _back.postValue(back) } private val _isExtend = MutableLiveData<Boolean>() val isExtend : LiveData<Boolean> = _isExtend fun setExtends(back : Boolean){ _isExtend.postValue(back) } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/list/ListViewModel.kt
345238279
package com.lxy.responsivelayout.list import android.view.LayoutInflater import android.view.ViewGroup import androidx.viewbinding.ViewBinding import com.lxy.responsivelayout.base.BaseAdapter import com.lxy.responsivelayout.databinding.ItemListBinding import com.lxy.responsivelayout.entity.Article class ListAdapter : BaseAdapter<Article>() { override fun onCreateViewBinding( viewType: Int, inflater: LayoutInflater?, parent: ViewGroup? ): ViewBinding { return ItemListBinding.inflate(inflater!!, parent, false) } override fun convert(holder: ViewBindHolder?, t: Article?, position: Int) { val binding = holder?.binding as ItemListBinding t?.let { binding.tvName.setText(it.title) } } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/list/ListAdapter.kt
3960619239
package com.lxy.responsivelayout.list import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.window.core.layout.WindowSizeClass import androidx.window.core.layout.WindowWidthSizeClass import androidx.window.layout.WindowMetricsCalculator import com.lxy.responsivelayout.R import com.lxy.responsivelayout.databinding.ActivityListBinding import com.lxy.responsivelayout.entity.Article import com.lxy.responsivelayout.main.MainViewModel class ListActivity : AppCompatActivity() { private val binding: ActivityListBinding by lazy { ActivityListBinding.inflate(layoutInflater) } private val mViewModel: ListViewModel by lazy { ViewModelProvider(this)[ListViewModel::class.java] } private val adapter: ListAdapter by lazy { val adapter = ListAdapter() adapter.setOnItemClickListener { view, t, position -> mViewModel.setSelectItem(t) binding.slide.open() } adapter } val list = arrayListOf<Article>( Article( "我是一个标题", "https://developer.android.google.cn/guide/topics/large-screens/support-different-screen-sizes?hl=zh-cn", "test" ), Article( "我是二个标题", "https://developer.android.google.cn/develop/ui/compose/layouts/adaptive?hl=zh-cn", "test2" ), ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) computeWindowSizeClasses() binding.rv.let { it.layoutManager = LinearLayoutManager(this@ListActivity) it.adapter = adapter } adapter.setData(list) } private fun computeWindowSizeClasses() { val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(this) val width = metrics.bounds.width() val height = metrics.bounds.height() val density = resources.displayMetrics.density val windowSizeClass = WindowSizeClass(widthDp = (width/density).toInt(), heightDp = (height/density).toInt()) // COMPACT, MEDIUM, or EXPANDED val widthWindowSizeClass = windowSizeClass.windowWidthSizeClass // COMPACT, MEDIUM, or EXPANDED val heightWindowSizeClass = windowSizeClass.windowHeightSizeClass mViewModel.setExtends(widthWindowSizeClass == WindowWidthSizeClass.EXPANDED) } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/list/ListActivity.kt
3164941586
package com.lxy.responsivelayout.nav import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController object RLDestinations { const val HOME_ROUTE = "home" const val INTERESTS_ROUTE = "list" } /** * Models the navigation actions in the app. */ class RLNavigationActions(navController: NavHostController) { val navigateToHome: () -> Unit = { navController.navigate(RLDestinations.HOME_ROUTE) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true // Restore state when reselecting a previously selected item restoreState = true } } val navigateToInterests: () -> Unit = { navController.navigate(RLDestinations.INTERESTS_ROUTE) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/nav/RLNavigation.kt
1006919618
package com.lxy.responsivelayout.nav import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navDeepLink import com.lxy.responsivelayout.entity.Article import com.lxy.responsivelayout.main.ArticleDetail import com.lxy.responsivelayout.main.ArticleList const val POST_ID = "postId" @Composable fun RLNavGraph( isExpandedScreen: Boolean, modifier: Modifier = Modifier, navController: NavHostController = rememberNavController(), openDrawer: () -> Unit = {}, startDestination: String = RLDestinations.HOME_ROUTE, ) { NavHost( navController = navController, startDestination = startDestination, modifier = modifier ) { composable( route = RLDestinations.HOME_ROUTE, // deepLinks = listOf( // navDeepLink { // uriPattern = // "$JETNEWS_APP_URI/${RLDestinations.HOME_ROUTE}?$POST_ID={$POST_ID}" // } // ) ) { navBackStackEntry -> val list = arrayListOf<Article>( Article("我是一个标题", "https://developer.android.google.cn/guide/topics/large-screens/support-different-screen-sizes?hl=zh-cn", "test"), Article("我是二个标题", "https://developer.android.google.cn/develop/ui/compose/layouts/adaptive?hl=zh-cn", "test2"), ) // ArticleList(messages = list, navController = navController) } composable(RLDestinations.INTERESTS_ROUTE) { // it.arguments?.getString("url")?.let { it1 -> ArticleDetail(url = it1) } } } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/nav/RLNavGraph.kt
2854899452
package com.lxy.responsivelayout.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.lxy.responsivelayout.entity.Article import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow class MainViewModel : ViewModel() { private val _select = MutableLiveData<Article>() val select : LiveData<Article> = _select fun setSelectItem(article: Article){ _select.postValue(article) } private val _back = MutableLiveData<Boolean>() val back : LiveData<Boolean> = _back fun back(back : Boolean){ _back.postValue(back) } private val _dragList = MutableLiveData<List<String>>() val dragList : LiveData<List<String>> = _dragList fun init(){ } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/MainViewModel.kt
906655988
package com.lxy.responsivelayout.main import androidx.compose.ui.graphics.vector.ImageVector /** * * @Author:liuxy * @Date:2024/4/11 15:28 * @Desc: * */ data class BottomItem( val iconId: ImageVector, val name: String, var selected: Boolean = false, )
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/BottomItem.kt
4047835446
package com.lxy.responsivelayout.main import android.util.Log import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.lxy.responsivelayout.entity.Article import com.lxy.responsivelayout.nav.RLDestinations @Composable fun article( navController: NavHostController, isExtend: Boolean, messages: List<Article>, ) { val viewModel : MainViewModel = viewModel() Row { ArticleList(messages = messages, viewModel = viewModel) Spacer(modifier = Modifier.padding(10.dp)) if (isExtend) { // ArticleDetail(viewModel) } } } @Composable fun ArticleList( messages: List<Article>, navController: NavHostController = rememberNavController(), viewModel: MainViewModel ) { Column { messages.forEach { message -> ArticleItem(message, navController, viewModel) } } } @Composable fun ArticleItem( article: Article, navController: NavHostController = rememberNavController(), viewModel: MainViewModel ) { Column(modifier = Modifier.clickable { Log.d("TAG", "ArticleItem: ${article.url}") viewModel.setSelectItem(article = article) }) { Text(text = article.title, modifier = Modifier.padding(5.dp)) Text(text = article.author, modifier = Modifier.padding(5.dp)) } } @Preview @Composable fun item() { val list = arrayListOf<Article>( Article( "我是一个标题", "https://developer.android.google.cn/guide/topics/large-screens/support-different-screen-sizes?hl=zh-cn", "test" ), Article( "我是二个标题", "https://developer.android.google.cn/develop/ui/compose/layouts/adaptive?hl=zh-cn", "test2" ), ) }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/ArticleList.kt
2203727466
package com.lxy.responsivelayout.main import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Person import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.PermanentNavigationDrawer import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.lxy.responsivelayout.R import com.lxy.responsivelayout.nav.RLNavGraph import com.lxy.responsivelayout.nav.RLNavigationActions import com.lxy.responsivelayout.ui.theme.ResponsiveLayoutTheme import kotlinx.coroutines.launch /** * * @Author:liuxy * @Date:2024/4/11 15:23 * @Desc: * */ val icons = arrayOf( BottomItem(Icons.Filled.Home, "工作台", true), BottomItem(Icons.Filled.Person, "主页"), ) class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ResponsiveLayoutTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val windowSizeClass = calculateWindowSizeClass(this) Log.d("TAG", "Greeting: ${windowSizeClass.toString()}") // MainApp(windowSizeClass.widthSizeClass) MyApp(windowSizeClass.widthSizeClass) } } } } } @Composable fun MyApp(widthSizeClass: WindowWidthSizeClass) { // Select a navigation element based on window size. val navController = rememberNavController() when (widthSizeClass) { WindowWidthSizeClass.Expanded -> { ExpandedScreen(navController) } else ->{ CompactScreen(navController) } } } @Composable fun CompactScreen(navController: NavHostController) { Scaffold( modifier = Modifier.fillMaxSize(), bottomBar = { NavigationBar { icons.forEach { item -> NavigationBarItem( selected = item.selected, onClick = { }, icon = { Icon(item.iconId, contentDescription = item.name) }) } } }, content = { it.calculateBottomPadding() RLNavGraph( isExpandedScreen = false, navController = navController, openDrawer = { }, ) }) } @Composable fun MediumScreen(navController: NavHostController) { PermanentNavigationDrawer( drawerContent = { icons.forEach { item -> NavigationDrawerItem( icon = { Icon(item.iconId, contentDescription = item.name) }, label = { }, selected = item.selected, onClick = { } ) } }, content = { // Other content } ) } @Composable fun ExpandedScreen(navController: NavHostController) { Scaffold( modifier = Modifier.fillMaxSize(), bottomBar = { NavigationRail { icons.forEach { item -> NavigationRailItem( selected = item.selected, onClick = { }, icon = { Icon(item.iconId, contentDescription = item.name) }) } } }, content = { it.calculateBottomPadding() RLNavGraph( isExpandedScreen = false, navController = navController, openDrawer = { }, ) }) }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/MainActivity.kt
311511151
package com.lxy.responsivelayout.main import android.util.Log import android.webkit.WebView import android.webkit.WebViewClient import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.viewinterop.AndroidView import com.lxy.responsivelayout.entity.Article @Composable fun ArticleDetail(article: Article , viewModel: MainViewModel){ Column(modifier = Modifier.fillMaxHeight()) { AndroidView(factory = { WebView(it).apply { settings.javaScriptEnabled = true webViewClient = WebViewClient() loadUrl(article.url) } }, modifier = Modifier.fillMaxSize()) } } @Preview @Composable fun ArticleDetailPreview(){ val list = Article("我是一个标题", "https://developer.android.google.cn/guide/topics/large-screens/support-different-screen-sizes?hl=zh-cn", "test") // ArticleDetail(list) }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/ArticleDetail.kt
3727144900
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lxy.responsivelayout.main import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Row import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue import androidx.compose.material3.Icon import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.rememberDrawerState import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.res.painterResource import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.lxy.responsivelayout.nav.RLDestinations import com.lxy.responsivelayout.nav.RLNavGraph import com.lxy.responsivelayout.nav.RLNavigationActions import com.lxy.responsivelayout.ui.theme.ResponsiveLayoutTheme import kotlinx.coroutines.launch @Composable fun MainApp( widthSizeClass: WindowWidthSizeClass, ) { ResponsiveLayoutTheme { val navController = rememberNavController() val navigationActions = remember(navController) { RLNavigationActions(navController) } val coroutineScope = rememberCoroutineScope() val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route ?: RLDestinations.HOME_ROUTE val isExpandedScreen = widthSizeClass == WindowWidthSizeClass.Expanded val sizeAwareDrawerState = rememberSizeAwareDrawerState(isExpandedScreen) ModalNavigationDrawer( drawerContent = { icons.forEach { item -> NavigationDrawerItem( icon = { Icon(item.iconId, contentDescription = item.name) }, label = { }, selected = item.selected, onClick = { } ) } }, drawerState = sizeAwareDrawerState, // Only enable opening the drawer via gestures if the screen is not expanded gesturesEnabled = !isExpandedScreen ) { Row { if (isExpandedScreen) { icons.forEach { item -> NavigationDrawerItem( icon = { Icon(item.iconId, contentDescription = item.name)}, label = { }, selected = item.selected, onClick = { } ) } } RLNavGraph( isExpandedScreen = isExpandedScreen, navController = navController, openDrawer = { coroutineScope.launch { sizeAwareDrawerState.open() } }, ) } } } } /** * Determine the drawer state to pass to the modal drawer. */ @Composable private fun rememberSizeAwareDrawerState(isExpandedScreen: Boolean): DrawerState { val drawerState = rememberDrawerState(DrawerValue.Closed) return if (!isExpandedScreen) { // If we want to allow showing the drawer, we use a real, remembered drawer // state defined above drawerState } else { // If we don't want to allow the drawer to be shown, we provide a drawer state // that is locked closed. This is intentionally not remembered, because we // don't want to keep track of any changes and always keep it closed DrawerState(DrawerValue.Closed) } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/main/MainApp.kt
4239528441
package com.lxy.responsivelayout import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import com.lxy.responsivelayout.list.ListActivity import com.lxy.responsivelayout.main.MainActivity import com.lxy.responsivelayout.ui.theme.ResponsiveLayoutTheme class LoginActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ResponsiveLayoutTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { // val windowSizeClass = calculateWindowSizeClass(this) // Greeting(windowSizeClass) MainPage() } } } } } @Composable fun Greeting(windowSize: WindowSizeClass, modifier: Modifier = Modifier) { Log.d("TAG", "Greeting: ${windowSize.toString()}") if (windowSize.widthSizeClass == WindowWidthSizeClass.Compact){ landView() }else{ hei() } } @Composable fun landView(){ val startActivityLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> // 在这里处理启动活动的结果 if (result.resultCode == Activity.RESULT_OK) { // 处理成功的情况 } } val context = LocalContext.current Column { Text(text = "我是标题") Button(onClick = { startActivityLauncher.launch(Intent(context, MainActivity::class.java)) }) { Text(text = "登录") } Button(onClick = { startActivityLauncher.launch(Intent(context, ListActivity::class.java)) }) { Text(text = "列表") } } } @Composable fun hei(){ val startActivityLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> // 在这里处理启动活动的结果 if (result.resultCode == Activity.RESULT_OK) { // 处理成功的情况 } } val context = LocalContext.current Row { Text(text = "我是标题") Button(onClick = { startActivityLauncher.launch(Intent(context, MainActivity::class.java)) }) { Text(text = "登录") } Button(onClick = { startActivityLauncher.launch(Intent(context, ListActivity::class.java)) }) { Text(text = "列表") } } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/LoginActivity.kt
4113858583
package com.lxy.responsivelayout import android.app.Application import android.content.Context import androidx.startup.Initializer import me.jessyan.autosize.AutoSize /** * * @Author:liuxy * @Date:2024/4/16 11:27 * @Desc: * */ class AutoSizeInitializer : Initializer<Unit> { override fun create(context: Context) { AutoSize.checkAndInit(context.applicationContext as Application) } override fun dependencies(): List<Class<out Initializer<*>>> { return emptyList() } }
ResponsiveLayoutDemo/app/src/main/java/com/lxy/responsivelayout/AutoSizeInitializer.kt
1209234114
package com.dist.screen 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.dist.screen.test", appContext.packageName) } }
ResponsiveLayoutDemo/screen/src/androidTest/java/com/dist/screen/ExampleInstrumentedTest.kt
254976409
package com.dist.screen 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) } }
ResponsiveLayoutDemo/screen/src/test/java/com/dist/screen/ExampleUnitTest.kt
4039381719
package com.example.traveldiary 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.traveldiary", appContext.packageName) } }
TravelDiary/app/src/androidTest/java/com/example/traveldiary/ExampleInstrumentedTest.kt
1466563345
package com.example.traveldiary 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) } }
TravelDiary/app/src/test/java/com/example/traveldiary/ExampleUnitTest.kt
3404572476
package com.example.traveldiary.ui.settings import android.content.Context import android.content.SharedPreferences import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.traveldiary.MainActivity import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentSettingsBinding import com.google.android.material.navigation.NavigationView import com.google.gson.Gson import java.util.* class SettingsFragment : Fragment() { private var _binding: FragmentSettingsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentSettingsBinding.inflate(inflater, container, false) val root: View = binding.root val homeViewModel = ViewModelProvider(this).get(SettingsViewModel::class.java) val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val currentUserJson = sharedPref.getString("currentUser", null) val editor = sharedPref.edit() val gson = Gson() if(currentUserJson != null) { val currentUser: User = gson.fromJson(currentUserJson, User::class.java) binding.darkModeSwitch.setChecked(currentUser.settings.nightMode) binding.satelliteSwitch.setChecked(currentUser.settings.satellite) } val spinner = binding.language var type = "" val adapter = ArrayAdapter.createFromResource( requireContext(), R.array.languages, R.layout.custom_spinner_item ).also { adapter -> adapter.setDropDownViewResource(R.layout.custom_spinner_item) spinner.adapter = adapter spinner.setSelection(0, false) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { type = parent.getItemAtPosition(position) as String } override fun onNothingSelected(parent: AdapterView<*>) { Toast.makeText(requireContext(), "nothing selected", Toast.LENGTH_SHORT).show() } } binding.saveButton.setOnClickListener { // Get the values of the switches val isDarkModeEnabled = binding.darkModeSwitch.isChecked val isSatelliteEnabled = binding.satelliteSwitch.isChecked // Create a toast message with the switch values if(currentUserJson == null) { Toast.makeText(requireContext(), R.string.pleaseLogInFirst , Toast.LENGTH_SHORT).show() } else { val currentUser: User = gson.fromJson(currentUserJson, User::class.java) currentUser.settings.satellite=isSatelliteEnabled currentUser.settings.nightMode=isDarkModeEnabled if(!type.equals("")) { currentUser.settings.language = type } val updatedCurrentUserJson = gson.toJson(currentUser) editor.putString("currentUser", updatedCurrentUserJson) // Apply the changes to SharedPreferences editor.apply() if(type.equals("Romanian") || type.equals("Romana")) { val locale = Locale("ro") // Change to French val config = Configuration(resources.configuration) config.setLocale(locale) resources.updateConfiguration(config, resources.displayMetrics) updateMenuItems() } else if(type.equals("English") || type.equals("Engleza")){ val config = Configuration(resources.configuration) config.setToDefaults() resources.updateConfiguration(config, resources.displayMetrics) updateMenuItems() } if(isDarkModeEnabled) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } if(type.equals("Romanian") || type.equals("Romana")) { val locale = Locale("ro") // Change to French val config = Configuration(resources.configuration) config.setLocale(locale) resources.updateConfiguration(config, resources.displayMetrics) updateMenuItems() } else if(type.equals("English") || type.equals("Engleza")){ val config = Configuration(resources.configuration) config.setToDefaults() resources.updateConfiguration(config, resources.displayMetrics) updateMenuItems() } Toast.makeText(requireContext(),R.string.settingsSaved, Toast.LENGTH_SHORT).show() findNavController().navigate(R.id.nav_settings) } } binding.backButton.setOnClickListener { findNavController().navigate(R.id.nav_home) } return root } private fun updateMenuItems() { val mainActivity = requireActivity() as MainActivity val navigationView = mainActivity.findViewById<NavigationView>(R.id.nav_view) val menu = navigationView.menu // Find and update each menu item val homeMenuItem = menu.findItem(R.id.nav_home) homeMenuItem.title = getString(R.string.home) val aboutUsMenuItem = menu.findItem(R.id.nav_gallery) aboutUsMenuItem.title = getString(R.string.aboutUs) val contactUsMenuItem = menu.findItem(R.id.nav_slideshow) contactUsMenuItem.title = getString(R.string.contactUs) val settingsMenuItem = menu.findItem(R.id.nav_settings) settingsMenuItem.title = getString(R.string.settings) val logoutMenuItem = menu.findItem(R.id.nav_login) logoutMenuItem.title = getString(R.string.logout) val deleteAccountMenuItem = menu.findItem(R.id.nav_delete) deleteAccountMenuItem.title = getString(R.string.deleteAccount) val deleteDataMenuItem = menu.findItem(R.id.nav_delete_all) deleteDataMenuItem.title = getString(R.string.deleteAllData) // Repeat this for other menu items... } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/settings/SettingsFragment.kt
2417863155
package com.example.traveldiary.ui.settings import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class SettingsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is settings Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/settings/SettingsViewModel.kt
1271723010
package com.example.traveldiary.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.traveldiary.MainActivity class HomeViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { if (MainActivity.currentUser?.destinationList == null) { value = "No destination added" } else { value = "" } } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/home/HomeViewModel.kt
2017864631
package com.example.traveldiary.ui.home import android.R import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.traveldiary.database.Destination import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentHomeBinding import com.example.traveldiary.ui.recycler.MyAdapter import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.gson.Gson import com.google.gson.reflect.TypeToken class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root val preferences = requireContext().getSharedPreferences("myPref", 0) preferences.edit().remove("currentDestination").commit() preferences.edit().remove("currentLocation").commit() // Set up the FloatingActionButton val addNewDestination: Button = binding.fab addNewDestination.setOnClickListener { view -> findNavController().navigate(com.example.traveldiary.R.id.nav_new_destination) } // Set up the TextView val textView: TextView = binding.textHome val sharedPreferences = requireContext().getSharedPreferences("myPref", Context.MODE_PRIVATE) val userJson = sharedPreferences.getString("currentUser", "") val gson = Gson() try { val user: User = gson.fromJson(userJson, User::class.java) // Now, you can access the destinationList from the User object val destinations: List<Destination> = user.destinationList // Set up the RecyclerView with a LinearLayoutManager val recyclerView: RecyclerView = binding.recyclerView val layoutManager = LinearLayoutManager(requireContext()) recyclerView.layoutManager = layoutManager // Set the adapter val adapter = MyAdapter(requireContext(), destinations) { clickedDestination -> // Handle the item click here using the entire Destination object // Save the clicked Destination to SharedPreferences val sharedPreferencesEditor = sharedPreferences.edit() val gson = Gson() val destinationJson = gson.toJson(clickedDestination) sharedPreferencesEditor.putString("currentDestination", destinationJson) sharedPreferencesEditor.apply() findNavController().navigate(com.example.traveldiary.R.id.nav_view_destination) } recyclerView.adapter = adapter if (destinations.isEmpty()) { // Handle the case when there are no destinations textView.text = getString(com.example.traveldiary.R.string.noDestinations) } else { // Set a message indicating the number of destinations textView.visibility = View.GONE textView.text = "You have ${destinations.size} destinations." } } catch (e: Exception) { // Handle JSON parsing errors or any other exceptions here textView.text = "Error loading destinations." e.printStackTrace() } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/home/HomeFragment.kt
333411982
package com.example.traveldiary.ui.view_destination import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ViewDestinationViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is about us Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/view_destination/ViewDestinationViewModel.kt
2355915389
package com.example.traveldiary.ui.view_destination import android.content.Context import android.content.pm.PackageManager import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentViewDestinationBinding import com.google.gson.Gson import com.google.gson.reflect.TypeToken class ViewDestinationFragment : Fragment() { private var _binding: FragmentViewDestinationBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(ViewDestinationViewModel::class.java) _binding = FragmentViewDestinationBinding.inflate(inflater, container, false) val root: View = binding.root val sharedPreferences = requireContext().getSharedPreferences("myPref", Context.MODE_PRIVATE) val destinationJson = sharedPreferences.getString("currentDestination", "") val gson = Gson() val destination: Destination = gson.fromJson(destinationJson, Destination::class.java) if (destination.name.isEmpty()) { binding.destinationName.visibility = View.GONE } else { binding.destinationName.text = destination.name binding.destinationName.visibility = View.VISIBLE } if (destination.date.isEmpty()) { binding.destinationDate.visibility = View.GONE } else { binding.destinationDate.text = getString(R.string.date) + ": " + "${destination.date}" binding.destinationDate.visibility = View.VISIBLE } if (destination.type == "") { binding.destinationType.visibility = View.GONE } else { binding.destinationType.text = getString(R.string.typeOfTransport) +": " + "${destination.type}" binding.destinationType.visibility = View.VISIBLE } if (destination.description.isEmpty()) { binding.destinationDescription.visibility = View.GONE } else { binding.destinationDescription.text = getString(R.string.description) + ": " + "${destination.description}" binding.destinationDescription.visibility = View.VISIBLE } if (destination.location == null) { binding.destinationDescription.visibility = View.GONE } else { if(destination.location.name.isEmpty()) { binding.destinationLocation.visibility = View.GONE } else { binding.destinationLocation.text = getString(R.string.place) + ": ${destination.location.name}\n" + getString(R.string.coordonates) + ": ${String.format("%.3f", destination.location.latitudine)}, " + "${String.format("%.3f", destination.location.longitudine)}\n" + getString(R.string.weather) + ": ${destination.location.weather}\n" + getString(R.string.temperature) + ": " + "${destination.location.temperature}\n" + getString(R.string.humidity) +": " + "${destination.location.humidity}" binding.destinationLocation.visibility = View.VISIBLE } } if (ActivityCompat.checkSelfPermission( requireContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ) { Glide.with(this) .load(destination.photo) .apply(RequestOptions().fitCenter()) // Use fitCenter to maintain aspect ratio .into(binding.destinationImage) } else { Glide.with(this) .load(destination.photo) .apply(RequestOptions().fitCenter()) // Use fitCenter to maintain aspect ratio .into(binding.destinationImage) } binding.deleteButton.setOnClickListener{ val currentUserJson = sharedPreferences.getString("currentUser", "") val currentUser: User? = gson.fromJson(currentUserJson, User::class.java) val builder = AlertDialog.Builder(requireContext()) // Set the dialog title and message builder.setTitle(R.string.sureQuestion) .setMessage(R.string.deleteDestinationQuestion) // Add "Yes" button builder.setPositiveButton(R.string.yes) { _, _ -> // User clicked "Yes," navigate to the login screen if (currentUser != null) { // Specify the name and date of the destination you want to delete val destinationNameToDelete = binding.destinationName.text val destinationDateToDelete = binding.destinationDate.text // Find the destination with the specified name and date, and remove it val updatedDestinations = currentUser.destinationList.filterNot { destination -> destination.name == destinationNameToDelete && destination.date == destinationDateToDelete } // Update the 'currentUser' object with the filtered destinations currentUser.destinationList = updatedDestinations as ArrayList<Destination> val userListJson = sharedPreferences.getString("userList", null) val editor = sharedPreferences.edit() val userListType = object : TypeToken<List<User>>() {}.type var userList = gson.fromJson<List<User>>(userListJson, userListType) if (userList == null) { userList = ArrayList() } // Find the current user in the user array and update it userList = userList.map { if (it.username == currentUser.username) currentUser else it } // Convert the updated user array to JSON and save it back to SharedPreferences val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) // Serialize the updated 'currentUser' object back to JSON val updatedCurrentUserJson = gson.toJson(currentUser) // Save the updated 'currentUser' object back to SharedPreferences editor.putString("currentUser", updatedCurrentUserJson).apply() editor.apply() // Optionally, you can notify the user that the destination has been deleted Toast.makeText(requireContext(), R.string.destinationDeleted, Toast.LENGTH_SHORT).show() findNavController().navigate(R.id.nav_home) } } // Add "No" button builder.setNegativeButton(R.string.no) { _, _ -> // User clicked "No," do nothing or handle it as needed // For example, you can dismiss the dialog or perform another action } // Create and show the AlertDialog val dialog = builder.create() dialog.show() } binding.editButton.setOnClickListener{ findNavController().navigate(R.id.nav_edit_destination) } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/view_destination/ViewDestinationFragment.kt
3808408546
package com.example.traveldiary.ui.location import android.content.Context import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.Location import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentMapsBinding import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.Place import com.google.android.libraries.places.api.model.Place.Field import com.google.android.libraries.places.widget.AutocompleteSupportFragment import com.google.android.libraries.places.widget.listener.PlaceSelectionListener import com.google.gson.Gson class MapsFragment : Fragment() { private var name: String = "" private var latitudine: Double = 0.0 private var longitudine: Double = 0.0 private val callback = OnMapReadyCallback { googleMap -> // Initialize the googleMap variable here this.googleMap = googleMap val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() val currentLocationJson = sharedPref.getString("currentDestination", null) val gson = Gson() var currentLocation = gson.fromJson(currentLocationJson, Location::class.java) val currentUserJson = sharedPref.getString("currentUser", null) val currentUser = gson.fromJson(currentUserJson, User::class.java) googleMap?.let { map -> // Check the current map type when (currentUser.settings.satellite) { true -> { // Switch to SATELLITE view map.mapType = GoogleMap.MAP_TYPE_SATELLITE } false -> { // Switch back to NORMAL view map.mapType = GoogleMap.MAP_TYPE_NORMAL } } } val currentDestinationJson = sharedPref.getString("currentDestination", null) var currentDestination = gson.fromJson(currentDestinationJson, Destination::class.java) if(currentDestinationJson != null && !currentDestination.location.name.equals("")) { val location : LatLng = LatLng(currentDestination.location.latitudine, currentDestination.location.longitudine) googleMap?.addMarker(MarkerOptions().position(location).title(currentDestination.location.name)) googleMap?.moveCamera(CameraUpdateFactory.newLatLng(location)) } // You can also customize the map settings here, if needed googleMap.uiSettings.isZoomControlsEnabled = true googleMap.uiSettings.isMapToolbarEnabled = true // Initialize the Places API Places.initialize(requireContext(), "AIzaSyDAQk2oI8PEdrJWWYwVlcQvZSPdV74MPCs") } private var _binding: FragmentMapsBinding? = null private val binding get() = _binding!! // Declare the googleMap variable private var googleMap: GoogleMap? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentMapsBinding.inflate(inflater, container, false) val root: View = binding.root // Check for Google Play services availability val googleApiAvailability = GoogleApiAvailability.getInstance() val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(requireContext()) if (resultCode != ConnectionResult.SUCCESS) { // Google Play services are not available on this device // You can show a message to the user or take other actions Toast.makeText(requireContext(), "Google Play services not available", Toast.LENGTH_SHORT).show() } else { // Initialize the map fragment val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(callback) } return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() val currentLocationJson = sharedPref.getString("currentDestination", null) val gson = Gson() var currentLocation = gson.fromJson(currentLocationJson, Location::class.java) val currentUserJson = sharedPref.getString("currentUser", null) val currentUser = gson.fromJson(currentUserJson, User::class.java) googleMap?.let { map -> // Check the current map type when (currentUser.settings.satellite) { true -> { // Switch to SATELLITE view map.mapType = GoogleMap.MAP_TYPE_SATELLITE } false -> { // Switch back to NORMAL view map.mapType = GoogleMap.MAP_TYPE_NORMAL } } } // Initialize the Places API Places.initialize(requireContext(), "AIzaSyDAQk2oI8PEdrJWWYwVlcQvZSPdV74MPCs") // Set up autocomplete functionality val autocompleteFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment? autocompleteFragment?.setPlaceFields(listOf(Field.ID, Field.NAME, Field.LAT_LNG)) autocompleteFragment?.view?.setBackgroundColor(Color.WHITE) // Set the text color (assuming you want black text) autocompleteFragment?.setOnPlaceSelectedListener(object : PlaceSelectionListener { override fun onPlaceSelected(place: Place) { // Handle the selected place val location = place.latLng if (location != null) { // Add a marker to the selected location on the map googleMap?.addMarker(MarkerOptions().position(location).title(place.name)) googleMap?.moveCamera(CameraUpdateFactory.newLatLng(location)) name = place.name ?: "" latitudine = location.latitude longitudine = location.longitude } } override fun onError(status: com.google.android.gms.common.api.Status) { // Handle errors Toast.makeText(requireContext(), "Error: ${status.statusMessage}", Toast.LENGTH_SHORT).show() } }) binding.saveButton.setOnClickListener { val navController = findNavController() val location: Location = Location(name, latitudine, longitudine, "", "","") val locationJson = gson.toJson(location) editor.putString("currentLocation", locationJson) // Apply the changes to SharedPreferences editor.apply() // Navigate back to the previous destination navController.popBackStack() } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/location/MapsFragment.kt
711354711
package com.example.traveldiary.ui.contact_us import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ContactUsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is contact us Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/contact_us/ContactUsViewModel.kt
705075810
package com.example.traveldiary.ui.contact_us 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.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.traveldiary.R import com.example.traveldiary.databinding.FragmentContactUsBinding class ContactUsFragment : Fragment() { private var _binding: FragmentContactUsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val slideshowViewModel = ViewModelProvider(this).get(ContactUsViewModel::class.java) _binding = FragmentContactUsBinding.inflate(inflater, container, false) val root: View = binding.root binding.linkedinButton.setOnClickListener { openGoogleSite("https://www.linkedin.com/in/marian-irimia-81637b253/") // Replace with your LinkedIn URL } binding.linkedInText.setOnClickListener { openGoogleSite("https://www.linkedin.com/in/marian-irimia-81637b253/") // Replace with your LinkedIn URL } binding.githubButton.setOnClickListener { openGoogleSite("https://github.com/Irimiaz") // Replace with your LinkedIn URL } binding.githubText.setOnClickListener { openGoogleSite("https://github.com/Irimiaz") // Replace with your LinkedIn URL } binding.sendButton.setOnClickListener { val subject : String = binding.subjectText.text.toString() val content : String = binding.description.text.toString() if(subject.isEmpty()) { Toast.makeText(requireContext(), R.string.pleaseWriteTheSubject, Toast.LENGTH_SHORT).show() } else { sendEmail(subject,content) } } return root } private fun openGoogleSite(url: String) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } fun sendEmail (subject : String, content : String) { val intent: Intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) intent.putExtra(Intent.EXTRA_SUBJECT, subject) intent.putExtra(Intent.EXTRA_TEXT, content) intent.setType("message/rfc822") startActivity(Intent.createChooser(intent, "Send Email")) binding.description.text.clear() binding.subjectText.text.clear() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/contact_us/ContactUsFragment.kt
3803139142
package com.example.traveldiary.ui.register import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class RegisterViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is register Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/register/RegisterViewModel.kt
3377042262
package com.example.traveldiary.ui.register import android.content.Context 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 import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.Settings import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentRegisterBinding import com.google.gson.Gson import com.google.gson.reflect.TypeToken class RegisterFragment : Fragment() { private var _binding: FragmentRegisterBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentRegisterBinding.inflate(inflater, container, false) val root: View = binding.root val homeViewModel = ViewModelProvider(this).get(RegisterViewModel::class.java) requireActivity().actionBar?.title = "Register" val registerButton: Button = binding.registerButton registerButton.setOnClickListener { val username: String = binding.username.text.toString() val password: String = binding.password.text.toString() val mail: String = binding.email.text.toString() val fullName: String = binding.name.text.toString() val destinationList = ArrayList<Destination>() // Retrieve the current userList from SharedPreferences val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val userListJson = sharedPref.getString("userList", null) val gson = Gson() if (userListJson != null) { // Deserialize the userList from SharedPreferences val userListType = object : TypeToken<ArrayList<User>>() {}.type val userList = gson.fromJson<ArrayList<User>>(userListJson, userListType) val packageName : String = "com.example.traveldiary" val photo = Uri.parse("android.resource://$packageName/${R.mipmap.ic_launcher_round}").toString() val settings = Settings("English", false, false) val newUser = User(username, password, mail, fullName, destinationList, photo, settings) // Add the new user to the userList userList.add(newUser) // Serialize the updated userList to JSON val updatedUserListJson = gson.toJson(userList) // Save the updated userList back to SharedPreferences val editor = sharedPref.edit() editor.putString("userList", updatedUserListJson) editor.apply() // Navigate to the login screen or wherever needed findNavController().navigate(R.id.nav_login) } else { // Handle the case where userList doesn't exist in SharedPreferences // You might want to create a new userList and save it val newUserList = ArrayList<User>() val packageName : String = "com.example.traveldiary" val photo = Uri.parse("android.resource://$packageName/${R.mipmap.ic_launcher_round}").toString() val settings = Settings("English", false, false) newUserList.add(User(username, password, mail, fullName, destinationList, photo, settings)) val updatedUserListJson = gson.toJson(newUserList) val editor = sharedPref.edit() editor.putString("userList", updatedUserListJson) editor.apply() // Navigate to the login screen or wherever needed findNavController().navigate(R.id.nav_login) } } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/register/RegisterFragment.kt
2920273875
package com.example.traveldiary.ui.recycler import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestOptions import com.example.traveldiary.R // Import your app's resources import com.example.traveldiary.database.Destination class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val nameView: TextView = itemView.findViewById(R.id.destinationName) private val descriptionView: TextView = itemView.findViewById(R.id.destinationDescription) private val descriptionDate: TextView = itemView.findViewById(R.id.destinationDate) private val photo : ImageView = itemView.findViewById(R.id.destinationPhoto) fun bind(destination: Destination) { // Bind the destination data to the views nameView.text = destination.name descriptionView.text = destination.description descriptionDate.text = destination.date Glide.with(itemView) .load(destination.photo) // Replace with the actual image URL or resource ID .apply(RequestOptions().fitCenter()) // Use fitCenter to maintain aspect ratio .transition(DrawableTransitionOptions.withCrossFade()) // Add a crossfade animation .into(photo) } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/recycler/MyViewHolder.kt
1624786911
package com.example.traveldiary.ui.recycler import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.traveldiary.R // Import your app's resources import com.example.traveldiary.database.Destination // Import your Destination class class MyAdapter(private val context: Context, private val destinations: List<Destination>, private val onItemClick: (Destination) -> Unit) : RecyclerView.Adapter<MyViewHolder>() { private val sharedPreferences = context.getSharedPreferences("myPref", Context.MODE_PRIVATE) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_view, parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val destination = destinations[position] holder.bind(destination) holder.itemView.setOnClickListener { onItemClick(destination) // Pass the destination name to the callback } } override fun getItemCount(): Int { return destinations.size } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/recycler/MyAdapter.kt
2337085575
package com.example.traveldiary.ui.splash_screen import androidx.lifecycle.ViewModel class SplashScreenViewModel : ViewModel() { // TODO: Implement the ViewModel }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/splash_screen/SplashScreenViewModel.kt
3009332298
package com.example.traveldiary.ui.splash_screen import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.traveldiary.R class SplashScreenFragment : Fragment() { companion object { fun newInstance() = SplashScreenFragment() } private lateinit var viewModel: SplashScreenViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_splash_screen, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(SplashScreenViewModel::class.java) // TODO: Use the ViewModel } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/splash_screen/SplashScreenFragment.kt
1441386688
package com.example.traveldiary.ui.edit_destination import android.app.Activity import android.app.DatePickerDialog import android.content.Context import android.content.Intent import android.net.Uri import androidx.lifecycle.ViewModelProvider import android.os.Bundle import android.provider.MediaStore import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.navigation.fragment.findNavController import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.Location import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentAboutUsBinding import com.example.traveldiary.databinding.FragmentEditDestinationBinding import com.example.traveldiary.ui.about_us.AboutUsViewModel import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.json.JSONObject import java.net.URL import java.util.* import kotlin.collections.ArrayList class EditDestinationFragment : Fragment() { private var _binding: FragmentEditDestinationBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! var photo : String = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(EditDestinationViewModel::class.java) _binding = FragmentEditDestinationBinding.inflate(inflater, container, false) val root: View = binding.root val saveButton : Button = binding.saveButton val calendar = Calendar.getInstance() val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() val destinationJson = sharedPref.getString("currentDestination", "") val gson = Gson() val prevDestination: Destination = gson.fromJson(destinationJson, Destination::class.java) // Retrieve the current user from the user array val currentUserJson = sharedPref.getString("currentUser", null) var currentUser = gson.fromJson(currentUserJson, User::class.java) val typesOfTransportArray = resources.getStringArray(R.array.typesOfTransport) val searchString = prevDestination.type // Replace with the string you want to find var position = -1 for (i in typesOfTransportArray.indices) { if (typesOfTransportArray[i] == searchString) { position = i break // Exit the loop once the string is found } } binding.PlaceName.setText(prevDestination.name, TextView.BufferType.EDITABLE); binding.destinationDate.setText(prevDestination.date, TextView.BufferType.EDITABLE) binding.Description.setText(prevDestination.description, TextView.BufferType.EDITABLE) //binding.destinationType.getItemAtPosition(2).toString() val destinationTypeSpinner = root.findViewById<Spinner>(R.id.destinationType) val adapter2 = ArrayAdapter.createFromResource(requireContext(), R.array.typesOfTransport, android.R.layout.simple_spinner_item) adapter2.setDropDownViewResource(R.layout.custom_spinner_item) destinationTypeSpinner.adapter = adapter2 // Set the adapter first destinationTypeSpinner.setSelection(2, false) // Then set the selected item binding.destinationDate.setOnClickListener { // Create a DatePickerDialog to pick a date val datePickerDialog = DatePickerDialog( requireContext(), DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int -> // This callback is called when a date is selected in the dialog val selectedDate = "$dayOfMonth-${monthOfYear + 1}-$year" // Format the selected date binding.destinationDate.text = selectedDate // Set the selected date to your EditText }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) // Show the DatePickerDialog datePickerDialog.show() } binding.destinationPhoto.setOnClickListener { val intent : Intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, 3) } var type : String = "" val spinner = root.findViewById<Spinner>(R.id.destinationType) val adapter = ArrayAdapter.createFromResource( requireContext(), R.array.typesOfTransport, R.layout.custom_spinner_item ).also { adapter -> adapter.setDropDownViewResource(R.layout.custom_spinner_item) spinner.adapter = adapter spinner.setSelection(0, false) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { type = parent.getItemAtPosition(position) as String } override fun onNothingSelected(parent: AdapterView<*>) { Toast.makeText(requireContext(), "nothing selected", Toast.LENGTH_SHORT).show() } } binding.destinationLocation.setOnClickListener { findNavController().navigate(R.id.nav_location) } saveButton.setOnClickListener { var name: String = binding.PlaceName.text.toString() var description: String = binding.Description.text.toString() var date: String = binding.destinationDate.text.toString() val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() val destinationJson = sharedPref.getString("currentDestination", "") val gson = Gson() val prevDestination: Destination = gson.fromJson(destinationJson, Destination::class.java) // Retrieve the current user from the user array val currentUserJson = sharedPref.getString("currentUser", null) var currentUser = gson.fromJson(currentUserJson, User::class.java) val currentLocationJson = sharedPref.getString("currentLocation", null) var currentLocation = gson.fromJson(currentLocationJson, Location::class.java) var location : Location var finalLocation : Location? = null if(currentLocationJson == null) { location = Location(prevDestination.location.name, prevDestination.location.latitudine, prevDestination.location.longitudine, prevDestination.location.weather,prevDestination.location.temperature,prevDestination.location.humidity) } else { location = Location(currentLocation.name, currentLocation.latitudine, currentLocation.longitudine,"","","") runWeather(location) { updatedLocation -> finalLocation = updatedLocation } } // Create a new Destination if(photo.equals("")) { val packageName : String = "com.example.traveldiary" // If the user didn't select an image, assign a default photo resource val defaultPhotoUri = Uri.parse("android.resource://$packageName/${R.drawable.no_image_placeholder_svg}") photo = defaultPhotoUri.toString() } if(type.equals("")) type = prevDestination.type if(photo.equals("android.resource://com.example.traveldiary/2131230963")) photo = prevDestination.photo var newDestination : Destination if (finalLocation == null) newDestination = Destination(name, description,date, photo, type, location) else newDestination = Destination(name, description,date, photo, type, finalLocation!!) // Modify the current user's destination list if (currentUser.destinationList == null) { currentUser.destinationList = ArrayList() } val existingDestinationIndex = currentUser.destinationList?.indexOfFirst { it.name == prevDestination.name && it.date == prevDestination.date } if (existingDestinationIndex != -1) { // Update the existing destination with the new one if (existingDestinationIndex != null) { currentUser.destinationList?.set(existingDestinationIndex, newDestination) } } else { // Add the new destination if it doesn't already exist currentUser.destinationList?.add(newDestination) } // Retrieve the user list from shared preferences val userListJson = sharedPref.getString("userList", null) val userListType = object : TypeToken<List<User>>() {}.type var userList = gson.fromJson<List<User>>(userListJson, userListType) if (userList == null) { userList = ArrayList() } // Find the current user in the user array and update it userList = userList.map { if (it.username == currentUser.username) currentUser else it } // Convert the updated user array to JSON and save it back to SharedPreferences val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) // Convert the modified current user to JSON and save it back to SharedPreferences val updatedCurrentUserJson = gson.toJson(currentUser) editor.putString("currentUser", updatedCurrentUserJson) // Apply the changes to SharedPreferences editor.apply() // Navigate to the desired destination findNavController().navigate(R.id.nav_home) } return root } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && data != null) { // User selected an image, get its URI val selectedImageUri = data.data // Now you can use the selectedImageUri to store or display the selected image photo = selectedImageUri.toString() Toast.makeText(requireContext(), R.string.photoSaved , Toast.LENGTH_SHORT).show() } } private fun runWeather(location: Location, callback: (Location) -> Unit) { val APIKey = "06e89098889b09aba8ad608208ec482f" val weatherUrl: String = "https://api.openweathermap.org/data/2.5/weather?lat=${location.latitudine}&lon=${location.longitudine}&appid=$APIKey&units=metric" // Use coroutines to perform the network operation in the background runBlocking { launch(Dispatchers.IO) { try { val resultJson = URL(weatherUrl).readText() //Log.d("Weather Report", resultJson) val jsonObj = JSONObject(resultJson) val main = jsonObj.getJSONObject("main") val weather = jsonObj.getJSONArray("weather") val condition = weather.getJSONObject(0).getString("main") val temperature = main.getString("temp") + "°C" val humidity = main.getString("humidity") + "%" val out = "$condition $temperature $humidity" //Log.d("Out", out) val newLocation = Location(location.name, location.latitudine, location.longitudine, condition, temperature, humidity) callback(newLocation) } catch (e: Exception) { Log.e("Weather Error", "Error fetching weather data: ${e.message}", e) callback(location) // Handle the error } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/edit_destination/EditDestinationFragment.kt
2585232455
package com.example.traveldiary.ui.edit_destination import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class EditDestinationViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is contact us Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/edit_destination/EditDestinationViewModel.kt
1425683997
package com.example.traveldiary.ui.about_us import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.example.traveldiary.databinding.FragmentAboutUsBinding class AboutUsFragment : Fragment() { private var _binding: FragmentAboutUsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val galleryViewModel = ViewModelProvider(this).get(AboutUsViewModel::class.java) _binding = FragmentAboutUsBinding.inflate(inflater, container, false) val root: View = binding.root return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/about_us/AboutUsFragment.kt
2970453161
package com.example.traveldiary.ui.about_us import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class AboutUsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is about us Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/about_us/AboutUsViewModel.kt
1070880004
package com.example.traveldiary.ui.new_destination import android.app.Activity import android.app.Activity.RESULT_OK import android.app.DatePickerDialog import android.content.Context import android.content.Intent import android.net.Uri import androidx.lifecycle.ViewModelProvider import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.navigation.fragment.findNavController import com.example.traveldiary.MainActivity import com.example.traveldiary.R import com.example.traveldiary.database.Destination import com.example.traveldiary.database.Location import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentNewDestinationBinding import com.example.traveldiary.databinding.FragmentRegisterBinding import com.example.traveldiary.ui.register.RegisterViewModel import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.json.JSONObject import java.net.URL import java.util.* import kotlin.collections.ArrayList class NewDestinationFragment : Fragment() { private var _binding: FragmentNewDestinationBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! var photo : String = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentNewDestinationBinding.inflate(inflater, container, false) val root: View = binding.root val homeViewModel = ViewModelProvider(this).get(NewDestinationViewModel::class.java) val saveButton : Button = binding.saveButton val calendar = Calendar.getInstance() binding.destinationDate.setOnClickListener { // Create a DatePickerDialog to pick a date val datePickerDialog = DatePickerDialog( requireContext(), DatePickerDialog.OnDateSetListener { _: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int -> // This callback is called when a date is selected in the dialog val selectedDate = "$dayOfMonth-${monthOfYear + 1}-$year" // Format the selected date binding.destinationDate.text = selectedDate // Set the selected date to your EditText }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) // Show the DatePickerDialog datePickerDialog.show() } binding.destinationPhoto.setOnClickListener { val intent : Intent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, 3) } var type : String = "" val spinner = root.findViewById<Spinner>(R.id.destinationType) val adapter = ArrayAdapter.createFromResource( requireContext(), R.array.typesOfTransport, R.layout.custom_spinner_item ).also { adapter -> adapter.setDropDownViewResource(R.layout.custom_spinner_item) spinner.adapter = adapter spinner.setSelection(0, false) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>, view: View?, position: Int, id: Long ) { type = parent.getItemAtPosition(position) as String } override fun onNothingSelected(parent: AdapterView<*>) { Toast.makeText(requireContext(), "nothing selected", Toast.LENGTH_SHORT).show() } } binding.destinationLocation.setOnClickListener { findNavController().navigate(R.id.nav_location) } saveButton.setOnClickListener { val name: String = binding.PlaceName.text.toString() val description: String = binding.Description.text.toString() val date: String = binding.destinationDate.text.toString() val sharedPref = requireActivity().getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() // Retrieve the current user from the user array val currentUserJson = sharedPref.getString("currentUser", null) val gson = Gson() var currentUser = gson.fromJson(currentUserJson, User::class.java) val currentLocationJson = sharedPref.getString("currentLocation", null) var currentLocation = gson.fromJson(currentLocationJson, Location::class.java) var location : Location? = null var finalLocation : Location? = null if(currentLocation != null) { if(!currentLocation.name.isEmpty()) { location = Location(currentLocation.name, currentLocation.latitudine, currentLocation.longitudine, "", "", "") runWeather(location) { updatedLocation -> finalLocation = updatedLocation } } else { location = Location("", 0.0,0.0, "", "", "") } } else { location = Location("", 0.0,0.0, "", "", "") } // Create a new Destination if(photo.equals("")) { val packageName : String = "com.example.traveldiary" // If the user didn't select an image, assign a default photo resource val defaultPhotoUri = Uri.parse("android.resource://$packageName/${R.drawable.no_image_placeholder_svg}") photo = defaultPhotoUri.toString() } var newDestination : Destination? = null if(finalLocation == null) newDestination = Destination(name, description,date, photo, type, location) else newDestination = Destination(name, description, date, photo, type, finalLocation!!) // Modify the current user's destination list if (currentUser.destinationList == null) { currentUser.destinationList = ArrayList() } currentUser.destinationList?.add(newDestination) // Retrieve the user list from shared preferences val userListJson = sharedPref.getString("userList", null) val userListType = object : TypeToken<List<User>>() {}.type var userList = gson.fromJson<List<User>>(userListJson, userListType) if (userList == null) { userList = ArrayList() } // Find the current user in the user array and update it userList = userList.map { if (it.username == currentUser.username) currentUser else it } // Convert the updated user array to JSON and save it back to SharedPreferences val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) // Convert the modified current user to JSON and save it back to SharedPreferences val updatedCurrentUserJson = gson.toJson(currentUser) editor.putString("currentUser", updatedCurrentUserJson) // Apply the changes to SharedPreferences editor.apply() // Navigate to the desired destination findNavController().navigate(R.id.nav_home) } val backButton : Button = binding.backButton backButton.setOnClickListener { findNavController().navigate(R.id.nav_home) } return root } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && data != null) { // User selected an image, get its URI val selectedImageUri = data.data // Now you can use the selectedImageUri to store or display the selected image photo = selectedImageUri.toString() Toast.makeText(requireContext(), R.string.photoSaved, Toast.LENGTH_SHORT).show() } } private fun runWeather(location: Location, callback: (Location) -> Unit) { val APIKey = "06e89098889b09aba8ad608208ec482f" val weatherUrl: String = "https://api.openweathermap.org/data/2.5/weather?lat=${location.latitudine}&lon=${location.longitudine}&appid=$APIKey&units=metric" // Use coroutines to perform the network operation in the background runBlocking { launch(Dispatchers.IO) { try { val resultJson = URL(weatherUrl).readText() //Log.d("Weather Report", resultJson) val jsonObj = JSONObject(resultJson) val main = jsonObj.getJSONObject("main") val weather = jsonObj.getJSONArray("weather") val condition = weather.getJSONObject(0).getString("main") val temperature = main.getString("temp") + "°C" val humidity = main.getString("humidity") + "%" val out = "$condition $temperature $humidity" //Log.d("Out", out) val newLocation = Location(location.name, location.latitudine, location.longitudine, condition, temperature, humidity) callback(newLocation) } catch (e: Exception) { Log.e("Weather Error", "Error fetching weather data: ${e.message}", e) callback(location) // Handle the error } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/new_destination/NewDestinationFragment.kt
2237556319
package com.example.traveldiary.ui.new_destination import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NewDestinationViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is register Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/new_destination/NewDestinationViewModel.kt
3222639645
package com.example.traveldiary.ui.login import android.content.Context.MODE_PRIVATE import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.example.traveldiary.MainActivity import com.example.traveldiary.R import com.example.traveldiary.database.User import com.example.traveldiary.databinding.FragmentLoginBinding // Import the correct binding class import com.google.gson.Gson import com.google.gson.reflect.TypeToken class LoginFragment : Fragment() { private var _binding: FragmentLoginBinding? = null // Use FragmentLoginBinding private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val homeViewModel = ViewModelProvider(this).get(LoginViewModel::class.java) _binding = FragmentLoginBinding.inflate(inflater, container, false) // Use FragmentLoginBinding val root: View = binding.root val LoginButton : Button = binding.loginButton val RegisterButton: Button = binding.registerButton RegisterButton.setOnClickListener { // Set the action bar title (requireActivity() as AppCompatActivity).supportActionBar?.title = "Register" // Use NavController to navigate to the nav_register fragment findNavController().navigate(R.id.nav_register) } val mainActivity = activity as? MainActivity mainActivity?.supportActionBar?.setDisplayHomeAsUpEnabled(false) LoginButton.setOnClickListener { val username: String = binding.username.text.toString() val password: String = binding.password.text.toString() val sharedPref = requireActivity().getSharedPreferences("myPref", MODE_PRIVATE) val editor = sharedPref.edit() val userListJson = sharedPref.getString("userList", null) var found: Boolean = false // Check if userListJson is not null and not empty if (!userListJson.isNullOrEmpty()) { // Deserialize the userList from SharedPreferences val gson = Gson() val userListType = object : TypeToken<ArrayList<User>>() {}.type val userList = gson.fromJson<ArrayList<User>>(userListJson, userListType) // Find the user with matching credentials val currentUser = userList.find { user -> user.password == password && user.username == username } if (currentUser != null) { // Convert the current user to JSON and save it as "currentUser" in SharedPreferences val currentJson = gson.toJson(currentUser) editor.putString("currentUser", currentJson) editor.apply() found = true findNavController().navigate(R.id.nav_home) } } if (!found) { Toast.makeText(requireContext(), R.string.wrongCredentials , Toast.LENGTH_SHORT).show() } } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/login/LoginFragment.kt
2523771059
package com.example.traveldiary.ui.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class LoginViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is login Fragment" } val text: LiveData<String> = _text }
TravelDiary/app/src/main/java/com/example/traveldiary/ui/login/LoginViewModel.kt
1823662119
package com.example.traveldiary.database class Settings (language : String, nightMode : Boolean, satellite : Boolean) { var language : String = language var nightMode : Boolean = nightMode var satellite : Boolean = satellite }
TravelDiary/app/src/main/java/com/example/traveldiary/database/Settings.kt
4053830726
package com.example.traveldiary.database class Location(name: String, latitudine : Double, longitudine : Double, weather : String, temperature : String, humidity : String) { val name : String = name val latitudine : Double = latitudine val longitudine : Double = longitudine val weather : String = weather val humidity : String = humidity val temperature : String = temperature }
TravelDiary/app/src/main/java/com/example/traveldiary/database/Location.kt
3098213471
package com.example.traveldiary.database class Destination(name : String, description : String, date : String, photo : String, type : String, location : Location) { val name : String = name val description : String = description val date : String = date val photo : String = photo val type : String = type val location : Location = location }
TravelDiary/app/src/main/java/com/example/traveldiary/database/Destination.kt
4029915648
package com.example.traveldiary.database import android.net.Uri import com.example.traveldiary.R class User(username: String, password: String, mail: String, fullName: String, destinationList: ArrayList<Destination>?, photo : String, settings : Settings) { val username: String = username val password: String = password val mail: String = mail val fullName: String = fullName var photo : String = photo var destinationList: ArrayList<Destination> = destinationList?.toCollection(mutableListOf()) as ArrayList<Destination> var settings : Settings = settings }
TravelDiary/app/src/main/java/com/example/traveldiary/database/User.kt
4242381889
package com.example.traveldiary import android.content.Context import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Bundle import android.os.Handler import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.bumptech.glide.Glide import com.example.traveldiary.database.User import com.example.traveldiary.databinding.ActivityMainBinding import com.google.android.material.navigation.NavigationView import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.util.* import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding private lateinit var drawerLayout: DrawerLayout companion object { var userList = ArrayList<User>() var currentUser : User? = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.hide() val sharedPref = getSharedPreferences("myPref", MODE_PRIVATE) val currentUserJson = sharedPref.getString("currentUser", null) val editor = sharedPref.edit() val gson = Gson() if (!currentUserJson.isNullOrEmpty()) { val currentUser: User = gson.fromJson(currentUserJson, User::class.java) if (currentUser.settings.language.equals("Romanian") || currentUser.settings.language.equals("Romana")) { val locale = Locale("ro") val config = Configuration(resources.configuration) config.setLocale(locale) resources.updateConfiguration(config, resources.displayMetrics) } else { val config = Configuration(resources.configuration) config.setToDefaults() resources.updateConfiguration(config, resources.displayMetrics) } } getSupportActionBar()?.setDisplayShowTitleEnabled(false); binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) supportActionBar?.title = "Travel Diary" drawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_content_main) getActionBar()?.setDisplayShowTitleEnabled(false); // Passing each menu ID as a set of Ids because each // menu should be considered as top-level destinations. appBarConfiguration = AppBarConfiguration( setOf( R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_settings ), drawerLayout ) val userListJson = sharedPref.getString("userList", null) if (userListJson != null) { // Deserialize the JSON string into userList val gson = Gson() val userListType = object : TypeToken<List<User>>() {}.type userList = gson.fromJson(userListJson, userListType) } else { // Initialize an empty userList if no data found userList = ArrayList() } setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) drawerLayout.closeDrawer(GravityCompat.START) if (!currentUserJson.isNullOrEmpty()) { val currentUser: User = gson.fromJson(currentUserJson, User::class.java) if (currentUser.settings.nightMode) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } updateMenuItems() } private fun updateMenuItems() { val navigationView = findViewById<NavigationView>(R.id.nav_view) val menu = navigationView.menu // Find and update each menu item val homeMenuItem = menu.findItem(R.id.nav_home) homeMenuItem.title = getString(R.string.home) val aboutUsMenuItem = menu.findItem(R.id.nav_gallery) aboutUsMenuItem.title = getString(R.string.aboutUs) val contactUsMenuItem = menu.findItem(R.id.nav_slideshow) contactUsMenuItem.title = getString(R.string.contactUs) val settingsMenuItem = menu.findItem(R.id.nav_settings) settingsMenuItem.title = getString(R.string.settings) val logoutMenuItem = menu.findItem(R.id.nav_login) logoutMenuItem.title = getString(R.string.logout) val deleteAccountMenuItem = menu.findItem(R.id.nav_delete) deleteAccountMenuItem.title = getString(R.string.deleteAccount) val deleteDataMenuItem = menu.findItem(R.id.nav_delete_all) deleteDataMenuItem.title = getString(R.string.deleteAllData) // Repeat this for other menu items... } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. drawerLayout.closeDrawer(GravityCompat.START) menuInflater.inflate(R.menu.main, menu) val upButton = menu.findItem(android.R.id.home) upButton?.isVisible = false getActionBar()?.setDisplayHomeAsUpEnabled(false); getSupportActionBar()?.setDisplayHomeAsUpEnabled(false) val item = menu.findItem(R.id.action_settings) item.setVisible(false) //menu item invisible above return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle item selection based on the selected menu item's ID drawerLayout.closeDrawer(GravityCompat.START) val navController = findNavController(R.id.nav_host_fragment_content_main) val navView: NavigationView = binding.navView navView.setupWithNavController(navController) if(item.title?.equals(R.string.settings) == true) { navController.navigate(R.id.nav_settings) } val usernameHeader = findViewById<TextView>(R.id.usernameHeader) val usermailHeader = findViewById<TextView>(R.id.usermailHeader) val sharedPref = getSharedPreferences("myPref", MODE_PRIVATE) val currentJson = sharedPref.getString("currentUser", null) val userPhotoHeader = findViewById<ImageView>(R.id.userPhotoHeader) userPhotoHeader.setOnLongClickListener { view -> val popupMenu = PopupMenu(this, view) // Pass the context and the view popupMenu.menuInflater.inflate(R.menu.popitem, popupMenu.menu) // Define your menu items in XML (res/menu/popup_menu.xml) // Set a click listener for the items in the popup menu popupMenu.setOnMenuItemClickListener { item -> val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(galleryIntent, 100) true } popupMenu.show() true // Return true to consume the event } if (currentJson != null) { val gson = Gson() val currentUser = gson.fromJson(currentJson, User::class.java) usernameHeader.text = currentUser.fullName usermailHeader.text = currentUser.mail // Load the user's photo using Glide Glide.with(this) .load(Uri.parse(currentUser.photo)) .into(userPhotoHeader) } else { } navView.setNavigationItemSelectedListener { item -> when (item.itemId) { R.id.nav_settings -> { navController.navigate(R.id.nav_settings) } R.id.nav_login -> { val builder = AlertDialog.Builder(this) // Set the dialog title and message builder.setTitle(R.string.sureQuestion) .setMessage(R.string.logoutQuestion) // Add "Yes" button builder.setPositiveButton(R.string.yes) { _, _ -> // User clicked "Yes," navigate to the login screen navController.navigate(R.id.nav_login) val preferences = getSharedPreferences("myPref", 0) preferences.edit().remove("currentDestination").commit() val sharedPref = getSharedPreferences("myPref", Context.MODE_PRIVATE) val editor = sharedPref.edit() val gson = Gson() val userListJson = sharedPref.getString("userList", null) val currentUserJson = sharedPref.getString("currentUser", null) val currentUser = gson.fromJson(currentUserJson, User::class.java) val userListType = object : TypeToken<List<User>>() {}.type var userList = gson.fromJson<List<User>>(userListJson, userListType) if (userList == null) { userList = ArrayList() } // Find the current user in the user array and update it userList = userList.map { if (it.username == currentUser.username) currentUser else it } // Convert the updated user array to JSON and save it back to SharedPreferences val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) // Convert the modified current user to JSON and save it back to SharedPreferences val updatedCurrentUserJson = gson.toJson(currentUser) editor.putString("currentUser", updatedCurrentUserJson) // Apply the changes to SharedPreferences editor.apply() } // Add "No" button builder.setNegativeButton(R.string.no) { _, _ -> // User clicked "No," do nothing or handle it as needed // For example, you can dismiss the dialog or perform another action } // Create and show the AlertDialog val dialog = builder.create() dialog.show() } R.id.nav_delete -> { val builder = AlertDialog.Builder(this) // Set the dialog title and message builder.setTitle(R.string.sureQuestion) .setMessage(R.string.deleteAccountQuestion) // Add "Yes" button builder.setPositiveButton(R.string.yes) { _, _ -> // User clicked "Yes," perform the delete action here val sharedPref = getSharedPreferences("myPref", MODE_PRIVATE) val currentJson = sharedPref.getString("currentUser", null) val userListJson = sharedPref.getString("userList", null) // Check if there is a valid user object in SharedPreferences val gson = Gson() val currentUser = gson.fromJson(currentJson, User::class.java) if (userListJson != null) { val userListType = object : TypeToken<List<User>>() {}.type val userList: MutableList<User> = gson.fromJson(userListJson, userListType) // Find the current user in the userList val currentUserInList = getUserByUsernameAndPassword(currentUser.username, currentUser.password, userList) if (currentUserInList != null) { // Remove the user from the userList userList.remove(currentUserInList) // Update the userList in SharedPreferences val editor = sharedPref.edit() val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) editor.apply() // Display a Toast message Toast.makeText(this, R.string.accountDeleted, Toast.LENGTH_SHORT).show() // Navigate to the login screen or perform any other desired action navController.navigate(R.id.nav_login) // Remove the "currentUser" key from SharedPreferences editor.remove("currentUser") editor.remove("currentDestination") editor.apply() } } } // Add "No" button builder.setNegativeButton(R.string.no) { _, _ -> // User clicked "No," do nothing or handle it as needed // For example, you can dismiss the dialog or perform another action } // Create and show the AlertDialog val dialog = builder.create() dialog.show() } R.id.nav_delete_all -> { // Create a dialog to prompt for the password val builder = AlertDialog.Builder(this) // Use the appropriate context // Inflate the password input layout val inflater = layoutInflater val dialogView = inflater.inflate(R.layout.delete_all, null) builder.setView(dialogView) val passwordEditText = dialogView.findViewById<EditText>(R.id.passwordEditText) val submitButton = dialogView.findViewById<Button>(R.id.submitButton) // Create the dialog val dialog = builder.create() // Set up the "Submit" button click listener submitButton.setOnClickListener { val enteredPassword = passwordEditText.text.toString() // Check if the entered password is correct (replace "your_password" with the actual password) val correctPassword = "test" if (enteredPassword == correctPassword) { // Password is correct, show a Toast message Toast.makeText(this, R.string.dataDeleted, Toast.LENGTH_SHORT).show() // Dismiss the dialog dialog.dismiss() // Perform the action you want when the password is correct // For example, show a specific view or perform a delete operation here navController.navigate(R.id.nav_login) val preferences = getSharedPreferences("myPref", 0) preferences.edit().remove("currentUser").commit() preferences.edit().remove("userList").commit() preferences.edit().remove("currentDestination").commit() } else { // Password is incorrect, show a Toast message Toast.makeText(this, R.string.incorrectPassword, Toast.LENGTH_SHORT).show() } } // Show the dialog dialog.show() } } navigate(item) } return super.onOptionsItemSelected(item) } private fun getUserByUsernameAndPassword(username: String, password: String, userList: List<User>): User? { for (user in userList) { if (user.username == username && user.password == password) { return user } } Toast.makeText(this, R.string.noUserFound, Toast.LENGTH_SHORT).show() return null } fun navigate(item: MenuItem): Boolean { drawerLayout.closeDrawer(GravityCompat.START) val navController = findNavController(R.id.nav_host_fragment_content_main) val navView: NavigationView = binding.navView navView.setupWithNavController(navController) when (item.itemId) { R.id.nav_new_destination -> { navController.navigate(R.id.nav_new_destination) return true } R.id.nav_home -> { navController.navigate(R.id.nav_home) val test = userList val test2 = currentUser return true } R.id.nav_gallery -> { navController.navigate(R.id.nav_gallery) return true } R.id.nav_slideshow -> { navController.navigate(R.id.nav_slideshow) return true } else -> { return super.onOptionsItemSelected(item) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 100 && resultCode == RESULT_OK && data != null) { val selectedImageUri: Uri? = data.data if (selectedImageUri != null) { // Load the selected image into the userPhotoHeader ImageView val sharedPref = getSharedPreferences("myPref", MODE_PRIVATE) val currentJson = sharedPref.getString("currentUser", null) // Check if there is a valid user object in SharedPreferences if (currentJson != null) { val gson = Gson() val currentUser = gson.fromJson(currentJson, User::class.java) // Update the user's photo property currentUser.photo = selectedImageUri.toString() // Save the updated user object back to SharedPreferences val editor = sharedPref.edit() val updatedJson = gson.toJson(currentUser) editor.putString("currentUser", updatedJson) val userListJson = sharedPref.getString("userList", null) val userListType = object : TypeToken<List<User>>() {}.type var userList = gson.fromJson<List<User>>(userListJson, userListType) if (userList == null) { userList = ArrayList() } // Find the current user in the user array and update it userList = userList.map { if (it.username == currentUser.username) currentUser else it } val updatedUserListJson = gson.toJson(userList) editor.putString("userList", updatedUserListJson) editor.apply() val userPhotoHeader = findViewById<ImageView>(R.id.userPhotoHeader) // Load the selected image into the userPhotoHeader ImageView using Glide Glide.with(this) .load(selectedImageUri) .into(userPhotoHeader) } } } } override fun onSupportNavigateUp(): Boolean { drawerLayout.closeDrawer(GravityCompat.START) val navController = findNavController(R.id.nav_host_fragment_content_main) getActionBar()?.setDisplayHomeAsUpEnabled(false); return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
TravelDiary/app/src/main/java/com/example/traveldiary/MainActivity.kt
157805207
package com.example.bragoproject 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.bragoproject", appContext.packageName) } }
BragoApplication/app/src/androidTest/java/com/example/bragoproject/ExampleInstrumentedTest.kt
1013250670
package com.example.bragoproject 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) } }
BragoApplication/app/src/test/java/com/example/bragoproject/ExampleUnitTest.kt
2306246319