content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
import kotlin.math.max import kotlin.math.min class Solution { fun solution(sizes: Array<IntArray>): Int { var w=0; var h=0; sizes.forEach { var maxEle=max(it[0],it[1]) var minEle= min(it[0],it[1]) w= max(w, maxEle) h= max(h,minEle) } return w*h } }
sparta/프로그래머스/1/86491. 최소직사각형/최소직사각형.kt
3640194691
class Solution { fun solution(food: IntArray): String { var answer: String = "" for(i in 1 until food.size) { repeat((food[i]/2)){answer+=i.toString()} } return answer+"0"+answer.reversed() } }
sparta/프로그래머스/1/134240. 푸드 파이트 대회/푸드 파이트 대회.kt
3535323475
class Solution { fun solution(n: Int, m: Int)= intArrayOf(gcd(n,m), n*m/gcd(n,m)) private tailrec fun gcd(n: Int, m: Int):Int=if(m<=0) n else gcd(m, n%m) }
sparta/프로그래머스/1/12940. 최대공약수와 최소공배수/최대공약수와 최소공배수.kt
3993345133
class Solution { fun solution(x: Int, n: Int)= LongArray(n){(it+1.toLong())*x.toLong()} }
sparta/프로그래머스/1/12954. x만큼 간격이 있는 n개의 숫자/x만큼 간격이 있는 n개의 숫자.kt
2259908110
class Solution { fun solution(n: Long)= IntArray(n.toString().length){(n.toString().reversed())[it].digitToInt()} }
sparta/프로그래머스/1/12932. 자연수 뒤집어 배열로 만들기/자연수 뒤집어 배열로 만들기.kt
3150605521
class Solution { fun solution(k: Int, m: Int, score: IntArray): Int { var answer: Int = 0 score.sortDescending() for(i in score.indices) { if((i+1)%m==0) answer+=score[i]*m } return answer } }
sparta/프로그래머스/1/135808. 과일 장수/과일 장수.kt
3198737782
class Solution { fun solution(n: Int)=(1..n).filter { n%it==0 }.sum() }
sparta/프로그래머스/1/12928. 약수의 합/약수의 합.kt
4289673373
class Solution { private fun isPrime(n: Int):Boolean = (2..n / 2).count { n%it==0 }==0 fun solution(nums: IntArray): Int { var answer = 0 for(i in nums.indices) for(j in i+1 until nums.size) for(n in j+1 until nums.size) if(isPrime(nums[i]+nums[j]+nums[n]))answer++ return answer } }
sparta/프로그래머스/1/12977. 소수 만들기/소수 만들기.kt
318055195
class Solution { fun solution(price: Int, money: Int, count: Int): Long { var answer: Long = 0 var arr=Array<Int>(count){i-> price*(i+1)} arr.forEach { answer+=it.toLong() } return if(money-answer>0L) 0L else answer-money } }
sparta/프로그래머스/1/82612. 부족한 금액 계산하기/부족한 금액 계산하기.kt
3060463957
class Solution { fun solution(s: String, skip: String, index: Int): String { val alpha = ('a'..'z').map { it }.toTypedArray() var answer: String = "" s.forEach{ var loop=1 var cnt=0 while (cnt!=index) { val tk=alpha[(alpha.indexOf(it)+loop++)%(alpha.size)] if(tk !in skip) { cnt++ } } answer+=alpha[(alpha.indexOf(it)+loop-1)%alpha.size] } return answer } }
sparta/프로그래머스/1/155652. 둘만의 암호/둘만의 암호.kt
2667734715
package com.example.luckynumber 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.luckynumber", appContext.packageName) } }
android-kotlin-LuckyNumApp/app/src/androidTest/java/com/example/luckynumber/ExampleInstrumentedTest.kt
1570244741
package com.example.luckynumber 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) } }
android-kotlin-LuckyNumApp/app/src/test/java/com/example/luckynumber/ExampleUnitTest.kt
2702732788
package com.example.luckynumber.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)
android-kotlin-LuckyNumApp/app/src/main/java/com/example/luckynumber/ui/theme/Color.kt
2218319724
package com.example.luckynumber.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 LuckyNumberTheme( 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 ) }
android-kotlin-LuckyNumApp/app/src/main/java/com/example/luckynumber/ui/theme/Theme.kt
1582595625
package com.example.luckynumber.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 ) */ )
android-kotlin-LuckyNumApp/app/src/main/java/com/example/luckynumber/ui/theme/Type.kt
1769871859
package com.example.luckynumber import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.luckynumber.ui.theme.LuckyNumberTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val b1 :Button = findViewById(R.id.wishBtn) // val welTxt: TextView = findViewById(R.id.welTxt) val etText : EditText = findViewById(R.id.etTxt) b1.setOnClickListener(){ val userName = etText.text val i = Intent(this, LuckyNumberActivity::class.java) i.putExtra("name", userName) startActivity(i) } } }
android-kotlin-LuckyNumApp/app/src/main/java/com/example/luckynumber/MainActivity.kt
2940512863
package com.example.luckynumber import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.activity.ComponentActivity import kotlin.random.Random class LuckyNumberActivity : ComponentActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lucky_number) // val resTxt : TextView = findViewById(R.id.resTxt) val luckyTxt:TextView =findViewById(R.id.LuckyTxtNum) val shareBtn : Button = findViewById(R.id.shareBtn) val user_name = recveUserName() val random_num = generateRandomNum() luckyTxt.setText(" "+random_num) shareBtn.setOnClickListener(){ shareData(user_name, random_num) } } fun recveUserName():String{ val bundle:Bundle? = intent.extras val usrName = bundle?.get("name").toString() return usrName } fun generateRandomNum():Int{ val random = Random.nextInt(1000) return random } fun shareData(username: String, num: Int){ val i = Intent(Intent.ACTION_SEND) i.setType("text/plain") i.putExtra(Intent.EXTRA_SUBJECT, "$username is lucky today") i.putExtra(Intent.EXTRA_TEXT, "Lucky number is $num") startActivity(i) } }
android-kotlin-LuckyNumApp/app/src/main/java/com/example/luckynumber/LuckyNumberActivity.kt
1023987539
package com.example.firebase_databaseproject 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.firebase_databaseproject", appContext.packageName) } }
firebase-android-connection/app/src/androidTest/java/com/example/firebase_databaseproject/ExampleInstrumentedTest.kt
1957672794
package com.example.firebase_databaseproject 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) } }
firebase-android-connection/app/src/test/java/com/example/firebase_databaseproject/ExampleUnitTest.kt
1425355770
package com.example.firebase_databaseproject import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Patterns import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.AuthResult import com.google.firebase.database.FirebaseDatabase class RegistrasiAct : AppCompatActivity() { private val PASSWORD_PATTERN = Regex( "^(?=.*[0-9])" + //paling sedikit 1 digit "(?=.*[a-z])" + //paling sedikit 1 lowercase karakter "(?=.*[A-Z])" + //paling sedikit 1 upercase karakter "(?=.*[@#$%^&+=])" + //paling sedikit 1 spesial karakter "(?=.*[\\s+$])." + //tanpa spasi "{6,}" + //paling sedikit 6 upercase karakter "$" ) private lateinit var inputEmail: EditText private lateinit var inputPassword: EditText private lateinit var inputNama: EditText private lateinit var inputTanggal: EditText private lateinit var inputjnsKelamin: EditText private lateinit var inputNoTelepon: EditText private lateinit var auth: FirebaseAuth private lateinit var progressBar: ProgressBar private lateinit var btnRegis: Button private lateinit var login: TextView @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registrasi) auth = FirebaseAuth.getInstance() inputNama = findViewById(R.id.nama1) inputTanggal = findViewById(R.id.tanggal1) inputjnsKelamin = findViewById(R.id.jnsKelamin1) inputNoTelepon = findViewById(R.id.noTelepon) inputEmail = findViewById(R.id.email1) inputPassword = findViewById(R.id.password1) progressBar = findViewById(R.id.progressBar1) btnRegis = findViewById(R.id.btn_register) btnRegis.setOnClickListener { val nama = inputNama.text.toString() val tgl = inputTanggal.text.toString() val jk = inputjnsKelamin.text.toString() val noHp = inputNoTelepon.text.toString() val email = inputEmail.text.toString() val password = inputPassword.text.toString() if (TextUtils.isEmpty(nama)) { Toast.makeText(applicationContext, "Masukan nama", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (!nama.matches("[a-zA-Z]+".toRegex())) { Toast.makeText(applicationContext, "Masukan hanya alfabet", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (TextUtils.isEmpty(tgl)) { Toast.makeText(applicationContext, "Masukan tanggal lahir", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (!tgl.matches("\\d{4}-\\d{2}-\\d{2}".toRegex())) { Toast.makeText( applicationContext, "Masukan hanya angka format YYYY-MM-DD", Toast.LENGTH_SHORT ).show() return@setOnClickListener } if (TextUtils.isEmpty(jk)) { Toast.makeText(applicationContext, "Masukan jenis kelamin", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (!jk.matches("(?:pria|Pria|wanita|Wanita|PRIA|WANITA|Not prefer to say)$".toRegex())) { Toast.makeText( applicationContext, "Masukan hanya alfabet format pria/wanita/PRIA/WANITA/", Toast.LENGTH_SHORT ).show() return@setOnClickListener } if (TextUtils.isEmpty(noHp)) { Toast.makeText(applicationContext, "Masukan nomor telepon", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (!noHp.matches("^[+][0-9]{10,13}$".toRegex())) { Toast.makeText( applicationContext, "Masukan hanya angka format +62xxxxxxxxxxx", Toast.LENGTH_SHORT ).show() return@setOnClickListener } if (TextUtils.isEmpty(email)) { Toast.makeText(applicationContext, "Masukan email", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { Toast.makeText(applicationContext, "Masukan email dengan valid", Toast.LENGTH_SHORT) .show() return@setOnClickListener } if (TextUtils.isEmpty(password)) { Toast.makeText(applicationContext, "Masukan password", Toast.LENGTH_SHORT).show() return@setOnClickListener } else if (password.length < 6) { Toast.makeText( applicationContext, "Password harus lebih dari 6 karakter", Toast.LENGTH_SHORT ).show() return@setOnClickListener } progressBar.visibility = View.VISIBLE auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this@RegistrasiAct) { task -> progressBar.visibility = View.GONE if (task.isSuccessful){ val firebaseUser = FirebaseAuth.getInstance().currentUser FirebaseDatabase.getInstance().getReference("Pengguna/" + FirebaseAuth.getInstance().currentUser!!.uid). setValue(Users(inputNama.text.toString(), inputTanggal.text.toString(), inputjnsKelamin.text.toString(), inputNoTelepon.text.toString(), inputEmail.text.toString(), inputPassword.text.toString())) Toast.makeText(applicationContext, "Registrasi berhasil", Toast.LENGTH_SHORT).show() startActivity(Intent(applicationContext, LoginAct::class.java)) } else{ Toast.makeText( this@RegistrasiAct,"maaf registrasi gagal", Toast.LENGTH_SHORT ).show() } } } login = findViewById(R.id.textLogin) login.setOnClickListener { startActivity(Intent(applicationContext, LoginAct::class.java)) } } }
firebase-android-connection/app/src/main/java/com/example/firebase_databaseproject/RegistrasiAct.kt
1857795845
package com.example.firebase_databaseproject import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth class MainActivity : AppCompatActivity() { val auth: FirebaseAuth = FirebaseAuth.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (FirebaseAuth.getInstance().currentUser == null) { startActivity(Intent(applicationContext, LoginAct::class.java)) } else { Toast.makeText( this, "Haloo ${FirebaseAuth.getInstance().currentUser?.email}", Toast.LENGTH_SHORT ).show() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.logout) { auth.signOut() startActivity(Intent(applicationContext, LoginAct::class.java)) return true } return super.onOptionsItemSelected(item) } }
firebase-android-connection/app/src/main/java/com/example/firebase_databaseproject/MainActivity.kt
554150525
package com.example.firebase_databaseproject import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.AuthResult import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task class LoginAct : AppCompatActivity() { private lateinit var inputEmail: EditText private lateinit var inputPassword: EditText private lateinit var auth: FirebaseAuth private lateinit var progressBar: ProgressBar private lateinit var btnLogin: Button private lateinit var register: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) register = findViewById(R.id.textRegister) register.setOnClickListener { startActivity(Intent(applicationContext, RegistrasiAct::class.java)) } auth = FirebaseAuth.getInstance() if (auth.currentUser != null) { startActivity(Intent(this@LoginAct, MainActivity::class.java)) finish() } inputEmail = findViewById(R.id.email) inputPassword = findViewById(R.id.password) progressBar = findViewById(R.id.progressBar) btnLogin = findViewById(R.id.btn_login) btnLogin.setOnClickListener { val email = inputEmail.text.toString() val password = inputPassword.text.toString() if (TextUtils.isEmpty(email)) { Toast.makeText(applicationContext, "Masukan email", Toast.LENGTH_SHORT).show() return@setOnClickListener } if (TextUtils.isEmpty(password)) { Toast.makeText(applicationContext, "Masukan password", Toast.LENGTH_SHORT).show() return@setOnClickListener } progressBar.visibility = View.VISIBLE auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this@LoginAct, OnCompleteListener<AuthResult> { task -> progressBar.visibility = View.GONE if (!task.isSuccessful) { if (password.length < 6) { inputPassword.error = "password harus 6 karakter" } else { Toast.makeText(this@LoginAct, "maaf login gagal", Toast.LENGTH_SHORT).show() } } else { val intent = Intent(this@LoginAct, MainActivity::class.java) startActivity(intent) finish() } }) } } }
firebase-android-connection/app/src/main/java/com/example/firebase_databaseproject/LoginAct.kt
1211750063
package com.example.firebase_databaseproject class Users { var inputNama: String? = null var inputTanggal: String? = null var inputjnsKelamin: String? = null var inputNoTelepon: String? = null var inputEmail: String? = null var inputPassword: String? = null constructor(){} constructor( inputNama: String?, inputTanggal: String?, inputjnsKelamin: String?, inputNoTelepon: String?, inputEmail: String?, inputPassword: String? ) { this.inputNama = inputNama this.inputTanggal = inputTanggal this.inputjnsKelamin = inputjnsKelamin this.inputNoTelepon = inputNoTelepon this.inputEmail = inputEmail this.inputPassword = inputPassword } }
firebase-android-connection/app/src/main/java/com/example/firebase_databaseproject/Users.kt
2536103568
package com.example.rental_app 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.rental_app", appContext.packageName) } }
Rentalapp/app/src/androidTest/java/com/example/rental_app/ExampleInstrumentedTest.kt
1219529246
package com.example.rental_app 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) } }
Rentalapp/app/src/test/java/com/example/rental_app/ExampleUnitTest.kt
283515300
package com.example.rental_app import android.Manifest import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.view.isVisible import androidx.recyclerview.widget.GridLayoutManager import android.content.SharedPreferences import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import com.example.rental_app.activities.LocalResultsActivity import com.example.rental_app.activities.LoginActivity import com.example.rental_app.activities.MyListingsActivity import com.example.rental_app.activities.MyShortlistingsActivity import com.example.rental_app.activities.PostRentalActivity import com.example.rental_app.activities.RegistrationActivity import com.example.rental_app.activities.ResultsActivity import com.example.rental_app.adapters.CitiesAdaptor import com.example.rental_app.databinding.ActivityMainBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import kotlinx.coroutines.launch import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding lateinit var sharedPreferences: SharedPreferences lateinit var prefEditor: SharedPreferences.Editor private lateinit var firebaseAuth: FirebaseAuth private var allPermissionsGrantedTracker = true private lateinit var fusedLocationClient: FusedLocationProviderClient private val APP_PERMISSIONS_LIST = arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE ) private val multiplePermissionsResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { resultsList -> Log.d("getMultiplePermissions", resultsList.toString()) for (item in resultsList.entries) { if (item.key in APP_PERMISSIONS_LIST && item.value == false) { allPermissionsGrantedTracker = false } } if (allPermissionsGrantedTracker == true) { var snackbar = Snackbar.make(binding.root, "All permissions granted", Snackbar.LENGTH_LONG) snackbar.show() // getDeviceLocation() } else { var snackbar = Snackbar.make(binding.root, "Some permissions NOT granted", Snackbar.LENGTH_LONG) snackbar.show() handlePermissionDenied() } } private fun getDeviceLocation() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) return } fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // Got last known location. In some rare situations this can be null. if (location === null) { Log.d("getLocation", "Location is null") return@addOnSuccessListener } // Output the location val message = "The device is located at: ${location.latitude}, ${location.longitude}" // binding.test.text = "${location.latitude},${location.longitude}" } } private fun handlePermissionDenied() { // output the rationale // disable the get device location button // binding.test.setText("Sorry, you need to give us permissions before we can get your location. Check your settings menu and update your location permissions for this app.") // disable the button multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) // binding.btnGetDeviceLocation.isEnabled = false } val citiesList = listOf<String>("Toronto","Calgary","Ottawa","Regina") val TAG = "mainactivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.binding = ActivityMainBinding.inflate(layoutInflater) setContentView(this.binding.root) this.binding.register.setOnClickListener{registerClickHandler()} this.binding.postRental.setOnClickListener { postrentalClickHandler() } this.binding.login.setOnClickListener { loginClickHandler() } this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) prefEditor = this.sharedPreferences.edit() this.firebaseAuth = FirebaseAuth.getInstance() setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) binding.searchButton.setOnClickListener { if(binding.search.text.toString().isNullOrEmpty()){ binding.searchError.isVisible = true return@setOnClickListener } SearchResults(binding.search.text.toString()) } binding.nearByProperty.setOnClickListener { multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) if(allPermissionsGrantedTracker == true){ SearchResultsNearMe() } } var adapter: CitiesAdaptor = CitiesAdaptor(citiesList, {pos -> buttonClicked(pos) }) binding.rvCities.adapter = adapter binding.rvCities.layoutManager = GridLayoutManager(this, 2) } override fun onResume() { super.onResume() binding.searchError.isVisible = false } fun SearchResults(searchval:String){ val ResultsIntent = Intent(this@MainActivity, ResultsActivity::class.java) ResultsIntent.putExtra("SEARCH_VAL",searchval) startActivity(ResultsIntent) } fun SearchResultsNearMe(){ val NearByResultsIntent = Intent(this@MainActivity, LocalResultsActivity::class.java) startActivity(NearByResultsIntent) } fun buttonClicked(position:Int){ SearchResults(citiesList.get(position)) } private fun registerClickHandler() { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") if(loggedInUser == "") { val registerIntent = Intent(this, RegistrationActivity::class.java) startActivity(registerIntent) } else { Snackbar.make(binding.root, "Already Logged In.", Snackbar.LENGTH_LONG).show() } } private fun postrentalClickHandler() { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") if(loggedInUser != "") { val postrentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postrentalIntent) } else { startActivity(Intent(this, LoginActivity::class.java)) } } private fun loginClickHandler() { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") if(loggedInUser == "") { val loginIntent = Intent(this, LoginActivity::class.java) startActivity(loginIntent) } else { Snackbar.make(binding.root, "Already Logged In.", Snackbar.LENGTH_LONG).show() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") return when(item.itemId){ R.id.menuMyListings -> { if(loggedInUser != ""){ val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuPostRental -> { if(loggedInUser != ""){ val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, LoginActivity::class.java)) return true } R.id.menuHome -> { return true } R.id.menuShortList -> { if(loggedInUser != ""){ startActivity(Intent(this, MyShortlistingsActivity::class.java)) }else{ startActivity(Intent(this, LoginActivity::class.java)) } startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } }
Rentalapp/app/src/main/java/com/example/rental_app/MainActivity.kt
1610223218
package com.example.rental_app.repositories import android.content.Context import android.util.Log import com.google.firebase.Firebase import com.google.firebase.firestore.firestore import com.example.rental_app.models.User import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.toObject import com.google.gson.Gson import kotlinx.coroutines.tasks.await class UserRepository(private val context: Context) { private val TAG = this.toString(); //get an instance of firestore database private val db = Firebase.firestore private val COLLECTION_USERS = "Users" private val FIELD_FIRST_NAME = "firstName" private val FIELD_LAST_NAME = "lastName" private val FIELD_EMAIL = "email" private val FIELD_PHONE_NUMBER = "phoneNumber" private val FIELD_PASSWORD = "password" private val FIELD_FAVOURITES = "shortListing" private val FIELD_LISTINGS = "listings" val gson = Gson() fun addUserToDB(newUser: User) { try { val data: MutableMap<String, Any> = HashMap() data[FIELD_EMAIL] = newUser.email data[FIELD_FIRST_NAME] = newUser.firstName data[FIELD_LAST_NAME] = newUser.lastName data[FIELD_PHONE_NUMBER] = newUser.phoneNumber data[FIELD_PASSWORD] = newUser.password data[FIELD_FAVOURITES] = newUser.shortListing data[FIELD_LISTINGS] = newUser.listings db.collection(COLLECTION_USERS) .document(newUser.email) .set(data) .addOnSuccessListener { docRef -> Log.d(TAG, "addUserToDB: New user document created with ID: $docRef") } .addOnFailureListener{ex -> Log.d(TAG, "addUserToDB: Unable to create user document. Error: $ex") } } catch (ex : java.lang.Exception) { Log.e(TAG, "addUserToDB: Unable to create user : $ex", ) } } suspend fun getLoggedInUser(userEmail: String?): User? { if(!userEmail.isNullOrEmpty()) { val userRef = db.collection(COLLECTION_USERS).document(userEmail) return try { val documentSnapshot = userRef.get().await() if(documentSnapshot.exists()) { val userData = documentSnapshot.toObject(User::class.java) userData } else { null } } catch (ex: java.lang.Exception) { Log.e(TAG, "getLoggedInUser: Unable to get user : $ex",) null } } return null } suspend fun getLoggedByEmail(userEmail: String?): User? { if(!userEmail.isNullOrEmpty()) { val userRef = db.collection(COLLECTION_USERS).document(userEmail) return try { val documentSnapshot = userRef.get().await() if(documentSnapshot.exists()) { val userData = documentSnapshot.toObject(User::class.java) userData } else { null } } catch (ex: java.lang.Exception) { Log.e(TAG, "getLoggedInUser: Unable to get user : $ex",) null } } return null } }
Rentalapp/app/src/main/java/com/example/rental_app/repositories/UserRepository.kt
2800129653
package com.example.rental_app.repositories import android.content.Context import android.content.SharedPreferences import android.location.Location import android.util.Log import androidx.lifecycle.MutableLiveData import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.google.firebase.Firebase import com.google.firebase.firestore.DocumentChange import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FieldPath import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.firestore import com.mapbox.geojson.Point import kotlinx.coroutines.tasks.await class PropertiesRepository(private val context: Context) { private var sharedPrefs: SharedPreferences = context.getSharedPreferences("MY_APP_PREFS", Context.MODE_PRIVATE) private var loggedInUserEmail = "" private val COLLECTION_USERS = "Users" private val COLLECTION_PROPERTIES = "Listings" private val FIELD_ID = "id" private val FIELD_USER = "user" private val FIELD_PROPERTY_TYPE = "propertyType" private val FIELD_BEDROOMS = "bedrooms" private val FIELD_KITCHEN = "kitchen" private val FIELD_BATHROOMS = "bathroom" private val FIELD_DESCRIPTION = "description" private val FIELD_ADDRESS = "address" private val FIELD_IS_AVAILABLE = "isAvailable" private val FIELD_BUILDING_NAME = "buildingName" private val FIELD_POSTAL_CODE = "postalCode" private val FIELD_PROVINCE = "province" private val FIELD_CITY = "city" private val FIELD_IMG = "img" private val FIELD_RENT = "rent" private val FIELD_PHONE_NUMBER = "phoneNumber" private val FIELD_COORDINATES = "coordinates" var allListings: MutableLiveData<List<Listings>> = MutableLiveData<List<Listings>>() var shortListings: MutableLiveData<List<Listings>> = MutableLiveData<List<Listings>>() var filteredResultsByName: MutableLiveData<List<Listings>> = MutableLiveData<List<Listings>>() var filteredResultByLocation: MutableLiveData<List<Listings>> = MutableLiveData<List<Listings>>() init { if(sharedPrefs.contains("USER_EMAIL")) { loggedInUserEmail = sharedPrefs.getString("USER_EMAIL", "NA").toString() } } private val TAG = this.toString() private val db = Firebase.firestore fun addPropertyToDB(newProperty: Listings) { if(loggedInUserEmail.isNotEmpty()) { try { val data: MutableMap<String, Any> = HashMap() data[FIELD_ID] = newProperty.id data[FIELD_USER] = newProperty.owner data[FIELD_PROPERTY_TYPE] = newProperty.propertyType data[FIELD_BEDROOMS] = newProperty.bedrooms data[FIELD_KITCHEN] = newProperty.kitchen data[FIELD_BATHROOMS] = newProperty.bathroom data[FIELD_DESCRIPTION] = newProperty.description data[FIELD_ADDRESS] = newProperty.address data[FIELD_IS_AVAILABLE] = newProperty.isAvailable data[FIELD_BUILDING_NAME] = newProperty.buildingName data[FIELD_POSTAL_CODE] = newProperty.postalCode data[FIELD_PROVINCE] = newProperty.province data[FIELD_CITY] = newProperty.city data[FIELD_IMG] = newProperty.img data[FIELD_RENT] = newProperty.rent data[FIELD_PHONE_NUMBER] = newProperty.phoneNumber data[FIELD_COORDINATES] = newProperty.coordinates db.collection(COLLECTION_PROPERTIES) .add(data) .addOnSuccessListener {docRef -> Log.d(TAG, "addPropertyToDB: Document successfully added with ID : ${docRef}") updateUserListings(loggedInUserEmail, docRef.id) } .addOnFailureListener { ex -> Log.e(TAG, "addPropertyToDB: Exception occurred while adding a document : $ex", ) } } catch (ex : java.lang.Exception) { Log.e(TAG, "addPropertyToDB: Unable to create listing : $ex", ) } } } private fun updateUserListings(userEmail: String = loggedInUserEmail, listingId: String) { if(loggedInUserEmail.isNotEmpty()) { try { val userRef = db.collection(COLLECTION_USERS).document(userEmail) userRef.update("listings", FieldValue.arrayUnion(listingId)) } catch (ex : java.lang.Exception) { Log.e(TAG, "updateUserListings: Unable to create listing : $ex", ) } } } fun updateUserFavourites(userEmail: String? = loggedInUserEmail, listingId: String?) { if(loggedInUserEmail.isNotEmpty() && !userEmail.isNullOrEmpty()) { try { val userRef = db.collection(COLLECTION_USERS).document(userEmail) userRef.update("shortListing", FieldValue.arrayUnion(listingId)) } catch (ex : java.lang.Exception) { Log.e(TAG, "updateUserListings: Unable to update user listing : $ex", ) } } } fun removeUserFavourites(userEmail: String? = loggedInUserEmail, listingId: String?) { if(loggedInUserEmail.isNotEmpty() && !userEmail.isNullOrEmpty()) { try { val userRef = db.collection(COLLECTION_USERS).document(userEmail) userRef.update("shortListing", FieldValue.arrayRemove(listingId)) } catch (ex : java.lang.Exception) { Log.e(TAG, "updateUserListings: Unable to update user listing : $ex", ) } } } fun getUserListings(listingIds: MutableList<String>?) { if(!listingIds.isNullOrEmpty()) { try { db.collection(COLLECTION_PROPERTIES) .whereIn(FieldPath.documentId(), listingIds) .addSnapshotListener(EventListener{result, error -> if(error != null) { Log.e(TAG, "getUserListings: Listening to Properties collection failed due to error : $error") return@EventListener } else { if(result != null) { Log.d(TAG, "getUserListings: Number of documents retrieved : ${result.size()}") val tempList: MutableList<Listings> = ArrayList() for(docChanges in result.documentChanges) { val currentDocument : Listings = docChanges.document.toObject(Listings::class.java) Log.d(TAG, "getUserListings: currentDocument : $currentDocument") when(docChanges.type){ DocumentChange.Type.ADDED -> { //do necessary changes to your local list of objects tempList.add(currentDocument) } DocumentChange.Type.MODIFIED -> { } DocumentChange.Type.REMOVED -> { } } } Log.d(TAG, "getUserListings: tempList : $tempList") allListings.postValue(tempList) } } }) } catch (ex : java.lang.Exception) { Log.e(TAG, "getUserListings: Unable to create listing : $ex", ) } } } fun getUserFavourites(listingIds: MutableList<String>?) { if(!listingIds.isNullOrEmpty()) { try { db.collection(COLLECTION_PROPERTIES) .whereIn(FieldPath.documentId(), listingIds) .addSnapshotListener(EventListener{result, error -> if(error != null) { Log.e(TAG, "getUserListings: Listening to Properties collection failed due to error : $error") return@EventListener } else { if(result != null) { Log.d(TAG, "getUserListings: Number of documents retrieved : ${result.size()}") val tempList: MutableList<Listings> = ArrayList() for(docChanges in result.documentChanges) { val currentDocument : Listings = docChanges.document.toObject(Listings::class.java) Log.d(TAG, "getUserListings: currentDocument : $currentDocument") when(docChanges.type){ DocumentChange.Type.ADDED -> { //do necessary changes to your local list of objects tempList.add(currentDocument) } DocumentChange.Type.MODIFIED -> { } DocumentChange.Type.REMOVED -> { } } } Log.d(TAG, "getUserListings: tempList : $tempList") shortListings.postValue(tempList) } } }) } catch (ex : java.lang.Exception) { Log.e(TAG, "getUserListings: Unable to create listing : $ex", ) } } } suspend fun updateProperty(propertyToUpdate: Listings) { try { val data: MutableMap<String, Any> = HashMap() data[FIELD_ID] = propertyToUpdate.id data[FIELD_USER] = propertyToUpdate.owner data[FIELD_PROPERTY_TYPE] = propertyToUpdate.propertyType data[FIELD_BEDROOMS] = propertyToUpdate.bedrooms data[FIELD_KITCHEN] = propertyToUpdate.kitchen data[FIELD_BATHROOMS] = propertyToUpdate.bathroom data[FIELD_DESCRIPTION] = propertyToUpdate.description data[FIELD_ADDRESS] = propertyToUpdate.address data[FIELD_IS_AVAILABLE] = propertyToUpdate.isAvailable data[FIELD_BUILDING_NAME] = propertyToUpdate.buildingName data[FIELD_POSTAL_CODE] = propertyToUpdate.postalCode data[FIELD_PROVINCE] = propertyToUpdate.province data[FIELD_CITY] = propertyToUpdate.city data[FIELD_IMG] = propertyToUpdate.img data[FIELD_RENT] = propertyToUpdate.rent data[FIELD_PHONE_NUMBER] = propertyToUpdate.phoneNumber data[FIELD_COORDINATES] = propertyToUpdate.coordinates val querySnapshot = db.collection(COLLECTION_PROPERTIES).whereEqualTo("id", propertyToUpdate.id).limit(1).get().await() if(!querySnapshot.isEmpty) { val documentId = querySnapshot.documents[0].id Log.d(TAG, "updateProperty: documentId: $documentId") db.collection(COLLECTION_PROPERTIES) .document(documentId) .update(data) .await() } } catch (ex : java.lang.Exception) { Log.e(TAG, "updateUserListings: Unable to update listing : $ex", ) } } suspend fun getPropertyById(propertyId: String?): Listings? { if(!propertyId.isNullOrEmpty()) { return try { val querySnapshot = db.collection(COLLECTION_PROPERTIES).whereEqualTo("id", propertyId).limit(1).get().await() if(!querySnapshot.isEmpty) { val documentSnapshot = querySnapshot.documents[0] val propertyData = documentSnapshot.toObject(Listings::class.java) propertyData } else { null } } catch (ex : java.lang.Exception) { Log.e(TAG, "getPropertyById: Unable to get listing : $ex", ) null } } return null } suspend fun getPropertyIdById(propertyId: String?): String? { if(!propertyId.isNullOrEmpty()) { return try { val querySnapshot = db.collection(COLLECTION_PROPERTIES).whereEqualTo("id", propertyId).limit(1).get().await() if(!querySnapshot.isEmpty) { val documentId = querySnapshot.documents[0].id documentId } else { null } } catch (ex : java.lang.Exception) { Log.e(TAG, "getPropertyById: Unable to get listing : $ex", ) null } } return null } fun filterByCity(cityName:String){ Log.d("please", "filterByCity: $cityName") if (!cityName.isNullOrEmpty()){ try { db.collection(COLLECTION_PROPERTIES) .whereEqualTo("city",cityName) .whereEqualTo("isAvailable",true) .addSnapshotListener(EventListener{result, error -> if (error != null){ Log.e(TAG, "filterByCity: Listening failed:$error " ) return@EventListener }else{ if (result != null){ Log.d(TAG, "getListingsResults: Number of documents retrieved : ${result.size()}") val tempList: MutableList<Listings> = ArrayList() for(docChanges in result.documentChanges) { val currentDocument: Listings = docChanges.document.toObject(Listings::class.java) Log.d( TAG, "getUserListings: currentDocument : ${currentDocument.city}" ) when (docChanges.type) { DocumentChange.Type.ADDED -> { //do necessary changes to your local list of objects tempList.add(currentDocument) } DocumentChange.Type.MODIFIED -> { } DocumentChange.Type.REMOVED -> { } } } filteredResultsByName.postValue(tempList) Log.d("getUserListings", "filterByCity: ${tempList}") } } }) }catch (ex: java.lang.Exception){ Log.e(TAG, "searchResults: Unable to fetch results for the city searched", ) } } } fun filterByCurrentLocation(coordinates:Point){ if (coordinates == null){ Log.d(TAG, "filterByCurrentLocation: no coordinates provided") }else{ try { db.collection(COLLECTION_PROPERTIES) .whereEqualTo("isAvailable",true) .addSnapshotListener(EventListener{result, error-> if(error != null) { Log.e(TAG, "getUserListings: Listening to Properties collection failed due to error : $error") return@EventListener } else{ if(result != null) { Log.d(TAG, "getListings: Number of documents retrieved : ${result.size()}") val tempList: MutableList<Listings> = ArrayList() for(docChanges in result.documentChanges) { val currentDocument : Listings = docChanges.document.toObject(Listings::class.java) Log.d(TAG, "getUserListings: currentDocument : $currentDocument") when(docChanges.type){ DocumentChange.Type.ADDED -> { //do necessary changes to your local list of objects val listingPoint = Location("point1") listingPoint.latitude = currentDocument.coordinates.latitude listingPoint.longitude = currentDocument.coordinates.longitude Log.d(TAG, "filterByCurrentLocation: ${coordinates.latitude()}") val devicePoint = Location("point2") devicePoint.latitude = coordinates.latitude() devicePoint.longitude = coordinates.longitude() val distance = listingPoint.distanceTo(devicePoint) Log.d(TAG, "filterByCurrentLocation: distance :${distance}") if (distance/1000 <= 25.0){ tempList.add(currentDocument) } } DocumentChange.Type.MODIFIED -> { } DocumentChange.Type.REMOVED -> { } } } Log.d(TAG, "getUserListings: tempList : $tempList") filteredResultByLocation.postValue(tempList) Log.d(TAG, "getUserListings: tempList : $filteredResultByLocation") } } }) }catch (er:java.lang.Exception){ Log.e(TAG, "getListingsbylocation: Unable to create listing : $er", ) } } } }
Rentalapp/app/src/main/java/com/example/rental_app/repositories/PropertiesRepository.kt
318203044
package com.example.rental_app.models import com.google.firebase.firestore.GeoPoint import com.mapbox.geojson.Point import java.util.UUID class Listings( var id : String = UUID.randomUUID().toString(), var owner: String = "", var phoneNumber: String = "" , var propertyType:String = "", var bedrooms:Int = 0, var kitchen:Int = 0, var bathroom: Double = 0.0, var description: String = "", var address:String = "", var isAvailable:Boolean = false, var buildingName:String = "", var postalCode:String = "", var province:String = "", var city:String = "", var img:String = "", var rent:Int = 0, var coordinates: GeoPoint = GeoPoint(0.0,0.0) ) { }
Rentalapp/app/src/main/java/com/example/rental_app/models/Listings.kt
3500450646
package com.example.rental_app.models class Results (img:String,description:String,val cost: Int, address:String){ val im = img }
Rentalapp/app/src/main/java/com/example/rental_app/models/Results.kt
1563265337
package com.example.rental_app.models class User( val id: String = "", var firstName: String = "", var lastName: String = "", var email: String = "", var phoneNumber: String = "", var password: String = "", var listings: MutableList<String> = mutableListOf(), var shortListing: MutableList<String> = mutableListOf(), var isLoggedIn: Boolean = false, ) { // fun addListing(listing: Listings) { // shortListing.add(listing) // } // // // fun removeListing(listing: Listings) { // shortListing.remove(listing) // } override fun toString(): String { return "User(firstName='$firstName', lastName='$lastName', email='$email', phoneNumber='$phoneNumber', password='$password', isLoggedIn=$isLoggedIn, listings=$shortListing)" } }
Rentalapp/app/src/main/java/com/example/rental_app/models/User.kt
3176535590
package com.example.rental_app.adapters import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.rental_app.R import com.example.rental_app.models.Listings class ResultsAdaptor( private val results:MutableList<Listings>, private val rowClickHandler:(Int) -> Unit, private val callButtonClickHandler: (Int) -> Unit, private val enquiryButtonHandler:(Int) -> Unit):RecyclerView.Adapter<ResultsAdaptor.ResultsViewHolder>() { inner class ResultsViewHolder(itemView: View) : RecyclerView.ViewHolder (itemView) { init { itemView.setOnClickListener { rowClickHandler(adapterPosition) } itemView.findViewById<Button>(R.id.enquiry).setOnClickListener { enquiryButtonHandler(adapterPosition) } itemView.findViewById<Button>(R.id.call).setOnClickListener { callButtonClickHandler(adapterPosition) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultsViewHolder { val view:View = LayoutInflater.from(parent.context).inflate(R.layout.card_layout_results, parent, false) return ResultsViewHolder(view) } override fun getItemCount(): Int { return results.size } override fun onBindViewHolder(holder: ResultsViewHolder, position: Int) { Log.d("getUserListings2", "onBindViewHolder: $results") val res_obj = results.get(position) val tv = holder.itemView.findViewById<TextView>(R.id.cost) tv.text = "$${res_obj.rent}/-" val desc = holder.itemView.findViewById<TextView>(R.id.property_description) desc.text = "${res_obj.bedrooms}Bed|${res_obj.bathroom}Bath|\n" + "${res_obj.kitchen}Kitchen" val cityprovince = holder.itemView.findViewById<TextView>(R.id.city_province) cityprovince.text = "${res_obj.city},${res_obj.province}" val context = holder.itemView.context val res = context.resources.getIdentifier(results.get(position).img, "drawable", context.packageName) val iv = holder.itemView.findViewById<ImageView>(R.id.card_img) iv.setImageResource(res) } }
Rentalapp/app/src/main/java/com/example/rental_app/adapters/ResultsAdaptor.kt
2001655414
package com.example.rental_app.adapters import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.rental_app.activities.DetailActivity import com.example.rental_app.R import com.example.rental_app.models.Listings import com.google.gson.Gson class MyShortlistingsAdapter( private var myListings: MutableList<Listings>, private val onItemRemoved: (Int) -> Unit, private val rowClickHandler:(Int) -> Unit ) : RecyclerView.Adapter<MyShortlistingsAdapter.MyShortlistingsViewHolder>() { private val gson = Gson() inner class MyShortlistingsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { init { val btnRemove = itemView.findViewById<Button>(R.id.btnRemoveListing) btnRemove.setOnClickListener { onItemRemoved(adapterPosition) } itemView.setOnClickListener { rowClickHandler(adapterPosition) } } val tvPropertyType: TextView = itemView.findViewById(R.id.tvPropertyType) val tvDescription: TextView = itemView.findViewById(R.id.tvDescription) val tvAddress: TextView = itemView.findViewById(R.id.tvAddress) val tvRent: TextView = itemView.findViewById(R.id.tvRent) val imageViewListing: ImageView = itemView.findViewById(R.id.imageViewListing) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyShortlistingsViewHolder { val view: View = LayoutInflater.from(parent.context) .inflate(R.layout.row_layout_my_shortlistings, parent, false) return MyShortlistingsViewHolder(view) } override fun getItemCount(): Int { return myListings.size } override fun onBindViewHolder(holder: MyShortlistingsViewHolder, position: Int) { val listing = myListings[position] holder.tvPropertyType.text = listing.propertyType holder.tvDescription.text = listing.description holder.tvAddress.text = listing.address holder.tvRent.text = "Rent: ${listing.rent}" val context = holder.itemView.context val resId = context.resources.getIdentifier(listing.img, "drawable", context.packageName) holder.imageViewListing.setImageResource(resId) } }
Rentalapp/app/src/main/java/com/example/rental_app/adapters/MyShortlistingsAdapter.kt
274918543
package com.example.rental_app.adapters import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.rental_app.R import com.example.rental_app.models.Listings class MyListingAdapter( private var myListings: List<Listings>, private val rowClickHandler:(Int) -> Unit, private val editClickHandler: (Int) -> Unit ) : RecyclerView.Adapter<MyListingAdapter.MyListingViewHolder>() { inner class MyListingViewHolder(itemView: View) : RecyclerView.ViewHolder (itemView) { init { itemView.setOnClickListener { rowClickHandler(adapterPosition) } val btnEdit = itemView.findViewById<ImageButton>(R.id.btnEdit) btnEdit.setOnClickListener { editClickHandler(adapterPosition) } } val buildName: TextView = itemView.findViewById(R.id.tvRowLine1) val tvDescription: TextView = itemView.findViewById(R.id.tvDescription) val tvAddress: TextView = itemView.findViewById(R.id.tvAddress) val tvRent: TextView = itemView.findViewById(R.id.tvRent) val img: ImageView = itemView.findViewById(R.id.ivCardImg) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyListingViewHolder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.row_layout_my_listings, parent, false) return MyListingViewHolder(view) } override fun getItemCount(): Int { return myListings.size } override fun onBindViewHolder(holder: MyListingViewHolder, position: Int) { val listing = myListings[position] Log.d("onBindViewHolder", "onBindViewHolder: listings: $listing") holder.buildName.text = listing.buildingName holder.tvDescription.text = "Description${ listing.description }" holder.tvAddress.text = "Address: ${listing.address}" holder.tvRent.text = "Rent: ${listing.rent}" val context = holder.itemView.context val res = context.resources.getIdentifier(myListings.get(position).img, "drawable", context.packageName) holder.img.setImageResource(res) } }
Rentalapp/app/src/main/java/com/example/rental_app/adapters/MyListingAdapter.kt
567284832
package com.example.rental_app.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.rental_app.R class CitiesAdaptor( private val cities:List<String>, private val buttonClickHandler:(Int) -> Unit):RecyclerView.Adapter<CitiesAdaptor.CitiesViewHolder>() { inner class CitiesViewHolder(itemView: View) : RecyclerView.ViewHolder (itemView) { init { itemView.findViewById<Button>(R.id.city).setOnClickListener{ buttonClickHandler(adapterPosition) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CitiesViewHolder { val view:View = LayoutInflater.from(parent.context).inflate(R.layout.layout_cities, parent, false) return CitiesViewHolder(view) } override fun getItemCount(): Int { return cities.size } override fun onBindViewHolder(holder: CitiesViewHolder, position: Int) { val tv = holder.itemView.findViewById<TextView>(R.id.city) tv.text = "${cities.get(position)}" } }
Rentalapp/app/src/main/java/com/example/rental_app/adapters/CitiesAdaptor.kt
883397625
package com.example.rental_app import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import androidx.annotation.DrawableRes import androidx.appcompat.content.res.AppCompatResources // Mapbox provides these functions for automatically converting an image // in your drawables/ folder into an Android Bitmap image that has the correct // height/width to display on your map as a map marker. object MapboxUtils { fun bitmapFromDrawableRes(context: Context, @DrawableRes resourceId: Int) = convertDrawableToBitmap(AppCompatResources.getDrawable(context, resourceId)) fun convertDrawableToBitmap(sourceDrawable: Drawable?): Bitmap? { if (sourceDrawable == null) { return null } return if (sourceDrawable is BitmapDrawable) { sourceDrawable.bitmap } else { // copying drawable object to not manipulate on the same reference val constantState = sourceDrawable.constantState ?: return null val drawable = constantState.newDrawable().mutate() val bitmap: Bitmap = Bitmap.createBitmap( drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) bitmap } } }
Rentalapp/app/src/main/java/com/example/rental_app/MapboxUtils.kt
2815282922
package com.example.rental_app.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.rental_app.databinding.ActivityProfileBinding class ProfileActivity : AppCompatActivity() { private lateinit var binding: ActivityProfileBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityProfileBinding.inflate(layoutInflater) setContentView(binding.root) val userEmail = intent.getStringExtra("USER_EMAIL") binding.tvUserEmail.text = userEmail ?: "No Email Provided" } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/ProfileActivity.kt
4174442953
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.ImageView import android.widget.TextView import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityDetailBinding import com.example.rental_app.models.Listings import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() val listingJson = intent.getStringExtra("LISTING_DETAILS") val listing = Gson().fromJson(listingJson, Listings::class.java) this.firebaseAuth = FirebaseAuth.getInstance() val imageViewListingDetail = findViewById<ImageView>(R.id.imageViewListingDetail) val tvPropertyType = findViewById<TextView>(R.id.tvDetailPropertyType) val tvBedrooms = findViewById<TextView>(R.id.tvDetailBedrooms) val tvKitchen = findViewById<TextView>(R.id.tvDetailKitchen) val tvBathroom = findViewById<TextView>(R.id.tvDetailBathroom) val tvDescription = findViewById<TextView>(R.id.tvDetailDescription) val tvAddress = findViewById<TextView>(R.id.tvDetailAddress) val tvAvailability = findViewById<TextView>(R.id.tvDetailAvailability) val tvBuildingName = findViewById<TextView>(R.id.tvDetailBuildingName) val tvPostalCode = findViewById<TextView>(R.id.tvDetailPostalCode) val tvProvince = findViewById<TextView>(R.id.tvDetailProvince) val tvCity = findViewById<TextView>(R.id.tvDetailCity) val tvRent = findViewById<TextView>(R.id.tvDetailRent) val btnBack = findViewById<Button>(R.id.btnBack) val resId = resources.getIdentifier(listing.img, "drawable", packageName) imageViewListingDetail.setImageResource(resId) tvPropertyType.text = listing.propertyType tvBedrooms.text = "Bedrooms: ${listing.bedrooms}" tvKitchen.text = "Kitchen: ${listing.kitchen}" tvBathroom.text = "Bathroom: ${listing.bathroom}" tvDescription.text = listing.description tvAddress.text = listing.address tvAvailability.text = if (listing.isAvailable) "Available" else "Not Available" tvBuildingName.text = listing.buildingName tvPostalCode.text = listing.postalCode tvProvince.text = listing.province tvCity.text = listing.city tvRent.text = "Rent: ${listing.rent}" btnBack.setOnClickListener { finish() } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/DetailActivity.kt
4101758822
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.adapters.MyShortlistingsAdapter import com.example.rental_app.databinding.ActivityMyShortlistingsBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.example.rental_app.repositories.UserRepository import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.launch class MyShortlistingsActivity : AppCompatActivity() { private lateinit var sharedPreferences: SharedPreferences private lateinit var binding: ActivityMyShortlistingsBinding private lateinit var adapter: MyShortlistingsAdapter private lateinit var prefEditor: SharedPreferences.Editor private var loggedUserObject: User? = User("", "", "", "", "", "") private lateinit var userRepository: UserRepository private lateinit var propertiesRepository: PropertiesRepository private lateinit var myListings: MutableList<Listings> private val TAG = javaClass.canonicalName private var loggedInUserEmail: String? = "" private lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyShortlistingsBinding.inflate(layoutInflater) setContentView(binding.root) sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() userRepository = UserRepository(applicationContext) propertiesRepository = PropertiesRepository(applicationContext) loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", null) myListings = mutableListOf() adapter = MyShortlistingsAdapter(myListings, { pos -> removeListingAndUpdate(pos)}, {pos -> rowClicked(pos)}) binding.rv.adapter = adapter binding.rv.layoutManager = LinearLayoutManager(this) binding.rv.addItemDecoration( DividerItemDecoration( this, LinearLayoutManager.VERTICAL ) ) if (loggedInUserEmail != "") { lifecycleScope.launch{ loggedUserObject = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${loggedUserObject?.shortListing}") propertiesRepository.getUserFavourites(loggedUserObject?.shortListing) } } } override fun onStart() { super.onStart() lifecycleScope.launch{ val userData: User? = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${userData?.shortListing}") propertiesRepository.getUserFavourites(userData?.shortListing) } this.propertiesRepository.shortListings?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { myListings.clear() myListings.addAll(receivedData) adapter.notifyDataSetChanged() } else { Log.d(TAG, "onStart: No data received from observer") } } } private fun removeListingAndUpdate(position: Int) { lifecycleScope.launch{ val firebaseListingId = propertiesRepository.getPropertyIdById(myListings[position].id) propertiesRepository.removeUserFavourites(loggedInUserEmail, firebaseListingId) val userData: User? = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "removeListingAndUpdate: userData: ${userData?.shortListing}") propertiesRepository.getUserFavourites(userData?.shortListing) } this.propertiesRepository.shortListings?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { myListings.clear() myListings.addAll(receivedData) adapter.notifyDataSetChanged() } else { Log.d(TAG, "removeListingAndUpdate: No data received from observer") } } } fun rowClicked(position:Int){ val detailIntent = Intent(this, DetailActivity::class.java) detailIntent.putExtra("PROPERTY_ID", myListings[position].id) detailIntent.putExtra("SOURCE", "MyListing") startActivity(detailIntent) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/MyShortlistingsActivity.kt
1427575998
package com.example.rental_app.activities import android.Manifest import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat.startActivity import androidx.lifecycle.lifecycleScope import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityEditListingBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.GeoPoint import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.launch import java.util.Locale class EditListingActivity : AppCompatActivity(), View.OnClickListener { private val TAG = this.javaClass.canonicalName private lateinit var binding: ActivityEditListingBinding private var rowPosition:Int = -1 private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var propertyTypeSelected: String private var propertyId: String = "" private lateinit var propertiesRepository: PropertiesRepository private lateinit var fusedLocationClient: FusedLocationProviderClient private var lat: Double = 0.0 private var lng: Double = 0.0 private lateinit var firebaseAuth: FirebaseAuth private val APP_PERMISSIONS_LIST = arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE ) private val multiplePermissionsResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { resultsList -> var allPermissionsGrantedTracker = true for (item in resultsList.entries) { if (item.key in APP_PERMISSIONS_LIST && item.value == false) { allPermissionsGrantedTracker = false } } if (allPermissionsGrantedTracker == true) { Snackbar.make(binding.root, "All permissions granted", Snackbar.LENGTH_LONG).show() getDeviceLocation() } else { Snackbar.make(binding.root, "Some permissions NOT granted", Snackbar.LENGTH_LONG).show() handlePermissionDenied() } } private fun getDeviceLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) return } fusedLocationClient.lastLocation .addOnSuccessListener { location : Location? -> if (location === null) { Log.d(TAG, "Location is null") return@addOnSuccessListener } val message = "The device is located at: ${location.latitude}, ${location.longitude}" Log.d(TAG, message) Snackbar.make(binding.root, message, Snackbar.LENGTH_LONG).show() } } private fun handlePermissionDenied() { val errorMsg = "Sorry, you need to give us permissions before we can get your location. Check your settings menu and update your location permissions for this app." Snackbar.make(binding.root, errorMsg, Snackbar.LENGTH_LONG).show() binding.btnGetLocation.isEnabled = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityEditListingBinding.inflate(layoutInflater) setContentView(binding.root) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() propertiesRepository = PropertiesRepository(applicationContext) fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) val propertyTypes = mutableListOf<String>("Property Type","Apartment", "Basement", "Condo", "House", "Multi Family House", "Townhouse") val spinner: Spinner = findViewById(R.id.etPropertyType) val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, propertyTypes) spinner.adapter = arrayAdapter this.binding.etPropertyType.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if(position > 0) { propertyTypeSelected = propertyTypes.get(position) } else { Snackbar.make(binding.root, "Please select property type", Snackbar.LENGTH_SHORT).show() } } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } } if (intent != null) { this.rowPosition = intent.getIntExtra("LISTING_POSITION", -1) val propertyId = intent.getStringExtra("PROPERTY_ID") if(!propertyId.isNullOrEmpty()) { this.propertyId = propertyId } lifecycleScope.launch { val propertyData = propertiesRepository.getPropertyById(propertyId) val spinnerPosition = arrayAdapter.getPosition(propertyData?.propertyType) spinner.setSelection(spinnerPosition) binding.etAddress.setText(propertyData?.address) binding.etBuildingName.setText(propertyData?.buildingName) binding.etProvince.setText(propertyData?.province) binding.etCity.setText(propertyData?.city) binding.etPostalCode.setText(propertyData?.postalCode) binding.etBedrooms.setText(propertyData?.bedrooms.toString()) binding.etKitchen.setText(propertyData?.kitchen.toString()) binding.etBathrooms.setText(propertyData?.bathroom.toString()) binding.etDescription.setText(propertyData?.description) binding.etRent.setText(propertyData?.rent.toString()) binding.etImage.setText(propertyData?.img) binding.etPhoneNumber.setText(propertyData?.phoneNumber) lat = propertyData?.coordinates!!.latitude lng = propertyData?.coordinates!!.longitude } } binding.btnEditRental.setOnClickListener(this) binding.btnGetLocation.setOnClickListener(this) } override fun onClick(p0: View?) { when(p0?.id) { R.id.btnEditRental -> { this.editRental() } R.id.btnGetLocation -> { this.getCurrentLocation() } } } private fun validateInputs(): Boolean { val bedrooms = binding.etBedrooms.text.toString() val kitchen = binding.etKitchen.text.toString() val bathrooms = binding.etBathrooms.text.toString() val description = binding.etDescription.text.toString() val address = binding.etAddress.text.toString() val buildingName = binding.etBuildingName.text.toString() val postalCode = binding.etPostalCode.text.toString() val province = binding.etProvince.text.toString() val city = binding.etCity.text.toString() val rent = binding.etRent.text.toString() if(bedrooms.isNullOrEmpty()) { binding.etBedrooms.error = "This field is required" return false } else if(kitchen.isNullOrEmpty()) { binding.etKitchen.error = "This field is required" return false } else if(bathrooms.isNullOrEmpty()) { binding.etBathrooms.error = "This field is required" return false } else if(description.isNullOrEmpty()) { binding.etDescription.error = "This field is required" return false } else if(address.isNullOrEmpty()) { binding.etAddress.error = "This field is required" return false } else if(buildingName.isNullOrEmpty()) { binding.etBuildingName.error = "This field is required" return false } else if(postalCode.isNullOrEmpty()) { binding.etPostalCode.error = "This field is required" return false } else if(province.isNullOrEmpty()) { binding.etProvince.error = "This field is required" return false } else if(city.isNullOrEmpty()) { binding.etCity.error = "This field is required" return false } else if(rent.isNullOrEmpty()) { binding.etRent.error = "This field is required" return false } else { return true } } private fun editRental() { val inputValidation = this.validateInputs() if(inputValidation) { val bedrooms = binding.etBedrooms.text.toString().toInt() val kitchen = binding.etKitchen.text.toString().toInt() val bathrooms = binding.etBathrooms.text.toString().toDouble() val description = binding.etDescription.text.toString() val address = binding.etAddress.text.toString() val isAvailable = binding.swAvailable.isChecked val buildingName = binding.etBuildingName.text.toString() val postalCode = binding.etPostalCode.text.toString() val province = binding.etProvince.text.toString() val city = binding.etCity.text.toString().uppercase() val rent = binding.etRent.text.toString().toInt() val img = binding.etImage.text.toString() val phoneNumber = binding.etPhoneNumber.text.toString() val loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", null) val streetAddress = "$address, $city, $province $postalCode" getCoordinatesFromAddress(streetAddress) if(loggedInUserEmail != null) { lifecycleScope.launch { val propertyData = propertiesRepository.getPropertyById(propertyId) val listing = Listings(propertyData!!.id, loggedInUserEmail, phoneNumber, propertyTypeSelected, bedrooms, kitchen, bathrooms, description, address, isAvailable, buildingName, postalCode, province, city, img, rent, GeoPoint(lat, lng)) propertiesRepository.updateProperty(listing) setResult(Activity.RESULT_OK, intent) finish() } } else { startActivity(Intent(this, LoginActivity::class.java)) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } private fun getCurrentLocation() { fusedLocationClient.lastLocation .addOnSuccessListener { location : Location? -> val geocoder: Geocoder = Geocoder(applicationContext, Locale.getDefault()) if (location == null) { Log.d(TAG, "Location is null") return@addOnSuccessListener } val message = "The device is located at: ${location.latitude}, ${location.longitude}" try { val searchResults: MutableList<Address>? = geocoder.getFromLocation(location.latitude, location.longitude, 1) if (searchResults == null) { Log.d(TAG, "ERROR: When retrieving results") } else if (searchResults.size == 0){ Log.d(TAG, "ERROR: No result found") } else{ Log.d(TAG, "getCurrentLocation: ****************************************************") val listingAddress = "${searchResults[0].featureName} ${searchResults[0].thoroughfare}" val addressEditText = findViewById<EditText>(R.id.etAddress) val cityEditText = findViewById<EditText>(R.id.etCity) val provinceEditText = findViewById<EditText>(R.id.etProvince) val postalCodeEditText = findViewById<EditText>(R.id.etPostalCode) addressEditText.setText(listingAddress) cityEditText.setText(searchResults[0].locality) provinceEditText.setText(searchResults[0].adminArea) postalCodeEditText.setText(searchResults[0].postalCode) lat = searchResults[0].latitude lng = searchResults[0].longitude } } catch (exception:Exception) { Log.d(TAG, "Exception occurred while getting matching address") Log.d(TAG, exception.toString()) } Log.d(TAG, message) } .addOnFailureListener{ Log.d(TAG, "getCurrentLocation: addOnFailureListener: $it") } } private fun getCoordinatesFromAddress(streetAddress: String) { val geocoder:Geocoder = Geocoder(applicationContext, Locale.getDefault()) try { val searchResults:MutableList<Address>? = geocoder.getFromLocationName(streetAddress, 1) if (searchResults == null) { Log.e(TAG, "searchResults variable is null") return } if (searchResults.size == 0) { Log.e(TAG, "getCoordinatesFromAddress: Search results are empty.", ) } else { val foundLocation:Address = searchResults[0] lat = foundLocation.latitude lng = foundLocation.longitude } } catch(ex:Exception) { Log.e(TAG, "Error encountered while getting coordinate location.") Log.e(TAG, ex.toString()) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/EditListingActivity.kt
446222398
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.annotation.DrawableRes import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import com.example.rental_app.MainActivity import com.example.rental_app.MapboxUtils import com.example.rental_app.R import com.example.rental_app.adapters.ResultsAdaptor import com.example.rental_app.databinding.ActivityResultsBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.example.rental_app.repositories.UserRepository import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.mapbox.geojson.Point import com.mapbox.maps.CameraOptions import com.mapbox.maps.plugin.annotation.AnnotationConfig import com.mapbox.maps.plugin.annotation.AnnotationSourceOptions import com.mapbox.maps.plugin.annotation.annotations import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager import kotlinx.coroutines.launch class ResultsActivity : AppCompatActivity() { private lateinit var binding: ActivityResultsBinding lateinit var sharedPreferences: SharedPreferences lateinit var prefEditor: SharedPreferences.Editor private lateinit var propertiesRepository: PropertiesRepository private lateinit var userRepository: UserRepository private lateinit var firebaseAuth: FirebaseAuth private lateinit var filteredList:MutableList<Listings> private lateinit var loggedInUserEmail:String private lateinit var adapter: ResultsAdaptor private val TAG = javaClass.canonicalName private lateinit var originalList: MutableList<Listings> private var currentView = "listview" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.binding = ActivityResultsBinding.inflate(layoutInflater) setContentView(this.binding.root) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) prefEditor = sharedPreferences.edit() binding.rv.isVisible = true binding.mapView.isVisible = false setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() propertiesRepository = PropertiesRepository(applicationContext) userRepository = UserRepository(applicationContext) loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", "").toString() filteredList = mutableListOf() originalList = mutableListOf() var receivedData = intent.getStringExtra("SEARCH_VAL").toString() receivedData = receivedData.trim().uppercase() val propertyTypes = mutableListOf<String>("Property Type","Apartment", "Basement", "Condo", "House", "Multi Family House", "Townhouse") val spinner: Spinner = findViewById(R.id.etPropertyType) val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, propertyTypes) spinner.adapter = arrayAdapter this.binding.etPropertyType.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if(position > 0) { val propertyTypeFilteredList = originalList.filter { it.propertyType == propertyTypes[position] } Log.d(TAG, "onItemSelected: propertyTypeFilteredList: $propertyTypeFilteredList") filteredList.clear() filteredList.addAll(propertyTypeFilteredList) adapter.notifyDataSetChanged() } else if(position == 0){ filteredList.clear() filteredList.addAll(originalList) adapter.notifyDataSetChanged() } } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } } binding.searchedValue.text = "${receivedData} :" Log.d("please", "onCreate: $receivedData") adapter = ResultsAdaptor( filteredList, {pos -> rowClicked(pos) }, {pos -> callButtonClicked(pos)}, {pos -> enquiryButtonClicked(pos)} ) binding.rv.adapter = adapter binding.rv.layoutManager = GridLayoutManager(this, 1) lifecycleScope.launch{ propertiesRepository.filterByCity(receivedData) } this.propertiesRepository.filteredResultsByName?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { filteredList.clear() filteredList.addAll(receivedData) originalList.addAll(receivedData) Log.d("getUserListings1", "onCreate: ${filteredList.get(0).city}") adapter.notifyDataSetChanged() val initialCameraOptions = CameraOptions.Builder() .center(Point.fromLngLat(filteredList[0].coordinates.longitude, filteredList[0].coordinates.latitude)) .pitch(0.0) .zoom(8.0) .bearing(0.0) .build() binding.mapView.mapboxMap.setCamera(initialCameraOptions) addManyAnnotations(filteredList) } else { Log.d("resultactivity", "onStart: No data received from observer") binding.empty.isVisible = true Handler().postDelayed({ finish() }, 2000) } } binding.listView.setOnClickListener { currentView = "listview" binding.mapView.isVisible = false binding.rv.isVisible = true binding.etPropertyType.isVisible = true } binding.mapViewBtn.setOnClickListener { currentView = "mapview" binding.mapView.isVisible = true binding.rv.isVisible = false binding.etPropertyType.isVisible = false } } fun rowClicked(position:Int){ if(loggedInUserEmail != "") { val descriptionIntent = Intent(this, ResultDescriptionActivity::class.java) descriptionIntent.putExtra("PROPERTY_ID", filteredList[position].id) descriptionIntent.putExtra("SOURCE", "ResultActivity") startActivity(descriptionIntent) } else { startActivity(Intent(this, LoginActivity::class.java)) } } fun callButtonClicked(position: Int){ val ph_no = filteredList[position].phoneNumber.toString() val callIntent = Intent(Intent.ACTION_CALL).apply { data = Uri.parse("tel:$ph_no") } if (callIntent.resolveActivity(packageManager) != null){ startActivity(callIntent) } } fun enquiryButtonClicked(position: Int){ val inquiryIntent = Intent(this, InquiryActivity::class.java) inquiryIntent.putExtra("PROPERTY_ID", filteredList[position].id) startActivity(inquiryIntent) } private fun IntentByCoordinates(clickedCoordinate: Point) { for (property in filteredList) { val geoPoint = property.coordinates geoPoint?.let { val point = Point.fromLngLat(geoPoint.longitude, geoPoint.latitude) if (point == clickedCoordinate) { if(loggedInUserEmail != "") { val descriptionIntent = Intent(this, ResultDescriptionActivity::class.java) descriptionIntent.putExtra("PROPERTY_ID", property.id) descriptionIntent.putExtra("SOURCE", "ResultActivity") startActivity(descriptionIntent) } else { startActivity(Intent(this, LoginActivity::class.java)) } } } } } private fun addManyAnnotations(ListingsList:MutableList<Listings>, @DrawableRes drawableImageResourceId: Int = R.drawable.red_marker) { val icon = MapboxUtils.bitmapFromDrawableRes(applicationContext, drawableImageResourceId) if (icon == null) { Log.d("addMany", "ERROR: Unable to convert provided image into the correct format.") return } val annotationApi = binding.mapView.annotations val pointAnnotationManager = annotationApi?.createPointAnnotationManager( AnnotationConfig( annotationSourceOptions = AnnotationSourceOptions(maxZoom = 16) ) ) // loop through our list of coordinates & add them to the map val pointAnnotationOptionsList: MutableList<PointAnnotationOptions> = ArrayList() for (property in ListingsList){ pointAnnotationOptionsList.add( PointAnnotationOptions() .withPoint(Point.fromLngLat(property.coordinates.longitude,property.coordinates.latitude)) .withIconImage(icon) ) } Log.d(TAG, "addManyAnnotations: $pointAnnotationManager") pointAnnotationManager?.create(pointAnnotationOptionsList) pointAnnotationManager?.addClickListener { pointAnnotation -> val clickedCoordinate = pointAnnotation.geometry IntentByCoordinates(clickedCoordinate) return@addClickListener true } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") return when(item.itemId){ R.id.menuMyListings -> { if(loggedInUser != ""){ val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuPostRental -> { if(loggedInUser != ""){ val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, LoginActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { if(loggedInUser != ""){ startActivity(Intent(this, MyShortlistingsActivity::class.java)) }else{ startActivity(Intent(this, LoginActivity::class.java)) } startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/ResultsActivity.kt
3711230767
package com.example.rental_app.activities import android.app.Activity import android.content.Intent import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.adapters.MyListingAdapter import com.example.rental_app.databinding.ActivityMyListingsBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.example.rental_app.repositories.UserRepository import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.launch class MyListingsActivity : AppCompatActivity() { private val TAG = this.javaClass.canonicalName private lateinit var binding: ActivityMyListingsBinding private lateinit var adapter: MyListingAdapter private var listingsList = listOf<Listings>() private lateinit var myListings: MutableList<Listings> private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var propertiesRepository: PropertiesRepository private lateinit var userRepository: UserRepository private var loggedInUserEmail: String? = "" private lateinit var firebaseAuth: FirebaseAuth private val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { if (result.data != null) { lifecycleScope.launch{ val userData: User? = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${userData?.listings}") propertiesRepository.getUserListings(userData?.listings) } this.propertiesRepository.allListings?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { myListings.clear() myListings.addAll(receivedData) adapter.notifyDataSetChanged() } else { Log.d(TAG, "onStart: No data received from observer") } } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMyListingsBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() propertiesRepository = PropertiesRepository(applicationContext) userRepository = UserRepository(applicationContext) loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", null) myListings = mutableListOf() this.adapter = MyListingAdapter(myListings, {pos -> rowClicked(pos)}, {pos -> editClickHandler(pos)}) binding.rv.adapter = adapter binding.rv.layoutManager = LinearLayoutManager(this) binding.rv.addItemDecoration( DividerItemDecoration( this, LinearLayoutManager.VERTICAL ) ) } override fun onStart() { super.onStart() lifecycleScope.launch { val userData: User? = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${userData?.listings}") propertiesRepository.getUserListings(userData?.listings) } propertiesRepository.allListings?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { myListings.clear() myListings.addAll(receivedData) adapter.notifyDataSetChanged() } else { Log.d(TAG, "onStart: No data received from observer") } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } fun rowClicked(position:Int){ val descriptionIntent = Intent(this, ResultDescriptionActivity::class.java) descriptionIntent.putExtra("PROPERTY_ID", myListings[position].id) descriptionIntent.putExtra("SOURCE", "MyListing") startActivity(descriptionIntent) } private fun editClickHandler(position: Int) { val editIntent = Intent(this, EditListingActivity::class.java) editIntent.putExtra("PROPERTY_ID", myListings[position].id) startForResult.launch(editIntent) } override fun onResume() { super.onResume() lifecycleScope.launch{ val userData: User? = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${userData?.listings}") propertiesRepository.getUserListings(userData?.listings) } this.propertiesRepository.allListings?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { myListings.clear() myListings.addAll(receivedData) adapter.notifyDataSetChanged() } else { Log.d(TAG, "onStart: No data received from observer") } } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/MyListingsActivity.kt
3667574332
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityInquiryBinding import com.example.rental_app.models.Listings import com.example.rental_app.repositories.PropertiesRepository import com.example.rental_app.repositories.UserRepository import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import kotlinx.coroutines.launch class InquiryActivity : AppCompatActivity(), View.OnClickListener { private lateinit var binding: ActivityInquiryBinding private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var firebaseAuth: FirebaseAuth private lateinit var propertiesRepository: PropertiesRepository private lateinit var userRepository: UserRepository override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityInquiryBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() propertiesRepository = PropertiesRepository(applicationContext) userRepository = UserRepository(applicationContext) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() if(intent != null) { val propertyId = intent.getStringExtra("PROPERTY_ID") lifecycleScope.launch { val propertyData = propertiesRepository.getPropertyById(propertyId) val userData = userRepository.getLoggedByEmail(propertyData?.owner) binding.etFirstName.setText(userData?.firstName) binding.etLastName.setText(userData?.lastName) binding.etEmail.setText(userData?.email) binding.etPhone.setText(userData?.phoneNumber) } } binding.btnSendInquiry.setOnClickListener(this) } override fun onClick(p0: View?) { when(p0?.id) { R.id.btnSendInquiry -> { this.sendInquiry() } } } private fun sendInquiry() { if(intent != null) { val propertyId = intent.getStringExtra("PROPERTY_ID") lifecycleScope.launch { val propertyData = propertiesRepository.getPropertyById(propertyId) val userData = userRepository.getLoggedByEmail(propertyData?.owner) val emailIntent = Intent(Intent.ACTION_SEND).apply { data = Uri.parse("mailto: ${userData?.email}") putExtra(Intent.EXTRA_EMAIL, userData?.email) putExtra(Intent.EXTRA_SUBJECT, "You have new inquiry for your listing") putExtra(Intent.EXTRA_TEXT, binding.etMessage.text.toString()) } if (emailIntent.resolveActivity(packageManager) != null){ startActivity(emailIntent) } Snackbar.make(binding.rootLayout, "Inquiry Sent", Snackbar.LENGTH_SHORT).show() Handler().postDelayed({ finish() }, 2000) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/InquiryActivity.kt
2515059245
package com.example.rental_app.activities import android.content.Intent import android.net.Uri import android.content.SharedPreferences import android.location.Geocoder import android.location.Location import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.annotation.DrawableRes import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import com.example.rental_app.MainActivity import com.example.rental_app.MapboxUtils import com.example.rental_app.R import com.example.rental_app.adapters.ResultsAdaptor import com.example.rental_app.databinding.ActivityLocalResultsBinding import com.example.rental_app.databinding.ActivityResultsBinding import com.example.rental_app.models.Listings import com.example.rental_app.repositories.PropertiesRepository import java.util.Locale import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.mapbox.geojson.Point import com.mapbox.maps.CameraOptions import com.mapbox.maps.plugin.annotation.AnnotationConfig import com.mapbox.maps.plugin.annotation.AnnotationSourceOptions import com.mapbox.maps.plugin.annotation.annotations import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager import kotlinx.coroutines.launch class LocalResultsActivity : AppCompatActivity() { private lateinit var binding: ActivityLocalResultsBinding private lateinit var fusedLocationClient: FusedLocationProviderClient lateinit var sharedPreferences: SharedPreferences lateinit var prefEditor: SharedPreferences.Editor private lateinit var propertiesRepository: PropertiesRepository private lateinit var loggedInUserEmail:String private lateinit var firebaseAuth: FirebaseAuth private lateinit var adapter: ResultsAdaptor var filteredList:MutableList<Listings> = mutableListOf() var filteredListcopy:MutableList<Listings> = mutableListOf() private lateinit var originalList: MutableList<Listings> private lateinit var receivedData : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.binding = ActivityLocalResultsBinding.inflate(layoutInflater) setContentView(this.binding.root) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) prefEditor = sharedPreferences.edit() setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() binding.rv.isVisible = true binding.mapView.isVisible = false propertiesRepository = PropertiesRepository(applicationContext) fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", "").toString() originalList = mutableListOf() val propertyTypes = mutableListOf("Property Type","Apartment", "Basement", "Condo", "House", "Multi Family House", "Townhouse") val spinner: Spinner = findViewById(R.id.etPropertyType) val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, propertyTypes) spinner.adapter = arrayAdapter this.binding.etPropertyType.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if(position > 0) { val propertyTypeFilteredList = originalList.filter { it.propertyType == propertyTypes[position] } filteredList.clear() filteredList.addAll(propertyTypeFilteredList) adapter.notifyDataSetChanged() } else if(position == 0){ filteredList.clear() filteredList.addAll(originalList) adapter.notifyDataSetChanged() } } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } } adapter = ResultsAdaptor( filteredList, {pos -> rowClicked(pos) }, {pos -> callButtonClicked(pos)}, {pos -> enquiryButtonClicked(pos)} ) binding.rv.adapter = adapter binding.rv.layoutManager = GridLayoutManager(this, 1) binding.searchedValue.text = "Listing Near You:" fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // Got last known location. In some rare situations this can be null. val geocoder: Geocoder = Geocoder(applicationContext, Locale.getDefault()) if (location === null) { Log.d("nearmeactivity", "Location is null") return@addOnSuccessListener } // Output the location val message = "The device is located at: ${location.latitude}, ${location.longitude}" Log.d("mayank", "onCreate:${message} ") addAnnotationToMap(location.latitude,location.longitude,R.drawable.mylocation) lifecycleScope.launch{ propertiesRepository.filterByCurrentLocation(Point.fromLngLat(location.longitude,location.latitude)) } this.propertiesRepository.filteredResultByLocation?.observe(this) { receivedData -> if (receivedData.isNotEmpty()) { filteredList.clear() filteredList.addAll(receivedData) originalList.addAll(receivedData) adapter.notifyDataSetChanged() val initialCameraOptions = CameraOptions.Builder() .center(Point.fromLngLat(filteredList[0].coordinates.longitude, filteredList[0].coordinates.latitude)) .pitch(0.0) .zoom(8.0) .bearing(0.0) .build() binding.mapView.mapboxMap.setCamera(initialCameraOptions) addManyAnnotations(filteredList) } else { Log.d("resultactivity", "onStart: No data received from observer") binding.empty.isVisible = true Handler().postDelayed({ finish() }, 2000) } Log.d("please", "onCreate: $receivedData") } } binding.listView.setOnClickListener { binding.mapView.isVisible = false binding.rv.isVisible = true binding.etPropertyType.isVisible = true } binding.mapViewBtn.setOnClickListener { binding.mapView.isVisible = true binding.rv.isVisible = false binding.etPropertyType.isVisible = false } this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) prefEditor = sharedPreferences.edit() } fun rowClicked(position:Int){ if(loggedInUserEmail != "") { val descriptionIntent = Intent(this, ResultDescriptionActivity::class.java) descriptionIntent.putExtra("PROPERTY_ID", filteredList[position].id) descriptionIntent.putExtra("SOURCE", "LocalResultActivity") startActivity(descriptionIntent) } else { startActivity(Intent(this, LoginActivity::class.java)) } } fun callButtonClicked(position: Int){ val ph_no = filteredList.get(position).phoneNumber val callIntent = Intent(Intent.ACTION_CALL).apply { data = Uri.parse("tel:$ph_no") } // if (callIntent.resolveActivity(packageManager) != null){ startActivity(callIntent) } } fun enquiryButtonClicked(position: Int){ val inquiryIntent = Intent(this, InquiryActivity::class.java) inquiryIntent.putExtra("PROPERTY_ID", filteredList[position].id) startActivity(inquiryIntent) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") return when(item.itemId){ R.id.menuMyListings -> { if(loggedInUser != ""){ val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuPostRental -> { if(loggedInUser != ""){ val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, LoginActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { if(loggedInUser != ""){ startActivity(Intent(this, MyShortlistingsActivity::class.java)) }else{ startActivity(Intent(this, LoginActivity::class.java)) } startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } private fun addManyAnnotations(ListingsList:MutableList<Listings>, @DrawableRes drawableImageResourceId: Int = R.drawable.red_marker) { val icon = MapboxUtils.bitmapFromDrawableRes(applicationContext, drawableImageResourceId) if (icon == null) { Log.d("addMany", "ERROR: Unable to convert provided image into the correct format.") return } val annotationApi = binding.mapView.annotations val pointAnnotationManager = annotationApi?.createPointAnnotationManager( AnnotationConfig( annotationSourceOptions = AnnotationSourceOptions(maxZoom = 16) ) ) // loop through our list of coordinates & add them to the map val pointAnnotationOptionsList: MutableList<PointAnnotationOptions> = ArrayList() for (property in ListingsList){ pointAnnotationOptionsList.add( PointAnnotationOptions() .withPoint(Point.fromLngLat(property.coordinates.longitude,property.coordinates.latitude)) .withIconImage(icon) ) } Log.d("test", "addManyAnnotations: $pointAnnotationManager") pointAnnotationManager?.create(pointAnnotationOptionsList) pointAnnotationManager?.addClickListener { pointAnnotation -> val clickedCoordinate = pointAnnotation.geometry IntentByCoordinates(clickedCoordinate) return@addClickListener true } } private fun IntentByCoordinates(clickedCoordinate: Point) { for (property in filteredList) { val geoPoint = property.coordinates geoPoint?.let { val point = Point.fromLngLat(geoPoint.longitude, geoPoint.latitude) if (point == clickedCoordinate) { if(loggedInUserEmail != "") { val descriptionIntent = Intent(this, ResultDescriptionActivity::class.java) descriptionIntent.putExtra("PROPERTY_ID", property.id) descriptionIntent.putExtra("SOURCE", "ResultActivity") startActivity(descriptionIntent) } else { startActivity(Intent(this, LoginActivity::class.java)) } } } } } private fun addAnnotationToMap(lat:Double, lng:Double, @DrawableRes drawableImageResourceId: Int = R.drawable.red_marker) { Log.d("addOne", "Attempting to add annotation to map") // get the image you want to use as a map marker // & resize it to fit the proportion of the map as the user zooms in and zoom out // val icon = MapboxUtils.bitmapFromDrawableRes(applicationContext, R.drawable.pikachu) val icon = MapboxUtils.bitmapFromDrawableRes(applicationContext, drawableImageResourceId) // error handling code: sometimes, the person may provide an image that cannot be // properly converted to a map marker if (icon == null) { Log.d("addOne", "ERROR: Unable to convert provided image into the correct format.") return } // code sets up the map so you can add markers val annotationApi = binding.mapView?.annotations val pointAnnotationManager = annotationApi?.createPointAnnotationManager( AnnotationConfig( annotationSourceOptions = AnnotationSourceOptions(maxZoom = 16) ) ) // Create a marker & configure the options for that marker val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions() .withPoint(Point.fromLngLat(lng, lat)) .withIconImage(icon) // Add the resulting pointAnnotation to the map. pointAnnotationManager?.create(pointAnnotationOptions) } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/LocalResultsActivity.kt
2964221843
package com.example.rental_app.activities import android.Manifest import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.Location import com.mapbox.geojson.Point import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.EditText import android.widget.Spinner import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityPostRentalBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.GeoPoint import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.launch import java.util.Locale import java.util.UUID class PostRentalActivity : AppCompatActivity(), View.OnClickListener { private val TAG = this.javaClass.canonicalName private lateinit var binding: ActivityPostRentalBinding private lateinit var propertyTypeSelected: String private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var propertiesRepository: PropertiesRepository private lateinit var fusedLocationClient: FusedLocationProviderClient private lateinit var firebaseAuth: FirebaseAuth private var lat: Double = 0.0 private var lng: Double = 0.0 private val APP_PERMISSIONS_LIST = arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE ) private val multiplePermissionsResultLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) { resultsList -> var allPermissionsGrantedTracker = true for (item in resultsList.entries) { if (item.key in APP_PERMISSIONS_LIST && item.value == false) { allPermissionsGrantedTracker = false } } if (allPermissionsGrantedTracker == true) { Snackbar.make(binding.root, "All permissions granted", Snackbar.LENGTH_LONG).show() getDeviceLocation() } else { Snackbar.make(binding.root, "Some permissions NOT granted", Snackbar.LENGTH_LONG).show() handlePermissionDenied() } } private fun getDeviceLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) { multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) return } fusedLocationClient.lastLocation .addOnSuccessListener { location : Location? -> if (location === null) { Log.d(TAG, "Location is null") return@addOnSuccessListener } val message = "The device is located at: ${location.latitude}, ${location.longitude}" Log.d(TAG, message) Snackbar.make(binding.root, message, Snackbar.LENGTH_LONG).show() } } private fun handlePermissionDenied() { val errorMsg = "Sorry, you need to give us permissions before we can get your location. Check your settings menu and update your location permissions for this app." Snackbar.make(binding.root, errorMsg, Snackbar.LENGTH_LONG).show() binding.btnGetLocation.isEnabled = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPostRentalBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) multiplePermissionsResultLauncher.launch(APP_PERMISSIONS_LIST) this.firebaseAuth = FirebaseAuth.getInstance() this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() this.propertiesRepository = PropertiesRepository(applicationContext) val loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", null) if(loggedInUserEmail == null) { startActivity(Intent(this, LoginActivity::class.java)) } val propertyTypes = mutableListOf<String>("Property Type","Apartment", "Basement", "Condo", "House", "Multi Family House", "Townhouse") val spinner: Spinner = findViewById(R.id.etPropertyType) val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, propertyTypes) spinner.adapter = arrayAdapter this.binding.etPropertyType.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if(position > 0) { propertyTypeSelected = propertyTypes[position] } else { Snackbar.make(binding.root, "Please select property type", Snackbar.LENGTH_SHORT).show() } } override fun onNothingSelected(parent: AdapterView<*>?) { TODO("Not yet implemented") } } binding.btnPostRental.setOnClickListener(this) binding.btnGetLocation.setOnClickListener(this) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.menuMyListings -> { val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) return true } R.id.menuPostRental -> { val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } private fun validateInputs(): Boolean { val bedrooms = binding.etBedrooms.text.toString() val kitchen = binding.etKitchen.text.toString() val bathrooms = binding.etBathrooms.text.toString() val description = binding.etDescription.text.toString() val address = binding.etAddress.text.toString() val buildingName = binding.etBuildingName.text.toString() val postalCode = binding.etPostalCode.text.toString() val province = binding.etProvince.text.toString() val city = binding.etCity.text.toString() val rent = binding.etRent.text.toString() if(bedrooms.isNullOrEmpty()) { binding.etBedrooms.error = "This field is required" return false } else if(kitchen.isNullOrEmpty()) { binding.etKitchen.error = "This field is required" return false } else if(bathrooms.isNullOrEmpty()) { binding.etBathrooms.error = "This field is required" return false } else if(description.isNullOrEmpty()) { binding.etDescription.error = "This field is required" return false } else if(address.isNullOrEmpty()) { binding.etAddress.error = "This field is required" return false } else if(buildingName.isNullOrEmpty()) { binding.etBuildingName.error = "This field is required" return false } else if(postalCode.isNullOrEmpty()) { binding.etPostalCode.error = "This field is required" return false } else if(province.isNullOrEmpty()) { binding.etProvince.error = "This field is required" return false } else if(city.isNullOrEmpty()) { binding.etCity.error = "This field is required" return false } else if(rent.isNullOrEmpty()) { binding.etRent.error = "This field is required" return false } else { return true } } override fun onClick(v: View?) { when(v?.id) { R.id.btnPostRental -> { this.postRental() } R.id.btnGetLocation -> { getCurrentLocation() } } } private fun postRental() { val inputValidation = this.validateInputs() if(inputValidation) { val bedrooms = binding.etBedrooms.text.toString().toInt() val kitchen = binding.etKitchen.text.toString().toInt() val bathrooms = binding.etBathrooms.text.toString().toDouble() val description = binding.etDescription.text.toString() val address = binding.etAddress.text.toString() val isAvailable = binding.swAvailable.isChecked val buildingName = binding.etBuildingName.text.toString() val postalCode = binding.etPostalCode.text.toString() val province = binding.etProvince.text.toString() val city = binding.etCity.text.toString().uppercase() val rent = binding.etRent.text.toString().toInt() val phoneNumber = binding.etPhoneNumber.text.toString() val img = binding.etImage.text.toString() val loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", null) Log.d(TAG, "postRental: $loggedInUserEmail") if(loggedInUserEmail != null) { val propertyId = UUID.randomUUID().toString() val listingToAdd = Listings(propertyId, loggedInUserEmail,phoneNumber, propertyTypeSelected, bedrooms, kitchen, bathrooms, description, address, isAvailable, buildingName, postalCode, province, city, img, rent, GeoPoint(lat,lng)) val streetAddress = "$address, $city, $province $postalCode" getCoordinatesFromAddress(streetAddress) lifecycleScope.launch{ propertiesRepository.addPropertyToDB(listingToAdd) binding.etBedrooms.text.clear() binding.etKitchen.text.clear() binding.etBathrooms.text.clear() binding.etDescription.text.clear() binding.etAddress.text.clear() binding.swAvailable.isChecked = false binding.etBuildingName.text.clear() binding.etPostalCode.text.clear() binding.etProvince.text.clear() binding.etCity.text.clear() binding.etRent.text.clear() binding.etPhoneNumber.text.clear() binding.etImage.text.clear() startActivity(Intent(this@PostRentalActivity, MyListingsActivity::class.java)) } } else { startActivity(Intent(this, LoginActivity::class.java)) } } } private fun getCurrentLocation() { fusedLocationClient.lastLocation .addOnSuccessListener { location : Location? -> val geocoder: Geocoder = Geocoder(applicationContext, Locale.getDefault()) if (location == null) { Log.d(TAG, "Location is null") return@addOnSuccessListener } val message = "The device is located at: ${location.latitude}, ${location.longitude}" try { val searchResults: MutableList<Address>? = geocoder.getFromLocation(location.latitude, location.longitude, 1) if (searchResults == null) { Log.d(TAG, "ERROR: When retrieving results") } else if (searchResults.size == 0){ Log.d(TAG, "ERROR: No result found") } else{ val listingAddress = "${searchResults[0].featureName} ${searchResults[0].thoroughfare}" val addressEditText = findViewById<EditText>(R.id.etAddress) val cityEditText = findViewById<EditText>(R.id.etCity) val provinceEditText = findViewById<EditText>(R.id.etProvince) val postalCodeEditText = findViewById<EditText>(R.id.etPostalCode) addressEditText.setText(listingAddress) cityEditText.setText(searchResults[0].locality) provinceEditText.setText(searchResults[0].adminArea) postalCodeEditText.setText(searchResults[0].postalCode) lat = searchResults[0].latitude lng = searchResults[0].longitude } } catch (exception:Exception) { Log.d(TAG, "Exception occurred while getting matching address") Log.d(TAG, exception.toString()) } Log.d(TAG, message) } .addOnFailureListener{ Log.d(TAG, "getCurrentLocation: addOnFailureListener: $it") } } private fun getCoordinatesFromAddress(streetAddress: String) { val geocoder:Geocoder = Geocoder(applicationContext, Locale.getDefault()) try { val searchResults:MutableList<Address>? = geocoder.getFromLocationName(streetAddress, 1) if (searchResults == null) { Log.e(TAG, "searchResults variable is null") return } if (searchResults.size == 0) { Log.e(TAG, "getCoordinatesFromAddress: Search results are empty.", ) } else { val foundLocation:Address = searchResults[0] lat = foundLocation.latitude lng = foundLocation.longitude } } catch(ex:Exception) { Log.e(TAG, "Error encountered while getting coordinate location.") Log.e(TAG, ex.toString()) } } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/PostRentalActivity.kt
778378244
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.view.View.OnClickListener import android.widget.Toast import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityLoginBinding import com.example.rental_app.models.User import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.google.gson.reflect.TypeToken class LoginActivity : AppCompatActivity(), OnClickListener { private lateinit var binding: ActivityLoginBinding private lateinit var sharedPreferences: SharedPreferences private lateinit var firebaseAuth: FirebaseAuth private val TAG = this.javaClass.canonicalName private lateinit var prefEditor: SharedPreferences.Editor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() this.firebaseAuth = FirebaseAuth.getInstance() binding.loginButton.setOnClickListener(this) } override fun onClick(view: View?) { if (view != null) { when (view.id) { R.id.loginButton -> { Log.d(TAG, "onClick: Sign In Button Clicked") this.validateData() } } } } private fun validateData() { var validData = true var email = "" var password = "" if ( binding.username.text.toString().isEmpty()) { binding.username.error = "Email Cannot be Empty" validData = false } else { email = binding.username.text.toString() } if (binding.password.text.toString().isEmpty()) { binding.password.error = "Password Cannot be Empty" validData = false } else { password = binding.password.text.toString() } if (validData) { signIn(email, password) } else { Toast.makeText(this, "Please provide correct inputs", Toast.LENGTH_SHORT).show() } } private fun signIn(email: String, password: String){ this.firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this){task -> if(task.isSuccessful) { Log.d(TAG, "signIn: Login Successful: ${task.result.user?.uid}") Toast.makeText(this, "Login Successful", Toast.LENGTH_SHORT).show() saveToPrefs(email, password) goToMain() } else { Log.d(TAG, "signIn: Login Failed: ${task.exception}") Toast.makeText(this, "Authentication Failed. Check your credentials", Toast.LENGTH_SHORT).show() } } } private fun saveToPrefs(email: String, password: String) { // val prefs = applicationContext.getSharedPreferences(packageName, MODE_PRIVATE) // prefs.edit().putString("USER_EMAIL", email).apply() // prefs.edit().putString("USER_PASSWORD", password).apply() this.prefEditor.putString("USER_EMAIL", email) this.prefEditor.putString("USER_PASSWORD", password) this.prefEditor.apply() } private fun goToMain() { val mainIntent = Intent(this, MainActivity::class.java) startActivity(mainIntent) } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/LoginActivity.kt
4252126522
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.method.LinkMovementMethod import android.util.Log import android.view.View import android.widget.Toast import com.example.rental_app.MainActivity import com.example.rental_app.R import com.example.rental_app.databinding.ActivityRegistrationBinding import com.example.rental_app.models.User import com.example.rental_app.repositories.UserRepository import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import java.util.UUID class RegistrationActivity : AppCompatActivity(), View.OnClickListener { private val TAG = this.javaClass.canonicalName private lateinit var binding: ActivityRegistrationBinding private var userList:MutableList<User> = mutableListOf() private lateinit var sharedPreferences: SharedPreferences private lateinit var prefEditor: SharedPreferences.Editor private lateinit var firebaseAuth: FirebaseAuth private lateinit var userRepository: UserRepository override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.binding = ActivityRegistrationBinding.inflate(layoutInflater) setContentView(this.binding.root) this.setupHyperLink() this.binding.btnSignUp.setOnClickListener(this) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) this.prefEditor = this.sharedPreferences.edit() this.firebaseAuth = FirebaseAuth.getInstance() this.userRepository = UserRepository(applicationContext) } private fun setupHyperLink() { binding.cbPrivacyPolicy.movementMethod = LinkMovementMethod.getInstance() } override fun onClick(v: View?) { when(v?.id) { R.id.btnSignUp -> { this.signUp() } } } private fun signUp() { val inputValidation = this.validateInputs() if (inputValidation) { val firstName = this.binding.etFirstName.text.toString() val lastName = this.binding.etLastName.text.toString() val email = this.binding.etEmail.text.toString() val phoneNumber = this.binding.etPhone.text.toString() val password = this.binding.etPassword.text.toString() val emailIntent = Intent(Intent.ACTION_SEND).apply { data = Uri.parse("mailto: $email") putExtra(Intent.EXTRA_EMAIL, email) putExtra(Intent.EXTRA_SUBJECT, "Welcome to 4Rent.ca") putExtra(Intent.EXTRA_TEXT, "Welcome to 4Rent.ca, $firstName. Your account has been created successfully") } if (emailIntent.resolveActivity(packageManager) != null){ startActivity(emailIntent) } this.firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this){task -> if(task.isSuccessful) { val id = UUID.randomUUID().toString() val userToAdd = User(id, firstName, lastName, email, phoneNumber, password, mutableListOf(), mutableListOf(), false) userRepository.addUserToDB(userToAdd) Log.d(TAG, "createAccount: User account created with email $email") saveToPrefs(email, password) goToMain() } else { Log.d(TAG, "createAccount: Unable to create user account", task.exception) Toast.makeText(this, "Account creation failed", Toast.LENGTH_SHORT).show() } } Snackbar.make(binding.rootLayout, "Registration Successful", Snackbar.LENGTH_SHORT).show() } } private fun validateInputs(): Boolean { val firstName = this.binding.etFirstName.text.toString() val lastName = this.binding.etLastName.text.toString() val email = this.binding.etEmail.text.toString() val phoneNumber = this.binding.etPhone.text.toString() val password = this.binding.etPassword.text.toString() val confirmPassword = this.binding.etConfirmPassword.text.toString() val privacyPolicyChecked = this.binding.cbPrivacyPolicy.isChecked if(firstName.isNullOrEmpty()) { binding.etFirstName.error = "First Name is required" return false } else if(lastName.isNullOrEmpty()) { binding.etLastName.error = "Last Name is required" return false } else if(email.isNullOrEmpty()) { binding.etEmail.error = "Email is required" return false }else if(phoneNumber.isNullOrEmpty()) { binding.etEmail.error = "Phone is required" return false } else if(password.isNullOrEmpty()) { binding.etPassword.error = "Password is required" return false } else if(confirmPassword.isNullOrEmpty()) { binding.etConfirmPassword.error = "Password confirmation is required" return false } else if(password != confirmPassword) { binding.tvError.error = "Passwords don't match" return false } else if(!privacyPolicyChecked) { binding.tvError.error = "You must agree to Privacy Policy." return false } else { return true } } private fun saveToPrefs(email: String, password: String) { val prefs = applicationContext.getSharedPreferences(packageName, MODE_PRIVATE) prefs.edit().putString("USER_EMAIL", email).apply() prefs.edit().putString("USER_PASSWORD", password).apply() } private fun goToMain() { val mainIntent = Intent(this, MainActivity::class.java) startActivity(mainIntent) } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/RegistrationActivity.kt
3942362856
package com.example.rental_app.activities import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.location.Geocoder import android.location.Location import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import androidx.annotation.DrawableRes import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.example.rental_app.MainActivity import com.example.rental_app.MapboxUtils import com.example.rental_app.R import com.example.rental_app.databinding.ActivityResultDescriptionBinding import com.example.rental_app.models.Listings import com.example.rental_app.models.User import com.example.rental_app.repositories.PropertiesRepository import com.example.rental_app.repositories.UserRepository import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.firebase.auth.FirebaseAuth import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.mapbox.geojson.Point import com.mapbox.maps.CameraOptions import com.mapbox.maps.plugin.annotation.AnnotationConfig import com.mapbox.maps.plugin.annotation.AnnotationSourceOptions import com.mapbox.maps.plugin.annotation.annotations import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager import kotlinx.coroutines.launch import java.util.Locale class ResultDescriptionActivity : AppCompatActivity() { private lateinit var binding: ActivityResultDescriptionBinding private lateinit var fusedLocationClient: FusedLocationProviderClient private lateinit var sharedPreferences: SharedPreferences lateinit var prefEditor: SharedPreferences.Editor private var loggedUserObject: User? = User("", "", "", "", "", "") private lateinit var propertiesRepository: PropertiesRepository private lateinit var userRepository: UserRepository private val TAG = javaClass.canonicalName private var firebasePropertyId: String? = "" private var propertyId: String? = "" private lateinit var phoneNumber:String private lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.binding = ActivityResultDescriptionBinding.inflate(layoutInflater) setContentView(this.binding.root) this.sharedPreferences = getSharedPreferences("MY_APP_PREFS", MODE_PRIVATE) prefEditor = sharedPreferences.edit() setSupportActionBar(this.binding.menuToolbar) supportActionBar?.setDisplayShowTitleEnabled(true) supportActionBar?.title = "4Rent.ca" this.firebaseAuth = FirebaseAuth.getInstance() propertiesRepository = PropertiesRepository(applicationContext) userRepository = UserRepository(applicationContext) fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) propertiesRepository = PropertiesRepository(applicationContext) userRepository = UserRepository(applicationContext) fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // Got last known location. In some rare situations this can be null. var city: String = "" val geocoder: Geocoder = Geocoder(applicationContext, Locale.getDefault()) if (location === null) { Log.d("nearmeactivity", "Location is null") return@addOnSuccessListener } // Output the location val message = "The device is located at: ${location.latitude}, ${location.longitude}" Log.d("mayank", "onCreate:${message} ") addAnnotationToMap(location.latitude,location.longitude,R.drawable.mylocation) } var sourceScreen = intent.getStringExtra("SOURCE") if(sourceScreen == "MyListing") { binding.callOwner.isVisible = false binding.enquiry.isVisible = false } val loggedInUserEmail = sharedPreferences.getString("USER_EMAIL", "") if (loggedInUserEmail != "") { lifecycleScope.launch{ loggedUserObject = userRepository.getLoggedInUser(loggedInUserEmail) Log.d(TAG, "onStart: userData: ${loggedUserObject?.listings}") } } val propertyId = intent.getStringExtra("PROPERTY_ID") this.propertyId = propertyId lifecycleScope.launch{ val propertyData: Listings? = propertiesRepository.getPropertyById(propertyId) val firebaseListingId = propertiesRepository.getPropertyIdById(propertyId) firebasePropertyId = firebaseListingId phoneNumber = propertyData?.phoneNumber.toString() if (propertyData != null){ val initialCameraOptions = CameraOptions.Builder() .center(Point.fromLngLat(propertyData.coordinates.longitude, propertyData.coordinates.latitude)) .pitch(0.0) .zoom(8.0) .bearing(0.0) .build() binding.mapView.mapboxMap.setCamera(initialCameraOptions) addAnnotationToMap(propertyData.coordinates.latitude,propertyData.coordinates.longitude,R.drawable.red_marker) } val res = resources.getIdentifier(propertyData?.img, "drawable", packageName) binding.listingImg.setImageResource(res) binding.rent.text = "$${propertyData?.rent}/-" binding.desc.text = propertyData?.description binding.address.text = propertyData?.address binding.specs.text = "${propertyData?.bedrooms}Bed|${propertyData?.bathroom}Bath|\n${propertyData?.kitchen}Kitchen" binding.cityProvince.text = "${propertyData?.city},${propertyData?.province}" } binding.shortlist.setOnClickListener { lifecycleScope.launch { propertiesRepository.updateUserFavourites(loggedInUserEmail, firebasePropertyId) finish() } } binding.mapView.setOnTouchListener { _, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { // Disable scrolling when touching the nonScrollableView binding.scrollBlock.requestDisallowInterceptTouchEvent(true) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { // Enable scrolling when the touch is released or canceled binding.scrollBlock.requestDisallowInterceptTouchEvent(false) } } false } binding.callOwner.setOnClickListener { val callIntent = Intent(Intent.ACTION_CALL).apply { data = Uri.parse("tel:${phoneNumber}") } if (callIntent.resolveActivity(packageManager) != null){ startActivity(callIntent) } } binding.enquiry.setOnClickListener { val inquiryIntent = Intent(this, InquiryActivity::class.java) inquiryIntent.putExtra("PROPERTY_ID", propertyId) startActivity(inquiryIntent) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_options, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val loggedInUser = sharedPreferences.getString("USER_EMAIL", "") return when(item.itemId){ R.id.menuMyListings -> { if(loggedInUser != ""){ val myListingIntent = Intent(this, MyListingsActivity::class.java) startActivity(myListingIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuPostRental -> { if(loggedInUser != ""){ val postRentalIntent = Intent(this, PostRentalActivity::class.java) startActivity(postRentalIntent) }else{ startActivity(Intent(this, LoginActivity::class.java)) } return true } R.id.menuLogout -> { prefEditor.remove("USER_EMAIL") prefEditor.remove("USER_PASSWORD") prefEditor.apply() this.firebaseAuth.signOut() startActivity(Intent(this, LoginActivity::class.java)) return true } R.id.menuHome -> { startActivity(Intent(this, MainActivity::class.java)) return true } R.id.menuShortList -> { if(loggedInUser != ""){ startActivity(Intent(this, MyShortlistingsActivity::class.java)) }else{ startActivity(Intent(this, LoginActivity::class.java)) } startActivity(Intent(this, MyShortlistingsActivity::class.java)) return true } else -> super.onOptionsItemSelected(item) } } private fun addAnnotationToMap(lat:Double, lng:Double, @DrawableRes drawableImageResourceId: Int = R.drawable.red_marker) { Log.d("addOne", "Attempting to add annotation to map") val icon = MapboxUtils.bitmapFromDrawableRes(applicationContext, drawableImageResourceId) // error handling code: sometimes, the person may provide an image that cannot be // properly converted to a map marker if (icon == null) { Log.d("addOne", "ERROR: Unable to convert provided image into the correct format.") return } // code sets up the map so you can add markers val annotationApi = binding.mapView?.annotations val pointAnnotationManager = annotationApi?.createPointAnnotationManager( AnnotationConfig( annotationSourceOptions = AnnotationSourceOptions(maxZoom = 16) ) ) // Create a marker & configure the options for that marker val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions() .withPoint(Point.fromLngLat(lng, lat)) .withIconImage(icon) // Add the resulting pointAnnotation to the map. pointAnnotationManager?.create(pointAnnotationOptions) } }
Rentalapp/app/src/main/java/com/example/rental_app/activities/ResultDescriptionActivity.kt
395762650
package com.mba.codigo_de_barras 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.mba.codigo_de_barras", appContext.packageName) } }
LectorCodigoBarras/app/src/androidTest/java/com/mba/codigo_de_barras/ExampleInstrumentedTest.kt
3919708650
package com.mba.codigo_de_barras 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) } }
LectorCodigoBarras/app/src/test/java/com/mba/codigo_de_barras/ExampleUnitTest.kt
499087093
package com.mba.codigo_de_barras import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.google.zxing.integration.android.IntentIntegrator import com.mba.codigo_de_barras.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnScanner.setOnClickListener { initScanner()} } private fun initScanner() { IntentIntegrator(this).initiateScan() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if(result != null){ if(result.contents == null){ Toast.makeText(this, "Cancelado", Toast.LENGTH_SHORT).show() }else{ Toast.makeText(this, "El valor escaneado es: ${result.contents}", Toast.LENGTH_SHORT).show() } } else{ super.onActivityResult(requestCode, resultCode, data) } } }
LectorCodigoBarras/app/src/main/java/com/mba/codigo_de_barras/MainActivity.kt
2466158200
package com.example.pokedexapp import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException /* Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-2.0 */ fun <T> LiveData<T>.getOrAwaitValueTest( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(value: T) { data = value latch.countDown() [email protected](this) } } this.observeForever(observer) // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData value was never set.") } @Suppress("UNCHECKED_CAST") return data as T }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/LiveDataUtil.kt
186542769
package com.example.pokedexapp.di import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object TestAppModule { }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/di/TestAppModule.kt
4069942194
package com.example.pokedexapp 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.pokedexapp", appContext.packageName) } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/ExampleInstrumentedTest.kt
3173988911
package com.example.pokedexapp import android.content.ComponentName import android.content.Intent import android.os.Bundle import androidx.annotation.StyleRes import androidx.core.util.Preconditions import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import androidx.fragment.app.testing.EmptyFragmentActivity import androidx.fragment.app.testing.FragmentScenario //import androidx.fragment.app.testing.FragmentScenario.EmptyFragmentActivity import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.ExperimentalCoroutinesApi /** * launchFragmentInContainer from the androidx.fragment:fragment-testing library * is NOT possible to use right now as it uses a hardcoded Activity under the hood * (i.e. [EmptyFragmentActivity]) which is not annotated with @AndroidEntryPoint. * * As a workaround, use this function that is equivalent. It requires you to add * [HiltTestActivity] in the debug folder and include it in the debug AndroidManifest.xml file * as can be found in this project. */ inline fun <reified T : Fragment> launchFragmentInHiltContainer( fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = androidx.fragment.testing.manifest.R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory, crossinline action: T.() -> Unit = {} ) { val startActivityIntent = Intent.makeMainActivity( ComponentName( ApplicationProvider.getApplicationContext(), HiltTestActivity::class.java ) ).putExtra(EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId) ActivityScenario.launch<HiltTestActivity>(startActivityIntent).onActivity { activity -> activity.supportFragmentManager.fragmentFactory = factory val fragment: Fragment = activity.supportFragmentManager.fragmentFactory.instantiate( Preconditions.checkNotNull(T::class.java.classLoader), T::class.java.name ) fragment.arguments = fragmentArgs activity.supportFragmentManager .beginTransaction() .add(android.R.id.content, fragment, "") .commitNow() (fragment as T).action() } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/HiltExtension.kt
1765904654
package com.example.pokedexapp import android.app.Application import android.content.Context import androidx.test.runner.AndroidJUnitRunner import dagger.hilt.android.testing.HiltTestApplication class HiltTestRunner : AndroidJUnitRunner() { override fun newApplication( cl: ClassLoader?, className: String?, context: Context? ): Application { return super.newApplication(cl, HiltTestApplication::class.java.name, context) } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/HiltTestRunner.kt
573041130
package com.example.pokedexapp.data.repository import com.example.pokedexapp.data.model.pokemon.Move import com.example.pokedexapp.data.model.pokemon.MoveX import com.example.pokedexapp.data.model.pokemon.OfficialArtwork import com.example.pokedexapp.data.model.pokemon.Other import com.example.pokedexapp.data.model.pokemon.PokemonDto import com.example.pokedexapp.data.model.pokemon.Species import com.example.pokedexapp.data.model.pokemon.Sprites import com.example.pokedexapp.data.model.pokemon.Stat import com.example.pokedexapp.data.model.pokemon.StatX import com.example.pokedexapp.data.model.pokemon.Type import com.example.pokedexapp.data.model.pokemon.TypeX import com.example.pokedexapp.data.model.pokemon_list.PokemonListDto import com.example.pokedexapp.data.model.pokemon_list.Result import com.example.pokedexapp.data.model.pokemon_species.FlavorTextEntry import com.example.pokedexapp.data.model.pokemon_species.Language import com.example.pokedexapp.data.model.pokemon_species.PokemonSpeciesDto import com.example.pokedexapp.data.model.pokemon_species.Version import com.example.pokedexapp.domain.repository.PokemonRepository class FakePokemonRepositoryImplTest : PokemonRepository { override suspend fun getAllPokemons(): PokemonListDto { return PokemonListDto( count = 1302, next = "null", previous = "null", results = listOf( Result( name = "bulbasaur", url = "https://pokeapi.co/api/v2/pokemon/1/" ), Result( name = "ivysaur", url = "https://pokeapi.co/api/v2/pokemon/2/" ), Result( name = "venusaur", url = "https://pokeapi.co/api/v2/pokemon/3/" ), Result( name = "charmander", url = "https://pokeapi.co/api/v2/pokemon/4/" ) ) ) } override suspend fun getPokemonByID(pokemonID: String): PokemonDto { return PokemonDto( id = 1, name = "Bulbasaur", types = listOf( Type( slot = 1, type = TypeX( name = "grass", url = "https://pokeapi.co/api/v2/type/12/" ) ), Type( slot = 2, type = TypeX( name = "poison", url = "https://pokeapi.co/api/v2/type/4/" ) ) ), weight = 69, height = 7, moves = listOf( Move( MoveX( name = "razor-wind", url = "" ), versionGroupDetails = listOf() ) ), stats = listOf( Stat( baseStat = 45, effort = 0, stat = StatX( name = "hp", url = "" ) ), Stat( baseStat = 49, effort = 0, stat = StatX( name = "attack", url = "" ) ), Stat( baseStat = 49, effort = 0, stat = StatX( name = "defense", url = "" ) ), Stat( baseStat = 65, effort = 0, stat = StatX( name = "special-attack", url = "" ) ), Stat( baseStat = 65, effort = 0, stat = StatX( name = "special-defense", url = "" ) ), Stat( baseStat = 45, effort = 0, stat = StatX( name = "speed", url = "" ) ) ), abilities = listOf(), baseExperience = 0, forms = listOf(), gameİndices = listOf(), heldİtems = listOf(), isDefault = true, locationAreaEncounters = "", order = 0, pastAbilities = listOf(), pastTypes = listOf(), species = Species( name = "", url = "" ), sprites = Sprites( backShinyFemale = null, backShiny = null, backFemale = null, backDefault = null, frontDefault = null, frontShinyFemale = null, frontShiny = null, frontFemale = null, versions = null, other = Other( dreamWorld = null, home = null, officialArtwork = OfficialArtwork( frontShiny = null, frontDefault = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ) ) ) ) } override suspend fun getPokemonAboutByID(pokemonID: String): PokemonSpeciesDto { return PokemonSpeciesDto( baseHappiness = null, captureRate = null, color = null, eggGroups = null, evolutionChain = null, evolvesFromSpecies = null, flavorTextEntries = listOf( FlavorTextEntry( flavorText = "This is pokemon detail", language = Language("", ""), version = Version("", "") ) ), formDescriptions = null, formsSwitchable = null, genderRate = null, genera = null, generation = null, growthRate = null, habitat = null, hasGenderDifferences = null, hatchCounter = null, id = null, isBaby = null, isLegendary = null, isMythical = null, name = null, names = null, order = null, palParkEncounters = null, pokedexNumbers = null, shape = null, varieties = null ) } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/data/repository/FakePokemonRepositoryImplTest.kt
2488782657
package com.example.pokedexapp.presentation.view.home import android.util.Log import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.test.espresso.Espresso import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.filters.MediumTest import com.example.pokedexapp.R import com.example.pokedexapp.data.repository.FakePokemonRepositoryImplTest import com.example.pokedexapp.domain.model.Pokemon import com.example.pokedexapp.domain.use_case.GetAllPokemonsUseCase import com.example.pokedexapp.getOrAwaitValueTest import com.example.pokedexapp.launchFragmentInHiltContainer import com.example.pokedexapp.presentation.MainFragmentFactory import com.example.pokedexapp.presentation.view.detail.DetailPokemonListData import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import javax.inject.Inject @MediumTest @HiltAndroidTest @ExperimentalCoroutinesApi class HomeFragmentTest { @get: Rule var hiltRule = HiltAndroidRule(this) @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @Inject lateinit var fragmentFactory: MainFragmentFactory private lateinit var navController: NavController private lateinit var testHomeViewModel: HomeViewModel @Before fun setup() { hiltRule.inject() navController = Mockito.mock(NavController::class.java) launchFragmentInHiltContainer<HomeFragment>( factory = fragmentFactory ) { Navigation.setViewNavController(requireView(), navController) testHomeViewModel = homeViewModel } } @Test fun testNavigationFromHomeToDetail() { Thread.sleep(3000) val pokemonList = testHomeViewModel.shownList.getOrAwaitValueTest()!! Espresso.onView(ViewMatchers.withId(R.id.pokemonListRecyclerView)).perform( RecyclerViewActions.actionOnItemAtPosition<HomeListAdapter.HomeListViewHolder>( 0, click() ) ) Mockito.verify(navController).navigate( HomeFragmentDirections.actionHomeFragmentToDetailFragment( "0", DetailPokemonListData(pokemonList) ) ) } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/presentation/view/home/HomeFragmentTest.kt
1234843958
package com.example.pokedexapp.presentation.view.detail import android.os.Bundle import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.test.espresso.Espresso import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.swipeLeft import androidx.test.espresso.action.ViewActions.swipeRight import androidx.test.espresso.matcher.ViewMatchers import androidx.test.filters.MediumTest import com.example.pokedexapp.R import com.example.pokedexapp.domain.model.Pokemon import com.example.pokedexapp.launchFragmentInHiltContainer import com.example.pokedexapp.presentation.MainFragmentFactory import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito import javax.inject.Inject @MediumTest @HiltAndroidTest @ExperimentalCoroutinesApi class DetailFragmentTest { @get:Rule var hiltRule = HiltAndroidRule(this) @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @Inject lateinit var fragmentFactory: MainFragmentFactory private lateinit var navController: NavController private lateinit var pokemonList: DetailPokemonListData private lateinit var pokemonPosition: String @Before fun setup() { hiltRule.inject() navController = Mockito.mock(NavController::class.java) pokemonPosition = "1" pokemonList = DetailPokemonListData( listOf( Pokemon( id = "1", name = "bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ), Pokemon( id = "2", name = "ivysaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png" ), Pokemon( id = "3", name = "venusaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png" ) ) ) val args = Bundle().apply { putString("pokemonPosition", pokemonPosition) putSerializable("pokemonList", pokemonList) } launchFragmentInHiltContainer<DetailFragment>( factory = fragmentFactory, fragmentArgs = args ) { Navigation.setViewNavController(requireView(), navController) } } @Test fun testNavigationFromDetailToRightDetail() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.detailToRightImageView)).perform(click()) Mockito.verify(navController).navigate( DetailFragmentDirections.actionDetailFragmentSelf( (pokemonPosition.toInt() + 1).toString(), pokemonList ) ) } @Test fun testNavigationFromDetailToLeftDetail() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.detailToLeftImageView)).perform(click()) Mockito.verify(navController).navigate( DetailFragmentDirections.actionDetailFragmentSelf( (pokemonPosition.toInt() - 1).toString(), pokemonList ) ) } @Test fun testNavigationFromMostLeftDetailToLeftDetail() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.detailToLeftImageView)).perform(click()) Mockito.verify(navController, Mockito.times(0)).navigate( DetailFragmentDirections.actionDetailFragmentSelf( (-1).toString(), pokemonList ) ) } @Test fun testNavigationFromMostRightDetailToRightDetail() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.detailToLeftImageView)).perform(click()) Mockito.verify(navController, Mockito.times(0)).navigate( DetailFragmentDirections.actionDetailFragmentSelf( pokemonList.pokemonList.size.toString(), pokemonList ) ) } @Test fun testNavigationSwipeToRightForLeft() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.PokemonDetailImage)).perform(swipeRight()) Mockito.verify(navController).navigate( DetailFragmentDirections.actionDetailFragmentSelf( (pokemonPosition.toInt() - 1).toString(), pokemonList ) ) } @Test fun testNavigationSwipeToLeftForRight() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.PokemonDetailImage)).perform(swipeLeft()) Mockito.verify(navController).navigate( DetailFragmentDirections.actionDetailFragmentSelf( (pokemonPosition.toInt() + 1).toString(), pokemonList ) ) } @Test fun testOnBackPressed() { Espresso.pressBack() Mockito.verify(navController).popBackStack(R.id.homeFragment, false) } @Test fun testOnBackButtonPressed() { Thread.sleep(2000) Espresso.onView(ViewMatchers.withId(R.id.detailOnBackImageView)).perform(click()) Mockito.verify(navController).popBackStack(R.id.homeFragment, false) } }
pokedex-app/app/src/androidTest/java/com/example/pokedexapp/presentation/view/detail/DetailFragmentTest.kt
1144648283
package com.example.pokedexapp import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException /* Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-2.0 */ fun <T> LiveData<T>.getOrAwaitValueTest( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(value: T) { data = value latch.countDown() [email protected](this) } } this.observeForever(observer) // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { throw TimeoutException("LiveData value was never set.") } @Suppress("UNCHECKED_CAST") return data as T }
pokedex-app/app/src/test/java/com/example/pokedexapp/LiveDataUtil.kt
186542769
package com.example.pokedexapp 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) } }
pokedex-app/app/src/test/java/com/example/pokedexapp/ExampleUnitTest.kt
3387862668
package com.example.pokedexapp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.rules.TestWatcher import org.junit.runner.Description @ExperimentalCoroutinesApi class MainDispatcherRule( val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(), ) : TestWatcher() { override fun starting(description: Description) { Dispatchers.setMain(testDispatcher) } override fun finished(description: Description) { Dispatchers.resetMain() } }
pokedex-app/app/src/test/java/com/example/pokedexapp/MainDispatcherRule.kt
189298932
package com.example.pokedexapp.data.repository import com.example.pokedexapp.data.model.pokemon.Move import com.example.pokedexapp.data.model.pokemon.MoveX import com.example.pokedexapp.data.model.pokemon.OfficialArtwork import com.example.pokedexapp.data.model.pokemon.Other import com.example.pokedexapp.data.model.pokemon.PokemonDto import com.example.pokedexapp.data.model.pokemon.Species import com.example.pokedexapp.data.model.pokemon.Sprites import com.example.pokedexapp.data.model.pokemon.Stat import com.example.pokedexapp.data.model.pokemon.StatX import com.example.pokedexapp.data.model.pokemon.Type import com.example.pokedexapp.data.model.pokemon.TypeX import com.example.pokedexapp.data.model.pokemon_list.PokemonListDto import com.example.pokedexapp.data.model.pokemon_list.Result import com.example.pokedexapp.data.model.pokemon_species.FlavorTextEntry import com.example.pokedexapp.data.model.pokemon_species.Language import com.example.pokedexapp.data.model.pokemon_species.PokemonSpeciesDto import com.example.pokedexapp.data.model.pokemon_species.Version import com.example.pokedexapp.domain.repository.PokemonRepository class FakePokemonRepositoryImpl : PokemonRepository { override suspend fun getAllPokemons(): PokemonListDto { return PokemonListDto( count = 1302, next = "null", previous = "null", results = listOf( Result( name = "bulbasaur", url = "https://pokeapi.co/api/v2/pokemon/1/" ), Result( name = "ivysaur", url = "https://pokeapi.co/api/v2/pokemon/2/" ), Result( name = "venusaur", url = "https://pokeapi.co/api/v2/pokemon/3/" ), Result( name = "charmander", url = "https://pokeapi.co/api/v2/pokemon/4/" ) ) ) } override suspend fun getPokemonByID(pokemonID: String): PokemonDto { return PokemonDto( id = 1, name = "Bulbasaur", types = listOf( Type( slot = 1, type = TypeX( name = "grass", url = "https://pokeapi.co/api/v2/type/12/" ) ), Type( slot = 2, type = TypeX( name = "poison", url = "https://pokeapi.co/api/v2/type/4/" ) ) ), weight = 69, height = 7, moves = listOf( Move( MoveX( name = "razor-wind", url = "" ), versionGroupDetails = listOf() ) ), stats = listOf( Stat( baseStat = 45, effort = 0, stat = StatX( name = "hp", url = "" ) ), Stat( baseStat = 49, effort = 0, stat = StatX( name = "attack", url = "" ) ), Stat( baseStat = 49, effort = 0, stat = StatX( name = "defense", url = "" ) ), Stat( baseStat = 65, effort = 0, stat = StatX( name = "special-attack", url = "" ) ), Stat( baseStat = 65, effort = 0, stat = StatX( name = "special-defense", url = "" ) ), Stat( baseStat = 45, effort = 0, stat = StatX( name = "speed", url = "" ) ) ), abilities = listOf(), baseExperience = 0, forms = listOf(), gameİndices = listOf(), heldİtems = listOf(), isDefault = true, locationAreaEncounters = "", order = 0, pastAbilities = listOf(), pastTypes = listOf(), species = Species( name = "", url = "" ), sprites = Sprites( backShinyFemale = null, backShiny = null, backFemale = null, backDefault = null, frontDefault = null, frontShinyFemale = null, frontShiny = null, frontFemale = null, versions = null, other = Other( dreamWorld = null, home = null, officialArtwork = OfficialArtwork( frontShiny = null, frontDefault = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ) ) ) ) } override suspend fun getPokemonAboutByID(pokemonID: String): PokemonSpeciesDto { return PokemonSpeciesDto( baseHappiness = null, captureRate = null, color = null, eggGroups = null, evolutionChain = null, evolvesFromSpecies = null, flavorTextEntries = listOf( FlavorTextEntry( flavorText = "This is pokemon detail", language = Language("", ""), version = Version("", "") ) ), formDescriptions = null, formsSwitchable = null, genderRate = null, genera = null, generation = null, growthRate = null, habitat = null, hasGenderDifferences = null, hatchCounter = null, id = null, isBaby = null, isLegendary = null, isMythical = null, name = null, names = null, order = null, palParkEncounters = null, pokedexNumbers = null, shape = null, varieties = null ) } }
pokedex-app/app/src/test/java/com/example/pokedexapp/data/repository/FakePokemonRepositoryImpl.kt
1518715662
package com.example.pokedexapp.presentation.home import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.pokedexapp.MainDispatcherRule import com.example.pokedexapp.data.repository.FakePokemonRepositoryImpl import com.example.pokedexapp.domain.model.Pokemon import com.example.pokedexapp.domain.use_case.GetAllPokemonsUseCase import com.example.pokedexapp.getOrAwaitValueTest import com.example.pokedexapp.presentation.view.home.HomeViewModel import com.example.pokedexapp.presentation.view.home.SortEvent import com.google.common.truth.Truth import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class HomeViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule val mainDispatcherRule = MainDispatcherRule() private lateinit var homeViewModel: HomeViewModel @Before fun setup() { homeViewModel = HomeViewModel(GetAllPokemonsUseCase(FakePokemonRepositoryImpl())) homeViewModel.shownList.getOrAwaitValueTest() } @Test fun `check list`() = runBlocking { val value = homeViewModel.shownList.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( listOf( Pokemon( id = "1", name = "bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ), Pokemon( id = "2", name = "ivysaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png" ), Pokemon( id = "3", name = "venusaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png" ), Pokemon( id = "4", name = "charmander", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/4.png" ) ) ) } @Test fun `search pokemon with id`() = runBlocking { homeViewModel.searchPokemon("1") val value = homeViewModel.shownList.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( listOf( Pokemon( id = "1", name = "bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ) ) ) } @Test fun `search pokemon with name`() = runBlocking { homeViewModel.searchPokemon("bulbasaur") val value = homeViewModel.shownList.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( listOf( Pokemon( id = "1", name = "bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ) ) ) } @Test fun `sort pokemons by name`() = runBlocking { homeViewModel.sortEvent.value = SortEvent.ByName homeViewModel.sortShownList() val value = homeViewModel.shownList.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( listOf( Pokemon( id = "1", name = "bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png" ), Pokemon( id = "4", name = "charmander", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/4.png" ), Pokemon( id = "2", name = "ivysaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png" ), Pokemon( id = "3", name = "venusaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png" ) ) ) } }
pokedex-app/app/src/test/java/com/example/pokedexapp/presentation/home/HomeViewModelTest.kt
3814661595
package com.example.pokedexapp.presentation.detail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.pokedexapp.MainDispatcherRule import com.example.pokedexapp.data.repository.FakePokemonRepositoryImpl import com.example.pokedexapp.domain.model.PokemonAbout import com.example.pokedexapp.domain.model.PokemonDetail import com.example.pokedexapp.domain.model.PokemonType import com.example.pokedexapp.domain.use_case.GetPokemonAboutByIDUseCase import com.example.pokedexapp.domain.use_case.GetPokemonByIDUseCase import com.example.pokedexapp.getOrAwaitValueTest import com.example.pokedexapp.presentation.view.detail.DetailViewModel import com.google.common.truth.Truth import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class DetailViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule val mainDispatcherRule = MainDispatcherRule() private lateinit var detailViewModel: DetailViewModel @Before fun setup() { detailViewModel = DetailViewModel( getPokemonAboutByIDUseCase = GetPokemonAboutByIDUseCase(FakePokemonRepositoryImpl()), getPokemonByIDUseCase = GetPokemonByIDUseCase(FakePokemonRepositoryImpl()) ) detailViewModel.loadData("1") } @Test fun `check detail`() = runBlocking { val value = detailViewModel.pokemonDetail.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( PokemonDetail( id = "#001", name = "Bulbasaur", imageUrl = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png", types = listOf( PokemonType( typeName = "Grass", typeColor = 2131034218 ), PokemonType( typeName = "Poison", typeColor = 2131034880 ) ), weight = "6,9 kg", height = "0,7 m", moves = listOf( "razor-wind", ), hp = "045", hpInt = 45, attack = "049", attackInt = 49, defense = "049", defenseInt = 49, specialAttack = "065", specialAttackInt = 65, specialDefence = "065", specialDefenceInt = 65, speed = "045", speedInt = 45, color = 2131034218, colorTransparent = 2131034218 ) ) } @Test fun `check about`() = runBlocking { val value = detailViewModel.pokemonAbout.getOrAwaitValueTest() Truth.assertThat(value).isEqualTo( PokemonAbout("This is pokemon detail") ) } }
pokedex-app/app/src/test/java/com/example/pokedexapp/presentation/detail/DetailViewModelTest.kt
4169038527
package com.example.pokedexapp.di import com.example.pokedexapp.data.remote.PokemonApi import com.example.pokedexapp.util.Constants.BASE_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Singleton fun providePokemonApi(): PokemonApi { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create() } }
pokedex-app/app/src/main/java/com/example/pokedexapp/di/AppModule.kt
3787022211
package com.example.pokedexapp.di import com.example.pokedexapp.data.repository.PokemonRepositoryImpl import com.example.pokedexapp.domain.repository.PokemonRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds @Singleton abstract fun bindPokemonRepository( pokemonRepositoryImpl: PokemonRepositoryImpl ): PokemonRepository }
pokedex-app/app/src/main/java/com/example/pokedexapp/di/RepositoryModule.kt
3458948889
package com.example.pokedexapp.util sealed class Resource<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T?): Resource<T>(data) class Error<T>(message: String, data: T? = null): Resource<T>(data, message) }
pokedex-app/app/src/main/java/com/example/pokedexapp/util/Resource.kt
215160029
package com.example.pokedexapp.util import android.widget.ImageView import androidx.annotation.ColorInt import androidx.databinding.BindingAdapter import androidx.swiperefreshlayout.widget.CircularProgressDrawable import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.pokedexapp.R import com.google.android.material.progressindicator.LinearProgressIndicator fun ImageView.downloadFromUrl(url: String?) { val options = RequestOptions() .placeholder( R.drawable.silhouette ) Glide.with(context) .setDefaultRequestOptions(options) .load(url) .into(this) } @BindingAdapter("android:downloadURL") fun downloadImage(view: ImageView, url: String?) { view.downloadFromUrl(url) } @BindingAdapter("app:indicatorColor") fun setIndicatorColor(progressIndicator: LinearProgressIndicator, @ColorInt color: Int) { progressIndicator.setIndicatorColor(color) }
pokedex-app/app/src/main/java/com/example/pokedexapp/util/Util.kt
2647215434
package com.example.pokedexapp.util object Constants { const val BASE_URL = "https://pokeapi.co/api/v2/" const val BASE_IMAGE_URL = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/" }
pokedex-app/app/src/main/java/com/example/pokedexapp/util/Constants.kt
2574548925
package com.example.pokedexapp.data.repository import com.example.pokedexapp.data.model.pokemon.PokemonDto import com.example.pokedexapp.data.model.pokemon_list.PokemonListDto import com.example.pokedexapp.data.model.pokemon_species.PokemonSpeciesDto import com.example.pokedexapp.data.remote.PokemonApi import com.example.pokedexapp.domain.repository.PokemonRepository import javax.inject.Inject class PokemonRepositoryImpl @Inject constructor( private val api: PokemonApi ) : PokemonRepository { override suspend fun getAllPokemons(): PokemonListDto { return api.getAllPokemons() } override suspend fun getPokemonByID(pokemonID: String): PokemonDto { return api.getPokemonByID(pokemonID) } override suspend fun getPokemonAboutByID(pokemonID: String): PokemonSpeciesDto { return api.getPokemonAboutByID(pokemonID) } }
pokedex-app/app/src/main/java/com/example/pokedexapp/data/repository/PokemonRepositoryImpl.kt
2320125838
package com.example.pokedexapp.data.mapper import androidx.core.graphics.toColor import com.example.pokedexapp.data.model.pokemon.PokemonDto import com.example.pokedexapp.data.model.pokemon.Stat import com.example.pokedexapp.domain.model.PokemonColor import com.example.pokedexapp.domain.model.PokemonDetail import com.example.pokedexapp.domain.model.PokemonType fun PokemonDto.toPokemonDetail(): PokemonDetail { return PokemonDetail( id = idOrganize(id.toString()), name = nameOrganize(name), imageUrl = sprites.other.officialArtwork.frontDefault, types = types.map { it.type.name }.map { pokemonTypeCreate(it) }, weight = weightAndHeightOrganize(weight) + " kg", height = weightAndHeightOrganize(height) + " m", moves = moves.map { it.move.name }, hp = statOrganizer(statFinder(stats, "hp")), hpInt = statFinder(stats, "hp").toInt(), attack = statOrganizer(statFinder(stats, "attack")), attackInt = statFinder(stats, "attack").toInt(), defense = statOrganizer(statFinder(stats, "defense")), defenseInt = statFinder(stats, "defense").toInt(), specialAttack = statOrganizer(statFinder(stats, "special-attack")), specialAttackInt = statFinder(stats, "special-attack").toInt(), specialDefence = statOrganizer(statFinder(stats, "special-defense")), specialDefenceInt = statFinder(stats, "special-defense").toInt(), speed = statOrganizer(statFinder(stats, "speed")), speedInt = statFinder(stats, "speed").toInt(), color = PokemonColor.getColor(types.map { it.type.name }[0]).color, colorTransparent = PokemonColor.getColor(types.map { it.type.name }[0]).color, ) } fun statFinder(stats: List<Stat>, statName: String): String { return stats.find { it.stat.name == statName }?.baseStat.toString() } fun statOrganizer(stat: String): String { return stat.padStart(3, '0') } fun weightAndHeightOrganize(number: Int): String { val formattedNumber = if (number < 10) { "0$number" } else { number.toString() } return if (formattedNumber.length == 2) { formattedNumber[0] + "," + formattedNumber[1] } else { formattedNumber.substring( 0, formattedNumber.length - 1 ) + "," + formattedNumber[formattedNumber.length - 1] } } fun pokemonTypeCreate(typeName: String): PokemonType { return PokemonType( typeName = nameOrganize(typeName), typeColor = PokemonColor.getColor(typeName).color ) } fun nameOrganize(name: String): String { return name.replaceFirstChar { it.uppercase() } } fun idOrganize(id: String): String { return "#" + id.padStart(3, '0') }
pokedex-app/app/src/main/java/com/example/pokedexapp/data/mapper/PokemonDetailMapper.kt
3399389009
package com.example.pokedexapp.data.mapper import com.example.pokedexapp.data.model.pokemon_species.PokemonSpeciesDto import com.example.pokedexapp.domain.model.PokemonAbout fun PokemonSpeciesDto.toPokemonDetail(): PokemonAbout { return PokemonAbout( about = aboutTextCleaner(flavorTextEntries.first().flavorText) ) } fun aboutTextCleaner(aboutText: String): String { return aboutText.replace("\n", " ") }
pokedex-app/app/src/main/java/com/example/pokedexapp/data/mapper/PokemonAboutMapper.kt
211124139
package com.example.pokedexapp.data.mapper import com.example.pokedexapp.data.model.pokemon_list.Result import com.example.pokedexapp.domain.model.Pokemon import com.example.pokedexapp.util.Constants.BASE_IMAGE_URL fun Result.toPokemon(): Pokemon { val id = url.trim('/').split("/").last() val imageUrl = "$BASE_IMAGE_URL$id.png" return Pokemon( id = id, name = name, imageUrl = imageUrl ) }
pokedex-app/app/src/main/java/com/example/pokedexapp/data/mapper/PokemonMapper.kt
4269483251
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class UltraSunUltraMoon( @SerializedName("front_default") val frontDefault: String, @SerializedName("front_female") val frontFemale: Any, @SerializedName("front_shiny") val frontShiny: String, @SerializedName("front_shiny_female") val frontShinyFemale: Any )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/UltraSunUltraMoon.kt
1983229797
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Gold( @SerializedName("back_default") val backDefault: String, @SerializedName("back_shiny") val backShiny: String, @SerializedName("front_default") val frontDefault: String, @SerializedName("front_shiny") val frontShiny: String, @SerializedName("front_transparent") val frontTransparent: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Gold.kt
2352878933
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Stat( @SerializedName("base_stat") val baseStat: Int, @SerializedName("effort") val effort: Int, @SerializedName("stat") val stat: com.example.pokedexapp.data.model.pokemon.StatX )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Stat.kt
4259166122
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Generationİv( @SerializedName("diamond-pearl") val diamondPearl: com.example.pokedexapp.data.model.pokemon.DiamondPearl, @SerializedName("heartgold-soulsilver") val heartgoldSoulsilver: com.example.pokedexapp.data.model.pokemon.HeartgoldSoulsilver, @SerializedName("platinum") val platinum: com.example.pokedexapp.data.model.pokemon.Platinum )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Generationİv.kt
2091283570
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Move( @SerializedName("move") val move: com.example.pokedexapp.data.model.pokemon.MoveX, @SerializedName("version_group_details") val versionGroupDetails: List<com.example.pokedexapp.data.model.pokemon.VersionGroupDetail> )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Move.kt
1388530021
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class VersionGroup( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/VersionGroup.kt
3489822739
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class FireredLeafgreen( @SerializedName("back_default") val backDefault: String, @SerializedName("back_shiny") val backShiny: String, @SerializedName("front_default") val frontDefault: String, @SerializedName("front_shiny") val frontShiny: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/FireredLeafgreen.kt
3681296982
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class MoveLearnMethod( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/MoveLearnMethod.kt
1867570859
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Form( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Form.kt
3687406006
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Generationİ( @SerializedName("red-blue") val redBlue: com.example.pokedexapp.data.model.pokemon.RedBlue, @SerializedName("yellow") val yellow: com.example.pokedexapp.data.model.pokemon.Yellow )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Generationİ.kt
273726208
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class HeartgoldSoulsilver( @SerializedName("back_default") val backDefault: String, @SerializedName("back_female") val backFemale: Any, @SerializedName("back_shiny") val backShiny: String, @SerializedName("back_shiny_female") val backShinyFemale: Any, @SerializedName("front_default") val frontDefault: String, @SerializedName("front_female") val frontFemale: Any, @SerializedName("front_shiny") val frontShiny: String, @SerializedName("front_shiny_female") val frontShinyFemale: Any )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/HeartgoldSoulsilver.kt
3098312775
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class VersionGroupDetail( @SerializedName("level_learned_at") val levelLearnedAt: Int, @SerializedName("move_learn_method") val moveLearnMethod: com.example.pokedexapp.data.model.pokemon.MoveLearnMethod, @SerializedName("version_group") val versionGroup: com.example.pokedexapp.data.model.pokemon.VersionGroup )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/VersionGroupDetail.kt
2676509580
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class DreamWorld( @SerializedName("front_default") val frontDefault: String, @SerializedName("front_female") val frontFemale: Any )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/DreamWorld.kt
635346327
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class PokemonDto( @SerializedName("abilities") val abilities: List<Ability>, @SerializedName("base_experience") val baseExperience: Int, @SerializedName("forms") val forms: List<Form>, @SerializedName("game_indices") val gameİndices: List<Gameİndice>, @SerializedName("height") val height: Int, @SerializedName("held_items") val heldİtems: List<Any>, @SerializedName("id") val id: Int, @SerializedName("is_default") val isDefault: Boolean, @SerializedName("location_area_encounters") val locationAreaEncounters: String, @SerializedName("moves") val moves: List<Move>, @SerializedName("name") val name: String, @SerializedName("order") val order: Int, @SerializedName("past_abilities") val pastAbilities: List<Any>, @SerializedName("past_types") val pastTypes: List<Any>, @SerializedName("species") val species: Species, @SerializedName("sprites") val sprites: Sprites, @SerializedName("stats") val stats: List<Stat>, @SerializedName("types") val types: List<Type>, @SerializedName("weight") val weight: Int )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/PokemonDto.kt
3694606572
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Versions( @SerializedName("generation-v") val generationV: com.example.pokedexapp.data.model.pokemon.GenerationV, @SerializedName("generation-vi") val generationVi: com.example.pokedexapp.data.model.pokemon.GenerationVi, @SerializedName("generation-vii") val generationVii: com.example.pokedexapp.data.model.pokemon.GenerationVii, @SerializedName("generation-viii") val generationViii: com.example.pokedexapp.data.model.pokemon.GenerationViii, @SerializedName("generation-i") val generationİ: com.example.pokedexapp.data.model.pokemon.Generationİ, @SerializedName("generation-ii") val generationİi: com.example.pokedexapp.data.model.pokemon.Generationİi, @SerializedName("generation-iii") val generationİii: com.example.pokedexapp.data.model.pokemon.Generationİii, @SerializedName("generation-iv") val generationİv: com.example.pokedexapp.data.model.pokemon.Generationİv )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Versions.kt
3247288091
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class AbilityX( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/AbilityX.kt
2660947781
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Generationİii( @SerializedName("emerald") val emerald: com.example.pokedexapp.data.model.pokemon.Emerald, @SerializedName("firered-leafgreen") val fireredLeafgreen: com.example.pokedexapp.data.model.pokemon.FireredLeafgreen, @SerializedName("ruby-sapphire") val rubySapphire: com.example.pokedexapp.data.model.pokemon.RubySapphire )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Generationİii.kt
1431542651
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class StatX( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/StatX.kt
1415746529
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class GenerationViii( @SerializedName("icons") val icons: com.example.pokedexapp.data.model.pokemon.İcons )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/GenerationViii.kt
1886322176
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Sprites( @SerializedName("back_default") val backDefault: String?, @SerializedName("back_female") val backFemale: Any?, @SerializedName("back_shiny") val backShiny: String?, @SerializedName("back_shiny_female") val backShinyFemale: Any?, @SerializedName("front_default") val frontDefault: String?, @SerializedName("front_female") val frontFemale: Any?, @SerializedName("front_shiny") val frontShiny: String?, @SerializedName("front_shiny_female") val frontShinyFemale: Any?, @SerializedName("other") val other: Other, @SerializedName("versions") val versions: Versions? )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Sprites.kt
3962617921
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class RubySapphire( @SerializedName("back_default") val backDefault: String, @SerializedName("back_shiny") val backShiny: String, @SerializedName("front_default") val frontDefault: String, @SerializedName("front_shiny") val frontShiny: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/RubySapphire.kt
3335557099
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Version( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Version.kt
4223134117
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Ability( @SerializedName("ability") val ability: com.example.pokedexapp.data.model.pokemon.AbilityX, @SerializedName("is_hidden") val isHidden: Boolean, @SerializedName("slot") val slot: Int )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Ability.kt
1707742700
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Species( @SerializedName("name") val name: String, @SerializedName("url") val url: String )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Species.kt
3179255029
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class OfficialArtwork( @SerializedName("front_default") val frontDefault: String, @SerializedName("front_shiny") val frontShiny: String? )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/OfficialArtwork.kt
3009523116
package com.example.pokedexapp.data.model.pokemon import com.google.gson.annotations.SerializedName data class Animated( @SerializedName("back_default") val backDefault: String, @SerializedName("back_female") val backFemale: Any, @SerializedName("back_shiny") val backShiny: String, @SerializedName("back_shiny_female") val backShinyFemale: Any, @SerializedName("front_default") val frontDefault: String, @SerializedName("front_female") val frontFemale: Any, @SerializedName("front_shiny") val frontShiny: String, @SerializedName("front_shiny_female") val frontShinyFemale: Any )
pokedex-app/app/src/main/java/com/example/pokedexapp/data/model/pokemon/Animated.kt
1429618008