content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.tddmasterclass.utils
object TestIdlingResource {
private const val RESOURCE = "GLOBAL"
@JvmField
val countingIdlingResource
= SimpleCountingIdlingResource(RESOURCE)
fun increment() {
countingIdlingResource.increment()
}
fun decrement() {
if (!countingIdlingResource.isIdleNow) {
countingIdlingResource.decrement()
}
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/utils/TestIdlingResource.kt | 3367716460 |
package com.example.shoping
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.shoping", appContext.packageName)
}
} | shoping.app/app/src/androidTest/java/com/example/shoping/ExampleInstrumentedTest.kt | 1245539152 |
package com.example.shoping
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)
}
} | shoping.app/app/src/test/java/com/example/shoping/ExampleUnitTest.kt | 2305989360 |
package com.example.shoping.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.shoping.util.Resource
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val firebaseAuth: FirebaseAuth
): ViewModel() {
private val _login = MutableSharedFlow<Resource<FirebaseUser>>()
val login = _login.asSharedFlow()
private val _resetPassword = MutableSharedFlow<Resource<String>>()
val resetPassword = _resetPassword.asSharedFlow()
fun login(email: String, password: String)
{
viewModelScope.launch {
_login.emit(Resource.Loading())
}
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener {
viewModelScope.launch {
it.user?.let {
_login.emit(Resource.Success(it))
}
}
}.addOnFailureListener {
viewModelScope.launch {
_login.emit(Resource.Error(it.message.toString()))
}
}
}
fun resetPassword(email: String)
{
viewModelScope.launch {
_resetPassword.emit(Resource.Loading())
}
firebaseAuth.sendPasswordResetEmail(email)
.addOnSuccessListener {
viewModelScope.launch{
_resetPassword.emit(Resource.Success(email))
}
}.addOnFailureListener{
viewModelScope.launch{
_resetPassword.emit(Resource.Error(it.message.toString()))
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/viewmodel/LoginViewModel.kt | 787592498 |
package com.example.shoping.viewmodel
import androidx.lifecycle.ViewModel
import com.example.shoping.data.User
import com.example.shoping.util.Constants.USER_COLLECTION
import com.example.shoping.util.RegisterFieldState
import com.example.shoping.util.RegisterValidation
import com.example.shoping.util.Resource
import com.example.shoping.util.validateEmail
import com.example.shoping.util.validatePassword
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
@HiltViewModel
class RegisterVIewModel @Inject constructor(
private val firebaseAuth: FirebaseAuth,
private val db: FirebaseFirestore
): ViewModel(){
private val _register = MutableStateFlow<Resource<User>>(Resource.Unspecified())
val register: Flow<Resource<User>> = _register
private val _validation = Channel<RegisterFieldState>()
val validation = _validation.receiveAsFlow()
fun createAccountWithEmailAndPassword(user: User, password: String)
{
if (checkValidation(user, password)) {
runBlocking {
_register.emit(Resource.Loading())
}
firebaseAuth.createUserWithEmailAndPassword(user.email, password)
.addOnSuccessListener {
it.user?.let {
saveUserInfo(it.uid,user)
}
}.addOnFailureListener {
_register.value = Resource.Error(it.message.toString())
}
}else{
val registerFieldState = RegisterFieldState(
validateEmail(user.email), validatePassword(password)
)
runBlocking {
_validation.send(registerFieldState)
}
}
}
private fun saveUserInfo(userUid: String, user: User) {
db.collection(USER_COLLECTION)
.document(userUid)
.set(user)
.addOnSuccessListener {
_register.value = Resource.Success(user)
}.addOnFailureListener {
_register.value = Resource.Error(it.message.toString())
}
}
private fun checkValidation(user: User, password: String) : Boolean
{
val emailValidation = validateEmail(user.email)
val passwordValidation = validatePassword(password)
val shouldRegister = emailValidation is RegisterValidation.Success && passwordValidation is RegisterValidation.Success
return shouldRegister
}
} | shoping.app/app/src/main/java/com/example/shoping/viewmodel/RegisterVIewModel.kt | 4157217731 |
package com.example.shoping.di
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideFirebaseAuth() = FirebaseAuth.getInstance()
@Provides
@Singleton
fun provideFireBaseFireStoreDatabase() = Firebase.firestore
} | shoping.app/app/src/main/java/com/example/shoping/di/AppModule.kt | 36673147 |
package com.example.shoping.fragments.shopping
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.shoping.R
/**
* A simple [Fragment] subclass.
* Use the [SearchFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class SearchFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false)
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/shopping/SearchFragment.kt | 1924000087 |
package com.example.shoping.fragments.shopping
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.shoping.R
class CartFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false)
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/shopping/CartFragment.kt | 2913677316 |
package com.example.shoping.fragments.shopping
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.shoping.R
import com.example.shoping.adapters.HomeViewpagerAdapter
import com.example.shoping.databinding.FragmentHomeBinding
import com.example.shoping.fragments.categories.AccessoryFragment
import com.example.shoping.fragments.categories.ChairFragment
import com.example.shoping.fragments.categories.CupboardFragment
import com.example.shoping.fragments.categories.FurnitureFragment
import com.example.shoping.fragments.categories.MainCategoryFragment
import com.example.shoping.fragments.categories.TableFragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
/**
* A simple [Fragment] subclass.
* Use the [HomeFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val categoriesFragment = arrayListOf<Fragment>(
MainCategoryFragment(),
ChairFragment(),
CupboardFragment(),
TableFragment(),
AccessoryFragment(),
FurnitureFragment()
)
val viewPager2Adapter = HomeViewpagerAdapter(categoriesFragment, childFragmentManager, lifecycle)
binding.idViewpagerHome.adapter = viewPager2Adapter
TabLayoutMediator(binding.idTabLayout, binding.idViewpagerHome){tab,position ->
when(position){
0 -> tab.text = "Main"
1 -> tab.text = "Chair"
2 -> tab.text = "Cupboard"
3 -> tab.text = "Table"
4 -> tab.text = "Accessory"
5 -> tab.text = "Furniture"
}
}.attach()
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/shopping/HomeFragment.kt | 825913628 |
package com.example.shoping.fragments.shopping
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.shoping.R
class ProfileFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false)
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/shopping/ProfileFragment.kt | 901841794 |
package com.example.shoping.fragments.loginRegister
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.shoping.R
import com.example.shoping.activities.ShopingActivity
import com.example.shoping.databinding.FragmentLoginBinding
import com.example.shoping.dialog.setupBottomSheetDialog
import com.example.shoping.local.Pref
import com.example.shoping.util.Resource
import com.example.shoping.viewmodel.LoginViewModel
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
@AndroidEntryPoint
class LoginFragment : Fragment() {
private lateinit var binding: FragmentLoginBinding
private val viewModel by viewModels<LoginViewModel>()
private val pref by lazy {
Pref(requireContext())
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentLoginBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvDoNotHaveAnAccountLoginFragment.setOnClickListener {
findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
}
binding.edEmailLogin.setText(pref.getLogin())
binding.edPasswordLogin.setText(pref.getPassword())
binding.apply {
btLoginLogin.setOnClickListener {
val email = edEmailLogin.text.toString().trim()
val password = edPasswordLogin.text.toString()
pref.saveLogin(email)
pref.savePassword(password)
viewModel.login(email,password)
}
}
binding.tvForgotPassword.setOnClickListener {
setupBottomSheetDialog { email ->
viewModel.resetPassword(email)
}
}
lifecycleScope.launchWhenStarted {
viewModel.login.collect{
when(it){
is Resource.Loading -> {
}
is Resource.Success -> {
Snackbar.make(requireView(),"Reset link was sent to your email", Snackbar.LENGTH_LONG).show()
}
is Resource.Error -> {
Snackbar.make(requireView(),"Error: ${it.message}", Snackbar.LENGTH_LONG).show()
}
else -> Unit
}
}
}
lifecycleScope.launchWhenStarted {
viewModel.login.collect{
when(it){
is Resource.Loading -> {
binding.btLoginLogin.startAnimation()
}
is Resource.Success -> {
binding.btLoginLogin.revertAnimation()
Intent(requireActivity(), ShopingActivity::class.java).also {intent ->
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK )
startActivity(intent)
}
}
is Resource.Error -> {
Toast.makeText(requireContext(),it.message,Toast.LENGTH_LONG).show()
binding.btLoginLogin.revertAnimation()
}
else -> Unit
}
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/loginRegister/LoginFragment.kt | 284910559 |
package com.example.shoping.fragments.loginRegister
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.shoping.R
import com.example.shoping.databinding.FragmentInroductionBinding
class IntroductionFragment : Fragment() {
private lateinit var binding: FragmentInroductionBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentInroductionBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonStart.setOnClickListener {
findNavController().navigate(R.id.action_introductionFragment_to_accountOptionFragment)
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/loginRegister/IntroductionFragment.kt | 3146274958 |
package com.example.shoping.fragments.loginRegister
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.shoping.R
import com.example.shoping.data.User
import com.example.shoping.databinding.FragmentRegisterBinding
import com.example.shoping.util.RegisterValidation
import com.example.shoping.util.Resource
import com.example.shoping.viewmodel.RegisterVIewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
val TAG = "RegisterFragment"
@AndroidEntryPoint
class RegisterFragment : Fragment() {
private lateinit var binding: FragmentRegisterBinding
private val vIewModel by viewModels<RegisterVIewModel> ()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentRegisterBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvDoYouHaveAnAccount.setOnClickListener {
findNavController().navigate(R.id.action_registerFragment_to_loginFragment)
}
binding.apply {
btRegister.setOnClickListener {
val user = User(
edNameText.text.toString().trim(),
edLastNameText.text.toString().trim(),
edEmailText.text.toString().trim()
)
val password = edPasswordRegisterText.text.toString()
vIewModel.createAccountWithEmailAndPassword(user,password)
}
}
lifecycleScope.launchWhenStarted {
vIewModel.register.collect{
when (it)
{
is Resource.Loading ->{
binding.btRegister.startAnimation()
}
is Resource.Success ->{
Log.d("text",it.data.toString())
binding.btRegister.revertAnimation()
}
is Resource.Error ->{
Log.e(TAG,it.message.toString())
binding.btRegister.revertAnimation()
}
else -> Unit
}
}
}
lifecycleScope.launchWhenStarted {
vIewModel.validation.collect{validation ->
if (validation.email is RegisterValidation.Failed) {
withContext(Dispatchers.Main) {
binding.edEmailText.apply {
requestFocus()
error = validation.email.message
}
}
}
if (validation.password is RegisterValidation.Failed)
{
withContext(Dispatchers.Main){
binding.edPasswordRegisterText.apply {
requestFocus()
error = validation.password.message
}
}
}
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/loginRegister/RegisterFragment.kt | 1961015711 |
package com.example.shoping.fragments.loginRegister
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.shoping.R
import com.example.shoping.databinding.FragmentAccountOptionBinding
class AccountOptionFragment : Fragment() {
private lateinit var binding: FragmentAccountOptionBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentAccountOptionBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
btLoginAccountOptions.setOnClickListener {
findNavController().navigate(R.id.action_accountOptionFragment_to_loginFragment)
}
btRegisterAccountOptions.setOnClickListener {
findNavController().navigate(R.id.action_accountOptionFragment_to_registerFragment)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/loginRegister/AccountOptionFragment.kt | 1706773712 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [AccessoryFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class AccessoryFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_accessory, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment AccessoryFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
AccessoryFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/AccessoryFragment.kt | 2060698267 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [BaseCategoryFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class BaseCategoryFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_base_category, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BaseCategoryFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
BaseCategoryFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/BaseCategoryFragment.kt | 3741474893 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [CupboardFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class CupboardFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cupboard, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment CupboardFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
CupboardFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/CupboardFragment.kt | 1482623055 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ChairFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ChairFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chair, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ChairFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ChairFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/ChairFragment.kt | 2878828552 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [MainCategoryFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class MainCategoryFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MainFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
MainCategoryFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/MainCategoryFragment.kt | 4158931276 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class FurnitureFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_furniture, container, false)
}
companion object {
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FurnitureFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/FurnitureFragment.kt | 1863077194 |
package com.example.shoping.fragments.categories
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.shoping.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [TableFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class TableFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_table, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TableFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
TableFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | shoping.app/app/src/main/java/com/example/shoping/fragments/categories/TableFragment.kt | 2203320535 |
package com.example.shoping.util
sealed class RegisterValidation()
{
object Success: RegisterValidation()
data class Failed(val message: String) : RegisterValidation()
}
data class RegisterFieldState(
val email: RegisterValidation,
val password: RegisterValidation
)
| shoping.app/app/src/main/java/com/example/shoping/util/RegisterValidation.kt | 1728263405 |
package com.example.shoping.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) : Resource<T>(message = message)
class Loading<T>: Resource<T>()
class Unspecified<T> : Resource<T>()
}
| shoping.app/app/src/main/java/com/example/shoping/util/Resource.kt | 3899600862 |
package com.example.shoping.util
import android.util.Patterns
fun validateEmail(email: String) : RegisterValidation{
if (email.isEmpty())
return RegisterValidation.Failed("Email cannot be empty")
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
return RegisterValidation.Failed("Wrong email format")
return RegisterValidation.Success
}
fun validatePassword(password: String): RegisterValidation
{
if (password.isEmpty())
return RegisterValidation.Failed("Password cannot be empty")
if (password.length < 6)
return RegisterValidation.Failed("Password should contain at least 6 char")
return RegisterValidation.Success
} | shoping.app/app/src/main/java/com/example/shoping/util/ValidationCheck.kt | 3291512662 |
package com.example.shoping.util
object Constants {
const val USER_COLLECTION = "user"
} | shoping.app/app/src/main/java/com/example/shoping/util/Constants.kt | 666959935 |
package com.example.shoping.local
import android.content.Context
class Pref(context: Context) {
private val pref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE)
fun saveLogin(login: String)
{
pref.edit().putString(LOGIN_GET, login).apply()
}
fun getLogin():String?
{
return pref.getString(LOGIN_GET,"")
}
fun savePassword(password: String)
{
pref.edit().putString(PASSWORD_GET,password).apply()
}
fun getPassword():String?
{
return pref.getString(PASSWORD_GET,"")
}
companion object
{
const val PREF_NAME = "pref.folder.name"
const val LOGIN_GET = "login.name"
const val PASSWORD_GET = "password.name"
}
} | shoping.app/app/src/main/java/com/example/shoping/local/Pref.kt | 220244187 |
package com.example.shoping.dialog
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import com.example.shoping.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
fun Fragment.setupBottomSheetDialog(
onSendClick: (String) -> Unit
)
{
val dialog = BottomSheetDialog(requireContext())
val view = layoutInflater.inflate(R.layout.reset_password_dialog,null)
dialog.setContentView(view)
dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
dialog.show()
val edEmail = view.findViewById<EditText>(R.id.edResetPasswordText)
val buttonSend = view.findViewById<Button>(R.id.buttonSendResetPassword)
val buttonCancel = view.findViewById<Button>(R.id.buttonCancelResetPassword)
buttonSend.setOnClickListener {
val email = edEmail.text.toString().trim()
onSendClick(email)
dialog.dismiss()
}
buttonCancel.setOnClickListener {
dialog.dismiss()
}
} | shoping.app/app/src/main/java/com/example/shoping/dialog/ResetPasswordDialog.kt | 3311797071 |
package com.example.shoping.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bumptech.glide.manager.Lifecycle
class HomeViewpagerAdapter(
private val fragments: List<Fragment>,
fm: FragmentManager,
lifecycle: androidx.lifecycle.Lifecycle
) : FragmentStateAdapter(fm,lifecycle){
override fun getItemCount(): Int {
return fragments.size
}
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
} | shoping.app/app/src/main/java/com/example/shoping/adapters/HomeViewpagerAdapter.kt | 1349423784 |
package com.example.shoping
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class PahlaviApplication: Application() {} | shoping.app/app/src/main/java/com/example/shoping/PahlaviApplication.kt | 2702322753 |
package com.example.shoping.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.example.shoping.R
import com.example.shoping.databinding.ActivityShopingBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ShopingActivity : AppCompatActivity() {
private val binding by lazy {
ActivityShopingBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val navController = findNavController(R.id.shoppingHostFragment)
binding.bottomNavigation.setupWithNavController(navController)
}
} | shoping.app/app/src/main/java/com/example/shoping/activities/ShopingActivity.kt | 890785690 |
package com.example.shoping.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.shoping.R
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LoginRegisterActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login_register)
}
} | shoping.app/app/src/main/java/com/example/shoping/activities/LoginRegisterActivity.kt | 2018083723 |
package com.example.shoping.data
data class User(
val firstName: String,
val lastName: String,
val email: String,
val imagePath: String = ""
){
constructor():this("","","", "")
}
| shoping.app/app/src/main/java/com/example/shoping/data/User.kt | 3450611368 |
package com.example.project_652263
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.project_652263", appContext.packageName)
}
} | educational-mobile-game/app/src/androidTest/java/com/example/project_652263/ExampleInstrumentedTest.kt | 1331702404 |
package com.example.project_652263
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)
}
} | educational-mobile-game/app/src/test/java/com/example/project_652263/ExampleUnitTest.kt | 2662880537 |
package com.example.project_652263
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
open class GameObject (var x:Int, var y:Int, var dx:Int, var dy:Int, var image:Drawable) {
var width: Int = 200 //Width of the game object
var height: Int = 200 //Height of the game object
val rectangle = Rect(x, y, x + width, y + height) //Rectangle/outline of the game object
/**
* Moves the game object on the canvas
* @param Canvas Canvas being drawn on
* @return none
*/
open fun move(canvas: Canvas) {
x += dx //Moves the game object on the x-axis
y += dy //Moves the game object on the y-axis
if(x > (canvas.width - width) || x < 0) dx = -dx //Changes the game object movement algorithm on the x-axis
if (y > (canvas.height - height) || y < 0) dy = -dy //Changes the game object movement algorithm on the y-axis
rectangle.set(x, y, x + width, y + height) //Sets the rectangle based on the position and size
image.setBounds(x, y, x + width, y + height) //Sets the image based on the position and size
image.draw(canvas) //Draws the image on the canvas
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/GameObject.kt | 4041530703 |
package com.example.project_652263
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnLayout
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.example.project_652263.databinding.FragmentFourthBlankBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FourthBlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class FourthBlankFragment : Fragment(), SensorEventListener {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var binding: FragmentFourthBlankBinding //Binds the UI elements to this class
private lateinit var navController: NavController //Navigator controller for moving between fragments
lateinit var sensorManager: SensorManager
lateinit var accelerometer: Sensor
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_fourth_blank, container, false)
binding = FragmentFourthBlankBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController() //Retrieve navigation controller
sensorManager = requireActivity().getSystemService(Context.SENSOR_SERVICE) as SensorManager
val deviceSensors: List<Sensor> = sensorManager.getSensorList(Sensor.TYPE_ALL)
for (s in deviceSensors) {
Log.d("MyTAG", s.name)
}
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!!
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_STATUS_ACCURACY_LOW)
val audioAttributes: AudioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(
AudioAttributes.CONTENT_TYPE_SONIFICATION).build() //Audio attributes of sound pool player
val soundPool = SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(2).build() //Set sound pool player
val buttonClick = soundPool.load(requireActivity(),R.raw.button_click,1) //Button click sound
binding.mercuryButton.setOnClickListener {
soundPool.play(buttonClick, 1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
binding.FourthFragmentSurfaceView.changeGravity(0)
binding.textView.text = "The asteroids are moving at mercury's gravity. Click one of the below planets to learn about their gravity."
}
binding.earthButton.setOnClickListener {
soundPool.play(buttonClick, 1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
binding.FourthFragmentSurfaceView.changeGravity(1)
binding.textView.text = "The asteroids are moving at earth's gravity. Click one of the below planets to learn about their gravity."
}
binding.marsButton.setOnClickListener {
soundPool.play(buttonClick, 1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
binding.FourthFragmentSurfaceView.changeGravity(2)
binding.textView.text = "The asteroids are moving at mars' gravity. Click one of the below planets to learn about their gravity."
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FourthBlankFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FourthBlankFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
override fun onSensorChanged(event: SensorEvent?) {
if (event == null) return
if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {
var x = event.values[0]
var y = event.values[1]
var z = event.values[2]
var mySpaceship = "%.2f".format(x) + "%.2f".format(y) + "%.2f".format(z)
Log.d("MyTAG", mySpaceship)
var w = 0
var h = 0
binding.FourthFragmentSurfaceView.spaceshipSprite.move(x.toInt(),z.toInt())
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FourthBlankFragment.kt | 822373502 |
package com.example.project_652263
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
import kotlin.random.Random
class FourthFragmentSurfaceView(context: Context?, attrs: AttributeSet?) : MySurfaceView(context, attrs), Runnable {
private var myGameObjects = ConcurrentHashMap<Int, GameObject>() //Stores the game objects/asteroids
private var asteroidImage = context!!.resources.getDrawable(R.drawable.asteroid, null)//Drawable/Image of the asteroid to be avoided by the player
private var gameOverImage = context!!.resources.getDrawable(R.drawable.game_over, null) //Drawable/Image of the game over UI displayed at the end of the game
private var addingAsteroid = false //Can add an asteroid to the canvas when false vice-versa
private var spaceshipImage = context!!.resources.getDrawable(R.drawable.spaceship, null) //Drawable/Image of the spaceship the player controls
var spaceshipSprite = FourthFragmentGameObject(400, 1200, 10, 10, spaceshipImage) //Game object of the spaceship
//Approximate gravities of various celestial bodies, planets, and/or moons
private val gravities = listOf(
listOf("mercury", 3),
listOf("earth", 9),
listOf("mars", 4))
var asteroidDy: Int = gravities[0][1] as Int //Gravity/speed of the asteroids. The gravity is set to 9 to represent earths gravity
/**
* Runs before the first frame and initializes the field variables
* @param none
* @return none
*/
init {
myThread = Thread(this) //Points the thread to this class
myThread.start()
myHolder = holder
paint.color = Color.WHITE
}
fun changeGravity(planetPosition: Int) {
asteroidDy = gravities[planetPosition][1] as Int
}
/**
* Adds new asteroids to the surface view
* @param Int spawnX: The position where the asteroid spawns on the x-axis
* @return none
*/
private suspend fun startAsteroidCycle(spawnX: Int){
withContext(Dispatchers.Main) {
var asteroid = FourthFragmentObstacle(spawnX, 1, 5, asteroidDy, asteroidImage) //Obstacles the spaceship must avoid
myGameObjects[myGameObjects.size] = asteroid //Adds the asteroid game object to the hash map to enable it to move every frame so it can be drawn and seen
delay(5000)//Wait for 5 seconds/5000 milliseconds
addingAsteroid = false//Asteroids can be added to the canvas again
}
}
/**
* Runs every frame
* @param none
* @return none
*/
override fun run() {
while (isRunning) {
if (!myHolder.surface.isValid) continue
val canvas: Canvas = myHolder.lockCanvas()
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), paint)
for ((key, asteroid) in myGameObjects) {
asteroid.dy = asteroidDy
asteroid.move(canvas)
if (canvas.height - asteroid.y <= 0) {
myGameObjects.remove(key)
}
if (Rect.intersects(spaceshipSprite.rectangle, asteroid.rectangle)) {
stop()
spaceshipSprite.image = gameOverImage
}
}
if(!addingAsteroid) {
addingAsteroid = true
CoroutineScope(Dispatchers.Main).launch {
var randomX = Random.nextInt(0, canvas.width - 201)
startAsteroidCycle(randomX) //Adds new asteroids to the canvas
}
}
myHolder.unlockCanvasAndPost(canvas)
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FourthFragmentSurfaceView.kt | 1814196305 |
package com.example.project_652263
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.example.project_652263.databinding.FragmentFirstBlankBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FirstBlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class FirstBlankFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var binding: FragmentFirstBlankBinding //Binds the UI elements to this class
private lateinit var navController: NavController //Navigator controller for moving between fragments
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_first_blank, container, false)
binding = FragmentFirstBlankBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController() //Retrieve navigation controller
val audioAttributes: AudioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(
AudioAttributes.CONTENT_TYPE_SONIFICATION).build() //Audio attributes of the sound pool player
val soundPool = SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(2).build() //Sound pool player
val buttonClick = soundPool.load(requireActivity(),R.raw.button_click,1) //Button click sound
val sheepSound = soundPool.load(requireActivity(), R.raw.sheep_sound, 1) //Sheep bleat sound
//Runs when the animal sound button is clicked
binding.soundButton.setOnClickListener {
soundPool.play(sheepSound, 1.0f, 1.0f, 0, 0, 1.0f) //Plays the sheep sound
}
//Runs when the next button is clicked
binding.nextButton.setOnClickListener {
soundPool.play(buttonClick, 1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
navController.navigate(R.id.action_firstBlankFragment_to_secondBlankFragment) //Loads the second blank fragment
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FirstBlankFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FirstBlankFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FirstBlankFragment.kt | 3460952652 |
package com.example.project_652263
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/MainActivity.kt | 4037667574 |
package com.example.project_652263
import android.graphics.Canvas
import android.graphics.drawable.Drawable
class ThirdFragmentGameObject (x:Int, y:Int, dx:Int, dy:Int, image: Drawable): GameObject(x, y, dx, dy, image){
var px: Int = 400 //Initial position the frog should move to on the x-axis
var py: Int = 500 //Initial position the frog should move to on the y-axis
/**
* Moves the frog to the px,py coordinate
* @param Canvas Canvas being drawn on
* @return none
*/
override fun move(canvas: Canvas) {
if(px > x) x += 5 else x -= 5 //Moves the frog on the x-axis towards px
if(py > y) y += 5 else y -= 5 //Moves the frog on the y-axis towards py
rectangle.set(x, y, x + width, y + height) //Sets the rectangle using the frogs position and size
image.setBounds(x, y, x + width, y + height) //Sets the image bounds using the frogs position and size
image.draw(canvas) //Draws the image on the canvas
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/ThirdFragmentGameObject.kt | 3909968551 |
package com.example.project_652263
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
import kotlin.random.Random
/**
* This class handles the surface view displayed in the third blank fragment.
* It extends/subclasses the Surface View class and handles multiple threads
*/
class ThirdFragmentSurfaceView(context: Context?, attrs: AttributeSet?) : MySurfaceView(context, attrs), Runnable {
private var canMate = true //The male and female frog can mate and lay an egg
private var myGameObjects = ConcurrentHashMap<Int, GameObject>() //Stores the game objects before they have grown into female frogs
private var femaleFrogObjects = ConcurrentHashMap<Int, GameObject>() //Stores the game object that grown into female frogs
private var maleFrogObjects = ConcurrentHashMap<Int, GameObject>() //Stores the game object that grown into female frogs
private val frogEggImage = context!!.resources.getDrawable(R.drawable.frog_egg, null) //Stores the image of frog eggs
private val tadpoleImage = context!!.resources.getDrawable(R.drawable.tadpole, null) //Stores the image of tadpoles
private val femaleFrogImage = context!!.resources.getDrawable(R.drawable.female_frog, null) //Stores the image of female frogs
private val maleFrogImage = context!!.resources.getDrawable(R.drawable.male_frog, null) //Stores the image of male frogs
private val maleFrogSprite = ThirdFragmentGameObject(400, 500, 7, 7, maleFrogImage) //Stores the game object of the male frogs
/**
* Runs before the first frame and initializes the field variables
* @param none
* @return none
*/
init {
myThread = Thread(this) //Points the thread to this class
myThread.start() //Starts the thread
myHolder = holder //Initializes the holder
val femaleFrogSprite = GameObject(100, 180, 5, 5, femaleFrogImage) //Stores the game object of the first female frog
paint.color = Color.BLUE //Sets the paint color to white
Log.d("femaleFrogObjects.size", "size") //Logs the number of female frogs in the concurrent hash map
femaleFrogObjects[femaleFrogObjects.size] = femaleFrogSprite //Adds the female frog to the hash map for female frogs
maleFrogObjects[maleFrogObjects.size] = maleFrogSprite //Adds the female frog to the hash map for female frogs
}
/**
* Runs when the screen is touched
* @param MotionEvent Touch event
* return Boolean true/false
*/
override fun onFilterTouchEventForSecurity(event: MotionEvent?): Boolean {
maleFrogSprite.px = event!!.x.toInt() //Makes the male frog move to the position touched on the x-axis
maleFrogSprite.py = event!!.y.toInt() //Makes the male frog move to the position touched on the y-axis
return true
}
/**
* Gives birth to baby frogs and adds them to the surface view
* @param Int birthX: The position where the frogs mated on the x-axis
* @param Int birthY: The position where the frogs mated on the y-axis
* @return none
*/
private suspend fun startBirthCycle(birthX: Int, birthY: Int){
withContext(Dispatchers.Main) {
val babyFrog = GameObject(birthX, birthY, 5, 5, frogEggImage) //Adds a frog egg game object to the surface view
myGameObjects[myGameObjects.size] = babyFrog //Adds the frog egg game object to the hash map to enable it to move every frame so it can be drawn and seen
//The egg hatches into a tadpole after 5 seconds/5000 milliseconds
delay(5000)
babyFrog.image = tadpoleImage
//The tadpole grows into a female frog after 5 seconds/5000 milliseconds
delay(5000)
var randomGender = Random.nextInt(0, 2)
if (randomGender == 0) {
babyFrog.image = maleFrogImage
maleFrogObjects[maleFrogObjects.size] = babyFrog //Adds the female frog to the female frog hash map so it can mate upon intersection with male frogs
} else {
babyFrog.image = femaleFrogImage
femaleFrogObjects[femaleFrogObjects.size] = babyFrog //Adds the female frog to the female frog hash map so it can mate upon intersection with male frogs
}
myGameObjects.remove(myGameObjects.size) //Removes the female frog from the my game objects hash map since its move function is already called in the female frog hash map
canMate = true //The male frog can mate now
}
}
/**
* Runs every frame
* @param none
* @return none
*/
override fun run() {
while (isRunning) {
if(!myHolder.surface.isValid) continue
val canvas: Canvas = myHolder.lockCanvas()
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), paint) //Places a canvas using the passed parameters
maleFrogSprite.move(canvas) //Moves the male frog
myGameObjects.forEach{(keys, gameObject) -> gameObject.move(canvas)} //Moves the baby frogs
maleFrogObjects.forEach{(keys, gameObject) -> gameObject.move(canvas)}
for ((key, femaleFrog) in femaleFrogObjects) {
femaleFrog.move(canvas) //Moves the female frogs
for ((key, maleFrog) in maleFrogObjects) {
//Runs if the male frog is trying to mate with a female frog and is allowed to
if (Rect.intersects(maleFrog.rectangle, femaleFrog.rectangle) && canMate) {
canMate = false //Male frog can not mate
Log.d("as", "intersected$canMate")
//Retrieve the best birth position on the x-axis based off the intersection position
var birthXParam = if(canvas.width - femaleFrog.x >= 400) {
femaleFrog.x + femaleFrog.width
} else {
femaleFrog.x - femaleFrog.width;
}
//Retrieve the best birth position on the y-axis based off the intersection position
var birthYParam = if(canvas.height - femaleFrog.y >= 400) {
femaleFrog.y + femaleFrog.width
} else {
femaleFrog.y - femaleFrog.width
}
CoroutineScope(Dispatchers.Main).launch {
startBirthCycle(birthX = birthXParam, birthY = birthYParam) //Gives birth to a new frog
}
}
}
}
myHolder.unlockCanvasAndPost(canvas)
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/ThirdFragmentSurfaceView.kt | 658302371 |
package com.example.project_652263
import android.Manifest
import android.content.Context
import android.content.Context.VIBRATOR_SERVICE
import android.content.pm.PackageManager
import androidx.fragment.app.Fragment
import android.media.AudioAttributes
import android.media.SoundPool
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.Log
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.project_652263.databinding.FragmentThirdBlankBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ThirdBlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ThirdBlankFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var binding: FragmentThirdBlankBinding//Binds the UI elements to this class
private lateinit var navController: NavController //Navigator controller for moving between fragments
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_third_blank, container, false)
binding = FragmentThirdBlankBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController() //Retrieve navigation controller
var frogSound = MediaPlayer.create(requireActivity(), R.raw.frog_sound) //Media player to play frog sounds
frogSound.isLooping = true //media player loops sound
frogSound.start() // Start playing the sound
val audioAttributes: AudioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(
AudioAttributes.CONTENT_TYPE_SONIFICATION).build() //Audio attributes of sound pool player
val soundPool = SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(2).build() //Set sound pool player
val buttonClick = soundPool.load(requireActivity(),R.raw.button_click,1) //Button click sound
//Runs if the next button is clicked
binding.nextButton3.setOnClickListener {
soundPool.play(buttonClick, 1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
navController.navigate(R.id.action_thirdBlankFragment_to_fourthBlankFragment) //Loads the fourth blank fragment
frogSound.stop()
frogSound.release()
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ThirdBlankFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
ThirdBlankFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/ThirdBlankFragment.kt | 3670379347 |
package com.example.project_652263
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.example.project_652263.databinding.FragmentSecondBlankBinding
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [SecondBlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class SecondBlankFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var binding: FragmentSecondBlankBinding //Binds the UI elements to this class
private lateinit var navController: NavController //Navigator controller for moving between fragments
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSecondBlankBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController() //Retrieve navigation controller
val audioAttributes: AudioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(
AudioAttributes.CONTENT_TYPE_SONIFICATION).build() //Audio attributes of the sound player
val soundPool = SoundPool.Builder().setAudioAttributes(audioAttributes).setMaxStreams(2).build() //The sound player
val buttonClick = soundPool.load(requireActivity(),R.raw.button_click,1) //Button click sound
val grassSound = soundPool.load(requireActivity(), R.raw.grass_sound, 1) //Grass moving sound
val ratSound = soundPool.load(requireActivity(), R.raw.rat_sound, 1) //Rat squeaking sound
val snakeSound = soundPool.load(requireActivity(),R.raw.snake_sound,1) //Snake hissing sound
val hawkSound = soundPool.load(requireActivity(),R.raw.hawk_sound,1) //Hawk crying sound
//Runs when the sun image button is clicked
binding.sunButton.setOnClickListener {
binding.imageView2.visibility = View.VISIBLE //Arrow pointing to grass image button becomes visible
binding.grassButton.visibility = View.VISIBLE //Grass image button becomes visible
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
soundPool.play(grassSound, 1.0f, 1.0f, 0, 0, 1.0f) //Grass moving sound plays
binding.foodChainTextView.text = "Try and guess what eats the grass before clicking it." //Changes the narrator text to teach the user about the food chain
}
//Runs when the grass image button is clicked
binding.grassButton.setOnClickListener {
binding.imageView3.visibility = View.VISIBLE //Arrow pointing to rat image button becomes visible
binding.ratButton.visibility = View.VISIBLE //Rat image button becomes visible
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
soundPool.play(ratSound, 1.0f, 1.0f, 0, 0, 1.0f) //Rat sound plays
binding.foodChainTextView.text = "You're getting the hang of this. Think of the many predators rats have before clicking the rat." //Changes the narrator text to teach the user about the food chain
}
//Runs when the rat image button is clicked
binding.ratButton.setOnClickListener {
binding.imageView4.visibility = View.VISIBLE //Arrow pointing to snake image button becomes visible
binding.snakeButton.visibility = View.VISIBLE //Snake image button becomes visible
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
soundPool.play(snakeSound, 1.0f, 1.0f, 0, 0, 1.0f) //Snake sound plays
binding.foodChainTextView.text = "Good job! Predators are animals that eat other animals. Click the snake to see its predator. Remember to think of all the predators it has." //Changes the narrator text to teach the user about the food chain
}
//Runs when the snake image button is clicked
binding.snakeButton.setOnClickListener {
binding.imageView5.visibility = View.VISIBLE //Arrow pointing to hawk image button becomes visible
binding.hawkButton.visibility = View.VISIBLE //Hawk image button becomes visible
binding.nextButton2.visibility = View.VISIBLE //Next button becomes visible. This button takes you to the next game/fragment
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
soundPool.play(hawkSound, 1.0f, 1.0f, 0, 0, 1.0f) //Hawk sound plays
binding.foodChainTextView.text = "A Hawk! It's at the top of the food chain meaning no animal eats it and it eats any prey it wants." //Changes the narrator text to teach the user about the food chain
}
//Runs when the hawk image button is clicked
binding.hawkButton.setOnClickListener {
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
soundPool.play(hawkSound, 1.0f, 1.0f, 0, 0, 1.0f) //Hawk sound plays
}
//Runs when the next button is clicked
binding.nextButton2.setOnClickListener {
soundPool.play(buttonClick,1.0f, 1.0f, 0, 0, 1.0f) //Button click sound plays
navController.navigate(R.id.action_secondBlankFragment_to_thirdBlankFragment) //Loads the third blank fragment
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SecondBlankFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
SecondBlankFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/SecondBlankFragment.kt | 3341659889 |
package com.example.project_652263
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color.WHITE
import android.graphics.Paint
import android.media.AudioAttributes
import android.media.SoundPool
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
open class MySurfaceView(context: Context?, attrs: AttributeSet?) : SurfaceView(context, attrs), Runnable {
var isRunning = true
var myThread: Thread
var myHolder: SurfaceHolder
var paint = Paint()
//Runs before the first frame and initializes field variables
init {
myThread = Thread(this)
myThread.start()
myHolder = holder
paint.color = WHITE
}
//Starts the thread
open fun start() {
isRunning = true
myThread = Thread(this)
myThread.start()
}
//Pauses the thread
open fun stop() {
isRunning = false;
while (true) {
try {
myThread.join()
break
} catch (e: InterruptedException) {
e.printStackTrace()
}
break
}
}
override fun run() {
while (isRunning) {
if (!myHolder.surface.isValid) continue
val canvas: Canvas = myHolder.lockCanvas()
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), paint)
myHolder.unlockCanvasAndPost(canvas)
}
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/MySurfaceView.kt | 1289201835 |
package com.example.project_652263
import android.graphics.Canvas
import android.graphics.drawable.Drawable
class FourthFragmentObstacle (x:Int, y:Int, dx:Int, dy:Int, image: Drawable): GameObject(x, y, dx, dy, image) {
/**
* Moves the game object on the canvas
* @param Canvas Canvas being drawn on
* @return none
*/
override fun move(canvas: Canvas) {
y += dy //Moves the game object on the y-axis
rectangle.set(x, y, x + width, y + height) //Sets the rectangle based on the position and size
image.setBounds(x, y, x + width, y + height) //Sets the image based on the position and size
image.draw(canvas) //Draws the image on the canvas
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FourthFragmentObstacle.kt | 1672881514 |
package com.example.project_652263
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.hardware.Sensor
import android.hardware.SensorManager
import android.provider.SyncStateContract.Helpers.update
import android.util.Log
class FourthFragmentGameObject(x:Int, y:Int, dx:Int, dy:Int, image: Drawable) : GameObject(x, y, dx, dy, image) {
// fun move(x1:Int, y1:Int){
// dx = x1
// dy = y1
// x += dx
// y += dy
//
// image.setBounds(x, y,x+width,y+height)
// image.draw(canvas)
// }
//
// fun appear(canvas: Canvas){
// update(canvas)
// image.setBounds(x, y,x+width,y+height)
// image.draw(canvas)
// }
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FourthFragmentGameObject.kt | 3469356562 |
package com.example.project_652263
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
class FirstFragmentView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
var paint = Paint() //Paint to be used on the canvas
var myX: Float = 100f
var myY: Float = 100f
lateinit var myBitmap: Bitmap
lateinit var myBitmapCanvas: Canvas //Canvas to be draw on
var myWidth: Int = 800 //Width of the canvas
var myHeight: Int = 800 //Height of the canvas
//Runs before the first frame and initializes field variables
init {
paint.color = Color.RED //Sets the paint color to red
paint.textSize = 80f //Sets the text size of the paint to 80f
}
override fun onDrawForeground(canvas: Canvas) {
super.onDrawForeground(canvas)
canvas!!.drawText("Hello from canvas", myX, myY, paint)
myBitmapCanvas.drawCircle(myX, myY, 10f, paint) //Draws circle on the bitmap canvas
canvas!!.drawBitmap(myBitmap, 0f, 0f, null) //Draws on the canvas
}
/**
* Runs if the screen is touched
* @param MotionEvent Touch event
* @return Boolean true/false
*/
override fun onFilterTouchEventForSecurity(event: MotionEvent?): Boolean {
//return super.onFilterTouchEventForSecurity(event)
myX = event!!.x //Point that was touched on the x-axis
myY = event!!.y //Point that was touched on the y-axis
invalidate()
return true //Returns true
}
/**
* Measures size of the canvas
* @param Int widthMeasureSpec Width of canvas
* @param Int heightMeasureSpec Height of canvas
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
myWidth = measuredWidth
myHeight = measuredHeight
myBitmap = Bitmap.createBitmap(myWidth, myHeight, Bitmap.Config.RGB_565)
myBitmapCanvas = Canvas(myBitmap)
}
} | educational-mobile-game/app/src/main/java/com/example/project_652263/FirstFragmentView.kt | 2718591146 |
package com.example.project_652263
class MyModel {
} | educational-mobile-game/app/src/main/java/com/example/project_652263/MyModel.kt | 2262998965 |
package com.geofencing.demo
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.geofencing.demo", appContext.packageName)
}
} | GeofencingDemo/app/src/androidTest/java/com/geofencing/demo/ExampleInstrumentedTest.kt | 2284282139 |
package com.geofencing.demo
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)
}
} | GeofencingDemo/app/src/test/java/com/geofencing/demo/ExampleUnitTest.kt | 1166654746 |
package com.geofencing.demo.ui.service_geofence
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import com.geofencing.demo.R
import com.geofencing.demo.data.service_models.CircularGeofence
import com.geofencing.demo.data.service_models.Geofence
import com.geofencing.demo.data.service_models.PolygonalGeofence
import com.geofencing.demo.databinding.ActivityServiceGeofencingBinding
import com.geofencing.demo.databinding.CreateGeofenceLayoutBinding
import com.geofencing.demo.service.GeofencingService
import com.geofencing.demo.util.Constants.ACTION_SERVICE_START
import com.geofencing.demo.util.Constants.ACTION_SERVICE_STOP
import com.geofencing.demo.util.ViewExtensions.hide
import com.geofencing.demo.util.ViewExtensions.show
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.Polygon
import com.google.android.gms.maps.model.PolygonOptions
class ServiceGeofencingActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private lateinit var polygonMap: Polygon
private lateinit var binding: ActivityServiceGeofencingBinding
private lateinit var map: GoogleMap
private var geofences= arrayListOf<Geofence>()
private var polygon = arrayListOf<LatLng>()// used to set a polygon
private var hole = arrayListOf<LatLng>()// used to set a hole
private var holes= arrayListOf<List<LatLng>>()
private var isDrawingOuterPolygon=true
private var markers= arrayListOf<Marker>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityServiceGeofencingBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.btnServiceAction.setOnClickListener {
sendActionCommandToService(if(GeofencingService.started.value!!) ACTION_SERVICE_STOP else ACTION_SERVICE_START)
}
binding.rgShape.setOnCheckedChangeListener { _, id ->
if (findViewById<RadioButton>(id)==binding.rbCircle){
binding.ll.hide()
}else{
binding.ll.show()
}
}
binding.btnSetPolygon.setOnClickListener {
addPolygon(polygon)
markers.forEach{
// it.remove()
}
hole.clear()
isDrawingOuterPolygon=false
}
binding.btnSetHole.setOnClickListener {
holes.add(hole.toList())
polygonMap.remove()
drawPolygonalGeofence(PolygonalGeofence(polygon,holes))
markers.forEach{
//it.remove()
}
hole.clear()
}
binding.btnSetGeofence.setOnClickListener{
geofences.add(PolygonalGeofence(polygon.toList(),holes.toList()))//save polygon
polygon.clear()
hole.clear()
holes.clear()
markers.forEach{
it.remove()
}
Toast.makeText(this,"Geofence ${geofences.size} saved ",Toast.LENGTH_SHORT).show()
isDrawingOuterPolygon=true
}
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
}
@SuppressLint("MissingPermission")
override fun onMapReady(map: GoogleMap) {
this.map=map
map.isMyLocationEnabled = true
map.setOnMapLongClickListener(this)
map.uiSettings.apply {
isMyLocationButtonEnabled = true
isZoomControlsEnabled = true
isMapToolbarEnabled = false
}
GeofencingService.geofences.observe(this) {
this.map.clear()
// circularGeofences.clear()
//polygonalGeofences.clear()
geofences.clear()
if (it.isNullOrEmpty().not()) {
it.forEach {geofence ->
if(geofence is CircularGeofence){
drawCircularGeofence(geofence)
}else if(geofence is PolygonalGeofence){
drawPolygonalGeofence(geofence)
}
}
}
}
GeofencingService.started.observe(this) {
binding.btnServiceAction.show()
if(it){
binding.btnServiceAction.text= getString(R.string.stop_service)
binding.rgShape.hide()
binding.ll.hide()
}else{
binding.btnServiceAction.text= getString(R.string.start_service)
binding.rgShape.show()
if(binding.rbPolygon.isChecked){
binding.ll.show()
}
}
}
}
override fun onMapLongClick(point: LatLng) {
if(GeofencingService.started.value!!){
return
}
if(binding.rbCircle.isChecked){
val inflater = layoutInflater
val binding = CreateGeofenceLayoutBinding.inflate(inflater)
val dialog = AlertDialog.Builder(this).create()
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)
dialog.setView(binding.root)
binding.btnAccept.setOnClickListener {
val geofence=CircularGeofence(point,binding.etRadius.text.toString().toFloat())
geofences.add(geofence)
drawCircularGeofence(geofence)
Toast.makeText(this,"Geofence ${geofences.size} saved ",Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
dialog.show()
}else{
if(isDrawingOuterPolygon){
polygon.add(point)
}else{
hole.add(point)
}
val marker= map.addMarker(
MarkerOptions().position(point).title(polygon.size.toString())
.alpha(1f)// opacity
.draggable(false)
.flat(false)
)
marker?.let {
markers.add(it)
}
}
}
private fun drawCircularGeofence(geofence: CircularGeofence) {
map.addCircle(
CircleOptions().center(geofence.center).radius(geofence.radius.toDouble())
.strokeColor(ContextCompat.getColor(this, R.color.blue_700))
.fillColor(ContextCompat.getColor(this, R.color.blue_transparent))
)
}
private fun drawPolygonalGeofence(geofence: PolygonalGeofence) {
polygonMap= map.addPolygon(
PolygonOptions().apply {
addAll(geofence.points)
if(geofence.holes.isNotEmpty()){
geofence.holes.forEach {
addHole(it)
}
}
strokeWidth(10f)
strokeColor(ContextCompat.getColor(this@ServiceGeofencingActivity, R.color.blue_700))
fillColor(ContextCompat.getColor(this@ServiceGeofencingActivity, R.color.blue_transparent))
geodesic(true)
}
)
}
private fun addPolygon(points:List<LatLng>){
polygonMap =map.addPolygon(
PolygonOptions().apply {
addAll(points)
strokeWidth(10f)
strokeColor(ContextCompat.getColor(this@ServiceGeofencingActivity, R.color.blue_700))
fillColor(ContextCompat.getColor(this@ServiceGeofencingActivity, R.color.blue_transparent))
geodesic(true)
}
)
}
private fun sendActionCommandToService(action: String) {
map.clear()
// val geofences= arrayListOf<Geofence>()
// geofences.addAll(this.geofences)
//geofences.addAll(polygonalGeofences)
Intent(this, GeofencingService::class.java).apply {
this.action = action
putParcelableArrayListExtra("geofences", geofences)
startService(this)
}
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/service_geofence/ServiceGeofencingActivity.kt | 1339300010 |
package com.geofencing.demo.ui
import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.geofencing.demo.databinding.ActivityInitBinding
import com.geofencing.demo.ui.google_geofencing.GoogleGeofencingActivity
import com.geofencing.demo.ui.service_geofence.ServiceGeofencingActivity
import com.geofencing.demo.util.Permissions.hasBackgroundLocationPermission
import com.geofencing.demo.util.Permissions.hasLocationPermission
import com.geofencing.demo.util.Permissions.hasPostNotificationsPermission
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class InitActivity : AppCompatActivity() {
private lateinit var binding: ActivityInitBinding
private lateinit var locationPermissionLauncher: ActivityResultLauncher<String>
private lateinit var backgroundLocationPermissionLauncher: ActivityResultLauncher<String>
private lateinit var postNotificationsPermissionLauncher: ActivityResultLauncher<String>
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInitBinding.inflate(layoutInflater)
setContentView(binding.root)
locationPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {isGranted ->
if (isGranted) {
// PERMISSION GRANTED
checkPermissions()
} else {
// PERMISSION NOT GRANTED
}
}
backgroundLocationPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {isGranted ->
if (isGranted) {
// PERMISSION GRANTED
checkPermissions()
} else {
// PERMISSION NOT GRANTED
}
}
postNotificationsPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {isGranted ->
if (isGranted) {
// PERMISSION GRANTED
checkPermissions()
} else {
// PERMISSION NOT GRANTED
}
}
lifecycleScope.launch {
delay(2000)
checkPermissions()
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun checkPermissions() {
if(hasLocationPermission(this)&& hasBackgroundLocationPermission(this)&& hasPostNotificationsPermission(this) ){
toNextScreen()
}
else if(!hasLocationPermission(this)){
locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}else if(!hasBackgroundLocationPermission(this)){
locationPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}else if(!hasPostNotificationsPermission(this)){
locationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
private fun toNextScreen(){
startActivity(Intent(this,
ServiceGeofencingActivity::class.java))
finish()
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/InitActivity.kt | 626920435 |
package com.geofencing.demo.ui.google_geofencing
import android.annotation.SuppressLint
import android.app.Application
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.geofencing.demo.broadcast.GeofencingBroadcastReceiver
import com.geofencing.demo.data.GeofenceEntity
import com.geofencing.demo.data.GeofenceRepository
import com.geofencing.demo.util.Permissions
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.maps.android.SphericalUtil
@HiltViewModel
class GoogleGeofencingViewModel @Inject constructor(
application: Application,
private val geofenceRepository: GeofenceRepository
) : AndroidViewModel(application) {
val app = application
private var geofencingClient = LocationServices.getGeofencingClient(app.applicationContext)
// Database
val geofences = geofenceRepository.geofences.asLiveData()
private fun getPendingIntent(): PendingIntent {
val intent = Intent(app, GeofencingBroadcastReceiver::class.java)
return PendingIntent.getBroadcast(
app,
0,
intent,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
(PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
else PendingIntent.FLAG_UPDATE_CURRENT
)
}
private fun addGeofenceToDatabase(geofenceEntity: GeofenceEntity) =
viewModelScope.launch(Dispatchers.IO) {
geofenceRepository.addGeofence(geofenceEntity)
}
fun removeGeofenceFromDatabase(geofenceEntity: GeofenceEntity) =
viewModelScope.launch(Dispatchers.IO) {
geofenceRepository.removeGeofence(geofenceEntity)
}
private fun removeGeofenceFromDatabaseById(id: Int) =
viewModelScope.launch(Dispatchers.IO) {
geofenceRepository.removeGeofenceByGeoId(id)
}
@SuppressLint("MissingPermission")
suspend fun addGeofenceToSystem(//Geofence API
latitude: Double,
longitude: Double, radius: Float
) {
if (Permissions.hasBackgroundLocationPermission(app)) {
var geoId = geofenceRepository.getNextGeoIdToCreate()
val geofence = Geofence.Builder()
.setRequestId(geoId.toString())
.setCircularRegion(
latitude,
longitude,
radius
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER
or Geofence.GEOFENCE_TRANSITION_EXIT
or Geofence.GEOFENCE_TRANSITION_DWELL
)
.setLoiteringDelay(7000)
.build()
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(
GeofencingRequest.INITIAL_TRIGGER_ENTER
// or GeofencingRequest.INITIAL_TRIGGER_EXIT
or GeofencingRequest.INITIAL_TRIGGER_DWELL
)
.addGeofence(geofence)
.build()
Log.d("Geofence adding", geoId.toString())
geofencingClient.addGeofences(geofencingRequest, getPendingIntent()).run {
addOnSuccessListener {
Log.d("Geofence adding", "Successfully added.")
Toast.makeText(
app.applicationContext,
"Geofence $geoId successfully added",
Toast.LENGTH_SHORT
).show()
addGeofenceToDatabase(
GeofenceEntity(
geoId,
latitude = latitude,
longitude = longitude,
radius = radius
)
)
}
addOnFailureListener {
Toast.makeText(
app.applicationContext,
"Error adding geofence",
Toast.LENGTH_SHORT
).show()
Log.e(
"Geofence adding Error ",
it.message.toString() + " " + it.localizedMessage + " " + it.stackTrace
)
}
}
} else {
Log.d("Geofence", "Permission not granted.")
}
}
suspend fun removeGeofenceFromSystem(id: Int) {
geofencingClient.removeGeofences(mutableListOf(id.toString()))
.addOnCompleteListener {
if (it.isSuccessful) {
Toast.makeText(
app.applicationContext,
"Geofence $id successfully removed from system",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
app.applicationContext,
"Failed to remove geofence from system",
Toast.LENGTH_SHORT
).show()
}
removeGeofenceFromDatabaseById(id)
}
}
fun getBounds(center: LatLng, radius: Float): LatLngBounds {
val distanceFromCenterToCorner = radius * kotlin.math.sqrt(2.0)
val southWestCorner = SphericalUtil.computeOffset(center, distanceFromCenterToCorner, 225.0)
val northEastCorner = SphericalUtil.computeOffset(center, distanceFromCenterToCorner, 45.0)
return LatLngBounds(southWestCorner, northEastCorner)
}
@SuppressLint("MissingPermission")
fun registerLocalGeofences(locals: MutableList<GeofenceEntity>) {
if(locals.isEmpty()){
return
}
val localGeofences =locals.map {
Geofence.Builder()
.setRequestId(it.id.toString())
.setCircularRegion(
it.latitude,
it.longitude,
it.radius
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(
Geofence.GEOFENCE_TRANSITION_ENTER
or Geofence.GEOFENCE_TRANSITION_EXIT
or Geofence.GEOFENCE_TRANSITION_DWELL
)
.setLoiteringDelay(7000)
.build()
}
val geofencingRequest = GeofencingRequest.Builder()
.setInitialTrigger(
GeofencingRequest.INITIAL_TRIGGER_ENTER
// or GeofencingRequest.INITIAL_TRIGGER_EXIT
or GeofencingRequest.INITIAL_TRIGGER_DWELL
)
.addGeofences(localGeofences)
.build()
geofencingClient.addGeofences(geofencingRequest, getPendingIntent()).run {
addOnSuccessListener {
Toast.makeText(
app.applicationContext,
" ${localGeofences.size} geofences successfully added to system",
Toast.LENGTH_SHORT
).show()
}
addOnFailureListener {
Toast.makeText(
app.applicationContext,
"Error adding geofences",
Toast.LENGTH_SHORT
).show()
}
}
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/google_geofencing/GoogleGeofencingViewModel.kt | 187945545 |
package com.geofencing.demo.ui.google_geofencing
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.geofencing.demo.R
import com.geofencing.demo.databinding.CreateGeofenceLayoutBinding
import com.geofencing.demo.databinding.FragmentMapsBinding
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class MapsFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private var _binding: FragmentMapsBinding? = null
private val binding get() = _binding!!
private lateinit var map: GoogleMap
private lateinit var circle: Circle
private val args by navArgs<MapsFragmentArgs>()
private val viewModel: GoogleGeofencingViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMapsBinding.inflate(layoutInflater, container, false)
binding.lifecycleOwner=viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)
binding.geofencesFab.setOnClickListener {
findNavController().navigate(R.id.toGeofences)
}
}
private fun backFromGeofencesFragment() {
if (args.geofenceEntity != null) {
val selectedGeofence = LatLng(
args.geofenceEntity!!.latitude,
args.geofenceEntity!!.longitude
)
zoomToGeofence(selectedGeofence, args.geofenceEntity!!.radius)
}
}
private fun zoomToGeofence(center: LatLng, radius: Float) {
map.animateCamera(
CameraUpdateFactory.newLatLngBounds(
viewModel.getBounds(center, radius), 10
), 1000, null
)
}
private fun drawCircle(location: LatLng, radius: Float) {
circle = map.addCircle(
CircleOptions().center(location).radius(radius.toDouble())
.strokeColor(ContextCompat.getColor(requireContext(), R.color.blue_700))
.fillColor(ContextCompat.getColor(requireContext(), R.color.blue_transparent))
)
}
private fun drawMarker(location: LatLng, name: String) {
map.addMarker(
MarkerOptions().position(location).title(name)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
)
}
@SuppressLint("MissingPermission")
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
map.isMyLocationEnabled = true
map.setOnMapLongClickListener(this)
map.uiSettings.apply {
isMyLocationButtonEnabled = true
isZoomControlsEnabled = true
isMapToolbarEnabled = false
}
viewModel.geofences.observe(viewLifecycleOwner) { geofences->
map.clear()
geofences.forEach {
drawCircle(LatLng(it.latitude, it.longitude), it.radius)
drawMarker(LatLng(it.latitude, it.longitude), it.name)
}
//viewModel.registerLocalGeofences(geofences)
}
backFromGeofencesFragment()
}
override fun onMapLongClick(loc: LatLng) {
val inflater = requireActivity().layoutInflater
val binding = CreateGeofenceLayoutBinding.inflate(inflater)
val dialog = AlertDialog.Builder(requireContext()).create()
dialog.setCancelable(false)
dialog.setCanceledOnTouchOutside(false)
dialog.setView(binding.root)
binding.btnAccept.setOnClickListener {
lifecycleScope.launch {
viewModel.addGeofenceToSystem(loc.latitude,loc.longitude,binding.etRadius.text.toString().toFloat())
}
dialog.dismiss()
}
dialog.show()
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/google_geofencing/MapsFragment.kt | 3415967064 |
package com.geofencing.demo.ui.google_geofencing
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.geofencing.demo.adapter.GeofencesAdapter
import com.geofencing.demo.databinding.FragmentGeofencesBinding
class GeofencesFragment : Fragment() {
private var _binding: FragmentGeofencesBinding? = null
private val binding get() = _binding!!
private val viewModel: GoogleGeofencingViewModel by activityViewModels()
private val geofencesAdapter by lazy { GeofencesAdapter(viewModel) }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentGeofencesBinding.inflate(inflater, container, false)
setupToolbar()
setupRecyclerView()
observeDatabase()
return binding.root
}
private fun setupToolbar() {
binding.toolbar.setNavigationOnClickListener {
requireActivity().onBackPressedDispatcher.onBackPressed()
}
}
private fun setupRecyclerView() {
binding.rvGeofences.layoutManager = LinearLayoutManager(requireContext())
binding.rvGeofences.adapter = geofencesAdapter
}
private fun observeDatabase() {
viewModel.geofences.observe(viewLifecycleOwner) {
geofencesAdapter.setData(it)
binding.rvGeofences.scheduleLayoutAnimation()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/google_geofencing/GeofencesFragment.kt | 4080174976 |
package com.geofencing.demo.ui.google_geofencing
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.geofencing.demo.R
import com.geofencing.demo.databinding.ActivityGoogleGeofencingBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class GoogleGeofencingActivity : AppCompatActivity() {
private lateinit var binding: ActivityGoogleGeofencingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGoogleGeofencingBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/ui/google_geofencing/GoogleGeofencingActivity.kt | 1086921651 |
package com.geofencing.demo.di
import android.content.Context
import androidx.room.Room
import com.geofencing.demo.data.GeofenceDatabase
import com.geofencing.demo.util.Constants.DATABASE_NAME
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
private object AppModule {
@Singleton
@Provides
fun provideDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(
context,
GeofenceDatabase::class.java,
DATABASE_NAME
).build()
@Singleton
@Provides
fun provideDao(database: GeofenceDatabase) = database.geofenceDao()
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/di/AppModule.kt | 3762731202 |
package com.geofencing.demo.di
import android.app.NotificationManager
import android.content.Context
import androidx.core.app.NotificationCompat
import com.geofencing.demo.R
import com.geofencing.demo.util.Constants.SERVICE_NOTIFICATION_CHANNEL_ID
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ServiceComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.android.scopes.ServiceScoped
@Module
@InstallIn(ServiceComponent::class)
class NotificationModule {
@ServiceScoped
@Provides
fun provideNotificationBuilder(
@ApplicationContext context: Context
): NotificationCompat.Builder {
return NotificationCompat.Builder(context, SERVICE_NOTIFICATION_CHANNEL_ID)
.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_notification)
}
@ServiceScoped
@Provides
fun provideNotificationManager(
@ApplicationContext context: Context
): NotificationManager {
return context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/di/NotificationModule.kt | 2954213217 |
package com.geofencing.demo.util
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
object Permissions {
fun hasLocationPermission(context: Context): Boolean =
ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
fun hasBackgroundLocationPermission(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
return true
}
fun hasPostNotificationsPermission(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
}
return true
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/util/Permissions.kt | 1641098469 |
package com.geofencing.demo.util
import androidx.recyclerview.widget.DiffUtil
class MyDiffUtil<T>(
private val oldList: List<T>,
private val newList: List<T>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] === newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/util/MyDiffUtil.kt | 473114328 |
package com.geofencing.demo.util
import android.view.View
object ViewExtensions {
fun View.enable(){
this.isEnabled = true
}
fun View.disable(){
this.isEnabled = false
}
fun View.show(){
this.visibility = View.VISIBLE
}
fun View.hide(){
this.visibility = View.GONE
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/util/ViewExtensions.kt | 3646000458 |
package com.geofencing.demo.util
import android.graphics.PointF
import com.google.android.gms.maps.model.LatLng
object GeofencingUtils {
fun isInsideCircle(target:LatLng,center:LatLng,radius:Double):Boolean{
val distance= distanceBetweenPoints(target,center)
return distance<=radius
}
private fun distanceBetweenPoints(point1:LatLng,point2:LatLng):Double{
val earthRadius=6371000
val lat1=Math.toRadians(point1.latitude)
val lon1=Math.toRadians(point1.longitude)
val lat2=Math.toRadians(point2.latitude)
val lon2=Math.toRadians(point2.longitude)
val dLat=lat2-lat1
val dLon=lon2-lon1
val a=Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.cos(lat1)*Math.cos(lat2)*
Math.sin(dLon/2)*Math.sin(dLon/2)
val c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))
return earthRadius*c
}
fun isPointInsidePolygon(point: LatLng, polygon: List<LatLng>): Boolean {
val p = PointF(point.latitude.toFloat(), point.longitude.toFloat())
val poly = polygon.map { PointF(it.latitude.toFloat(), it.longitude.toFloat()) }
var c = false
var i = -1
var j = poly.size - 1
while (++i < poly.size) {
if ((poly[i].y <= p.y && p.y < poly[j].y || poly[j].y <= p.y && p.y < poly[i].y) &&
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x
) {
c = !c
}
j = i
}
return c
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/util/GeofencingUtils.kt | 2645844376 |
package com.geofencing.demo.util
object Constants {
const val DATABASE_TABLE_NAME = "geofence_table"
const val DATABASE_NAME = "geofence_db"
const val NOTIFICATION_CHANNEL_ID = "geofence_transition_id"
const val NOTIFICATION_CHANNEL_NAME = "geofence_notification"
const val SERVICE_NOTIFICATION_CHANNEL_ID="service_notification_id"
const val SERVICE_NOTIFICATION_CHANNEL_NAME="service_notification_name"
const val SERVICE_NOTIFICATION_ID=100
const val LOCATION_UPDATE_INTERVAL = 3000L
const val ACTION_SERVICE_START="ACTION_SERVICE_START"
const val ACTION_SERVICE_STOP="ACTION_SERVICE_STOP"
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/util/Constants.kt | 2722551612 |
package com.geofencing.demo.adapter
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.viewModelScope
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.geofencing.demo.data.GeofenceEntity
import com.geofencing.demo.databinding.GeofenceItemBinding
import com.geofencing.demo.ui.google_geofencing.GeofencesFragmentDirections
import com.geofencing.demo.ui.google_geofencing.GoogleGeofencingViewModel
import com.geofencing.demo.util.MyDiffUtil
import kotlinx.coroutines.launch
class GeofencesAdapter(private val viewModel: GoogleGeofencingViewModel) :
RecyclerView.Adapter<GeofencesAdapter.MyViewHolder>() {
private var geofenceEntity = mutableListOf<GeofenceEntity>()
class MyViewHolder(val binding: GeofenceItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(geofenceEntity: GeofenceEntity) {
binding.geofencesEntity = geofenceEntity
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = GeofenceItemBinding.inflate(layoutInflater, parent, false)
return MyViewHolder(binding)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder.from(parent)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentGeofence = geofenceEntity[position]
holder.bind(currentGeofence)
holder.binding.deleteImageView.setOnClickListener {
removeItem(holder, position)
}
holder.binding.clContent.setOnClickListener {
val action =
GeofencesFragmentDirections.backToMaps(currentGeofence)
holder.itemView.findNavController().navigate(action)
}
}
private fun removeItem(holder: MyViewHolder, position: Int) {
viewModel.viewModelScope.launch {
viewModel.removeGeofenceFromSystem(geofenceEntity[position].id)
}
}
override fun getItemCount(): Int {
return geofenceEntity.size
}
fun setData(newGeofenceEntity: MutableList<GeofenceEntity>) {
val geofenceDiffUtil = MyDiffUtil(geofenceEntity, newGeofenceEntity)
val diffUtilResult = DiffUtil.calculateDiff(geofenceDiffUtil)
geofenceEntity = newGeofenceEntity
diffUtilResult.dispatchUpdatesTo(this)
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/adapter/GeofencesAdapter.kt | 178055457 |
package com.geofencing.demo.service
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.location.Location
import android.os.Build
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import com.geofencing.demo.R
import com.geofencing.demo.data.service_models.CircularGeofence
import com.geofencing.demo.data.service_models.Geofence
import com.geofencing.demo.util.Constants.ACTION_SERVICE_START
import com.geofencing.demo.util.Constants.ACTION_SERVICE_STOP
import com.geofencing.demo.util.Constants.LOCATION_UPDATE_INTERVAL
import com.geofencing.demo.util.Constants.SERVICE_NOTIFICATION_CHANNEL_ID
import com.geofencing.demo.util.Constants.SERVICE_NOTIFICATION_CHANNEL_NAME
import com.geofencing.demo.util.Constants.SERVICE_NOTIFICATION_ID
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.maps.model.LatLng
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class GeofencingService: LifecycleService() {
companion object{
const val DWELLING_TIME=10000
val started= MutableLiveData(false)
val geofences = MutableLiveData<MutableList<Geofence>>()
}
private lateinit var states: MutableList<Boolean?>
private lateinit var enteringTime: MutableList<Long?>
@Inject
lateinit var notification: NotificationCompat.Builder
@Inject
lateinit var notificationManager: NotificationManager
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private fun setInitialValues(){
started.value=false
geofences.value= mutableListOf()
}
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
super.onLocationResult(result)
result.locations.let { locations ->
for (location in locations) {
Log.d("GeofencingService", LatLng(location.latitude,location.longitude).toString())
updateNotificationPeriodically(LatLng(location.latitude,location.longitude))
}
}
}
}
override fun onCreate() {
super.onCreate()
setInitialValues()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
intent?.let {
when(it.action){
ACTION_SERVICE_START->{
started.value=true
val geofences= if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableArrayListExtra("geofences",Geofence::class.java)
} else {
TODO("VERSION.SDK_INT < TIRAMISU")
}
geofences?.forEach {geofence->
//Log.d("TestLog",geofence.radius.toString())
}
states= MutableList(geofences!!.size){null}
enteringTime= MutableList(geofences!!.size){null}
Companion.geofences.value=geofences
startForegroundService()
startLocationUpdates()
}
ACTION_SERVICE_STOP->{
setInitialValues()
stopForegroundService()
}
else->{
}
}
}
return super.onStartCommand(intent, flags, startId)
}
private fun startForegroundService(){
createNotificationChannel()
startForeground(SERVICE_NOTIFICATION_ID,notification.build())
}
@SuppressLint("MissingPermission")
private fun startLocationUpdates(){
val locationRequest = LocationRequest.Builder(
Priority.PRIORITY_HIGH_ACCURACY, LOCATION_UPDATE_INTERVAL
).build()
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
SERVICE_NOTIFICATION_CHANNEL_ID,
SERVICE_NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(channel)
}
private fun stopForegroundService() {
removeLocationUpdates()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(
SERVICE_NOTIFICATION_ID
)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun removeLocationUpdates() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
}
private fun updateNotificationPeriodically(myLocation:LatLng) {
var message=""
geofences.value?.forEachIndexed { index, circularGeofence ->
val isInside=circularGeofence.isInsideGeofence(myLocation)
if(states.get(index)==false&&isInside){//show entering geofence
showGeofenceEvent(index+1,"Entering Geofence ${index+1}")
enteringTime[index]=System.currentTimeMillis()
}else if(states.get(index)==true&&!isInside){//show exiting geofence
showGeofenceEvent(index+1,"Exiting Geofence ${index+1}")
enteringTime[index]=null
}
if(enteringTime[index]!=null&&isInside&&(System.currentTimeMillis()- enteringTime[index]!! >= DWELLING_TIME)){
showGeofenceEvent(index+1,"Dwelling in Geofence ${index+1}")
enteringTime[index]=null
}
states[index]=isInside
message += "${if (isInside) {
"Inside of"
} else "Outside of"} Geofence ${index + 1} \n"
}
notification.apply {
setContentTitle("Geofence States")
setContentText(message)
setOngoing(true)
setStyle(NotificationCompat.BigTextStyle())
}
notificationManager.notify(SERVICE_NOTIFICATION_ID, notification.build())
}
private fun showGeofenceEvent(id:Int,msg:String){
notification.apply {
setContentTitle("Geofence Event")
setContentText(msg)
setOngoing(false)
}
notificationManager.notify(id, notification.build())
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/service/GeofencingService.kt | 4095914384 |
package com.geofencing.demo.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@Dao
interface GeofenceDao {
@Query("SELECT * FROM geofence_table ORDER BY id ASC")
fun getGeofences(): Flow<MutableList<GeofenceEntity>>
@Query("SELECT * FROM geofence_table WHERE id=:id LIMIT 1")
fun getGeofenceById(id:Int): GeofenceEntity?
@Query("SELECT id FROM geofence_table ORDER BY id DESC LIMIT 1 ")
suspend fun getLastGeoId():Int?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addGeofence(geofenceEntity: GeofenceEntity)
@Delete
suspend fun removeGeofence(geofenceEntity: GeofenceEntity)
@Query("DELETE FROM geofence_table WHERE id=:id")
suspend fun removeGeofenceByGeoId(id: Int)
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/GeofenceDao.kt | 1021790235 |
package com.geofencing.demo.data
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@ViewModelScoped
class GeofenceRepository @Inject constructor(private val geofenceDao: GeofenceDao) {
val geofences: Flow<MutableList<GeofenceEntity>> = geofenceDao.getGeofences()
suspend fun addGeofence(geofenceEntity: GeofenceEntity) {
geofenceDao.addGeofence(geofenceEntity)
}
suspend fun removeGeofence(geofenceEntity: GeofenceEntity) {
geofenceDao.removeGeofence(geofenceEntity)
}
suspend fun getNextGeoIdToCreate():Int {
return if(geofenceDao.getLastGeoId()!=null) (geofenceDao.getLastGeoId()!!)+1 else 1
}
suspend fun removeGeofenceByGeoId(geoId: Int) {
geofenceDao.removeGeofenceByGeoId(geoId)
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/GeofenceRepository.kt | 31762953 |
package com.geofencing.demo.data
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.geofencing.demo.util.Constants.DATABASE_TABLE_NAME
import kotlinx.parcelize.Parcelize
@Entity(tableName = DATABASE_TABLE_NAME)
@Parcelize
class GeofenceEntity(
@PrimaryKey(autoGenerate = false)
var id: Int,
val name: String="Geofence $id",
val latitude: Double,
val longitude: Double,
val radius: Float,
): Parcelable {
override fun toString(): String {
return name
}
}
| GeofencingDemo/app/src/main/java/com/geofencing/demo/data/GeofenceEntity.kt | 2861541801 |
package com.geofencing.demo.data
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [GeofenceEntity::class],
version = 1,
exportSchema = false
)
abstract class GeofenceDatabase: RoomDatabase() {
abstract fun geofenceDao(): GeofenceDao
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/GeofenceDatabase.kt | 2531962597 |
package com.geofencing.demo.data.service_models
import android.os.Parcelable
import com.google.android.gms.maps.model.LatLng
import kotlinx.parcelize.Parcelize
interface Geofence:Parcelable {
fun isInsideGeofence(target:LatLng):Boolean
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/service_models/Geofence.kt | 3999620650 |
package com.geofencing.demo.data.service_models
import android.os.Parcelable
import com.geofencing.demo.util.GeofencingUtils
import com.google.android.gms.maps.model.LatLng
import kotlinx.parcelize.Parcelize
@Parcelize
data class PolygonalGeofence(val points:List<LatLng>,val holes:List<List<LatLng>> = emptyList()):Geofence,Parcelable {
override fun isInsideGeofence(target: LatLng): Boolean {
return if(holes.isEmpty()) GeofencingUtils.isPointInsidePolygon(target,points) else
GeofencingUtils.isPointInsidePolygon(target,points) && holes.none { GeofencingUtils.isPointInsidePolygon(target, it) }
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/service_models/PolygonalGeofence.kt | 255128978 |
package com.geofencing.demo.data.service_models
import android.os.Parcelable
import com.geofencing.demo.util.GeofencingUtils
import com.google.android.gms.maps.model.LatLng
import kotlinx.parcelize.Parcelize
import java.io.Serializable
@Parcelize
data class CircularGeofence(val center:LatLng, val radius:Float):Parcelable,Geofence {
override fun isInsideGeofence(point: LatLng):Boolean {
return GeofencingUtils.isInsideCircle(point,center,radius.toDouble())
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/data/service_models/CircularGeofence.kt | 1543025643 |
package com.geofencing.demo.binding_adapters
import android.widget.TextView
import androidx.databinding.BindingAdapter
@BindingAdapter("latitude", "longitude", requireAll = true)
fun TextView.parseCoordinates(lat: Double,long:Double) {
val lat = String.format("%.4f", lat)
val long = String.format("%.4f", long)
"$lat , $long".also { this.text = it }
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/binding_adapters/BindingAdapters.kt | 1629041492 |
package com.geofencing.demo.broadcast
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.NotificationCompat
import com.geofencing.demo.R
import com.geofencing.demo.data.GeofenceDao
import com.geofencing.demo.util.Constants.NOTIFICATION_CHANNEL_ID
import com.geofencing.demo.util.Constants.NOTIFICATION_CHANNEL_NAME
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.location.GeofencingEvent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class GeofencingBroadcastReceiver: BroadcastReceiver() {
@Inject
lateinit var geofenceDao: GeofenceDao
override fun onReceive(context: Context, intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if(geofencingEvent?.hasError()!!){
val errorMessage = GeofenceStatusCodes
.getStatusCodeString(geofencingEvent.errorCode)
Log.e("BroadcastReceiver", errorMessage)
return
}
CoroutineScope(Dispatchers.IO).launch {
geofencingEvent.triggeringGeofences?.forEach {
var geofence= geofenceDao.getGeofenceById((it.requestId.toInt()))
// Log.d("GeofenceReceiver",geofence.toString())
if(geofence==null){
//unregister
return@forEach
}
when(geofencingEvent.geofenceTransition){
Geofence.GEOFENCE_TRANSITION_ENTER -> {
Log.d("GeofenceReceiver", "Geofence ENTER")
displayNotification(geofence.id, context,"ENTERING TO $geofence" )
}
Geofence.GEOFENCE_TRANSITION_EXIT -> {
Log.d("GeofenceReceiver", "Geofence EXIT")
displayNotification(geofence.id,context, "EXITING FROM $geofence")
}
Geofence.GEOFENCE_TRANSITION_DWELL -> {
Log.d("GeofenceReceiver", "Geofence DWELL")
displayNotification(geofence.id ,context, "DWELLING IN $geofence ")
}
else -> {
Log.d("GeofenceReceiver", "Invalid Type")
displayNotification(geofence.id ,context, "Geofence INVALID TYPE $geofence")
}
}
}
}
}
private fun displayNotification(notificationId:Int, context: Context, geofenceTransition: String){
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
createNotificationChannel(notificationManager)
val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Geofence Event")
.setDefaults(Notification.DEFAULT_VIBRATE)
.setContentText(geofenceTransition)
notificationManager.notify(notificationId, notification.build())
}
private fun createNotificationChannel(notificationManager: NotificationManager){
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
}
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/broadcast/GeofencingBroadcastReceiver.kt | 2386080184 |
package com.geofencing.demo
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class GeofencingApplication:Application() {
} | GeofencingDemo/app/src/main/java/com/geofencing/demo/GeofencingApplication.kt | 3757767081 |
package com.example.androidcryptoexample
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.androidcryptoexample", appContext.packageName)
}
} | AndroidCryptoExample/app/src/androidTest/java/com/example/androidcryptoexample/ExampleInstrumentedTest.kt | 580729953 |
package com.example.androidcryptoexample
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)
}
} | AndroidCryptoExample/app/src/test/java/com/example/androidcryptoexample/ExampleUnitTest.kt | 4000172380 |
package com.example.androidcryptoexample.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) | AndroidCryptoExample/app/src/main/java/com/example/androidcryptoexample/ui/theme/Color.kt | 560183343 |
package com.example.androidcryptoexample.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 AndroidCryptoExampleTheme(
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
)
} | AndroidCryptoExample/app/src/main/java/com/example/androidcryptoexample/ui/theme/Theme.kt | 3170907495 |
package com.example.androidcryptoexample.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
)
*/
) | AndroidCryptoExample/app/src/main/java/com/example/androidcryptoexample/ui/theme/Type.kt | 1177054052 |
package com.example.androidcryptoexample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewDynamicColors
import androidx.compose.ui.tooling.preview.PreviewFontScale
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.tooling.preview.PreviewScreenSizes
import androidx.compose.ui.unit.dp
import com.example.androidcryptoexample.ui.theme.AndroidCryptoExampleTheme
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
BuildConfig.API_KEY
val cryptoManager = CryptoManager()
setContent {
AndroidCryptoExampleTheme {
var messageToEncrypt by remember {
mutableStateOf("")
}
var messageToDecrypt by remember {
mutableStateOf("")
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(32.dp)
) {
TextField(value = messageToEncrypt
, onValueChange = {
messageToEncrypt = it
},
modifier = Modifier.fillMaxWidth(),
placeholder = { Text(text = "Encrypt string")}
)
Spacer(modifier = Modifier.height(8.dp))
Row {
Button(onClick = {
val bytes = messageToEncrypt.encodeToByteArray()
val file = File(filesDir,"secret.txt")
if (!file.exists()){
file.createNewFile()
}
val fos = FileOutputStream(file)
messageToDecrypt = cryptoManager.encrypt(
bytes = bytes,
outputStream = fos
).decodeToString()
}) {
Text(text = "Encrypt")
}
Spacer(modifier = Modifier.width(16.dp))
Button(onClick = {
val file = File(filesDir,"secret.txt")
messageToEncrypt = cryptoManager.decrypt(
inputStream = FileInputStream(file)
).decodeToString()
}) {
Text(text = "Decrypt")
}
}
Text(text = messageToDecrypt)
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@PreviewScreenSizes
@PreviewFontScale
@PreviewLightDark
@PreviewDynamicColors
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AndroidCryptoExampleTheme {
Greeting("Android")
}
} | AndroidCryptoExample/app/src/main/java/com/example/androidcryptoexample/MainActivity.kt | 3524387059 |
package com.example.androidcryptoexample
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.io.InputStream
import java.io.OutputStream
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
class CryptoManager {
private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply {
load(null)
}
private val encryptCipher = Cipher.getInstance(TRANSFORMATION).apply {
init(
Cipher.ENCRYPT_MODE,getKey()
)
}
//Iv - Initialisation vector (Initial state of encryption)
private fun getDecryptCipherForIv(iv : ByteArray) : Cipher {
return Cipher.getInstance(TRANSFORMATION).apply {
init(Cipher.DECRYPT_MODE,getKey(),IvParameterSpec(iv))
}
}
//Check if key exists
private fun getKey() : SecretKey {
val existingKey = keyStore.getEntry("secret",null) as? KeyStore.SecretKeyEntry
return existingKey?.secretKey ?: createKey()
}
private fun createKey() : SecretKey {
return KeyGenerator.getInstance(ALGORITHM).apply {
init(
KeyGenParameterSpec.Builder(
"secret",
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(BLOCK_MODE)
.setEncryptionPaddings(PADDING)
.setUserAuthenticationRequired(false)
.setRandomizedEncryptionRequired(true)
.build()
)
}.generateKey()
}
//encrypt
fun encrypt(bytes : ByteArray,outputStream: OutputStream) : ByteArray {
val encryptedBytes = encryptCipher.doFinal(bytes)
outputStream.use {
it.write(encryptCipher.iv.size)
it.write(encryptCipher.iv)
it.write(encryptedBytes.size)
it.write(encryptedBytes)
}
return encryptedBytes
}
//decrypt
fun decrypt(inputStream: InputStream) : ByteArray {
return inputStream.use {
val ivSize = it.read()
val iv = ByteArray(ivSize)
it.read(iv)
val encryptedBytesSize = it.read()
val encryptedBytes = ByteArray(encryptedBytesSize)
it.read(encryptedBytes)
getDecryptCipherForIv(iv).doFinal(encryptedBytes)
}
}
companion object {
private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_AES
private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC
private const val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7
private const val TRANSFORMATION = "$ALGORITHM/$BLOCK_MODE/$PADDING"
}
} | AndroidCryptoExample/app/src/main/java/com/example/androidcryptoexample/CryptoManager.kt | 2792518455 |
package com.example.composenavtest
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.composenavtest", appContext.packageName)
}
} | ComposeUI_1.6.0_androidx.nav_bug/app/src/androidTest/java/com/example/composenavtest/ExampleInstrumentedTest.kt | 3038772311 |
package com.example.composenavtest.ui
import android.os.Bundle
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
class Screen2 : ComposableFragment() {
@Composable
override fun Content(args: Bundle?) {
Box(
modifier = Modifier
.background(Color.Red)
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = "SCREEN 2",
color = Color.White
)
}
}
}
| ComposeUI_1.6.0_androidx.nav_bug/app/src/main/java/com/example/composenavtest/ui/Screen2.kt | 278426308 |
package com.example.composenavtest.ui.theme
import android.app.Activity
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Typography
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColors(
background = Color.Black,
)
private val LightColorScheme = lightColors(
background = Color.White,
)
@Composable
fun ComposeNavTestTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = when {
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colors.background.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colors = colors,
typography = Typography(),
content = content
)
} | ComposeUI_1.6.0_androidx.nav_bug/app/src/main/java/com/example/composenavtest/ui/theme/Theme.kt | 381240503 |
package com.example.composenavtest.ui
import android.os.Bundle
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
class Screen1 : ComposableFragment() {
@Composable
override fun Content(args: Bundle?) {
Box(
modifier = Modifier
.background(Color.Blue)
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = "SCREEN 1",
color = Color.White
)
}
}
}
| ComposeUI_1.6.0_androidx.nav_bug/app/src/main/java/com/example/composenavtest/ui/Screen1.kt | 2049726761 |
package com.example.composenavtest.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import com.example.composenavtest.databinding.ComposableFragmentBinding
abstract class ComposableFragment : Fragment() {
private var _binding: ComposableFragmentBinding? = null
private val binding get() = _binding!!
@Composable
abstract fun Content(args: Bundle?): @Composable Unit
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = ComposableFragmentBinding.inflate(inflater, container, false)
binding.composeView.apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
Content(arguments)
}
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
postponeEnterTransition()
view.doOnPreDraw {
startPostponedEnterTransition()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| ComposeUI_1.6.0_androidx.nav_bug/app/src/main/java/com/example/composenavtest/ui/ComposableFragment.kt | 2065705560 |
package com.example.composenavtest
import android.content.res.ColorStateList
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.navigation.NavController
import androidx.navigation.createGraph
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.fragment.fragment
import com.example.composenavtest.databinding.MainActivityBinding
import com.example.composenavtest.ui.Screen1
import com.example.composenavtest.ui.Screen2
import com.example.composenavtest.ui.theme.ComposeNavTestTheme
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeNavTestTheme {
var navController by remember {
mutableStateOf<NavController?>(null)
}
Column(modifier = Modifier.fillMaxWidth()) {
AndroidViewBinding(
modifier = Modifier
.background(Color.Black)
.fillMaxWidth()
.weight(1f),
factory = { layoutInflater, viewGroup, boolean ->
MainActivityBinding.inflate(layoutInflater, viewGroup, boolean).apply {
navHostFragment.setBackgroundColor(Color.Black.hashCode())
navHostFragment.backgroundTintList =
ColorStateList.valueOf(Color.Black.hashCode())
}.also {
val navHost =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val nav: NavController = navHost.navController
val graph = nav.createGraph(
id = R.id.main_nav_graph,
startDestination = R.id.screen1,
) {
fragment<Screen1>(R.id.screen1) {
label = "screen1"
}
fragment<Screen2>(R.id.screen2) {
label = "screen2"
}
}
nav.setGraph(graph, null)
navController = nav
}
},
)
Box(
modifier = Modifier
.background(Color.Black)
.fillMaxWidth()
.padding(16.dp),
contentAlignment = Alignment.Center,
) {
Button(
onClick = {
navController?.navigate(
resId = R.id.screen2,
args = null,
navOptions = androidx.navigation.navOptions {
anim {
enter = R.anim.slide_in_from_right
exit = R.anim.slide_out_to_left
popEnter = R.anim.slide_in_from_left
popExit = R.anim.slide_out_to_right
}
}
)
}
) {
Text(
text = "Open screen 2",
)
}
}
}
}
}
}
}
| ComposeUI_1.6.0_androidx.nav_bug/app/src/main/java/com/example/composenavtest/MainActivity.kt | 1804879305 |
package com.example.madb
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.madb", appContext.packageName)
}
} | MadB/app/src/androidTest/java/com/example/madb/ExampleInstrumentedTest.kt | 777709902 |
package com.example.madb
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)
}
} | MadB/app/src/test/java/com/example/madb/ExampleUnitTest.kt | 2296551795 |
package com.example.madb
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | MadB/app/src/main/java/com/example/madb/MainActivity.kt | 1515154300 |
package com.derry.databinding_kt
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.derry.databinding_kt", appContext.packageName)
}
} | AndroidDataBinding/app/src/androidTest/java/com/derry/databinding_kt/ExampleInstrumentedTest.kt | 3219245142 |
package com.derry.databinding_kt
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)
}
} | AndroidDataBinding/app/src/test/java/com/derry/databinding_kt/ExampleUnitTest.kt | 493148969 |
package com.derry.databinding_kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.databinding.DataBindingUtil
import com.derry.databinding_kt.databinding.ActivityMainBinding
import com.derry.databinding_kt.model.StudentInfo
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
private val studentInfo = StudentInfo()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
// TODO 单向绑定第一种方式:<Model ---> View>
studentInfo.name = "zhangsan"
studentInfo.pwd = "123456"
binding.studentInfo = studentInfo
// 数据的刷新 发现界面没有效果,目前:界面不会根据Model的变化 而 变化
// 未修复:
Log.d(TAG, "name:${studentInfo.name}, pwd:${studentInfo.pwd}")
Handler().postDelayed({
studentInfo.name = "Lisi"
studentInfo.pwd = "999999"
}, 3000)
// 修复后: Model ---> View 一向
Log.d(TAG, "name:${studentInfo.nameF.get()}, pwd:${studentInfo.pwdF.get()}")
Handler().postDelayed({
studentInfo.nameF.set("Lisi")
studentInfo.pwdF.set("999999")
}, 3000)
// TODO 双向绑定(Model ---> View 一向 and View ---> Model 一向 ) == 双向
// Model ---> View 一向
studentInfo.nameF.set("zhangsan")
studentInfo.pwdF.set("123456") // 修改Model --> View
binding.studentInfo = studentInfo
Log.d(TAG, "name:${studentInfo.nameF.get()}, pwd:${studentInfo.pwdF.get()}")
Handler().postDelayed({
// 10秒后,测试 View ---> Model Model是否被修改了
Log.d(TAG, "name:${studentInfo.nameF.get()}, pwd:${studentInfo.pwdF.get()}")
}, 10000)
// 我们开发用的多的是, Model(修改888) ---> View(888) 一向
}
} | AndroidDataBinding/app/src/main/java/com/derry/databinding_kt/MainActivity.kt | 283781238 |
package com.derry.databinding_kt.model
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.ObservableField
// DataBinding BindingAdapter 涉及到判空 后面看
class StudentInfo /*: BaseObservable()*/ {
// 第一种方式 未修复 KT放弃第一种方式
var name: String? = null
// @Bindable
get() {
return field
}
set(value) {
field = value
// notifyPropertyChanged(BR.name)
}
var pwd : String? = null
get() {
return field
}
set(value) {
field = value
}
// 第二种方式 已修复 懒加载
val nameF : ObservableField<String> by lazy { ObservableField<String>() }
val pwdF : ObservableField<String> by lazy { ObservableField<String>() }
} | AndroidDataBinding/app/src/main/java/com/derry/databinding_kt/model/StudentInfo.kt | 2935566003 |
package com.example.constraintlayout08012024
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.constraintlayout08012024", appContext.packageName)
}
} | ConstraintLayout08012024/app/src/androidTest/java/com/example/constraintlayout08012024/ExampleInstrumentedTest.kt | 128106748 |
package com.example.constraintlayout08012024
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)
}
} | ConstraintLayout08012024/app/src/test/java/com/example/constraintlayout08012024/ExampleUnitTest.kt | 693317701 |
package com.example.constraintlayout08012024
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
} | ConstraintLayout08012024/app/src/main/java/com/example/constraintlayout08012024/MainActivity.kt | 145861708 |
package org.grove.taskmanager.configuration.properties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(prefix = "kafka")
data class KafkaProperties(
val producer: Topic,
val metricsManagerConsumer: Consumer
) {
data class Consumer(
val topic: Topic,
val consumerGroupName: String
)
data class Topic(
val name: String,
val partitionsCount: Int,
val replicationFactor: Short
)
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/configuration/properties/KafkaProperties.kt | 3298404263 |
package org.grove.taskmanager.configuration
import org.apache.kafka.clients.admin.NewTopic
import org.grove.taskmanager.configuration.properties.KafkaProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(KafkaProperties::class)
class KafkaTopicConfiguration(
private val properties: KafkaProperties
) {
@Bean
fun mainProducerTopic(): NewTopic {
val topicConfig = properties.producer
return NewTopic(
topicConfig.name,
topicConfig.partitionsCount,
topicConfig.replicationFactor
)
}
@Bean
fun metricsManagerConsumerTopic(): NewTopic {
val topicConfig = properties.metricsManagerConsumer.topic
return NewTopic(
topicConfig.name,
topicConfig.partitionsCount,
topicConfig.replicationFactor
)
}
}
| grove-task-manager/src/main/kotlin/org/grove/taskmanager/configuration/KafkaTopicConfiguration.kt | 1249564934 |