path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
JetBlogCleanArchitecture/app/src/androidTest/java/com/example/jetblogca/ExampleInstrumentedTest.kt
3162659573
package com.example.jetblogca 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.jetblogca", appContext.packageName) } }
JetBlogCleanArchitecture/app/src/test/java/com/example/jetblogca/ExampleUnitTest.kt
3364174505
package com.example.jetblogca 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) } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/ui/theme/Color.kt
1559614938
package com.example.jetblogca.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)
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/ui/theme/Theme.kt
521733272
package com.example.jetblogca.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 JetBlogCATheme( 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 ) }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/ui/theme/Type.kt
1757230384
package com.example.jetblogca.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 ) */ )
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/MainActivity.kt
1538056851
package com.example.jetblogca import android.os.Build import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.navigation.compose.rememberNavController import com.example.core.domain.model.Blog import com.example.jetblogca.navigation.Navigation import com.example.jetblogca.ui.theme.JetBlogCATheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetBlogCATheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val isFromFav = intent.getBooleanExtra("fromfav", false) val blog = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra<Blog>("blogf", Blog::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra<Blog>("blogf") } Log.d("0212", "onCreate: $isFromFav, $blog") val navController = rememberNavController() Navigation(navController = navController, isFromFav, blogf = blog) } } } } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/di/AppModule.kt
2224339874
package com.example.jetblogca.di import com.example.core.domain.usecases.BlogInteractor import com.example.core.domain.usecases.BlogUseCase import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class AppModule { @Binds abstract fun provideBlogUseCase(blogInteractor: BlogInteractor): BlogUseCase }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/di/FavoriteModuleDependencies.kt
308858973
package com.example.jetblogca.di import com.example.core.domain.usecases.BlogUseCase import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @EntryPoint @InstallIn(SingletonComponent::class) interface FavoriteModuleDependencies { fun blogUseCase(): BlogUseCase }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/navigation/Navigation.kt
439903012
package com.example.jetblogca.navigation import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.example.core.domain.model.Blog import com.example.jetblogca.screen.detail.DetailScreen import com.example.jetblogca.screen.home.HomeScreen @Composable fun Navigation(navController: NavHostController, from: Boolean, blogf: Blog? = null) { // val detailViewModel: DetailViewModel = hiltViewModel() NavHost( navController = navController, // startDestination = Screen.Home.route startDestination = if (from) { Screen.Detail.route } else { Screen.Home.route } ) { composable(Screen.Home.route) { HomeScreen(navController = navController) } composable(Screen.Detail.route) { val blog: Blog? = if (from) { blogf } else { navController.previousBackStackEntry?.savedStateHandle?.get<Blog>("blog") } DetailScreen(blog,navController) } } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/navigation/Screen.kt
2634271142
package com.example.jetblogca.navigation sealed class Screen (val route: String) { object Home: Screen("home") object Detail: Screen("detail") object Favorite: Screen("detail") }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/BaseApplication.kt
1130577937
package com.example.jetblogca import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class BaseApplication : Application()
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/screen/home/HomeViewModel.kt
3655097324
package com.example.jetblogca.screen.home import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.core.data.source.Resource import com.example.core.domain.usecases.BlogUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor(private val getBlogUseCase: BlogUseCase) : ViewModel() { private val _blogs= mutableStateOf<HomeState>(HomeState()) val blogs: State<HomeState> = _blogs init { Log.d("MyApp", "homeviewmodel init ") getBlogs() } fun getBlogs() { Log.d("MyApp", "getblog exe") viewModelScope.launch { Log.d("MyApp", "getblog vscope") getBlogUseCase.getAllBlog().collect { Log.d("MyApp", "onEach executed: $it") when(it){ is Resource.Loading -> { _blogs.value = HomeState(isLoading = true) } is Resource.Success -> { _blogs.value = HomeState(data = it.data) } is Resource.Error -> { _blogs.value = HomeState(error = it.error.toString()) } else -> {} } } } } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/screen/home/HomeState.kt
3378348156
package com.example.jetblogca.screen.home import com.example.core.domain.model.Blog data class HomeState ( var isLoading: Boolean = false, var data: List<Blog>? = null, var error: String = "" )
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/screen/home/HomeScreen.kt
440186590
package com.example.jetblogca.screen.home import android.annotation.SuppressLint import android.content.Intent import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.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.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material3.Card import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import coil.compose.rememberAsyncImagePainter import com.example.core.domain.model.Blog import com.example.jetblogca.navigation.Screen @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeScreen(navController: NavHostController, homeViewModel: HomeViewModel = hiltViewModel()) { val res = homeViewModel.blogs.value if (res.isLoading) { Box(modifier = Modifier.fillMaxSize()) { CircularProgressIndicator(modifier = Modifier.align(Alignment.Center)) } } if (res.error.isNotBlank()) { Box(modifier = Modifier.fillMaxSize()) { Text(text = res.error.toString(), modifier = Modifier.align(Alignment.Center)) } } val context = LocalContext.current Scaffold( floatingActionButton = { FloatingActionButton(onClick = { try { context.startActivity( Intent( context, Class.forName("com.example.favorite.fav.FavoriteActivity") ) ) } catch (e: Exception) { Toast.makeText( context, "Fitur ini belum ada, harap menunggu", Toast.LENGTH_SHORT ).show() } }) { Icon(imageVector = Icons.Default.Favorite, contentDescription = "favorite") } } ) { LazyColumn(modifier = Modifier.fillMaxSize()) { res.data?.let { items(it) { PostItem(it, onClick = { navController.currentBackStackEntry?.savedStateHandle?.set( key = "blog", value = it ) navController.navigate(Screen.Detail.route) }) } } } } } @Composable fun PostItem(it: Blog, onClick: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { CircularImage(50.0, 50.0, 25.0, it.owner.picture) Spacer(modifier = Modifier.width(6.dp)) Text(text = "${it.owner.firstName} ${it.owner.lastName}") } Image( modifier = Modifier .fillMaxWidth() .height(300.dp), painter = rememberAsyncImagePainter(model = it.image), contentDescription = null, contentScale = ContentScale.Crop ) Text( text = it.text, modifier = Modifier.padding(12.dp), style = TextStyle(color = Color.Gray, fontSize = 20.sp) ) Divider() } } @Composable fun CircularImage(width: Double, height: Double, radius: Double, imageUrl: String) { Card( modifier = Modifier .width(width = width.dp) .height(height = height.dp), shape = RoundedCornerShape(radius.dp) ) { Image( painter = rememberAsyncImagePainter(model = imageUrl), contentDescription = null, contentScale = ContentScale.Crop ) } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/screen/detail/DetailViewModel.kt
2245734239
package com.example.jetblogca.screen.detail import androidx.lifecycle.ViewModel import com.example.core.domain.model.Blog import com.example.core.domain.usecases.BlogUseCase import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class DetailViewModel @Inject constructor(private val blogUseCase: BlogUseCase) : ViewModel() { fun setFavoriteBlog(blog: Blog, newStatus: Boolean) { blogUseCase.setFavorite(blog, newStatus) } }
JetBlogCleanArchitecture/app/src/main/java/com/example/jetblogca/screen/detail/DetailScreen.kt
2174471610
package com.example.jetblogca.screen.detail import android.util.Log import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow 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.wrapContentHeight import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text 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.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import coil.compose.rememberAsyncImagePainter import com.example.core.domain.model.Blog import com.example.jetblogca.screen.home.CircularImage @OptIn(ExperimentalLayoutApi::class) @Composable fun DetailScreen( blog: Blog? = null, navController: NavHostController, detailViewModel: DetailViewModel = hiltViewModel() ) { var favoriteState by remember { mutableStateOf(blog?.isFavorite) } Log.d("123r4", "DetailScreen: $favoriteState") if (blog != null) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Row(modifier = Modifier.fillMaxWidth()) { CircularImage(50.0, 50.0, 25.0, blog.owner.picture) Spacer(modifier = Modifier.height(16.dp)) Text( text = "${blog.owner.firstName} ${blog.owner.lastName}", style = TextStyle( fontWeight = FontWeight.Bold, fontSize = 24.sp, color = Color.Black ) ) IconButton(onClick = { favoriteState = !favoriteState!! Log.d("222TAG", "DetailScreen: $favoriteState") detailViewModel.setFavoriteBlog(blog, favoriteState!!) }) { Icon( imageVector = if (favoriteState!!) { Icons.Default.Favorite } else { Icons.Default.FavoriteBorder }, contentDescription = "favorite" ) } } Spacer(modifier = Modifier.height(8.dp)) Image( modifier = Modifier .fillMaxWidth() .height(300.dp), painter = rememberAsyncImagePainter(model = blog.image), contentDescription = null, contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.height(16.dp)) Text( text = blog.text, style = TextStyle( fontSize = 18.sp, color = Color.Black ) ) FlowRow { blog.tags.forEach { TagItem(it = it) } } } } } @Composable fun TagItem(it: String) { Card( modifier = Modifier .wrapContentWidth() .wrapContentHeight() .padding(8.dp), shape = RoundedCornerShape( 40.dp ), border = BorderStroke(0.5.dp, color = Color.Gray) ) { Text(text = it, style = TextStyle(color = Color.Black), modifier = Modifier.padding(12.dp)) } }
JetBlogCleanArchitecture/favorite/src/androidTest/java/com/example/favorite/ExampleInstrumentedTest.kt
3624269527
package com.example.favorite 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.favorite", appContext.packageName) } }
JetBlogCleanArchitecture/favorite/src/test/java/com/example/favorite/ExampleUnitTest.kt
509106448
package com.example.favorite 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) } }
JetBlogCleanArchitecture/favorite/src/main/java/com/example/favorite/di/ViewModelFactory.kt
1358166424
package com.example.favorite.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.core.domain.usecases.BlogUseCase import com.example.favorite.screen.FavoriteViewModel import javax.inject.Inject class ViewModelFactory @Inject constructor(private val blogUseCase: BlogUseCase) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T = when { modelClass.isAssignableFrom(FavoriteViewModel::class.java) -> { FavoriteViewModel(blogUseCase) as T } else -> throw Throwable("Unknown ViewModel class: " + modelClass.name) } }
JetBlogCleanArchitecture/favorite/src/main/java/com/example/favorite/di/FavoriteModule.kt
3327120596
package com.example.favorite.di import android.content.Context import com.example.favorite.fav.FavoriteActivity import com.example.jetblogca.di.FavoriteModuleDependencies import dagger.BindsInstance import dagger.Component @Component(dependencies = [FavoriteModuleDependencies::class]) interface FavoriteModule { fun inject(activity: FavoriteActivity) // fun inject(fragment: FavoriteFragment) @Component.Builder interface Builder { fun context(@BindsInstance context: Context): Builder fun appDependencies(FavoriteModuleDependencies: FavoriteModuleDependencies): Builder fun build(): FavoriteModule } }
JetBlogCleanArchitecture/favorite/src/main/java/com/example/favorite/fav/FavoriteActivity.kt
1374667952
package com.example.favorite.fav import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.ui.platform.LocalContext import com.example.favorite.di.DaggerFavoriteModule import com.example.favorite.di.ViewModelFactory import com.example.favorite.screen.FavoriteScreen import com.example.favorite.screen.FavoriteViewModel import com.example.jetblogca.di.FavoriteModuleDependencies import com.example.jetblogca.ui.theme.JetBlogCATheme import dagger.hilt.android.EntryPointAccessors import javax.inject.Inject class FavoriteActivity : ComponentActivity() { @Inject lateinit var factory: ViewModelFactory private val viewModel: FavoriteViewModel by viewModels { factory } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DaggerFavoriteModule.builder() .context(this) .appDependencies( EntryPointAccessors.fromApplication( applicationContext, FavoriteModuleDependencies::class.java ) ) .build() .inject(this) DaggerFavoriteModule.builder() setContent { JetBlogCATheme { val context = LocalContext.current FavoriteScreen(viewModel = viewModel) } } } }
JetBlogCleanArchitecture/favorite/src/main/java/com/example/favorite/screen/FavoriteViewModel.kt
2066409838
package com.example.favorite.screen import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.example.core.domain.usecases.BlogUseCase import javax.inject.Inject class FavoriteViewModel @Inject constructor(blogUseCase: BlogUseCase) : ViewModel() { val moviesFavorite = blogUseCase.getFavorite().asLiveData() }
JetBlogCleanArchitecture/favorite/src/main/java/com/example/favorite/screen/FavoriteScreen.kt
3805624731
package com.example.favorite.screen import android.annotation.SuppressLint import android.content.Intent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import com.example.jetblogca.MainActivity import com.example.jetblogca.screen.home.PostItem @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @OptIn(ExperimentalMaterial3Api::class) @Composable fun FavoriteScreen( viewModel: FavoriteViewModel, ) { val blogFavorite by viewModel.moviesFavorite.observeAsState(initial = emptyList()) val context = LocalContext.current Scaffold( topBar = { TopAppBar( title = { Text(text = "Favorite Blog") } ) } ) { if (blogFavorite.isNotEmpty()) { LazyColumn(modifier = Modifier.fillMaxSize().padding(it)) { blogFavorite.let { items(it) { PostItem(it, onClick = { context.startActivity( Intent( context, MainActivity::class.java ).putExtra("blogf", it) .putExtra("fromfav", true) ) } ) } } } } else { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize().padding(it) ) { Text(text = "No favorite movies found") } } } }
Mobile_Development_EndProject_JC_JvL/app/src/androidTest/java/com/example/mobile_dev_endproject_jc_jvl/ExampleInstrumentedTest.kt
1612852204
package com.example.mobile_dev_endproject_jc_jvl 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.mobile_dev_endproject_jc_jvl", appContext.packageName) } }
Mobile_Development_EndProject_JC_JvL/app/src/test/java/com/example/mobile_dev_endproject_jc_jvl/ExampleUnitTest.kt
1883023079
package com.example.mobile_dev_endproject_jc_jvl 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) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/ui/theme/Color.kt
2579888121
package com.example.mobile_dev_endproject_jc_jvl.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)
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/ui/theme/Theme.kt
2230991709
package com.example.mobile_dev_endproject_jc_jvl.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 Mobile_Dev_EndProject_JC_JvLTheme( 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 ) }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/ui/theme/Type.kt
1588491100
package com.example.mobile_dev_endproject_jc_jvl.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 ) */ )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/MatchReservation.kt
3080609153
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class MatchReservation( val clubName: String = "", val clubEstablishmentName: String = "", val courtName: String = "", val matchId: String = "", val clubEstablishmentAddress: String = "", val timeslot: String = "", val dateReservation: String = "", val typeOfMatch: String = "", val gendersAllowed: String = "", val participators: Map<String, Any> = emptyMap() )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/ClubEstablishment.kt
2526626354
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class ClubEstablishment( val clubName: String, val clubEstablishmentName: String, val clubEstablishmentAddress: String, )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/CourtReservation.kt
200284672
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class CourtReservation( val clubEstablishmentName: String, val clubEstablishmentAddress: String, val courtName: String, val dateReservation: String, val timeslot: String )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/Match.kt
2396903138
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class Match( val clubName: String = "", val clubEstablishmentName: String = "", val courtName: String = "", val matchId: String = "", val clubEstablishmentAddress: String = "", val timeslot: String = "", val dateReservation: String = "", val typeOfMatch: String = "", val gendersAllowed: String = "", val participators: Map<String, String> = emptyMap() )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/PlayerReservation.kt
554268340
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class PlayerReservation( val clubName: String = "", val clubEstablishmentName: String = "", val courtName: String = "", val matchId: String = "", val clubEstablishmentAddress: String = "", val timeslot: String = "", val dateReservation: String = "" )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/ClubDetails.kt
1534659175
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory import android.os.Parcel import android.os.Parcelable import com.google.firebase.firestore.GeoPoint data class ClubDetails( val clubName: String, val clubAddress: String, val clubLocation: GeoPoint ) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString()!!, parcel.readString()!!, GeoPoint(parcel.readDouble(), parcel.readDouble()) ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(clubName) parcel.writeString(clubAddress) parcel.writeDouble(clubLocation.latitude) parcel.writeDouble(clubLocation.longitude) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ClubDetails> { override fun createFromParcel(parcel: Parcel): ClubDetails { return ClubDetails(parcel) } override fun newArray(size: Int): Array<ClubDetails?> { return arrayOfNulls(size) } } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/dataClassesDirectory/Preferences.kt
845601323
package com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory data class Preferences( val preferredPlayLocation: String = "", val preferredTypeMatch: String = "", val preferredHandPlay: String = "", val preferredTimeToPlay: String = "", val preferredCourtPosition: String = "", val preferredGenderToPlayAgainst: String = "" )
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/adaptersDirectory/ClubEstablishmentAdapter.kt
2565150760
package com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.ClubEstablishment import com.example.mobile_dev_endproject_jc_jvl.R class ClubEstablishmentAdapter( private val establishments: List<ClubEstablishment>, private val onItemClickListener: (ClubEstablishment) -> Unit ) : RecyclerView.Adapter<ClubEstablishmentAdapter.ViewHolder>() { inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val nameTextView: TextView = itemView.findViewById(R.id.textViewClubEstablishmentName) val addressTextView: TextView = itemView.findViewById(R.id.textViewClubEstablishmentAddress) init { itemView.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { onItemClickListener(establishments[position]) } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_club_establishment, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val establishment = establishments[position] holder.nameTextView.text = establishment.clubEstablishmentName holder.addressTextView.text = establishment.clubEstablishmentAddress } override fun getItemCount(): Int { return establishments.size } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/adaptersDirectory/CourtAdapter.kt
4110165068
package com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R class CourtAdapter(private val onItemClick: (String) -> Unit) : RecyclerView.Adapter<CourtAdapter.ViewHolder>() { private val courtList: MutableList<String> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_court, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val courtName = courtList[position] holder.bind(courtName) holder.itemView.setOnClickListener { onItemClick(courtName) } } override fun getItemCount(): Int = courtList.size fun addData(courtName: String) { courtList.add(courtName) notifyDataSetChanged() } fun clearData() { courtList.clear() notifyDataSetChanged() } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val courtNameTextView: TextView = itemView.findViewById(R.id.courtNameTextView) fun bind(courtName: String) { courtNameTextView.text = courtName } } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/adaptersDirectory/CourtReservationAdapter.kt
4126875113
package com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.CourtReservation class CourtReservationAdapter(private val courtReservations: List<CourtReservation>) : RecyclerView.Adapter<CourtReservationAdapter.CourtReservationViewHolder>() { class CourtReservationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val clubName: TextView = itemView.findViewById(R.id.clubName) val establishmentName: TextView = itemView.findViewById(R.id.establishmentName) val courtName: TextView = itemView.findViewById(R.id.courtName) val dateReservation: TextView = itemView.findViewById(R.id.dateReservation) val timeslot: TextView = itemView.findViewById(R.id.timeslot) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourtReservationViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_reservation, parent, false) return CourtReservationViewHolder(view) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: CourtReservationViewHolder, position: Int) { val courtReservation = courtReservations[position] holder.clubName.text = "Establishment: ${courtReservation.clubEstablishmentName}" holder.establishmentName.text = "Address: ${courtReservation.clubEstablishmentAddress}" holder.courtName.text = "Court: ${courtReservation.courtName}" holder.dateReservation.text = "Date: ${courtReservation.dateReservation}" holder.timeslot.text = "TimeSlot: ${courtReservation.timeslot}" } override fun getItemCount(): Int { return courtReservations.size } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/adaptersDirectory/MatchAdapter.kt
2302277557
package com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory import android.annotation.SuppressLint import android.content.Intent import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory.AccountActivity import com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory.JoinMatchActivity import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Match class MatchAdapter(private val matches: List<Match>) : RecyclerView.Adapter<MatchAdapter.MatchViewHolder>() { class MatchViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val addressTextView: TextView = itemView.findViewById(R.id.textViewClubEstablishmentAddress) val dateTimeTextView: TextView = itemView.findViewById(R.id.textViewDateTime) val typeOfMatchAndGender: TextView = itemView.findViewById(R.id.typeOfMatchAndGender) val imagesLayout: LinearLayout = itemView.findViewById(R.id.linearImages) val usernamesLayout: LinearLayout = itemView.findViewById(R.id.linearUsernames) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.match_item, parent, false) return MatchViewHolder(view) } @SuppressLint("ResourceAsColor") override fun onBindViewHolder(holder: MatchViewHolder, position: Int) { val match = matches[position] holder.addressTextView.text = match.clubEstablishmentAddress holder.dateTimeTextView.text = "Date: ${match.dateReservation} TimeSlot: ${match.timeslot}" holder.typeOfMatchAndGender.text = "Type Match: ${match.typeOfMatch} Gender: ${match.gendersAllowed}" // Clear existing views in layouts holder.imagesLayout.removeAllViews() holder.usernamesLayout.removeAllViews() // Bind data to the images layout (LinearLayout) val imageLinearLayout = LinearLayout(holder.itemView.context) imageLinearLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) imageLinearLayout.orientation = LinearLayout.HORIZONTAL imageLinearLayout.gravity = Gravity.CENTER // Bind data to the usernames layout (LinearLayout) val usernameLinearLayout = LinearLayout(holder.itemView.context) usernameLinearLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) usernameLinearLayout.orientation = LinearLayout.HORIZONTAL usernameLinearLayout.gravity = Gravity.CENTER for (i in 1..4) { val avatarKey = "UserAvatar_$i" val usernameKey = "UserName_$i" val userIdKey = "UserId_$i" val avatarValue = match.participators[avatarKey] val usernameValue = match.participators[usernameKey] val userIdValue = match.participators[userIdKey] val imageView = ImageView(holder.itemView.context) val layoutParams = LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f ) // Check if avatar is "Default" if (avatarValue != null && avatarValue == "Default") { imageView.setImageResource(R.drawable.ic_joinmatch) } else { Glide.with(holder.itemView).load(avatarValue).into(imageView) } imageView.layoutParams = layoutParams // Padding in pixels val paddingPx = 16 imageView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx) imageView.setOnClickListener { // Check if avatar is "Default" if (avatarValue != null && avatarValue == "Default") { // Launch JoinMatchActivity val intent = Intent(holder.itemView.context, JoinMatchActivity::class.java) intent.putExtra("dateReservation", match.dateReservation) intent.putExtra("timeslot", match.timeslot) intent.putExtra("PositionSquare", i.toString()) intent.putExtra("matchId", match.matchId) intent.putExtra("typeOfMatch", match.typeOfMatch) intent.putExtra("gendersAllowed", match.gendersAllowed) val sentThroughClubName = sanitizeForFirestore(match.clubName) val sentThroughClubEstablishmentName = sanitizeForFirestore(match.clubEstablishmentName) val sentThroughCourtName = sanitizeForFirestore(match.courtName) intent.putExtra("sentThroughClubName", sentThroughClubName) intent.putExtra( "sentThroughClubEstablishmentName", sentThroughClubEstablishmentName ) intent.putExtra("sentThroughCourtName", sentThroughCourtName) // Pass any necessary data to JoinMatchActivity using intent.putExtra if needed holder.itemView.context.startActivity(intent) } else { // Launch AccountActivity val intent = Intent(holder.itemView.context, AccountActivity::class.java) intent.putExtra("sentThroughUserId", userIdValue) // Pass any necessary data to AccountActivity using intent.putExtra if needed holder.itemView.context.startActivity(intent) } } imageLinearLayout.addView(imageView) // Check if username is "Default" if (usernameValue != null && usernameValue == "Default") { // Add an empty TextView for "Default" username val emptyUsernameTextView = TextView(holder.itemView.context) emptyUsernameTextView.text = "Available" emptyUsernameTextView.layoutParams = layoutParams val usernamePaddingPx = 16 emptyUsernameTextView.setPadding( usernamePaddingPx * 4, 0, usernamePaddingPx, usernamePaddingPx ) usernameLinearLayout.addView(emptyUsernameTextView) } else { // Add the username TextView val usernameTextView = TextView(holder.itemView.context) usernameTextView.text = usernameValue usernameTextView.layoutParams = layoutParams val usernamePaddingPx = 16 usernameTextView.setPadding( usernamePaddingPx * 4, 0, usernamePaddingPx, usernamePaddingPx ) usernameLinearLayout.addView(usernameTextView) } } holder.imagesLayout.addView(imageLinearLayout) holder.usernamesLayout.addView(usernameLinearLayout) } override fun getItemCount(): Int { return matches.size } private fun sanitizeForFirestore(username: String): String { // Implement your logic to sanitize the username (remove spaces or special characters) // For example, you can replace spaces with underscores return username.replace("\\s+".toRegex(), "") } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/mapFunctionalitiesDirectory/CustomOverlayItem.kt
1641810435
package com.example.mobile_dev_endproject_jc_jvl.mapFunctionalitiesDirectory import org.osmdroid.api.IGeoPoint import org.osmdroid.views.overlay.OverlayItem class CustomOverlayItem(title: String?, snippet: String?, point: IGeoPoint?) : OverlayItem(title, snippet, point) { var extraData: HashMap<String, String?> = HashMap() }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/MapActivity.kt
3134730418
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Parcelable import android.util.Log import android.view.MotionEvent import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.mapFunctionalitiesDirectory.CustomOverlayItem import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.firestore.FirebaseFirestore import org.osmdroid.api.IGeoPoint import org.osmdroid.config.Configuration import org.osmdroid.events.MapEventsReceiver import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController import org.osmdroid.views.MapView import org.osmdroid.views.overlay.ItemizedIconOverlay import org.osmdroid.views.overlay.MapEventsOverlay import org.osmdroid.views.overlay.OverlayItem import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay class MapActivity : AppCompatActivity() { private lateinit var mapView: MapView private val firestore = FirebaseFirestore.getInstance() private val ZOOM_REPEAT_INTERVAL = 50L private var isZoomingOut = false private var zoomOutHandler: Handler? = null private val zoomOutRunnable: Runnable = object : Runnable { override fun run() { if (isZoomingOut) { mapView.controller.zoomOut() zoomOutHandler?.postDelayed(this, ZOOM_REPEAT_INTERVAL) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize osmdroid Configuration.getInstance().load(applicationContext, getPreferences(MODE_PRIVATE)) setContentView(R.layout.map_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.labelVisibilityMode = BottomNavigationView.LABEL_VISIBILITY_LABELED bottomNavigationView.menu.findItem(R.id.navigation_home).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } mapView = findViewById(R.id.mapView) mapView.setTileSource(TileSourceFactory.MAPNIK) mapView.zoomController.setVisibility(CustomZoomButtonsController.Visibility.SHOW_AND_FADEOUT) mapView.setMultiTouchControls(true) mapView.controller.setZoom(15.0) fetchClubsFromFirebase() val myLocationOverlay = MyLocationNewOverlay(GpsMyLocationProvider(applicationContext), mapView) myLocationOverlay.enableMyLocation() mapView.overlays.add(myLocationOverlay) val mapCoordinates = intent.getParcelableExtra<GeoPoint>("TheMapCoordinates") if (mapCoordinates != null) { // If "TheMapCoordinates" is present, set the map location to the geopoint setMapLocation(mapCoordinates) } else { // Default location: Antwerp mapView.controller.setCenter(createGeoPoint(51.2194, 4.4025)) } val mapEventsOverlay = MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { val threshold = 225 val itemList = getOverlayItemsList() for (marker in itemList) { val distance = p.distanceToAsDouble(marker.point) if (distance < threshold) { // If the tapped point is close to a marker, start HomeActivity launchEstablishmentDetailsActivity(marker) return true } } // When nothing is pressed return false } override fun longPressHelper(p: GeoPoint): Boolean { if (!isZoomingOut) { isZoomingOut = true zoomOutHandler = Handler(mainLooper) zoomOutHandler?.postDelayed(zoomOutRunnable, ZOOM_REPEAT_INTERVAL) } return true } }) mapView.overlays.add(mapEventsOverlay) } override fun onTouchEvent(event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_UP || event.action == MotionEvent.ACTION_CANCEL) { // Long press ended stopZoomingOut() } return super.onTouchEvent(event) } private fun stopZoomingOut() { isZoomingOut = false zoomOutHandler?.removeCallbacksAndMessages(null) zoomOutHandler = null } private fun createGeoPoint(latitude: Double, longitude: Double): IGeoPoint { return GeoPoint(latitude, longitude) } private fun fetchClubsFromFirebase() { firestore.collection("TheClubDetails") .get() .addOnSuccessListener { result -> for (document in result) { val clubName = document.id firestore.collection("TheClubDetails").document(clubName) .collection("TheClubEstablishments") .get() .addOnSuccessListener { establishmentResult -> for (establishmentDocument in establishmentResult) { val clubEstablishmentName = establishmentDocument.getString("ClubEstablishmentName") val clubEstablishmentAddress = establishmentDocument.getString("ClubEstablishmentAddress") val clubEstablishmentLocation = establishmentDocument.getGeoPoint("ClubEstablishmentLocation") if (clubEstablishmentName != null && clubEstablishmentLocation != null) { val clubMarker = CustomOverlayItem( clubEstablishmentName, "Club Location", createGeoPoint( clubEstablishmentLocation.latitude, clubEstablishmentLocation.longitude ) ) // Attach extra values clubMarker.extraData = createMarkerExtrasData( clubName, clubEstablishmentAddress, clubEstablishmentName ) val clubMarkerOverlay = ItemizedIconOverlay<OverlayItem>( applicationContext, listOf(clubMarker), null ) mapView.overlays.add(clubMarkerOverlay) } } // Force redraw of the map mapView.invalidate() } .addOnFailureListener { exception -> Log.e( "MapActivity", "Error fetching establishments from Firebase: $exception" ) } } } .addOnFailureListener { exception -> Log.e("MapActivity", "Error fetching clubs from Firebase: $exception") } } private fun launchEstablishmentDetailsActivity(marker: OverlayItem) { val intent = Intent(this@MapActivity, EstablishmentDetailsActivity::class.java) if (marker is CustomOverlayItem) { val extrasData = marker.extraData intent.putExtra("ClubName", extrasData["ClubName"]) intent.putExtra("ClubEstablishmentAddress", extrasData["ClubEstablishmentAddress"]) intent.putExtra("EstablishmentName", extrasData["EstablishmentName"]) } intent.putExtra("TheMapCoordinates", marker.point as Parcelable) startActivity(intent) } private fun getOverlayItemsList(): List<OverlayItem> { val overlays = mapView.overlays val itemList = mutableListOf<OverlayItem>() for (overlay in overlays) { if (overlay is ItemizedIconOverlay<*> && overlay.size() > 0) { val item = overlay.getItem(0) as? OverlayItem if (item != null) { itemList.add(item) } } } return itemList } // Forward lifecycle events to the MapView override fun onResume() { super.onResume() mapView.onResume() } override fun onPause() { super.onPause() mapView.onPause() } override fun onDestroy() { super.onDestroy() mapView.onDetach() } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } private fun setMapLocation(geopoint: GeoPoint) { mapView.controller.setCenter(geopoint) } private fun createMarkerExtrasData( clubName: String, establishmentAddress: String?, establishmentName: String? ): HashMap<String, String?> { val extrasData = HashMap<String, String?>() extrasData["ClubName"] = clubName extrasData["ClubEstablishmentAddress"] = establishmentAddress extrasData["EstablishmentName"] = establishmentName return extrasData } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/ChangePasswordActivity.kt
3653406269
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser class ChangePasswordActivity : AppCompatActivity() { private lateinit var etCurrentPassword: EditText private lateinit var etNewPassword: EditText private lateinit var etConfirmNewPassword: EditText private lateinit var btnConfirm: Button private lateinit var btnReturn: Button private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.change_password_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_account).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } etCurrentPassword = findViewById(R.id.etCurrentPassword) etNewPassword = findViewById(R.id.etNewPassword) etConfirmNewPassword = findViewById(R.id.etConfirmNewPassword) btnConfirm = findViewById(R.id.btnConfirm) btnReturn = findViewById(R.id.btnReturn) auth = FirebaseAuth.getInstance() btnConfirm.setOnClickListener { changePassword() } btnReturn.setOnClickListener { finish() } } private fun changePassword() { val user: FirebaseUser? = auth.currentUser val currentPassword = etCurrentPassword.text.toString() val newPassword = etNewPassword.text.toString() val confirmNewPassword = etConfirmNewPassword.text.toString() if (newPassword != confirmNewPassword) { showToast("New passwords do not match.") return } if (user != null && user.email != null) { // Reauthenticate with the current email and password val credential = EmailAuthProvider .getCredential(user.email!!, currentPassword) user.reauthenticate(credential) .addOnCompleteListener { reauthTask -> if (reauthTask.isSuccessful) { // Password successfully reauthenticated, now change the password user.updatePassword(newPassword) .addOnCompleteListener { updateTask -> if (updateTask.isSuccessful) { showToast("Password changed successfully.") finish() } else { showToast("Failed to change password. Please try again.") } } } else { showToast("Authentication failed. Please check your current password.") } } } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/RegisterActivity.kt
1853313713
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.Spinner import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth class RegisterActivity : AppCompatActivity() { private lateinit var emailEditText: EditText private lateinit var passwordEditText: EditText private lateinit var usernameEditText: EditText private lateinit var genderOfPlayerSpinner: Spinner private lateinit var submitButton: Button private lateinit var returnButton: Button private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.register_screen) auth = FirebaseAuth.getInstance() emailEditText = findViewById(R.id.emailRegisterEditText) passwordEditText = findViewById(R.id.passwordRegisterEditText) usernameEditText = findViewById(R.id.usernameEditText) genderOfPlayerSpinner = findViewById(R.id.chooseGenderSpinner) submitButton = findViewById(R.id.submitButton) returnButton = findViewById(R.id.returnButton) submitButton.setOnClickListener { val email = emailEditText.text.toString().trim() val password = passwordEditText.text.toString().trim() val username = usernameEditText.text.toString().trim() val gender = genderOfPlayerSpinner.selectedItem.toString() if (email.isNotEmpty() && password.isNotEmpty() && username.isNotEmpty()) { registerUser(email, password, gender) } else { // Check which fields are empty and display corresponding error messages when { email.isEmpty() -> { emailEditText.error = "Email cannot be empty" } password.isEmpty() -> { passwordEditText.error = "Password cannot be empty" } username.isEmpty() -> { usernameEditText.error = "Username cannot be empty" } } showSnackbar("Please fill in all fields.") } } returnButton.setOnClickListener { startActivity(Intent(this, LoginActivity::class.java)) } } private fun registerUser(email: String, password: String, gender: String) { auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val user = auth.currentUser user?.let { val userId = user.uid val username = usernameEditText.text.toString().trim() // Add user to "ThePlayers" collection val player = hashMapOf( "userId" to userId, "email" to email, "username" to usernameEditText.text.toString().trim(), "gender" to gender ) val db = Firebase.firestore val sanitizedUsername = username.replace("[\\s,\\\\/]".toRegex(), "") db.collection("ThePlayers") .document(userId) .set(player) .addOnSuccessListener { // After success create sub-collection "TheProfileDetails" and its document val profileDetails = hashMapOf( "Avatar" to "https://firebasestorage.googleapis.com/v0/b/mobile-development4.appspot.com/o/default_image.jpg?alt=media", "Followers" to 0, "Following" to 0, "Level" to 1, "Username" to usernameEditText.text.toString().trim(), "Gender" to gender ) db.collection("ThePlayers") .document(userId) .collection("TheProfileDetails") .document(sanitizedUsername) .set(profileDetails) .addOnSuccessListener { // After success create sub-collection "ThePreferencesPlayer" and its document val preferencesPlayer = hashMapOf( "preferredPlayLocation" to "Location Not Yet Stated", "preferredTypeMatch" to "Not Yet Stated", "preferredHandPlay" to "Not Yet Stated", "preferredTimeToPlay" to "Not Yet Stated", "preferredCourtPosition" to "Not Yet Stated", "preferredGenderToPlayAgainst" to "Not Yet Stated" ) db.collection("ThePlayers") .document(userId) .collection("ThePreferencesPlayer") .document("Preferences") .set(preferencesPlayer) .addOnSuccessListener { // Document creation successful showSnackbar("Registration successful!") startActivity( Intent( this, LoginActivity::class.java ) ) finish() } .addOnFailureListener { e -> // Handle document creation failure showSnackbar("Error creating preferences player: ${e.message}") } } .addOnFailureListener { e -> // Handle document creation failure showSnackbar("Error creating profile details: ${e.message}") } } .addOnFailureListener { e -> // Handle player creation failure showSnackbar("Error creating player: ${e.message}") } } } else { // If registration fails, display a message to the user. // You can customize the error message based on the task.exception // For example, task.exception?.message // Handle registration errors val errorMessage = task.exception?.message ?: "Registration failed" showSnackbar(errorMessage) } } } private fun showSnackbar(message: String) { // Assuming your root view is a CoordinatorLayout, replace it with the appropriate view type if needed val rootView = findViewById<View>(android.R.id.content) Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show() } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/EstablishmentsActivity.kt
2328582091
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.ClubEstablishmentAdapter import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.ClubEstablishment import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import com.google.firebase.firestore.FirebaseFirestore class EstablishmentsActivity : AppCompatActivity() { private val db = FirebaseFirestore.getInstance() private val clubEstablishments = mutableListOf<ClubEstablishment>() private lateinit var adapter: ClubEstablishmentAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.establishments_screen) val tabLayout: TabLayout = findViewById(R.id.tabLayout_Establishments) // Add tabs with titles val establishmentsTab = tabLayout.newTab().setText("Establishments") val reservationsTab = tabLayout.newTab().setText("Your Courts Reservations") tabLayout.addTab(establishmentsTab) tabLayout.addTab(reservationsTab) // Set up a tab selected listener tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { when (tab.position) { 0 -> { // Start EstablishmentsActivity //launchActivity(ClubEstablishmentsActivity::class.java) } 1 -> { // Start YourCourtReservationsActivity launchActivity(YourCourtReservationsActivity::class.java) } } } override fun onTabUnselected(tab: TabLayout.Tab) { // Handle tab unselection if needed } override fun onTabReselected(tab: TabLayout.Tab) { // Handle tab reselection if needed } }) // Select the tab you want (e.g., "Your Courts Reservations") establishmentsTab.select() val recyclerView: RecyclerView = findViewById(R.id.recyclerViewClubEstablishments) recyclerView.layoutManager = LinearLayoutManager(this) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } // Initialize the adapter adapter = ClubEstablishmentAdapter(clubEstablishments) { clubEstablishment -> onClubEstablishmentClicked(clubEstablishment) } recyclerView.adapter = adapter // Replace this with the actual path to your Firestore collection val collectionPath = "TheClubDetails" // Retrieve data from Firestore db.collection(collectionPath) .get() .addOnSuccessListener { documents -> for (document in documents) { // Extract data and add to the list val clubNameDocumentId = document.id val establishmentsCollectionPath = "$collectionPath/$clubNameDocumentId/TheClubEstablishments" // Retrieve data from the sub-collection db.collection(establishmentsCollectionPath) .get() .addOnSuccessListener { establishmentDocuments -> for (establishmentDocument in establishmentDocuments) { val establishmentName = establishmentDocument.getString("ClubEstablishmentName") ?: "" val establishmentAddress = establishmentDocument.getString("ClubEstablishmentAddress") ?: "" Log.d( "Firestore", "Fetched document - ClubName: $clubNameDocumentId, EstablishmentName: $establishmentName, EstablishmentAddress: $establishmentAddress" ) val clubEstablishment = ClubEstablishment( clubNameDocumentId, establishmentName, establishmentAddress ) clubEstablishments.add(clubEstablishment) // Add log statement to check which documents are being fetched Log.d( "Firestore", "Fetched document - ClubName: $clubNameDocumentId, EstablishmentName: $establishmentName, EstablishmentAddress: $establishmentAddress" ) } // Notify the adapter that the data set has changed adapter.notifyDataSetChanged() } .addOnFailureListener { exception -> // Handle failures here Log.e("Firestore", "Error fetching establishment documents", exception) } } } .addOnFailureListener { exception -> // Handle failures here Log.e("Firestore", "Error fetching documents", exception) } } private fun onClubEstablishmentClicked(clubEstablishment: ClubEstablishment) { val intent = Intent(this, EstablishmentDetailsActivity::class.java).apply { putExtra("ClubName", clubEstablishment.clubName) putExtra("ClubEstablishmentAddress", clubEstablishment.clubEstablishmentAddress) putExtra("EstablishmentName", clubEstablishment.clubEstablishmentName) } startActivity(intent) } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/HomeActivity.kt
415053955
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.home_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) val container = findViewById<LinearLayout>(R.id.container) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_home).isChecked = true // Add custom navigation items addNavigationItem( container, "Book A court", "Navigates to book a court", EstablishmentsActivity::class.java ) addNavigationItem( container, "Show Club Map", "Shows all available clubs on a Map", MapActivity::class.java ) bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } } private fun addNavigationItem( container: LinearLayout, title: String, description: String, targetActivity: Class<*> ) { val customNavItem = layoutInflater.inflate(R.layout.custom_navigation_item, null) as ConstraintLayout val titleTextView = customNavItem.findViewById<TextView>(R.id.titleTextView) val descriptionTextView = customNavItem.findViewById<TextView>(R.id.descriptionTextView) titleTextView.text = title descriptionTextView.text = description customNavItem.setOnClickListener { launchActivity(targetActivity) } container.addView(customNavItem) } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/ReservationActivity.kt
1492543678
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.annotation.SuppressLint import android.app.DatePickerDialog import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.View import android.widget.ArrayAdapter import android.widget.Button import android.widget.CheckBox import android.widget.DatePicker import android.widget.LinearLayout import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.MatchReservation import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.PlayerReservation import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import java.text.SimpleDateFormat import java.util.* class ReservationActivity : AppCompatActivity() { private lateinit var establishmentTextView: TextView private lateinit var courtNameTextView: TextView private var startingTimePlay: String = "" private var endingTimePlay: String = "" private lateinit var createMatchCheckBox: CheckBox private lateinit var orderFieldButton: Button private lateinit var returnButton: Button private lateinit var datePickerButton: Button private lateinit var dateTextView: TextView private lateinit var selectedDate: Date private var yearReservation: Int = 0 private var monthReservation: Int = 0 private var dayReservation: Int = 0 private lateinit var timeGrid: LinearLayout private var takenTimeSlots = mutableListOf<String>() private lateinit var reservedTimeText: TextView private var makeMatchCollections: Boolean = false private lateinit var sentThroughEstablishment: String private lateinit var sentThroughCourtName: String private lateinit var sentThroughClubName: String private lateinit var sentThroughEstablishmentAddress: String private lateinit var usernameOfUserOne: String private lateinit var avatarOfUserOne: String private lateinit var typeOfMatchSpinner: Spinner private lateinit var gendersAllowedSpinner: Spinner private lateinit var genderOfPlayer: String private var completedUpdates: Int = 0 private var expectedUpdates: Int = 0 private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.reservation_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } sentThroughEstablishment = intent.getStringExtra("sentThroughClubEstablishment").toString() sentThroughCourtName = intent.getStringExtra("sentThroughCourtName").toString() sentThroughClubName = intent.getStringExtra("sentThroughClubName").toString() sentThroughEstablishmentAddress = intent.getStringExtra("sentThroughEstablishmentAddress").toString() establishmentTextView = findViewById(R.id.establishmentTextView) courtNameTextView = findViewById(R.id.courtNameTextView) datePickerButton = findViewById(R.id.datePickerButton) dateTextView = findViewById(R.id.dateTextView) // Set up the initial date val calendar1 = Calendar.getInstance() calendar1.add(Calendar.DAY_OF_MONTH, 1) selectedDate = calendar1.time updateDateTextView() // Set up default values for year, month, and day setupDefaultValues() // Set up the DatePickerDialog datePickerButton.setOnClickListener { showDatePickerDialog() } // Get the layout components (Time) timeGrid = findViewById(R.id.timeGrid) reservedTimeText = findViewById(R.id.reservedTimeText) // Time createMatchCheckBox = findViewById(R.id.createMatchCheckBox) orderFieldButton = findViewById(R.id.orderFieldButton) returnButton = findViewById(R.id.returnButton) // Inside your onCreate method after initializing createMatchCheckBox createMatchCheckBox = findViewById(R.id.createMatchCheckBox) typeOfMatchSpinner = findViewById(R.id.typeOfMatchSpinner) gendersAllowedSpinner = findViewById(R.id.gendersAllowedSpinner) typeOfMatchSpinner.alpha = 0.5f gendersAllowedSpinner.alpha = 0.5f typeOfMatchSpinner.isEnabled = false gendersAllowedSpinner.isEnabled = false // Add an OnCheckedChangeListener to createMatchCheckBox createMatchCheckBox.setOnCheckedChangeListener { _, isChecked -> // Set the boolean variable makeMatchCollections based on checkbox state makeMatchCollections = isChecked Log.d("ReservationActivity", "Checkbox: $makeMatchCollections") // Adjust transparency and usability of spinners based on checkbox state val alphaValue = if (isChecked) 1.0f else 0.5f typeOfMatchSpinner.alpha = alphaValue typeOfMatchSpinner.isEnabled = isChecked gendersAllowedSpinner.alpha = alphaValue gendersAllowedSpinner.isEnabled = isChecked // Declare genderOptions outside the loop var genderOptions: Array<String> // Fetch the gender of the player fetchGenderFirestore { playerGender -> // Update spinner options based on player's gender and checkbox state genderOptions = if (isChecked) { when (playerGender) { "Male" -> arrayOf("Male", "Either") // First option for Male else -> arrayOf( "Female", "Either" ) // Default to second option for other cases } } else { when (playerGender) { "Female" -> arrayOf("Female", "Either") // First option for Female else -> arrayOf("Male", "Either") // Default to first option for other cases } } val genderAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, genderOptions) gendersAllowedSpinner.adapter = genderAdapter // Set the default selection based on fetched gender gendersAllowedSpinner.setSelection(getIndex(gendersAllowedSpinner, playerGender)) } } // Retrieve data from the intent and set the text views accordingly establishmentTextView.text = sentThroughEstablishment courtNameTextView.text = sentThroughCourtName // Set up the time grid val sdf = SimpleDateFormat("HH:mm", Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, 8) calendar.set(Calendar.MINUTE, 0) for (i in 0 until 6) { // 6 rows for 8:00 to 19:30 val rowLayout = LinearLayout(this) rowLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) rowLayout.orientation = LinearLayout.HORIZONTAL for (j in 0 until 4) { val startTime = sdf.format(calendar.time) calendar.add(Calendar.MINUTE, 30) val timeSquare = TextView(this) val params = LinearLayout.LayoutParams( 50, // width in dp 140, // height in dp 1f ) params.setMargins(24, 24, 24, 24) timeSquare.layoutParams = params timeSquare.text = startTime timeSquare.tag = startTime timeSquare.gravity = Gravity.CENTER timeSquare.setBackgroundResource(R.drawable.selector_time_square) timeSquare.setTextColor( ContextCompat.getColorStateList( this, R.color.text_color ) ) // Add this line timeSquare.setOnClickListener { view -> // Clear the selection of all other time squares if (timeSquare.tag != "disabled") { clearSelection(timeGrid) // Toggle the selection of the current time square view.isSelected = !view.isSelected val selectedTime = view.tag as String val reservedEndTime = calculateReservedEndTime(selectedTime) startingTimePlay = selectedTime; endingTimePlay = reservedEndTime reservedTimeText.text = "Time Reserved: $selectedTime to $reservedEndTime" } } rowLayout.addView(timeSquare) } timeGrid.addView(rowLayout) } // Fetch reserved time slots and update UI fetchReservedTimeSlots("$yearReservation-$monthReservation-$dayReservation") // Set click listener for the "Order Field" button orderFieldButton.setOnClickListener { // Handle order field logic if (startingTimePlay == "" || endingTimePlay == "") { // Show a warning to the user // You can display a toast, dialog, or any other suitable UI element to notify the user // For example, using a Toast: findViewById<View>(R.id.redBorder).visibility = View.VISIBLE Toast.makeText( this, "Please select a time slot before ordering the field", Toast.LENGTH_SHORT ).show() } else if (takenTimeSlots.any { it.contains(startingTimePlay) || it.contains( endingTimePlay ) }) { findViewById<View>(R.id.redBorder).visibility = View.VISIBLE Toast.makeText(this, "Times overlap! Can't make reservation!", Toast.LENGTH_SHORT) .show() } else { findViewById<View>(R.id.redBorder).visibility = View.GONE orderField { launchActivity(EstablishmentsActivity::class.java) } } } // Set click listener for the "Return" button returnButton.setOnClickListener { // Handle return logic finish() } } private fun orderField(callback: () -> Unit) { // Counter to track the number of completed updates completedUpdates = 0 // Variable to store the expected number of updates expectedUpdates = if (!makeMatchCollections) { 2 } else { 3 } // Get the current user's ID from Firebase Authentication val currentUser = FirebaseAuth.getInstance().currentUser val currentUserId = currentUser?.uid fetchUserNameandAvatarFireStore { usernameOfUserOne, avatarOfUserOne -> val sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment") val sanitizedCourtName = intent.getStringExtra("SanitizedCourtName") val courtName = intent.getStringExtra("sentThroughCourtName") val sanitizedClubName = intent.getStringExtra("SanitizedClubName") val yearForFirestore = yearReservation val monthForFirestore = monthReservation val dayForFirestore = dayReservation val startTimeForFireStoreInsert = startingTimePlay val endTimeForFireStoreInsert = endingTimePlay val dateReservation = "$yearForFirestore-$monthForFirestore-$dayForFirestore" val dateReservationSanitized = formatDate(yearForFirestore, monthForFirestore, dayForFirestore) val timeslot = "$startTimeForFireStoreInsert-$endTimeForFireStoreInsert" val sanitizedStartTimeMoment = startTimeForFireStoreInsert.replace(":", "") val sanitizedEndTimeMoment = endTimeForFireStoreInsert.replace(":", "") val sanitizedTimeslot = "$sanitizedStartTimeMoment$sanitizedEndTimeMoment" // unique MatchId: Courtname_year_month_day_hour-begin_hour-end val matchId = "$courtName$dateReservationSanitized$sanitizedTimeslot" // Sample data with default values (initially set to default) val reservationData = hashMapOf( "DateReservation" to dateReservation, "MatchId" to matchId, "Timeslot" to timeslot, "Participators" to hashMapOf( "UserName_1" to usernameOfUserOne, "UserAvatar_1" to avatarOfUserOne, "UserId_1" to currentUserId, "UserName_2" to "Default", "UserAvatar_2" to "Default", "UserId_2" to "Default", "UserName_3" to "Default", "UserAvatar_3" to "Default", "UserId_3" to "Default", "UserName_4" to "Default", "UserAvatar_4" to "Default", "UserId_4" to "Default" ) ) Log.d("ReservationActivity", "Data: $dateReservationSanitized, $matchId, $timeslot") Log.d( "ReservationActivity", "Data: $sanitizedClubName, $sanitizedClubEstablishment, $sanitizedCourtName" ) // Update Firestore with the reservation data if (sanitizedClubName != null && sanitizedClubEstablishment != null && sanitizedCourtName != null) { val courtDocument = firestore.collection("TheClubDetails") .document(sanitizedClubName) .collection("TheClubEstablishments") .document(sanitizedClubEstablishment) .collection("TheClubCourts") .document(sanitizedCourtName) // Check if the "CourtReservations" field exists courtDocument.get().addOnCompleteListener { task -> if (task.isSuccessful) { val documentSnapshot = task.result val existingReservations = documentSnapshot?.get("CourtReservations") as? HashMap<String, Any> ?: hashMapOf() // Create or update the "DateReservation" entry with a list of reservations val dateReservationData = existingReservations[dateReservation] as? ArrayList<HashMap<String, Any>> ?: arrayListOf() val reservationDataJava = reservationData as HashMap<String, Any> dateReservationData.add(reservationDataJava) existingReservations[dateReservation] = dateReservationData // Update "CourtReservations" field courtDocument.update("CourtReservations", existingReservations) .addOnSuccessListener { Log.d("ReservationActivity", "Yeey the update was successful") completedUpdates++ checkAndUpdateCompletion(callback) } .addOnFailureListener { e -> Log.e("ReservationActivity", "Update failed", e) } } else { Log.e("ReservationActivity", "Document check failed", task.exception) } } } // Replace these variables with actual values val playerReservation = PlayerReservation( clubName = sentThroughClubName, clubEstablishmentName = sentThroughEstablishment, courtName = sentThroughCourtName, matchId = matchId, clubEstablishmentAddress = sentThroughEstablishmentAddress, timeslot = timeslot, dateReservation = dateReservation ) val db = FirebaseFirestore.getInstance() // Reference to the document in the sub-collection val documentReference = db.collection("ThePlayers/$currentUserId/ThePlayerReservationsCourts") .document(matchId) // Add data to Firestore documentReference.set(playerReservation) .addOnSuccessListener { // Successfully added data completedUpdates++ checkAndUpdateCompletion(callback) // Handle success as needed } .addOnFailureListener { e -> // Handle error // e.g., Log.e("TAG", "Error adding document", e) } if (makeMatchCollections) { val preferredTypeMatch = typeOfMatchSpinner.selectedItem.toString() val gendersAllowed = gendersAllowedSpinner.selectedItem.toString() // Replace these variables with actual values val matchReservation = MatchReservation( clubName = sentThroughClubName, clubEstablishmentName = sentThroughEstablishment, courtName = sentThroughCourtName, matchId = matchId, clubEstablishmentAddress = sentThroughEstablishmentAddress, timeslot = timeslot, dateReservation = dateReservation, typeOfMatch = preferredTypeMatch, gendersAllowed = gendersAllowed, participators = hashMapOf( "UserName_1" to usernameOfUserOne, "UserAvatar_1" to avatarOfUserOne, "UserId_1" to (currentUserId ?: ""), "UserName_2" to "Default", "UserAvatar_2" to "Default", "UserId_2" to "Default", "UserName_3" to "Default", "UserAvatar_3" to "Default", "UserId_3" to "Default", "UserName_4" to "Default", "UserAvatar_4" to "Default", "UserId_4" to "Default" ) ) val db = FirebaseFirestore.getInstance() // Reference to the document in the sub-collection val documentReference = db.collection("TheMatches") .document(matchId) // Add data to Firestore documentReference.set(matchReservation) .addOnSuccessListener { // Successfully added data completedUpdates++ checkAndUpdateCompletion(callback) // Handle success as needed } .addOnFailureListener { e -> // Handle error // e.g., Log.e("TAG", "Error adding document", e) } } } } private fun formatDate(year: Int, month: Int, day: Int): String { val calendar = Calendar.getInstance() calendar.set(year, month, day) val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault()) return dateFormat.format(calendar.time) } // Function to clear the selection of all time squares in the grid private fun clearSelection(parentLayout: LinearLayout) { for (i in 0 until parentLayout.childCount) { val rowLayout = parentLayout.getChildAt(i) as LinearLayout for (j in 0 until rowLayout.childCount) { val timeSquare = rowLayout.getChildAt(j) as TextView timeSquare.isSelected = false } } } private fun calculateReservedEndTime(selectedTime: String): String { val sdf = SimpleDateFormat("HH:mm", Locale.getDefault()) val calendar = Calendar.getInstance() val startTime = sdf.parse(selectedTime) if (startTime != null) { calendar.time = startTime } calendar.add(Calendar.MINUTE, 90) return sdf.format(calendar.time) } private fun showDatePickerDialog() { val calendar = Calendar.getInstance() calendar.add(Calendar.DAY_OF_MONTH, 1) val datePickerDialog = DatePickerDialog( this, { _: DatePicker, year: Int, month: Int, dayOfMonth: Int -> val selectedCalendar = Calendar.getInstance() selectedCalendar.set(year, month, dayOfMonth) selectedDate = selectedCalendar.time yearReservation = year monthReservation = month dayReservation = dayOfMonth updateDateTextView() enableAllTimeSlots(timeGrid) fetchReservedTimeSlots("$yearReservation-$monthReservation-$dayReservation") }, yearReservation, monthReservation, dayReservation ) // Set the minimum and maximum date calendar.add(Calendar.DAY_OF_MONTH, 30) // 31 days in the future datePickerDialog.datePicker.maxDate = calendar.timeInMillis datePickerDialog.datePicker.minDate = System.currentTimeMillis() datePickerDialog.show() } @SuppressLint("SetTextI18n") private fun updateDateTextView() { val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) val formattedDate = dateFormat.format(selectedDate) dateTextView.text = "Date picked: $formattedDate" } private fun setupDefaultValues() { val defaultCalendar = Calendar.getInstance() defaultCalendar.add(Calendar.DAY_OF_MONTH, 1) yearReservation = defaultCalendar.get(Calendar.YEAR) monthReservation = defaultCalendar.get(Calendar.MONTH) dayReservation = defaultCalendar.get(Calendar.DAY_OF_MONTH) } private fun fetchTimeSlots( sanitizedClubName: String, sanitizedClubEstablishment: String, sanitizedCourtName: String, dateToFetchLeTimeSlots: String, onTimeSlotsFetched: (List<String>) -> Unit, onError: (Exception) -> Unit ) { val firestore = FirebaseFirestore.getInstance() // Reference to the CourtReservations collection val courtReservationsRef = firestore.collection("TheClubDetails") .document(sanitizedClubName) .collection("TheClubEstablishments") .document(sanitizedClubEstablishment) .collection("TheClubCourts") .document(sanitizedCourtName) // Fetch the CourtReservations document courtReservationsRef.get() .addOnSuccessListener { documentSnapshot -> val timeSlots = mutableListOf<String>() if (documentSnapshot.exists()) { // Extract the CourtReservations map field val courtReservations = documentSnapshot.get("CourtReservations") as? Map<*, *> Log.d("ReservationActivity", "0) Fetch Successful $courtReservations") // Check if DetailsReservation exists val detailsReservations = courtReservations?.get(dateToFetchLeTimeSlots) as? List<Map<*, *>> Log.d("ReservationActivity", "0.1) Fetch Successful $detailsReservations") // Iterate over the entries in the DetailsReservations list detailsReservations?.forEach { details -> // Extract Timeslot if it exists val timeslot = details["Timeslot"] as? String if (timeslot != null) { Log.d("ReservationActivity", "1) Fetch Successful: $timeslot") timeSlots.add(timeslot) } } // Disable reserved time slots in the UI Log.d("ReservationActivity", "2.0) Reaches here?") disableReservedTimeSlots(timeGrid, timeSlots) } // Invoke the callback with the list of time slots onTimeSlotsFetched(timeSlots) } .addOnFailureListener { e -> // Invoke the error callback in case of failure onError(e) } } private fun fetchReservedTimeSlots(dateToFetchLeTimeSlots: String) { val sanitizedClubName = intent.getStringExtra("SanitizedClubName") val sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment") val sanitizedCourtName = intent.getStringExtra("SanitizedCourtName") if (sanitizedClubName != null) { if (sanitizedClubEstablishment != null) { if (sanitizedCourtName != null) { fetchTimeSlots(sanitizedClubName, sanitizedClubEstablishment, sanitizedCourtName, dateToFetchLeTimeSlots, onTimeSlotsFetched = { reservedTimeSlots -> Log.d("ReservationActivity", "3) reservedTimeSlots: $reservedTimeSlots") updateReservedTimeSlotsUI(reservedTimeSlots) }, onError = { e -> Log.e("ReservationActivity", "Error fetching reserved time slots", e) } ) } } } } private fun updateReservedTimeSlotsUI(reservedTimeSlots: List<String>) { Log.d("ReservationActivity", "4) UpdateUI called") val timeGrid: LinearLayout = findViewById(R.id.timeGrid) for (i in 0 until timeGrid.childCount) { val rowLayout = timeGrid.getChildAt(i) as LinearLayout for (j in 0 until rowLayout.childCount) { val timeSquare = rowLayout.getChildAt(j) as TextView val timeSlot = timeSquare.text.toString() // Disable the time square if the time slot is reserved timeSquare.isEnabled = !reservedTimeSlots.contains(timeSlot) } } } private fun disableReservedTimeSlots( parentLayout: LinearLayout, reservedTimeSlots: List<String> ) { val updatedReservedTimeSlots = mutableListOf<String>() Log.d("ReservationActivity", "before Show list:$reservedTimeSlots") for (element in reservedTimeSlots) { val startTime = element.split("-")[0].trim() val endTime = element.split("-")[1].trim() // Add the original time slot to the updated list updatedReservedTimeSlots.add(startTime) if (endTime.endsWith("30")) { // If the ending timeslot ends with "30" val hour = endTime.split(":")[0].toInt() var firstTime: String var secondTime: String if (hour <= 10) { firstTime = "0${hour - 1}:30" secondTime = "0${hour}:00" } else { firstTime = "${hour - 1}:30" secondTime = "${hour}:00" } // Add the new timeslots to the updatedReservedTimeSlots list updatedReservedTimeSlots.add("$firstTime-$secondTime") } else if (endTime.endsWith("00")) { // If the ending timeslot ends with "00" val hour = endTime.split(":")[0].toInt() - 1 var firstTime: String var secondTime: String if (hour <= 10) { firstTime = "0$hour:00" secondTime = "0$hour:30" } else { firstTime = "$hour:00" secondTime = "$hour:30" } // Add the new timeslots to the updatedReservedTimeSlots list updatedReservedTimeSlots.add("$firstTime-$secondTime") } } Log.d("ReservationActivity", "Show list:$updatedReservedTimeSlots") takenTimeSlots = updatedReservedTimeSlots // Apply the disabled state to the UI for (i in 0 until parentLayout.childCount) { val rowLayout = parentLayout.getChildAt(i) as LinearLayout for (j in 0 until rowLayout.childCount) { val timeSquare = rowLayout.getChildAt(j) as TextView val time = timeSquare.text.toString() Log.d("ReservationActivity", "Which tags are applied? ${timeSquare.tag}") if (updatedReservedTimeSlots.any { it.contains(time) }) { timeSquare.isEnabled = false timeSquare.setBackgroundResource(R.drawable.selector_disabled_time_square) timeSquare.tag = "disabled" } } } } private fun enableAllTimeSlots(parentLayout: LinearLayout) { // Enable all time squares in the UI val sdf = SimpleDateFormat("HH:mm", Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, 8) calendar.set(Calendar.MINUTE, 0) for (i in 0 until parentLayout.childCount) { val rowLayout = parentLayout.getChildAt(i) as LinearLayout for (j in 0 until rowLayout.childCount) { val timeSquare = rowLayout.getChildAt(j) as TextView val startTime = sdf.format(calendar.time) timeSquare.isEnabled = true timeSquare.setBackgroundResource(R.drawable.selector_time_square) timeSquare.tag = startTime timeSquare.isSelected = false // Clear selection calendar.add(Calendar.MINUTE, 30) } } reservedTimeText.text = "" // Set reservedTimeText to an empty string startingTimePlay = "" endingTimePlay = "" } private fun fetchUserNameandAvatarFireStore(callback: (String, String) -> Unit) { val currentUser = FirebaseAuth.getInstance().currentUser val currentUserId = currentUser?.uid val db = FirebaseFirestore.getInstance() val userReference = currentUserId?.let { db.collection("ThePlayers") .document(it) } // Fetch the username from the user's document userReference?.get()?.addOnSuccessListener { userDocumentSnapshot -> if (userDocumentSnapshot.exists()) { // User document exists, extract the username val username = userDocumentSnapshot.getString("username") // Sanitize the username and use it in the sub-collection reference val sanitizedUsername = sanitizeUsername(username) // Reference to the user's profile details document val profileDetailsReference = db.collection("ThePlayers") .document(currentUserId) .collection("TheProfileDetails") .document(sanitizedUsername) // Fetch data from Firestore profileDetailsReference.get() .addOnSuccessListener { profileDetailsSnapshot -> if (profileDetailsSnapshot.exists()) { // Document exists, extract Avatar and Username avatarOfUserOne = profileDetailsSnapshot.getString("Avatar").toString() usernameOfUserOne = profileDetailsSnapshot.getString("Username").toString() callback(usernameOfUserOne, avatarOfUserOne) Log.d( "ReservationActivity", "avatar: $usernameOfUserOne, $avatarOfUserOne" ) } else { // Document does not exist Log.d("ReservationActivity", "Profile details not found for the user.") } } .addOnFailureListener { e -> // Handle errors Log.d("ReservationActivity", "Error fetching profile details: $e") } } else { // User document does not exist Log.d("ReservationActivity", "User not found.") } }?.addOnFailureListener { e -> // Handle errors Log.d("ReservationActivity", "Error fetching user data: $e") } } // Helper function to sanitize the username private fun sanitizeUsername(username: String?): String { // Remove symbols "/" "\", and " " return username?.replace("[/\\\\ ]".toRegex(), "") ?: "" } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } // Add this function to find the index of an item in the spinner's adapter private fun getIndex(spinner: Spinner, value: String): Int { val adapter = spinner.adapter for (i in 0 until adapter.count) { if (adapter.getItem(i).toString() == value) { return i } } return 0 // Default to the first item if not found } private fun fetchGenderFirestore(callback: (String) -> Unit) { // Get the current user's ID from Firebase Authentication val currentUser = FirebaseAuth.getInstance().currentUser val currentUserId = currentUser?.uid val db = FirebaseFirestore.getInstance() // Reference to the document in the sub-collection val documentReference = currentUserId?.let { db.collection("ThePlayers") .document(it) } // Add data to Firestore documentReference?.get()?.addOnSuccessListener { documentSnapshot -> // Successfully fetched data if (documentSnapshot.exists()) { // Check if the document exists genderOfPlayer = documentSnapshot.getString("gender").toString() // Now 'gender' contains the value of the 'gender' field // Handle the gender data as needed callback(genderOfPlayer) } else { // Document does not exist // Handle accordingly callback("Unknown") } }?.addOnFailureListener { e -> // Handle error // e.g., Log.e("TAG", "Error getting document", e) callback("Unknown") } } // Function to check and update the completion status private fun checkAndUpdateCompletion(callback: () -> Unit) { Log.d( "ReservationActivity", "CompletedUpdates: $completedUpdates | CompletedUpdates: $expectedUpdates" ) if (completedUpdates == expectedUpdates) { callback() } } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/JoinMatchActivity.kt
2773841766
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class JoinMatchActivity : AppCompatActivity() { private lateinit var dateReservationTextView: TextView private lateinit var timeslotTextView: TextView private lateinit var positionSquareTextView: TextView private lateinit var typeOfMatchTextview: TextView private lateinit var gendersAllowedTextview: TextView private lateinit var joinMatchButton: Button private var completedUpdates: Int = 0 private var expectedUpdates: Int = 0 private lateinit var matchId: String private lateinit var positionSquare: String private val userId: String get() = FirebaseAuth.getInstance().currentUser?.uid ?: "" @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.joinmatch_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } dateReservationTextView = findViewById(R.id.dateReservationTextView) timeslotTextView = findViewById(R.id.timeslotTextView) positionSquareTextView = findViewById(R.id.positionSquareTextView) typeOfMatchTextview = findViewById(R.id.typeOfMatchTextview) gendersAllowedTextview = findViewById(R.id.gendersAllowedTextview) joinMatchButton = findViewById(R.id.joinMatchButton) val intent = intent matchId = intent.getStringExtra("matchId") ?: "" positionSquare = intent.getStringExtra("PositionSquare") ?: "" Log.d("JoinMatchActivity", "Data $positionSquare") // Set values from intent dateReservationTextView.text = "Date Match: ${intent.getStringExtra("dateReservation")}" timeslotTextView.text = "Time Match: ${intent.getStringExtra("timeslot")}" positionSquareTextView.text = "Place you join: $positionSquare" typeOfMatchTextview.text = "Type of match: ${intent.getStringExtra("typeOfMatch")}" gendersAllowedTextview.text = "Genders allowed in match: ${intent.getStringExtra("gendersAllowed")}" joinMatchButton.setOnClickListener { joinMatch { launchActivity(MatchActivity::class.java) } } val returnButton: Button = findViewById(R.id.returnButton) returnButton.setOnClickListener { finish() } } private fun joinMatch(callback: () -> Unit) { // Counter to track the number of completed updates completedUpdates = 0 // Variable to store the expected number of updates expectedUpdates = 3 val auth = FirebaseAuth.getInstance() val userId = auth.currentUser?.uid if (userId != null) { val db = FirebaseFirestore.getInstance() val matchRef = db.collection("TheMatches").document(matchId) // Fetch current user details val userRef = db.collection("ThePlayers").document(userId) userRef.get().addOnSuccessListener { userSnapshot -> if (userSnapshot.exists()) { val username = userSnapshot.getString("username") ?: "" val sanitizedUsername = sanitizeUsername(username) Log.d( "JoinMatchActivity", "1) username $username, sanitizedUsername, $sanitizedUsername" ) // Fetch user profile details val profileRef = userRef.collection("TheProfileDetails").document(sanitizedUsername) profileRef.get().addOnSuccessListener { profileSnapshot -> if (profileSnapshot.exists()) { val avatar = profileSnapshot.getString("Avatar") ?: "" Log.d("JoinMatchActivity", " 2) avatar $avatar") // Update ThePlayerReservationsCourts subcollection val reservationsRef = userRef.collection("ThePlayerReservationsCourts").document(matchId) val reservationsData = hashMapOf( "matchId" to matchId ) matchRef.get().addOnSuccessListener { documentSnapshot -> Log.d( "JoinMatchActivity", " 2.1) document ${documentSnapshot.data}" ) if (documentSnapshot.exists()) { val participators = documentSnapshot["participators"] as Map<*, *>? Log.d("JoinMatchActivity", " 3) participators $participators") // Check if the user is already in the match if (participators == null || participators.values.none { it == userId }) { Log.d("JoinMatchActivity", " 4) Triggers?") // Update the participator map with the user's information val updatedParticipators = participators?.toMutableMap() ?: mutableMapOf() val userKey = "UserName_$positionSquare" val avatarKey = "UserAvatar_$positionSquare" val userIdKey = "UserId_$positionSquare" updatedParticipators[userKey] = username updatedParticipators[avatarKey] = avatar updatedParticipators[userIdKey] = userId // Check and update only if the fields have the value "Default" var hasDefaultValues = false for ((key, value) in updatedParticipators) { if (value == "Default") { hasDefaultValues = true // Set the actual values from the user's details updatedParticipators[userKey] = username updatedParticipators[avatarKey] = avatar updatedParticipators[userIdKey] = userId } } // Update the document with the new participators if there are "Default" values if (hasDefaultValues) { matchRef.update("participators", updatedParticipators) Toast.makeText( this, "Joined the match!", Toast.LENGTH_SHORT ).show() completedUpdates++ checkAndUpdateCompletion(callback) reservationsRef.set(reservationsData) .addOnSuccessListener { Log.d("JoinMatchActivity", "Added matchId to ThePlayerReservationsCourts") completedUpdates++ checkAndUpdateCompletion(callback) } .addOnFailureListener { e -> // Handle failure } } else { Toast.makeText( this, "Another player already joined!", Toast.LENGTH_SHORT ).show() } } else { Toast.makeText( this, "You are already in this match", Toast.LENGTH_SHORT ).show() } } } val sentThroughClubName = intent.getStringExtra("sentThroughClubName") ?: "" val sentThroughClubEstablishmentName = intent.getStringExtra("sentThroughClubEstablishmentName") ?: "" val sentThroughCourtName = intent.getStringExtra("sentThroughCourtName") ?: "" val dateReservation = intent.getStringExtra("dateReservation") val matchId = intent.getStringExtra("matchId") positionSquare = intent.getStringExtra("PositionSquare") ?: "" val db = FirebaseFirestore.getInstance() // Reference to the document in the sub-collection val documentReference = db.collection("TheClubDetails/$sentThroughClubName/TheClubEstablishments/$sentThroughClubEstablishmentName/TheClubCourts") .document(sentThroughCourtName) documentReference.get() .addOnSuccessListener { documentSnapshot -> if (documentSnapshot.exists()) { // Get CourtReservations map val courtReservations = documentSnapshot.get("CourtReservations") as? Map<*, *> if (courtReservations != null) { // Get the specific array object based on dateReservation val reservationsArray = courtReservations[dateReservation] as? List<*> if (reservationsArray != null) { // Find the object with matching matchId val matchingReservation = reservationsArray.find { (it as? Map<*, *>)?.get("MatchId") == matchId } if (matchingReservation != null) { // Get the Participators map val participators = (matchingReservation as Map<*, *>)["Participators"] as? MutableMap<String, Any> // Update values based on positionSquare participators?.let { it["UserName_$positionSquare"] = username it["UserAvatar_$positionSquare"] = avatar it["UserId_$positionSquare"] = userId // Update the Participators map in Firestore documentReference.update( "CourtReservations.$dateReservation", reservationsArray ) .addOnSuccessListener { completedUpdates++ checkAndUpdateCompletion(callback) } .addOnFailureListener { e -> // Handle failure } } } } } } } .addOnFailureListener { e -> // Handle failure } } } } } } } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } private fun sanitizeUsername(username: String): String { // Implement your logic to sanitize the username (remove spaces or special characters) // For example, you can replace spaces with underscores return username.replace("\\s+".toRegex(), "") } // Function to check and update the completion status private fun checkAndUpdateCompletion(callback: () -> Unit) { Log.d( "ReservationActivity", "CompletedUpdates: $completedUpdates | CompletedUpdates: $expectedUpdates" ) if (completedUpdates == expectedUpdates) { callback() } } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/CourtListActivity.kt
1013657700
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.CourtAdapter import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.firestore.FirebaseFirestore class CourtListActivity : AppCompatActivity() { private lateinit var recyclerView: RecyclerView private lateinit var adapter: CourtAdapter private lateinit var sanitizedClubName: String private lateinit var sanitizedClubEstablishment: String private lateinit var sentThroughClubName: String private lateinit var sentThroughClubEstablishment: String private lateinit var sentThroughEstablishmentAddress: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.courtslist_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } sentThroughEstablishmentAddress = intent.getStringExtra("sentThroughEstablishmentAddress").toString() // Retrieve sanitized club and establishment names from the intent sanitizedClubName = intent.getStringExtra("SanitizedClubName") ?: "" sanitizedClubEstablishment = intent.getStringExtra("SanitizedClubEstablishment") ?: "" sentThroughClubName = intent.getStringExtra("sentThroughClubName") ?: "" sentThroughClubEstablishment = intent.getStringExtra("sentThroughClubEstablishment") ?: "" Log.d( "CourtListActivity", "1) Sent along?: $sanitizedClubName, $sanitizedClubEstablishment" ) recyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(this) adapter = CourtAdapter { sentThroughCourtName -> // Handle item click, and navigate to AccountActivity navigateToAccountActivity(sentThroughCourtName) } recyclerView.adapter = adapter // Fetch courts from Firebase Firestore fetchCourts() } private fun fetchCourts() { val db = FirebaseFirestore.getInstance() // Reference to the club's courts collection val courtsRef = db.collection("TheClubDetails") .document(sanitizedClubName) .collection("TheClubEstablishments") .document(sanitizedClubEstablishment) .collection("TheClubCourts") Log.d( "CourtListActivity", "1.2) Sent along?: $sanitizedClubName, $sanitizedClubEstablishment" ) courtsRef.get() .addOnSuccessListener { documents -> Log.d("CourtListActivity", "2) Reaches here?: ${documents.documents}") // Clear existing data adapter.clearData() for (document in documents) { val courtName = document.getString("CourtName") ?: "" Log.d("CourtListActivity", "3) Fetch?: $courtName") adapter.addData(courtName) } } .addOnFailureListener { exception -> Toast.makeText(this, "Error fetching courts: $exception", Toast.LENGTH_SHORT).show() } } private fun navigateToAccountActivity(sentThroughCourtName: String) { // Create an explicit intent to navigate to AccountActivity val sanitizedCourtName = sentThroughCourtName.replace("[\\s,\\\\/]".toRegex(), "") Log.d( "CourtListActivity", "The right stuff sent? $sentThroughCourtName, $sanitizedCourtName" ) val intent = Intent(this, ReservationActivity::class.java).apply { putExtra("SanitizedClubName", sanitizedClubName) putExtra("SanitizedClubEstablishment", sanitizedClubEstablishment) putExtra("SanitizedCourtName", sanitizedCourtName) putExtra("sentThroughClubName", sentThroughClubName) putExtra("sentThroughClubEstablishment", sentThroughClubEstablishment) putExtra("sentThroughCourtName", sentThroughCourtName) putExtra("sentThroughEstablishmentAddress", sentThroughEstablishmentAddress) } startActivity(intent) } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/MatchActivity.kt
3996558639
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.MatchAdapter import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Match import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class MatchActivity : AppCompatActivity() { private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.match_screen) // Fetch current user's gender from Firestore val currentUserUid = FirebaseAuth.getInstance().currentUser?.uid if (currentUserUid != null) { fetchUserGender(currentUserUid) } val tabLayout: TabLayout = findViewById(R.id.tabLayout_Establishments) // Add tabs with titles val allMatchesTab = tabLayout.newTab().setText("All Matches") val yourMatchesTab = tabLayout.newTab().setText("Your Matches") tabLayout.addTab(allMatchesTab) tabLayout.addTab(yourMatchesTab) // Set up a tab selected listener tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { when (tab.position) { 0 -> { // Start EstablishmentsActivity //launchActivity(ClubEstablishmentsActivity::class.java) } 1 -> { // Start YourCourtReservationsActivity launchActivity(YourMatchesActivity::class.java) } } } override fun onTabUnselected(tab: TabLayout.Tab) { // Handle tab unselection if needed } override fun onTabReselected(tab: TabLayout.Tab) { // Handle tab reselection if needed } }) // Select the tab you want (e.g., "Your Courts Reservations") allMatchesTab.select() val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } recyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(this) //fetchDataFromFirestore() } private fun displayMatches(matches: List<Match>) { val adapter = MatchAdapter(matches) recyclerView.adapter = adapter } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } private fun fetchUserGender(userId: String) { firestore.collection("ThePlayers") .document(userId) .get() .addOnSuccessListener { documentSnapshot -> val userGender = documentSnapshot.getString("gender") if (userGender != null) { // Now that you have the user's gender, fetch and display matches fetchDataFromFirestore(userGender) } else { Log.e("MatchActivity", "User gender not found") } } .addOnFailureListener { exception -> Log.e("MatchActivity", "Error fetching user gender: $exception") } } private fun fetchDataFromFirestore(userGender: String) { firestore.collection("TheMatches") .get() .addOnSuccessListener { querySnapshot -> val matches = mutableListOf<Match>() for (document in querySnapshot.documents) { val match = document.toObject(Match::class.java) Log.d("MatchActivity", "$match") match?.let { // Check if the match should be displayed based on user's gender and gendersAllowed if (shouldDisplayMatch(it, userGender)) { matches.add(it) } } } displayMatches(matches) } .addOnFailureListener { exception -> Log.e("Firestore", "Error fetching data: $exception") } } private fun shouldDisplayMatch(match: Match, userGender: String): Boolean { val gendersAllowed = match.gendersAllowed // Check if the match should be displayed based on user's gender and gendersAllowed return when (userGender) { "Male" -> gendersAllowed != "Female" "Female" -> gendersAllowed != "Male" else -> true // Handle other cases or use a default value as needed } } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/YourCourtReservationsActivity.kt
4202251540
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.CourtReservationAdapter import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.CourtReservation import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class YourCourtReservationsActivity : AppCompatActivity() { private lateinit var recyclerView: RecyclerView private lateinit var courtReservationAdapter: CourtReservationAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.yourreservationscourts_screen) val tabLayout: TabLayout = findViewById(R.id.tabLayout_reservationCourt) // Add tabs with titles val establishmentsTab = tabLayout.newTab().setText("Establishments") val reservationsTab = tabLayout.newTab().setText("Your Courts Reservations") tabLayout.addTab(establishmentsTab) tabLayout.addTab(reservationsTab) // Set up a tab selected listener tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { when (tab.position) { 0 -> { // Start EstablishmentsActivity launchActivity(EstablishmentsActivity::class.java) } 1 -> { // Start YourCourtReservationsActivity //launchActivity(YourCourtReservationsActivity::class.java) } } } override fun onTabUnselected(tab: TabLayout.Tab) { // Handle tab unselection if needed } override fun onTabReselected(tab: TabLayout.Tab) { // Handle tab reselection if needed } }) // Select the tab you want (e.g., "Your Courts Reservations") reservationsTab.select() recyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(this) val userId = FirebaseAuth.getInstance().currentUser?.uid val query = FirebaseFirestore.getInstance() .collection("ThePlayers") .document(userId!!) .collection("ThePlayerReservationsCourts") query.get().addOnSuccessListener { documents -> val courtReservations = mutableListOf<CourtReservation>() for (document in documents) { val isEmpty = document.getString("clubEstablishmentName") ?: "" val courtReservation = CourtReservation( document.getString("clubEstablishmentName") ?: "", document.getString("clubEstablishmentAddress") ?: "", document.getString("courtName") ?: "", document.getString("dateReservation") ?: "", document.getString("timeslot") ?: "" ) if (isEmpty != "") { courtReservations.add(courtReservation) } } courtReservationAdapter = CourtReservationAdapter(courtReservations) recyclerView.adapter = courtReservationAdapter }.addOnFailureListener { exception -> // Handle failure } val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/AccountActivity.kt
4028384997
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage; import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import com.example.mobile_dev_endproject_jc_jvl.R class AccountActivity : AppCompatActivity() { private lateinit var profileImage: ImageView private lateinit var usernameText: TextView private lateinit var locationText: TextView private lateinit var genderText: TextView private lateinit var followersText: TextView private lateinit var followingText: TextView private lateinit var levelText: TextView private lateinit var editProfileButton: Button private lateinit var changePasswordButton: Button private lateinit var preferencesTitle: TextView private lateinit var typeMatchText: TextView private lateinit var handPlayText: TextView private lateinit var timeToPlayText: TextView private lateinit var courtPositionText: TextView private lateinit var genderToPlayAgainstText: TextView private lateinit var logoutButton: Button private lateinit var pickImageLauncher: ActivityResultLauncher<Intent> private lateinit var userId: String private val db = FirebaseFirestore.getInstance() private val auth = FirebaseAuth.getInstance() @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.account_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.menu.findItem(R.id.navigation_account).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { launchActivity(AccountActivity::class.java) true } else -> false } } // Initialize views profileImage = findViewById(R.id.profileImage) usernameText = findViewById(R.id.usernameText) locationText = findViewById(R.id.locationText) genderText = findViewById(R.id.genderText) followersText = findViewById(R.id.followersText) followingText = findViewById(R.id.followingText) levelText = findViewById(R.id.levelText) editProfileButton = findViewById(R.id.editProfileButton) changePasswordButton = findViewById(R.id.changePasswordButton) preferencesTitle = findViewById(R.id.preferencesTitle) typeMatchText = findViewById(R.id.typeMatchText) handPlayText = findViewById(R.id.handPlayText) timeToPlayText = findViewById(R.id.timeToPlayText) courtPositionText = findViewById(R.id.courtPositionText) genderToPlayAgainstText = findViewById(R.id.genderToPlayAgainstText) logoutButton = findViewById(R.id.logoutButton) var sentThroughUserId: String = "" Log.d("AccountActivity", "Hello? $sentThroughUserId") sentThroughUserId = intent.getStringExtra("sentThroughUserId") ?: "" Log.d("AccountActivity", "Hello? $sentThroughUserId") // Fetch data from Firestore if (sentThroughUserId == "") { userId = auth.currentUser?.uid.toString() Log.d("AccountActivity", "Hello1? $userId") } else { userId = sentThroughUserId Log.d("AccountActivity", "Hello2? $userId") } var sanitizedUsername: String? = null if (userId != null) { val userRef = db.collection("ThePlayers").document(userId) userRef.get().addOnSuccessListener { document -> if (document != null && document.exists()) { // Retrieve the "TheProfileDetails" sub-collection val profileDetailsRef = userRef.collection("TheProfileDetails") profileDetailsRef.get().addOnSuccessListener { profileDetailsSnapshot -> for (profileDetailsDocument in profileDetailsSnapshot.documents) { // Now you have access to each document in the "TheProfileDetails" sub-collection val profileDetailsData = profileDetailsDocument.data if (profileDetailsData != null) { // Extract fields val levelInformation = profileDetailsData["Level"]?.toString()?.toInt() val followersInformation = profileDetailsData["Followers"]?.toString()?.toInt() val followingInformation = profileDetailsData["Following"]?.toString()?.toInt() val avatarUrl = profileDetailsData["Avatar"] as? String val username = profileDetailsData["Username"] as? String val gender = profileDetailsData["Gender"] as? String // Sanitize username sanitizedUsername = username?.replace("[\\s,\\\\/]".toRegex(), "") // Check if any of the required fields is null before updating UI if (avatarUrl != null && username != null && levelInformation != null && followersInformation != null && followingInformation != null) { // Update UI with fetched data Glide.with(this).load(avatarUrl).into(profileImage) usernameText.text = username followersText.text = "Followers: $followersInformation" followingText.text = "Following: $followingInformation" levelText.text = "Level: $levelInformation" genderText.text = "$gender" // Fetch "ThePreferencesPlayer" sub-collection val preferencesRef = userRef.collection("ThePreferencesPlayer") preferencesRef.get() .addOnSuccessListener { preferencesSnapshot -> for (preferencesDocument in preferencesSnapshot.documents) { // Now you have access to each document in the "ThePreferencesPlayer" sub-collection val preferencesData = preferencesDocument.data // Extract fields from the "ThePreferencesPlayer" document val typeMatch = preferencesData?.get("preferredTypeMatch") as? String val handPlay = preferencesData?.get("preferredHandPlay") as? String val timeToPlay = preferencesData?.get("preferredTimeToPlay") as? String val courtPosition = preferencesData?.get("preferredCourtPosition") as? String val genderToPlayAgainst = preferencesData?.get("preferredGenderToPlayAgainst") as? String val playLocation = preferencesData?.get("preferredPlayLocation") as? String // Check if any of the required preference fields is null before updating UI if (typeMatch != null && handPlay != null && timeToPlay != null && courtPosition != null && genderToPlayAgainst != null && playLocation != null ) { // Update UI with fetched preferences locationText.text = playLocation typeMatchText.text = "Type Match: $typeMatch" handPlayText.text = "Preferred Hand: $handPlay" timeToPlayText.text = "Preferred Time: $timeToPlay" courtPositionText.text = "Preferred Court Position: $courtPosition" genderToPlayAgainstText.text = "Preferred Gender to play against: $genderToPlayAgainst" } else { // Handle the case where some preference fields are null // Show an error message or take appropriate action } } } } else { // Handle the case where some fields in "Nickname" document are null // Show an error message or take appropriate action } } else { // Handle the case where "Nickname" document is null // Show an error message or take appropriate action } } } // additional code } } } pickImageLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { val data: Intent? = result.data if (data != null && data.data != null) { val imageUri: Uri = data.data!! sanitizedUsername?.let { uploadImageToFirebaseStorage(imageUri, it) } } } } profileImage.setOnClickListener { // Open the image picker or camera to choose a new avatar // You can use an external library like Intent.ACTION_PICK or Intent.ACTION_GET_CONTENT // or implement your own image picker logic openImagePicker() } // Set up the rest of your UI and handle button clicks as needed editProfileButton = findViewById(R.id.editProfileButton); editProfileButton.setOnClickListener { startActivity(Intent(this, EditProfileActivity::class.java)) } changePasswordButton.setOnClickListener { startActivity(Intent(this, ChangePasswordActivity::class.java)) } logoutButton.setOnClickListener { auth.signOut() val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } private fun openImagePicker() { val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) pickImageLauncher.launch(galleryIntent) } private fun uploadImageToFirebaseStorage(imageUri: Uri, sanitizedUsername: String) { // Implement logic to upload the image to Firebase Storage // You can use the Firebase Storage API to upload the image // Example: val storageRef = FirebaseStorage.getInstance().reference val imageRef = storageRef.child("avatars/${auth.currentUser?.uid}.jpg") // Upload file to Firebase Storage imageRef.putFile(imageUri) .addOnSuccessListener { taskSnapshot -> // Image uploaded successfully // Get the download URL and update the user's profile imageRef.downloadUrl.addOnSuccessListener { uri -> // Update the user's avatar URL in Firestore updateAvatarUrl(uri.toString(), sanitizedUsername) } } .addOnFailureListener { e -> Log.e("AccountActivity", "Image upload failed: ${e.message}") } } private fun updateAvatarUrl(avatarUrl: String, sanitizedUsername: String) { // Update the "Avatar" field in Firestore val userId = auth.currentUser?.uid if (userId != null) { val userRef = db.collection("ThePlayers").document(userId) val profileDetailsRef = userRef.collection("TheProfileDetails").document(sanitizedUsername) // Update the "Avatar" field with the new URL profileDetailsRef.update("Avatar", avatarUrl) .addOnSuccessListener { // Avatar URL updated successfully // Update the UI with the new avatar Glide.with(this).load(avatarUrl).into(profileImage) } .addOnFailureListener { e -> Log.e("AccountActivity", "Failed to update avatar URL: ${e.message}") } } } companion object { private const val PICK_IMAGE_REQUEST = 1 } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/YourMatchesActivity.kt
1335854163
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.mobile_dev_endproject_jc_jvl.R import com.example.mobile_dev_endproject_jc_jvl.adaptersDirectory.MatchAdapter import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Match import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.tabs.TabLayout import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FieldPath class YourMatchesActivity : AppCompatActivity() { private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance() private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.yourmatches_screen) val tabLayout: TabLayout = findViewById(R.id.tabLayout_Establishments) // Add tabs with titles val allMatchesTab = tabLayout.newTab().setText("All Matches") val yourMatchesTab = tabLayout.newTab().setText("Your Matches") tabLayout.addTab(allMatchesTab) tabLayout.addTab(yourMatchesTab) // Set up a tab selected listener tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { when (tab.position) { 0 -> { // Start EstablishmentsActivity launchActivity(MatchActivity::class.java) } 1 -> { // Start YourCourtReservationsActivity //launchActivity(YourCourtReservationsActivity::class.java) } } } override fun onTabUnselected(tab: TabLayout.Tab) { // Handle tab unselection if needed } override fun onTabReselected(tab: TabLayout.Tab) { // Handle tab reselection if needed } }) // Select the tab you want (e.g., "Your Courts Reservations") yourMatchesTab.select() val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_match).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } recyclerView = findViewById(R.id.recyclerView) recyclerView.layoutManager = LinearLayoutManager(this) fetchDataFromFirestore() } private fun fetchDataFromFirestore() { val currentUser = FirebaseAuth.getInstance().currentUser val userId = currentUser?.uid userId?.let { uid -> val playersCollection = firestore.collection("ThePlayers").document(uid) val reservationsCollection = playersCollection.collection("ThePlayerReservationsCourts") reservationsCollection.get() .addOnSuccessListener { reservationSnapshot -> Log.d("YourMatchesActivity", " 1) data ${reservationSnapshot.documents}") val matchIds = mutableListOf<String>() Log.d("YourMatchesActivity", " 2) data $matchIds") for (reservationDocument in reservationSnapshot.documents) { Log.d("YourMatchesActivity", " 3) data $reservationDocument") val matchId = reservationDocument.getString("matchId") matchId?.let { if (it.isNotEmpty()) { // Check if MatchId is not empty matchIds.add(it) } } } if (matchIds.isNotEmpty()) { // Check if matchIds list is not empty val matchesCollection = firestore.collection("TheMatches") val matchesQuery = matchesCollection.whereIn(FieldPath.documentId(), matchIds) matchesQuery.get() .addOnSuccessListener { matchSnapshot -> val matches = mutableListOf<Match>() for (matchDocument in matchSnapshot.documents) { val match = matchDocument.toObject(Match::class.java) match?.let { matches.add(it) } } displayMatches(matches) } .addOnFailureListener { exception -> Log.e("Firestore", "Error fetching matches: $exception") } } else { Log.d("Firestore", "No valid MatchIds found") // Handle the case where there are no valid MatchIds } } .addOnFailureListener { exception -> Log.e("Firestore", "Error fetching matchIds: $exception") } } } private fun displayMatches(matches: List<Match>) { val adapter = MatchAdapter(matches) recyclerView.adapter = adapter } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/EstablishmentDetailsActivity.kt
3634827596
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import android.os.Parcelable import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import org.osmdroid.util.GeoPoint class EstablishmentDetailsActivity : AppCompatActivity() { private lateinit var firestore: FirebaseFirestore private var sanitizedClubName: String? = null private var sanitizedEstablishmentName: String? = null private lateinit var sentThroughClubName: String private lateinit var sentThroughClubEstablishment: String private lateinit var sentThroughEstablishmentAddress: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.establishmentdetails_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_establishment).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } sentThroughEstablishmentAddress = intent.getStringExtra("ClubEstablishmentAddress").toString() firestore = FirebaseFirestore.getInstance() val intent = intent sentThroughClubName = intent.getStringExtra("ClubName").toString() if (sentThroughClubName != null) { sanitizedClubName = sentThroughClubName.replace("[\\s,\\\\/]".toRegex(), "") } val courtAddress = intent.getStringExtra("ClubEstablishmentAddress") sentThroughClubEstablishment = intent.getStringExtra("EstablishmentName").toString() if (sentThroughClubEstablishment != null) { sanitizedEstablishmentName = sentThroughClubEstablishment.replace("[\\s,\\\\/]".toRegex(), "") } findViewById<TextView>(R.id.textViewCourtAddress).text = courtAddress findViewById<TextView>(R.id.textViewClubEstablishmentName).text = sentThroughClubEstablishment fetchClubData(sentThroughClubName) } private fun fetchClubData(clubName: String?) { if (clubName == null) { // Handle the case where clubName is null return } val clubDocumentRef = firestore.collection("TheClubDetails").document(clubName) clubDocumentRef.get() .addOnSuccessListener { documentSnapshot: DocumentSnapshot? -> if (documentSnapshot != null && documentSnapshot.exists()) { // DocumentSnapshot exists, extract data val clubNameWithSpaces = documentSnapshot.getString("ClubName") val clubDescription = documentSnapshot.getString("ClubDescription") val imageURL = documentSnapshot.getString("ClubLogo") // Set data to the corresponding TextViews findViewById<TextView>(R.id.textViewClubName).text = clubNameWithSpaces findViewById<TextView>(R.id.textViewClubDescription).text = clubDescription loadClubLogo(imageURL) } else { // Handle the case where the document doesn't exist } } .addOnFailureListener { exception: Exception -> Log.e( "EstablishmentDetailsActivity", "Exception occurred: ${exception.message}", exception ) } } private fun loadClubLogo(imageURL: String?) { if (imageURL != null) { Log.d("EstablishmentDetailsActivity", "Image URL: $imageURL") // Load club logo using an image loading library like Picasso or Glide val imageViewClubLogo = findViewById<ImageView>(R.id.imageViewClubLogo) Glide.with(this) .load(imageURL) .into(imageViewClubLogo) } } fun onReserveClicked(view: View) { val mapIntent = Intent(this, CourtListActivity::class.java) mapIntent.putExtra("SanitizedClubName", sanitizedClubName) mapIntent.putExtra("SanitizedClubEstablishment", sanitizedEstablishmentName) mapIntent.putExtra("sentThroughClubName", sentThroughClubName) mapIntent.putExtra("sentThroughClubEstablishment", sentThroughClubEstablishment) mapIntent.putExtra("sentThroughEstablishmentAddress", sentThroughEstablishmentAddress) startActivity(mapIntent) } // .xml relies on view!!!! fun onReturnClicked(view: View) { val receivedCoordinates = intent.getParcelableExtra<Parcelable>("TheMapCoordinates") as? GeoPoint if (receivedCoordinates != null) { val mapIntent = Intent(this, MapActivity::class.java) mapIntent.putExtra("TheMapCoordinates", receivedCoordinates as Parcelable) startActivity(mapIntent) } else { val clubIntent = Intent(this, EstablishmentsActivity::class.java) startActivity(clubIntent) } } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/EditProfileActivity.kt
3824033184
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.dataClassesDirectory.Preferences import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class EditProfileActivity : AppCompatActivity() { private lateinit var playLocationEditText: EditText private lateinit var typeMatchSpinner: Spinner private lateinit var handPlaySpinner: Spinner private lateinit var timeToPlaySpinner: Spinner private lateinit var courtPositionSpinner: Spinner private lateinit var genderSpinner: Spinner private lateinit var saveButton: Button private lateinit var returnButton: Button private lateinit var userId: String private lateinit var firestore: FirebaseFirestore override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.edit_profile_screen) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) // Right Icon active bottomNavigationView.menu.findItem(R.id.navigation_account).isChecked = true bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { launchActivity(HomeActivity::class.java) true } R.id.navigation_establishment -> { launchActivity(EstablishmentsActivity::class.java) true } R.id.navigation_match -> { launchActivity(MatchActivity::class.java) true } R.id.navigation_account -> { item.isChecked = true launchActivity(AccountActivity::class.java) true } else -> false } } // Initialize UI components playLocationEditText = findViewById(R.id.playLocationEditText) typeMatchSpinner = findViewById(R.id.typeMatchSpinner) handPlaySpinner = findViewById(R.id.handPlaySpinner) timeToPlaySpinner = findViewById(R.id.timeToPlaySpinner) courtPositionSpinner = findViewById(R.id.courtPositionSpinner) genderSpinner = findViewById(R.id.genderSpinner) saveButton = findViewById(R.id.saveButton) returnButton = findViewById(R.id.returnButton) // Initialize Firestore and current user ID firestore = FirebaseFirestore.getInstance() userId = FirebaseAuth.getInstance().currentUser?.uid ?: "" // Populate UI with Firestore data populateUIFromFirestore() // Set onClickListener for buttons returnButton.setOnClickListener { startActivity(Intent(this, AccountActivity::class.java)) } saveButton.setOnClickListener { saveProfileDataToFirestore() } } private fun populateUIFromFirestore() { // Retrieve user preferences from Firestore and populate UI firestore.collection("ThePlayers") .document(userId) .collection("ThePreferencesPlayer") .document("UserId") .get() .addOnSuccessListener { documentSnapshot -> val preferences = documentSnapshot.toObject(Preferences::class.java) if (documentSnapshot.exists() && preferences != null) { // Update fields with non-default values val playLocation = preferences.preferredPlayLocation if (playLocation != "Location Not Yet Stated") { playLocationEditText.setText(preferences.preferredPlayLocation) } //playLocationEditText.setText(preferences.preferredPlayLocation) typeMatchSpinner.setSelection( getIndex( typeMatchSpinner, preferences.preferredTypeMatch ) ) handPlaySpinner.setSelection( getIndex( handPlaySpinner, preferences.preferredHandPlay ) ) timeToPlaySpinner.setSelection( getIndex( timeToPlaySpinner, preferences.preferredTimeToPlay ) ) courtPositionSpinner.setSelection( getIndex( courtPositionSpinner, preferences.preferredCourtPosition ) ) genderSpinner.setSelection( getIndex( genderSpinner, preferences.preferredGenderToPlayAgainst ) ) } else { // Error handling } } } private fun saveProfileDataToFirestore() { // Get selected values from UI val preferredPlayLocation = playLocationEditText.text.toString().trim() val preferredTypeMatch = typeMatchSpinner.selectedItem.toString() val preferredHandPlay = handPlaySpinner.selectedItem.toString() val preferredTimeToPlay = timeToPlaySpinner.selectedItem.toString() val preferredCourtPosition = courtPositionSpinner.selectedItem.toString() val preferredGenderToPlayAgainst = genderSpinner.selectedItem.toString() // Check if playLocationEditText is empty if (preferredPlayLocation.isEmpty()) { playLocationEditText.error = "Please fill in the location" return } // Update Firestore with new values val preferences = Preferences( preferredPlayLocation, preferredTypeMatch, preferredHandPlay, preferredTimeToPlay, preferredCourtPosition, preferredGenderToPlayAgainst ) firestore.collection("ThePlayers") .document(userId) .collection("ThePreferencesPlayer") .document("UserId") .set(preferences) .addOnSuccessListener { // Data saved successfully // You can add any additional logic here setResult(RESULT_OK) startActivity(Intent(this, AccountActivity::class.java)) } .addOnFailureListener { Toast.makeText(this, "Failed to save data", Toast.LENGTH_SHORT).show() } } private fun getIndex(spinner: Spinner, value: String): Int { for (i in 0 until spinner.count) { if (spinner.getItemAtPosition(i).toString() == value) { return i } } return 0 // Default to the first item if not found } private fun launchActivity(cls: Class<*>) { val intent = Intent(this, cls) startActivity(intent) } }
Mobile_Development_EndProject_JC_JvL/app/src/main/java/com/example/mobile_dev_endproject_jc_jvl/activitiesDirectory/LoginActivity.kt
676657208
package com.example.mobile_dev_endproject_jc_jvl.activitiesDirectory import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.example.mobile_dev_endproject_jc_jvl.R import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth class LoginActivity : AppCompatActivity() { private lateinit var emailEditText: EditText private lateinit var passwordEditText: EditText private lateinit var forgotPasswordTextView: TextView private lateinit var loginButton: Button private lateinit var registerButton: Button private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.login_screen) auth = FirebaseAuth.getInstance() emailEditText = findViewById(R.id.emailEditText) passwordEditText = findViewById(R.id.passwordEditText) forgotPasswordTextView = findViewById(R.id.forgotPasswordTextView) loginButton = findViewById(R.id.loginButton) registerButton = findViewById(R.id.registerButton) loginButton.setOnClickListener { val email = emailEditText.text.toString().trim() val password = passwordEditText.text.toString().trim() if (email.isNotEmpty() && password.isNotEmpty()) { loginUser(email, password) } else { // empty fields if (email.isEmpty()) { emailEditText.setBackgroundResource(R.drawable.edit_text_error_border) } else { emailEditText.setBackgroundResource(R.drawable.edit_text_default_border) } if (password.isEmpty()) { passwordEditText.setBackgroundResource(R.drawable.edit_text_error_border) } else { passwordEditText.setBackgroundResource(R.drawable.edit_text_default_border) } } } forgotPasswordTextView.setOnClickListener { // Handle forgot password } registerButton.setOnClickListener { startActivity(Intent(this, RegisterActivity::class.java)) } } private fun loginUser(email: String, password: String) { auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Login successful startActivity(Intent(this, HomeActivity::class.java)) } else { // If login fails, display a message to the user. // You can customize the error message based on the task.exception // For example, task.exception?.message // Handle authentication errors } val errorMessage = task.exception?.message ?: "Login failed" showSnackbar(errorMessage) // Set red contour for email and password fields emailEditText.setBackgroundResource(R.drawable.edit_text_error_border) passwordEditText.setBackgroundResource(R.drawable.edit_text_error_border) } } private fun showSnackbar(message: String) { // Assuming your root view is a CoordinatorLayout, replace it with the appropriate view type if needed val rootView = findViewById<View>(android.R.id.content) Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show() } }
TranslateMe-App/client/app/src/androidTest/java/com/wordle/client/ExampleInstrumentedTest.kt
2664295102
package com.wordle.client 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.wordle.client", appContext.packageName) } }
TranslateMe-App/client/app/src/test/java/com/wordle/client/ExampleUnitTest.kt
842567638
package com.wordle.client 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) } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/MainActivity.kt
753323058
package com.wordle.client import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import androidx.fragment.app.Fragment import com.google.android.material.bottomnavigation.BottomNavigationView import com.wordle.client.fragment.* class MainActivity : AppCompatActivity() { lateinit var demoButton: Button var mContext:Context = this // var g:SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if(savedInstanceState == null) { loadFragment(HomeFragment()) } initView() } private lateinit var mBottomNavigationView: BottomNavigationView private fun loadFragment(fragment: Fragment){ val transaction = supportFragmentManager.beginTransaction() .setCustomAnimations(R.anim.slide_in, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out) transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } private fun initView(){ mBottomNavigationView = findViewById(R.id.bottom_navigation_view) mBottomNavigationView.setOnItemSelectedListener{ when (it.itemId){ R.id.home ->{ setTitle(R.string.home) loadFragment(HomeFragment()) return@setOnItemSelectedListener true } R.id.favorite ->{ setTitle(R.string.favorite) loadFragment(FavoriteFragment()) return@setOnItemSelectedListener true } R.id.currency ->{ setTitle(R.string.currency) loadFragment(CurrencyFragment()) return@setOnItemSelectedListener true } } false } } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/util/LocalDBHelper.kt
1654210871
package com.wordle.client.util import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper /** * This LocalDBHelper will using sqlite to manage data created by the ap */ class LocalDBHelper(context: Context?):SQLiteOpenHelper(context, "translator", null,1) { // first table store the supported translate languages val table1 = "create table languages(id integer primary key,language text,name text, supports_formality text)" // second table store user favorite translated language val table2 = "create table favorites(id integer primary key, _from text, _to text, from_text text, to_text)" // create those table when onCreate happen override fun onCreate(p0: SQLiteDatabase?) { p0?.execSQL(table1) p0?.execSQL(table2) } override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) { } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/util/RetrofitClient.kt
3525665958
package com.wordle.client.util import com.wordle.client.interfaces.TranslateService import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClient { // Free language translator api const val DEEPL_TRANSLATE_BASE_URL = "https://api-free.deepl.com/" // OKhttp logging setting val loggingInterceptor = HttpLoggingInterceptor(HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY) // OKhttp client register with logging val okHttpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).build() // Retrofit client with ok http val retrofit = Retrofit.Builder().baseUrl(DEEPL_TRANSLATE_BASE_URL).addConverterFactory(GsonConverterFactory.create()).client( okHttpClient).build() // Translate service created by retrofit client val translateService = retrofit.create(TranslateService::class.java) }
TranslateMe-App/client/app/src/main/java/com/wordle/client/util/OkHttpUtil.kt
4038095867
// //import android.app.AlertDialog //import android.content.Context //import android.os.Bundle //import android.os.Handler //import android.os.Looper //import android.os.Message //import com.wordle.client.util.ProgressDialog //import okhttp3.* //import java.io.IOException // ///** // * Asynchronous calls to server api helper classes // * Created by Zhiqiang Liu // */ //open class OkHttpUtil { // // // OKHttp instance // val client = OkHttpClient() // // var mContext: Context? = null // // // Static Variable // companion object { // // The base server url // const val BASE_URL = "http://10.0.2.2:5000/" // // // Bundle message // const val MSG = "msg" // const val TITLE = "title" // const val DEFAULT_MSG = 0x0 // const val ALL_USER_MSG = 0x1 // const val LOGIN_MSG = 0x2 // const val SERVER_ERROR="Server Error" // const val PROGRESS_DIALOG_SHOW = 0x11 // const val PROGRESS_DIALOG_CLOSE = 0x12 // const val ALERT_DIALOG_SHOW = 0x13 // } // // /** // * This handler handle the dialog show and close // * // */ // var dialogHandler = object : Handler(Looper.getMainLooper()) { // // // Progress Dialog // var progressDialog: ProgressDialog? =null // // fun openProgressDialog(){ // if(progressDialog == null) { // progressDialog = ProgressDialog() // } // // non null call // progressDialog!!.showProgress(mContext) // } // // fun closeProgressDialog(){ // progressDialog?.closeProgress() // } // // fun showMessage(title:String, msg:String){ // var dialog = AlertDialog.Builder(mContext) // dialog.create() // dialog.setMessage(msg) // dialog.setTitle(title) // dialog.show() // } // // override fun handleMessage(msg: Message) { // super.handleMessage(msg) // when(msg?.what){ // PROGRESS_DIALOG_SHOW->{ // openProgressDialog() // } // PROGRESS_DIALOG_CLOSE->{ // closeProgressDialog() // } // ALERT_DIALOG_SHOW->{ // var title = msg.data.getString(TITLE) // var message = msg.data.getString(MSG) // if (title != null && message!=null) { // showMessage(title, message) // } // } // } // } // } // // /** // * To receive the message // * You must implement a handler in the activity, and pass it in. // */ // open fun notifyActivity(mHandler: Handler, mBundle: Bundle?, what: Int){ // mHandler.sendMessage(createMessage(mBundle,what)) // } // // /** // * Create a Message and return // */ // open fun createMessage(mBundle: Bundle? , what: Int): Message { // val mMessage = Message() // mMessage.data = mBundle // mMessage.what = what // return mMessage // } // // /** // * Send a message to dialog handler // */ // open fun sendMessage(mBundle: Bundle?, what:Int){ // dialogHandler?.sendMessage(createMessage(mBundle, what)) // } // // /** // * Send message to show ProgressDialog // */ // open fun sendProgressDialogShowMessage() { // sendMessage(Bundle(), PROGRESS_DIALOG_SHOW) // } // // /** // * Send message to close ProgressDialog // */ // open fun sendProgressDialogCloseMessage() { // sendMessage(Bundle(), PROGRESS_DIALOG_CLOSE) // } // // /** // * Send message to show AlertDialog // */ // open fun sendMessage(message: String, title: String) { // val mBundle = Bundle() // mBundle.putString(MSG, message) // mBundle.putString(TITLE, title) // sendMessage(mBundle, ALERT_DIALOG_SHOW) // } // // // /** // * Get request // * Asynchronous calls to server api // * func, the api // * handleMsg, the message type // * handler, the handler that deal with the data returned by server. // */ // open fun get(func: String, handleMsg: Int, handler: Handler, mContext:Context) { // this.mContext = mContext // sendProgressDialogShowMessage() // val request = Request.Builder() // .url(BASE_URL + func) // .build() // client.newCall(request).enqueue(object : Callback { // // override fun onFailure(call: Call, e: IOException) { // sendProgressDialogCloseMessage() // e.printStackTrace() // } // // override fun onResponse(call: Call, response: Response) { // response.use { // sendProgressDialogCloseMessage() // // if (!response.isSuccessful) { // sendMessage("Cannot connect to the local web server.",SERVER_ERROR) // throw IOException() // } // var data = response.body!!.string() // // var bundle = Bundle() // bundle.putString(MSG, data) // notifyActivity(mHandler = handler, bundle, ALL_USER_MSG) // } // } // }) // } // // /** // * Post request // * Asynchronous calls to server api // * func, the api // * handleMsg, the message type // * handler, the handler that deal with the data returned by server. // */ // open fun login( // username: String, // password: String, // handler: Handler, // mContext: Context // ) { // this.mContext = mContext // val builder = FormBody.Builder() // builder.add("username", username) // builder.add("password", password) // post("login", builder, handler, ALL_USER_MSG) // } // // open fun post( // func: String, // params:FormBody.Builder, // handler: Handler, // what: Int // ) { // // sendProgressDialogShowMessage() // val formBody = params.build() // val request = Request.Builder() // .url(BASE_URL + func) // .post(formBody) // .build() // client.newCall(request).enqueue(object : Callback { // // override fun onFailure(call: Call, e: IOException) { // sendProgressDialogCloseMessage() // e.printStackTrace() // } // // override fun onResponse(call: Call, response: Response) { // response.use { // sendProgressDialogCloseMessage() // if (response.code == 401) { // sendMessage("Incorrect user or password input", "Login fail") // } // else if (!response.isSuccessful) { // sendMessage("Cannot connect to the local web server.",SERVER_ERROR) // throw IOException() // } // var data = response.body!!.string() // val mBundle = Bundle() // mBundle.putString(MSG, data) // notifyActivity(handler, mBundle, what) // } // } // }) // } //}
TranslateMe-App/client/app/src/main/java/com/wordle/client/util/ProgressDialog.kt
3882120602
package com.wordle.client.util import android.app.AlertDialog import android.content.Context import android.graphics.Color import android.view.Gravity import android.view.ViewGroup import android.view.Window import android.view.WindowManager import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView /** * Using code to show the progress dialog when we need to let the user waiting */ open class ProgressDialog { lateinit var dialog: AlertDialog /** * Close the dialog */ fun closeProgress(){ if(dialog!=null){ dialog.dismiss() } } /** * Show the dialog */ fun showProgress(mContext: Context?){ val llPadding = 30 val ll = LinearLayout(mContext) ll.orientation = LinearLayout.HORIZONTAL ll.setPadding(llPadding, llPadding, llPadding, llPadding) ll.gravity = Gravity.CENTER var llParam = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) llParam.gravity = Gravity.CENTER ll.layoutParams = llParam val progressBar = ProgressBar(mContext) progressBar.isIndeterminate = true progressBar.setPadding(0, 0, llPadding, 0) progressBar.layoutParams = llParam llParam = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) llParam.gravity = Gravity.CENTER val tvText = TextView(mContext) tvText.text = "Loading ..." tvText.setTextColor(Color.parseColor("#000000")) tvText.textSize = 20f tvText.layoutParams = llParam ll.addView(progressBar) ll.addView(tvText) val builder: AlertDialog.Builder = AlertDialog.Builder(mContext) builder.setCancelable(false) builder.setView(ll) dialog = builder.create() dialog.show() val window: Window? = dialog.window if (window != null) { val layoutParams = WindowManager.LayoutParams() layoutParams.copyFrom(window.getAttributes()) layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT window.setAttributes(layoutParams) } } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/util/HttpLogger.kt
947671958
package com.wordle.client.util import android.util.Log import okhttp3.logging.HttpLoggingInterceptor class HttpLogger: HttpLoggingInterceptor.Logger { /** * Log the request and response */ override fun log(message: String) { Log.d("TranslateMe, Http Info:", message) } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Favorites.kt
3071400127
package com.wordle.client.entity /** * The response body is : * * { "data": { "translations": [{"translatedText": "¡Hola Mundo!"}] } } */ class Favorites(from:String, to:String, from_text:String, to_Text:String) { private lateinit var from: String private lateinit var to: String private lateinit var from_text: String private lateinit var to_text: String fun getFrom():String{ return from } fun getTo():String{ return to } fun getFromText():String{ return from_text } fun getToText():String{ return to_text } init{ this.from = from this.to = to this.from_text = from_text this.to_text = to_Text } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Translation.kt
3722426191
package com.wordle.client.entity /** * The response body is : * * { "data": { "translations": [{"translatedText": "¡Hola Mundo!"}] } } */ class Translation { private lateinit var translations: List<Translations> fun getTranslations():List<Translations>{ return translations } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Languages.kt
678272777
package com.wordle.client.entity import org.intellij.lang.annotations.Language /** * The response body is : * * { "data": { "translations": [{"translatedText": "¡Hola Mundo!"}] } } */ class Languages { private lateinit var language: String private lateinit var name: String private var supports_formality: Boolean = false fun getLanguage():String{ return language } fun getName():String{ return name } fun getSupportsFormality():Boolean{ return supports_formality } fun setLanguage(language: String){ this.language = language } fun setName(name: String){ this.name = name } fun setSupportsFormality(supports_formality: Boolean){ this.supports_formality = supports_formality } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Currency.kt
767415519
package com.wordle.client.entity class Currency( // BASE CURRENCY = US DOLLARS // var USD: Double, // NEW ZEALAND DOLLARS var NZD: Double, // AUSTRALIA DOLLARS var AUD: Double, // BRITISH POUND var GBP: Double, // EUROPE EUROS var EUR: Double, // CANADA DOLLARS var CAD: Double, // MEXICO PESOS var MXN: Double, )
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Request.kt
216357645
package com.wordle.client.entity class Request( // ALL VARIABLE BELOW REFER TO DATA FROM JSON FILE: SEE README.md // SUCCESS OR FAILURE var result: String, // LAST TIME DATA WAS UPDATED var time_last_update_utc: String, // NEXT TIME DATA WILL BE UPDATED var time_next_update_utc: String, // IMPLEMENT BASE CODE: USD = US DOLLARS var base_code: String, // CURRENT RATE OF CURRENCY var rates: Currency )
TranslateMe-App/client/app/src/main/java/com/wordle/client/entity/Translations.kt
764375623
package com.wordle.client.entity class Translations { private lateinit var detected_source_language: String private lateinit var text:String fun getDetectedSourceLanguage():String{ return detected_source_language } fun getText():String{ return text } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/LoadingActivity.kt
3601957561
package com.wordle.client import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.content.Intent import android.os.Handler import android.os.Looper import android.view.WindowManager import android.widget.ProgressBar import android.widget.TextView @Suppress("DEPRECATION") class LoadingActivity : AppCompatActivity() { private var progressBar: ProgressBar? = null private var i = 0 private var txtView: TextView? = null private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_loading) // finding progressbar by its id progressBar = findViewById<ProgressBar>(R.id.progress_Bar) as ProgressBar // finding textview by its id txtView = findViewById<TextView>(R.id.text_view) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) // we used the postDelayed(Runnable, time) method // to send a message with a delayed time. //Normal Handler is deprecated , so we have to change the code little bit // Handler().postDelayed({ Handler(Looper.getMainLooper()).postDelayed({ val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }, 1000) // 5000 is the delayed time in milliseconds. } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/HomeViewModel.kt
3483509916
package com.wordle.client.fragment import androidx.lifecycle.ViewModel class HomeViewModel : ViewModel() { // the text before translated var translateText:String="" // the text after translated var translatedText:String="" // from which language var from:String="" // to which language var to:String="ES" // is darkmode var isDarkMode: Boolean=false }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/FavoriteViewModel.kt
2779030655
package com.wordle.client.fragment import androidx.lifecycle.ViewModel class FavoriteViewModel : ViewModel() { // TODO: Implement the ViewModel }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/SettingsFragment.kt
1384273578
package com.wordle.client.fragment import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.wordle.client.R class SettingsFragment : Fragment() { companion object { fun newInstance() = SettingsFragment() } private lateinit var viewModel: SettingsViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_settings, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(SettingsViewModel::class.java) // TODO: Use the ViewModel } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/CurrencyViewModel.kt
3344356406
package com.wordle.client.fragment import androidx.lifecycle.ViewModel class CurrencyViewModel : ViewModel() { // TODO: Implement the ViewModel }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/SettingsViewModel.kt
1553774175
package com.wordle.client.fragment import androidx.lifecycle.ViewModel class SettingsViewModel : ViewModel() { // TODO: Implement the ViewModel }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/BottomDialogSheetFragment.kt
847278712
package com.wordle.client.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.Button import android.widget.ListView import android.widget.TextView import com.andrefrsousa.superbottomsheet.SuperBottomSheetFragment import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.wordle.client.R import com.wordle.client.entity.Languages open class BottomDialogSheetFragment(isFrom:Boolean, homeFragment: HomeFragment): SuperBottomSheetFragment() { var isFrom:Boolean = false var homeFragment: HomeFragment init{ this.isFrom = isFrom this.homeFragment = homeFragment } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) // the layout for the dialog var root = layoutInflater.inflate(R.layout.dialog_show_from_bottom, null) // the listview for the dialog var listView: ListView = root.findViewById(R.id.listview) var title: TextView = root.findViewById(R.id.title) var detectButton: Button = root.findViewById(R.id.detect_language) var searchView:androidx.appcompat.widget.SearchView = root.findViewById(R.id.searchview) var languageList:MutableList<Languages> = homeFragment.loadLanguagesLocally() // listview adapter listView.adapter = HomeFragment.LanguagesAdapter(context, languageList) // listview item click listener listView.setOnItemClickListener(languagesItemClickListener) if(isFrom){ listView.tag=homeFragment.TAG_FROM_LANGUAGE title.setText(R.string.translate_from) } else { listView.tag=homeFragment.TAG_TO_LANGUAGE title.setText(R.string.translate_to) detectButton.visibility = View.INVISIBLE } detectButton.setOnClickListener { // only supports from original text homeFragment.binding.fromLanguage.setText(R.string.detect_language) homeFragment.viewModel.from = "" dismiss() } searchView.setOnQueryTextListener(object: androidx.appcompat.widget.SearchView.OnQueryTextListener { override fun onQueryTextSubmit(p0: String?): Boolean { return false } override fun onQueryTextChange(p0: String?): Boolean { val filterList = mutableListOf<Languages>() languageList.forEach { if(it.getName().contains(p0!!)){ filterList.add(it) } } listView.adapter = HomeFragment.LanguagesAdapter(context, filterList) return false } }) return root } /** * The languages list item click listener */ var languagesItemClickListener: AdapterView.OnItemClickListener = AdapterView.OnItemClickListener{ adapterView: AdapterView<*>, view1: View, i: Int, l: Long -> if(adapterView.tag!=null) { // get which language the user click var language: Languages = adapterView.getItemAtPosition(i) as Languages if(adapterView.tag == homeFragment.TAG_FROM_LANGUAGE){ // update the text of the language homeFragment.binding.fromLanguage.text = language.getName() // set the abbreviation for the language, this will be send to the homeFragment.viewModel.from = language.getLanguage() } else if (adapterView.tag == homeFragment.TAG_TO_LANGUAGE){ // update the text of the language homeFragment.binding.toLanguage.text = language.getName() // set the abbreviation for the language, this will be send to the homeFragment.viewModel.to = language.getLanguage() } dismiss() } } override fun getPeekHeight(): Int { super.getPeekHeight() with(resources.displayMetrics) { return heightPixels - 300 } } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/FavoriteFragment.kt
418743
package com.wordle.client.fragment import android.content.Context import android.content.res.Configuration import android.database.sqlite.SQLiteDatabase import androidx.lifecycle.ViewModelProvider import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.wordle.client.R import com.wordle.client.databinding.FragmentFavoriteBinding import com.wordle.client.databinding.FragmentHomeBinding import com.wordle.client.entity.Favorites import com.wordle.client.entity.Languages import com.wordle.client.util.LocalDBHelper import java.lang.Exception class FavoriteFragment : Fragment() { companion object { fun newInstance() = FavoriteFragment() } private val viewModel: FavoriteViewModel by activityViewModels() // Using binding to init all layout elements private lateinit var binding: FragmentFavoriteBinding // Local db util helper private var dbHelper: LocalDBHelper? =null // Local db object private var db:SQLiteDatabase? = null private val TAG = FavoriteFragment::class.java.name override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Using binding to do the findViewbyId things binding = FragmentFavoriteBinding.inflate(layoutInflater) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // TODO: Use the ViewModel // Initialize the local db helper dbHelper = LocalDBHelper(context) var layoutManager:RecyclerView.LayoutManager?= null // Dynamically choose layout based on the orientation of device if(resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE){ layoutManager = GridLayoutManager(context,3) layoutManager.orientation = LinearLayoutManager.VERTICAL } else if(resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT){ layoutManager = LinearLayoutManager(context) } binding.listview.layoutManager = layoutManager binding.listview.adapter = FavoritesRecyclearViewAdapter(context, loadFavoritesLocally()) } /** * Load languages from the local database */ fun loadFavoritesLocally():MutableList<Favorites>{ var favorites:MutableList<Favorites> = mutableListOf() // find all the languages like "select * from languages" statement var cursor = getDB()?.query("favorites",null,null,null,null,null,null) if(cursor!!.moveToFirst()){ do{ var fav = Favorites(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)) favorites.add(fav) } while(cursor.moveToNext()) } return favorites } inner class FavoritesRecyclearViewAdapter(val context: Context?, var data:MutableList<Favorites>):RecyclerView.Adapter<FavoritesRecyclearViewAdapter.ViewHolder>(){ inner class ViewHolder(view: View):RecyclerView.ViewHolder(view) { val from:TextView = view.findViewById(R.id.from_language) val to:TextView = view.findViewById(R.id.to_language) val fromText:TextView = view.findViewById(R.id.from_text_language) val toText:TextView = view.findViewById(R.id.to_text_language) val deleteButton:Button = view.findViewById(R.id.deleteButton) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoritesRecyclearViewAdapter.ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.listview_item_favorite, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(vh: ViewHolder, position: Int) { var favorite:Favorites = data.get(position) vh.from.text = favorite.getFrom() vh.to.text = favorite.getTo() vh.fromText.text = favorite.getFromText() vh.toText.text = favorite.getToText() vh.deleteButton.setOnClickListener{ try { if(removeFromDB(favorite)) { Log.d(TAG, "Delete item succeesfully!") data.remove(favorite) binding.listview.adapter = FavoritesRecyclearViewAdapter(context, data) } else{ Log.d(TAG, "Delete item failed!") } } catch (e:Exception){ Log.d(TAG, "Delete item failed!") Toast.makeText(context, "Failed to remove item", Toast.LENGTH_SHORT).show() } } } } /** * Delete a favorite item from local database */ fun removeFromDB(favorites: Favorites):Boolean{ return getDB()?.delete("favorites", "from_text=? and to_text=?", arrayOf(favorites.getFromText(), favorites.getToText()))!! >0 } /** * Get the local database object */ fun getDB(): SQLiteDatabase?{ if (db==null){ try { db = dbHelper?.writableDatabase Log.d(TAG, "SQLite write mode") } catch (e: Exception){ db = dbHelper?.readableDatabase Log.d(TAG, "SQLite read mode") } } return db } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/HomeFragment.kt
3105312738
package com.wordle.client.fragment import android.app.Activity import android.content.* import android.database.sqlite.SQLiteDatabase import android.os.Bundle import android.speech.tts.TextToSpeech import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.appcompat.app.AppCompatDelegate import androidx.datastore.core.DataStore import androidx.datastore.dataStore import androidx.datastore.preferences.core.* import androidx.datastore.preferences.preferencesDataStore import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.wordle.client.R import com.wordle.client.databinding.FragmentHomeBinding import com.wordle.client.entity.Favorites import com.wordle.client.entity.Languages import com.wordle.client.entity.Translation import com.wordle.client.util.LocalDBHelper import com.wordle.client.util.ProgressDialog import com.wordle.client.util.RetrofitClient import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.runBlocking import retrofit2.Call import retrofit2.Callback import retrofit2.Response class HomeFragment : Fragment() { companion object { fun newInstance() = HomeFragment() } // Using binding to init all layout elements lateinit var binding:FragmentHomeBinding // Using videModel to store data val viewModel: HomeViewModel by activityViewModels() // Local db util helper private var dbHelper:LocalDBHelper? =null // Local db object private var db:SQLiteDatabase? = null // The tag for this Fragment private val TAG = HomeFragment::class.java.name // The tag of the textview val TAG_FROM_LANGUAGE = 0x3 // The tag of the textview val TAG_TO_LANGUAGE = 0x4 var initListener = TextToSpeech.OnInitListener { if(it == TextToSpeech.SUCCESS){ Log.d(TAG, "TTS is speaking") } else { Log.d(TAG, "TTS can't work") } } lateinit var tts:TextToSpeech // val NIGHT_MODE = "night_mode" // // private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name=NIGHT_MODE) // // object PreferenceKeys{ // val NIGHT_MODE_KEY = stringPreferencesKey("mode_key") // } // // private suspend fun Context.saveNightMode(mode:String){ // dataStore.edit { // it[PreferenceKeys.NIGHT_MODE_KEY] = mode // } // } // // suspend fun Context.getNightMode() = dataStore.data.catch {exception-> // emit(emptyPreferences()) // }.map { // val mode = it[PreferenceKeys.NIGHT_MODE_KEY]?:-1 // // return@map mode // } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.i(TAG, " onCreateView") // Using binding to do the findViewbyId things binding = FragmentHomeBinding.inflate(layoutInflater) // Set the onclick event for the textview(from language) binding.fromLanguage.setOnClickListener(buttonClickListener) // Set the onclick event for the textview((to language) binding.toLanguage.setOnClickListener(buttonClickListener) // set the translate button click listener binding.translateToButton.setOnClickListener(buttonClickListener) binding.markButton.setOnClickListener(buttonClickListener) binding.copyButton.setOnClickListener(buttonClickListener) binding.swapImage.setOnClickListener(buttonClickListener) binding.fromEdittext.setText(viewModel.translateText) binding.play1Button.setOnClickListener(buttonClickListener) binding.play2Button.setOnClickListener(buttonClickListener) binding.darkmodeButton.setOnCheckedChangeListener{ buttonView, isChecked-> viewModel.isDarkMode = isChecked if (isChecked) { Log.e("Msg","Night mode button switch on") AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { Log.e("Msg","Night mode button switch off") AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } } binding.fromEdittext.addTextChangedListener ( object :TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(p0: Editable?) { viewModel.translateText = p0.toString() if(isBookmarkExisted()!=null){ binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24) } else{ binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_border_24) } } }) binding.translatedTextview.setText(viewModel.translatedText) binding.darkmodeButton.isChecked = viewModel.isDarkMode return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Initialize the local db helper dbHelper = LocalDBHelper(context) // Load all the languages from local database var languages = loadLanguagesLocally() // if the data is empty in the local database, then fetch from restful api if(languages == null || languages.size<1){ fetchLanguages() } if(isBookmarkExisted()!=null){ binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24) } tts = TextToSpeech(context,initListener) } /** * Handle all button clicklistener in one function */ private var buttonClickListener:View.OnClickListener = View.OnClickListener { if(it == binding.fromLanguage || it == binding.toLanguage){ chooseLanguage(it==binding.fromLanguage) } else if (it == binding.translateToButton){ translate() } else if (it == binding.markButton){ bookmark() } else if (it == binding.copyButton) run { if(binding.translatedTextview.text.toString().isEmpty()){ Toast.makeText(context, R.string.error_copy_translated_language, Toast.LENGTH_SHORT).show() return@OnClickListener } var cm: ClipboardManager = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager var clipData:ClipData = ClipData.newPlainText("Label", binding.toLanguage.text.toString()) cm.setPrimaryClip(clipData) Toast.makeText(context,R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show() } else if (it==binding.swapImage){ if(viewModel.from.equals("")){ Toast.makeText(context,R.string.error_from_language, Toast.LENGTH_SHORT).show() return@OnClickListener } // exchange val tempFrom = viewModel.from val tempText = binding.fromLanguage.text binding.fromLanguage.text = binding.toLanguage.text binding.toLanguage.text = tempText viewModel.from = viewModel.to viewModel.to = tempFrom } else if (it == binding.play2Button){ tts.speak(binding.translatedTextview.text.toString(), TextToSpeech.QUEUE_FLUSH, null, null) } else if (it==binding.play1Button){ tts.speak(binding.fromEdittext.text.toString(), TextToSpeech.QUEUE_FLUSH, null, null) } } /** * Choose a language from a pop up dialog */ private fun chooseLanguage(isFrom:Boolean){ // The bottom sheet dialog will show BottomDialogSheetFragment(isFrom, this).show(requireActivity().supportFragmentManager,"BottomDialogSheetFragment") } /** * Check if the book mark is already existed */ private fun isBookmarkExisted(): Favorites? { var cursor = getDB()?.query("favorites",null,"from_text=? and to_text=?", arrayOf(binding.fromEdittext.text.toString(), binding.translatedTextview.text.toString()),null,null,null) if(cursor!!.moveToFirst()){ do{ var fav = Favorites(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)) return fav } while(cursor.moveToNext()) } return null } /** * Book mark */ private fun bookmark(){ // If the book mark is existed val fav = isBookmarkExisted() if(fav!=null){ if(getDB()?.delete("favorites", "from_text=? and to_text=?", arrayOf(fav.getFromText(), fav.getToText()))!! >0){ binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_border_24) Log.d(TAG, "bookmark remove!") } else{ Log.d(TAG, "bookmark remove failed!") } } else { val content = ContentValues().apply { // only save those supported language put("_from", binding.fromLanguage.text.toString()) put("_to", binding.toLanguage.text.toString()) put("from_text", binding.fromEdittext.text.toString()) put("to_text", binding.translatedTextview.text.toString()) } getDB()?.insert("favorites", null, content) binding.markButton.setBackgroundResource(R.drawable.ic_baseline_bookmark_24) } } private fun translate(){ val inputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(view?.windowToken, 0) // record the click event Log.i(TAG, "Translate button are clicked.") // get the text user input val text = binding.fromEdittext.text.toString() if (checkTranslateText(text)){ // translate service api val api = RetrofitClient.translateService // progress dialog var dialog = ProgressDialog() // show the progress dialog.showProgress(context) var from = "" if(viewModel.from!=null){ from = viewModel.from var fromList:List<String> = from.split("-") if(fromList.size>1){ from = fromList.get(0) } } // call restful api, post request. api.translate(text,from, viewModel.to).enqueue(object : Callback<Translation> { override fun onResponse( call: Call<Translation>, response: Response<Translation> ) { println(response.body()) var translated: Translation? = response.body() if (translated != null) { Log.d(TAG, "Translated success, $text") Log.d( TAG, "detected_source_language: ${translated.getTranslations()[0].getDetectedSourceLanguage()}" ) Log.d(TAG, "text: ${translated.getTranslations()[0].getText()}") binding.translatedTextview.setText(translated.getTranslations()[0].getText()) viewModel.translatedText = binding.translatedTextview.text.toString() } dialog.closeProgress() } override fun onFailure(call: Call<Translation>, t: Throwable) { Log.e(TAG, "Translated failed, $text") dialog.closeProgress() } }) } } private fun checkTranslateText(text:String):Boolean{ if (text.isEmpty()){ Toast.makeText(context, R.string.empty_string_checking, Toast.LENGTH_SHORT).show() } return !text.isEmpty() } /** * Load languages from the local database */ fun loadLanguagesLocally():MutableList<Languages>{ var languages:MutableList<Languages> = mutableListOf() // find all the languages like "select * from languages" statement var cursor = getDB()?.query("languages",null,null,null,null,null,null) if(cursor!!.moveToFirst()){ do{ var lan = Languages() lan.setLanguage(cursor.getString(1)) lan.setName(cursor.getString(2)) lan.setSupportsFormality(cursor.getInt(3)>0) // add the languages to a mutable list languages?.add(lan) } while(cursor.moveToNext()) } return languages } /** * Fetch all languages from the remote restful service. */ fun fetchLanguages(){ // custom progress dialog var dialog = ProgressDialog() // show the progress dialog to let the user wait dialog.showProgress(context) // translate service api val api = RetrofitClient.translateService // async run api.languages().enqueue(object : Callback<List<Languages>> { override fun onResponse(call: Call<List<Languages>>, response: Response<List<Languages>>) { Log.d(TAG,response.body().toString()) if(response.isSuccessful){ var languages: List<Languages>? = response.body() if (languages != null) { for (language in languages){ val content = ContentValues().apply { // only save those supported language put("language", language.getLanguage()) put("name", language.getName()) put("supports_formality", language.getSupportsFormality()) } if(content!=null) getDB()?.insert("languages", null , content) } Log.d(TAG, "Fetched all languages") } } else{ Toast.makeText(context, R.string.fetch_data_fail, Toast.LENGTH_SHORT).show() } dialog.closeProgress() } override fun onFailure(call: Call<List<Languages>>, t: Throwable) { Log.e(TAG,"Fetch languages failed!") Toast.makeText(context, R.string.fetch_data_fail, Toast.LENGTH_SHORT).show() dialog.closeProgress() } }) } /** * Get the local database object */ fun getDB():SQLiteDatabase?{ if (db==null){ try { db = dbHelper?.writableDatabase Log.d(TAG, "SQLite write mode") } catch (e:Exception){ db = dbHelper?.readableDatabase Log.d(TAG, "SQLite read mode") } } return db } /** * The languages adapter for the bottom sheet dialog */ open class LanguagesAdapter(val context: Context?, var data:MutableList<Languages>): BaseAdapter() { override fun getCount(): Int { return data.size } override fun getItem(p0: Int): Any { return data.get(p0) } override fun getItemId(p0: Int): Long { return p0.toLong() } inner class ViewHolder(v: View) { val name: TextView = v.findViewById(R.id.name) } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var vh: ViewHolder? =null val view: View if (convertView == null) { view = LayoutInflater.from(context).inflate(R.layout.listview_item_language, parent, false) vh = ViewHolder(view) view.tag = vh } else{ view = convertView vh = view.tag as ViewHolder } var languages:Languages = getItem(position) as Languages if (languages!=null){ if (vh != null) { vh.name.text = languages.getName() } } return view } } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/fragment/CurrencyFragment.kt
3181761521
@file:Suppress("DEPRECATION") package com.wordle.client.fragment import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import com.google.gson.Gson import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView import com.wordle.client.databinding.FragmentCurrencyBinding import com.wordle.client.entity.Request import java.io.InputStreamReader import java.net.URL import javax.net.ssl.HttpsURLConnection class CurrencyFragment : Fragment() { // SET VARIABLE FOR VIDEO VIEW // SET VARIABLE BINDING TO FRAGMENT CURRENCY BINDING private lateinit var binding: FragmentCurrencyBinding // SET VARIABLE VIEW MODEL TO FRAGMENT CURRENCY VIEW-MODEL private lateinit var viewModel: CurrencyViewModel // private var youTubePlayerView: YouTubePlayerView? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentCurrencyBinding.inflate(layoutInflater) fetchCurrencyData().start() return binding.root } @Deprecated("Deprecated in Java") override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this)[CurrencyViewModel::class.java] } override fun onStop() { super.onStop() } override fun onDestroy() { super.onDestroy() } override fun onResume() { super.onResume() } // FETCH DATA FROM API @SuppressLint("SetTextI18n") private fun fetchCurrencyData(): Thread { return Thread { // PLACE API URL IN A VARIABLE val url = URL("https://open.er-api.com/v6/latest/USD") // USE VARIABLE CONNECTION AS HTTPS CONNECTION val connection = url.openConnection() as HttpsURLConnection // IF CONNECTION RESPONSE IS EQUAL TO 200 (OK) if (connection.responseCode == 200) { // val inputSystem = connection.inputStream // THEN LOG (LOGCAT) RESULTS // println(inputSystem.toString()) val inputStreamReader = InputStreamReader(inputSystem, "UTF-8") // val request = Gson().fromJson(inputStreamReader, Request::class.java) // UPDATE OUR FUNCTION UI REQUEST updateUI(request) inputStreamReader.close() inputSystem.close() } else { // ELSE LOG "FAILED TO CONNECT" binding.baseCurrency.text = "Failed to Connect!" } } } private fun updateUI(request: Request) { // requireActivity().runOnUiThread { kotlin.run { binding.lastUpdated.text = String.format("Updated: " + request.time_last_update_utc) binding.nextUpdated.text = String.format("Next Update: " + request.time_next_update_utc) binding.nzd.text = String.format("NZD: %.2f", request.rates.NZD) binding.aud.text = String.format("AUD: %.2f", request.rates.AUD) binding.gbp.text = String.format("GBP: %.2f", request.rates.GBP) binding.eur.text = String.format("EUR: %.2f", request.rates.EUR) binding.cad.text = String.format("CAD: %.2f", request.rates.CAD) binding.mxn.text = String.format("MXN: %.2f", request.rates.MXN) } } } }
TranslateMe-App/client/app/src/main/java/com/wordle/client/interfaces/TranslateService.kt
1469214367
package com.wordle.client.interfaces import com.wordle.client.entity.Languages import com.wordle.client.entity.Translation import retrofit2.Call import retrofit2.http.* /** * Deeply translate service * translate: Post * fetch supported languages: Get */ interface TranslateService { @FormUrlEncoded @Headers("Authorization: DeepL-Auth-Key 07db4d6f-087c-fd9e-4432-39527b7ba521:fx") @POST("v2/translate") fun translate(@Field("text") q:String, @Field("source_lang") source_lang:String, @Field("target_lang") target_lang:String): Call<Translation> @Headers("Authorization: DeepL-Auth-Key 07db4d6f-087c-fd9e-4432-39527b7ba521:fx") @GET("v2/languages?type=target") fun languages(): Call<List<Languages>> }
Depression.Detection./app/src/androidTest/java/com/example/detectdepression/ExampleInstrumentedTest.kt
112820263
package com.example.detectdepression 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.detectdepression", appContext.packageName) } }
Depression.Detection./app/src/test/java/com/example/detectdepression/ExampleUnitTest.kt
1835145531
package com.example.detectdepression 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) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/DoctorLoginActivity.kt
1508493995
package com.example.detectdepression import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityDoctorLoginBinding class DoctorLoginActivity : AppCompatActivity() { private lateinit var binding : ActivityDoctorLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@DoctorLoginActivity,R.layout.activity_doctor_login) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/PersonalInfoFragment.kt
3037044697
package com.example.detectdepression import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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"
Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/AddPatientFragment.kt
1500517751
package com.example.detectdepression.operationFragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.detectdepression.R import com.example.detectdepression.databinding.FragmentAddPatientBinding class AddPatientFragment : Fragment() { private lateinit var binding : FragmentAddPatientBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentAddPatientBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnGenerateID.setOnClickListener { } } }
Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/SettingsFragment.kt
2224449234
package com.example.detectdepression.operationFragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.detectdepression.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 [SettingsFragment.newInstance] factory method to * create an instance of this fragment. */ class SettingsFragment : 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_settings, 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 SettingsFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = SettingsFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Depression.Detection./app/src/main/java/com/example/detectdepression/operationFragments/HomeFragment.kt
1864221888
package com.example.detectdepression.operationFragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.detectdepression.R import com.example.detectdepression.databinding.FragmentHomeBinding class HomeFragment : Fragment() { private lateinit var binding : FragmentHomeBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentHomeBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/MainActivity.kt
2684226484
package com.example.detectdepression import android.annotation.SuppressLint import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.View import android.widget.EditText import android.widget.Toast import androidx.annotation.RequiresApi import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityMainBinding import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Date import java.util.Objects class MainActivity : AppCompatActivity() { //binding private lateinit var binding : ActivityMainBinding //firestore private lateinit var db : FirebaseFirestore //collection name private var PATIENT_DETAIL_COLLECTION = "PatientDetails" //arraylist of questions var questions = ArrayList<String>() //details lateinit var patientName : String lateinit var patientAge : String lateinit var patientPhoneNumber : String lateinit var patientEmail : String lateinit var date : String private val PATIENT_ID = "PatientId" private var DOC_NAME = "DoctorName" lateinit var docName : String lateinit var patientId : String lateinit var patientGender : String var score : String = "none" var objectiveDepressionLevel = "none" var subjectiveDepressionLevel = "none" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this,R.layout.activity_main) db = FirebaseFirestore.getInstance() docName = intent.getStringExtra(DOC_NAME)!! patientId = intent.getStringExtra(PATIENT_ID)!! binding.progressBar.visibility = View.INVISIBLE } // private fun loadData() { // GlobalScope.launch(Dispatchers.IO) { // // } // } // private fun applyEditTextChnages() { // binding.apply { // edtName.addTextChangedListener(changeBackground(binding.edtName)) // edtAge.addTextChangedListener(changeBackground(binding.edtAge)) // edtPhoneNumber.addTextChangedListener(changeBackground(binding.edtPhoneNumber)) // edtEmail.addTextChangedListener(changeBackground(binding.edtEmail)) // } // } @RequiresApi(Build.VERSION_CODES.O) fun btnNextClicked(view : View) { binding.apply { progressBar.visibility = View.VISIBLE patientName = edtName.text.toString().trim() patientAge = edtAge.text.toString().trim() patientPhoneNumber = edtPhoneNumber.text.toString().trim() patientEmail = edtEmail.text.toString().trim() //deal with it if (TextUtils.isEmpty(patientName)) { edtName.setBackgroundColor(resources.getColor(R.color.purple_200)) } else { edtName.background = null } if (TextUtils.isEmpty(patientAge)) { edtAge.setBackgroundColor(resources.getColor(R.color.purple_200)) } else { edtAge.background = null } if (TextUtils.isEmpty(patientPhoneNumber)) { edtPhoneNumber.setBackgroundColor(resources.getColor(R.color.purple_200)) } else { edtPhoneNumber.background = null } if (TextUtils.isEmpty(patientEmail)) { edtEmail.setBackgroundColor(resources.getColor(R.color.purple_200)) } else { edtEmail.background = null } if (radioGroupGender.checkedRadioButtonId != -1) { patientGender = when(radioGroupGender.checkedRadioButtonId) { R.id.rbMale -> "Male" R.id.rbFemale -> "Female" else -> "Other" } } else { rbFemale.setBackgroundColor(resources.getColor(R.color.purple_200)) rbMale.setBackgroundColor(resources.getColor(R.color.purple_200)) rbOther.setBackgroundColor(resources.getColor(R.color.purple_200)) } if (!(TextUtils.isEmpty(patientName) || TextUtils.isEmpty(patientAge) || TextUtils.isEmpty(patientPhoneNumber) || TextUtils.isEmpty(patientEmail))) { var details = hashMapOf( "Id" to patientId, "Name" to patientName, "Age" to patientAge, "Gender" to patientGender, "Phone Number" to patientPhoneNumber, "Email" to patientEmail, "Doc Name" to docName, "Date" to FieldValue.serverTimestamp(), "Score" to 0, "Result" to "No" ) db.collection(PATIENT_DETAIL_COLLECTION).document(patientId).set(details).addOnSuccessListener { val intent = Intent(this@MainActivity,InfoActivty::class.java) intent.putExtra(PATIENT_ID,patientId) intent.putExtra(DOC_NAME,docName) startActivity(intent) finish() }.addOnFailureListener { Toast.makeText(this@MainActivity,"Ooops!! Something went wrong...",Toast.LENGTH_SHORT).show() } } } } // fun changeBackground(editText : EditText) : TextWatcher{ // // val textWatcher = object : TextWatcher { // override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // // } // // override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // // } // // @SuppressLint("UseCompatLoadingForDrawables") // override fun afterTextChanged(s: Editable?) { // if (s.isNullOrBlank()) { // editText.setBackgroundDrawable(getDrawable(R.drawable.empty_editext_background)) // } else { // editText.background = null // } // } // // } // return textWatcher // // } }
Depression.Detection./app/src/main/java/com/example/detectdepression/InfoActivty.kt
2469205858
package com.example.detectdepression import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityInfoActivtyBinding class InfoActivty : AppCompatActivity() { private lateinit var binding : ActivityInfoActivtyBinding private val PATIENT_ID = "PatientId" private var DOC_NAME = "DoctorName" lateinit var docName : String lateinit var patientId : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@InfoActivty,R.layout.activity_info_activty) docName = intent.getStringExtra(DOC_NAME)!! patientId = intent.getStringExtra(PATIENT_ID)!! } fun btnNext(view : View) { var intent = Intent(this@InfoActivty,ObjectiveQuestionsActivity::class.java) intent.putExtra(PATIENT_ID,patientId) intent.putExtra(DOC_NAME,docName) startActivity(intent) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/SplashScreenActivity.kt
3217726547
package com.example.detectdepression import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivitySplashScreenBinding class SplashScreenActivity : AppCompatActivity() { private lateinit var binding : ActivitySplashScreenBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this,R.layout.activity_splash_screen) Handler().postDelayed( Runnable {},2000 ) startActivity(Intent(this@SplashScreenActivity,MainActivity::class.java)) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/OperationsActivity.kt
1521604172
package com.example.detectdepression import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.example.detectdepression.databinding.ActivityOperationsBinding import com.example.detectdepression.models.PatientListItemInfo import com.example.detectdepression.operationFragments.AddPatientFragment import com.example.detectdepression.operationFragments.HomeFragment import com.example.detectdepression.operationFragments.SettingsFragment import com.google.android.material.bottomnavigation.BottomNavigationView class OperationsActivity : AppCompatActivity() { private lateinit var binding : ActivityOperationsBinding var patientListItemInfo = ArrayList<PatientListItemInfo>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@OperationsActivity,R.layout.activity_operations) binding.apply { bottomNavigationOperation.selectedItemId = R.id.homeNavigation bottomNavigationOperation.setOnItemSelectedListener(navListener) } supportFragmentManager.beginTransaction().replace( binding.frameLayout.id, HomeFragment() ).commit() } private val navListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> var selectedFragment: Fragment? = null when (item.itemId) { R.id.addPatientNavigation -> selectedFragment = AddPatientFragment() R.id.homeNavigation -> selectedFragment = HomeFragment() R.id.settingsNavigation -> selectedFragment = SettingsFragment() } supportFragmentManager.beginTransaction().replace( binding.frameLayout.id, selectedFragment!! ).commit() true } }
Depression.Detection./app/src/main/java/com/example/detectdepression/PatientListFragment.kt
3037044697
package com.example.detectdepression import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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"
Depression.Detection./app/src/main/java/com/example/detectdepression/models/PatientListItemInfo.kt
2860831969
package com.example.detectdepression.models data class PatientListItemInfo( var patientName : String, var patientId : String, var date : String, var score : Int )
Depression.Detection./app/src/main/java/com/example/detectdepression/models/PatientLoginInfo.kt
1824263934
package com.example.detectdepression.models data class PatientLoginInfo( var patientId : String, var docName : String )
Depression.Detection./app/src/main/java/com/example/detectdepression/SubjectiveQuestionsActivity.kt
2091694763
package com.example.detectdepression import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivitySubjectiveQuestionsBinding import com.example.detectdepression.ml.Dd import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import org.tensorflow.lite.DataType import org.tensorflow.lite.support.tensorbuffer.TensorBuffer import java.nio.ByteBuffer class SubjectiveQuestionsActivity : AppCompatActivity() { private lateinit var binding : ActivitySubjectiveQuestionsBinding private var QUESTION_NUMBER = 1 private var SUBJECTIVE_QUESTIONS = "SubjectiveQuestions" private var questions = ArrayList<String>() private var TOTAL_QUESTIONS = 0 private var score = 0 private lateinit var reference: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@SubjectiveQuestionsActivity,R.layout.activity_subjective_questions) reference = FirebaseDatabase.getInstance().getReference(SUBJECTIVE_QUESTIONS) // if (questions.size == 0) { // loadQuestions() // } else { // setQuestion() // } binding.btnPrevious.setOnClickListener { btnPrevious() } binding.btnNext.setOnClickListener { btnNext() } } private fun loadQuestions() { binding.apply { progressBar2.visibility = View.VISIBLE constraintLayout.visibility = View.INVISIBLE reference.get().addOnSuccessListener { for (question in it.children) { questions.add(question.value.toString()) TOTAL_QUESTIONS++ } progressBar2.visibility = View.INVISIBLE constraintLayout.visibility = View.VISIBLE setQuestion() }.addOnFailureListener { Toast.makeText(this@SubjectiveQuestionsActivity,"Oops! Something went wrong",Toast.LENGTH_SHORT).show() } } } private fun setQuestion() { binding.apply { // var text = binding.edtAns.text.toString() // val model = Dd.newInstance(this@SubjectiveQuestionsActivity) // //// Creates inputs for reference. // val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 500), DataType.FLOAT32) // inputFeature0.loadBuffer(ByteBuffer.wrap(text.toByteArr // //// Runs model inference and gets result. // val outputs = model.process(inputFeature0) // val outputFeature0 = outputs.outputFeature0AsTensorBuffer // // Toast.makeText(this@SubjectiveQuestionsActivity,outputFeature0.toString(),Toast.LENGTH_SHORT).show() // //// Releases model resources if no longer used. // model.close() // // txtQuestion.text = questions[QUESTION_NUMBER-1] if (QUESTION_NUMBER == 1) { btnPrevious.visibility = View.INVISIBLE btnPrevious.isClickable = false } else { btnPrevious.visibility = View.VISIBLE btnPrevious.isClickable = true btnPrevious.text = "Previous" } if (QUESTION_NUMBER == TOTAL_QUESTIONS) { btnNext.text = "Submit" } else { btnNext.text = "Next" } } } private fun btnPrevious() { if (QUESTION_NUMBER > 1) { QUESTION_NUMBER-- setQuestion() } } fun btnNext() { if (QUESTION_NUMBER == TOTAL_QUESTIONS) { startActivity(Intent(this@SubjectiveQuestionsActivity,TestResultActivity::class.java)) } else { QUESTION_NUMBER++ setQuestion() binding.edtAns.setText("") } } }
Depression.Detection./app/src/main/java/com/example/detectdepression/PatientLoginActivity.kt
2633561224
package com.example.detectdepression import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.View import android.widget.Toast import androidx.compose.material3.rememberTopAppBarState import androidx.compose.ui.text.toLowerCase import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityPatientLoginBinding import com.example.detectdepression.models.PatientLoginInfo import com.google.firebase.Firebase import com.google.firebase.database.database class PatientLoginActivity : AppCompatActivity() { private lateinit var binding : ActivityPatientLoginBinding private val PATIENT_ID = "PatientId" private var DOC_NAME = "DoctorName" private val ASSIGNED_PATIENT_LIST = "Assigned Patient List" private var assignedPatientList = ArrayList<PatientLoginInfo>() private var PATIENT_LIST = "Patient Login List" private val databaseReference = Firebase.database override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this,R.layout.activity_patient_login) } fun btnNext(view : View) { binding.apply { var temp = 0 var patientId = edtPatientIdLogin.text.toString().trim() var docName = edtDocNameLogin.text.toString().trim() if (!TextUtils.isEmpty(patientId) && !TextUtils.isEmpty(docName)) { for (patient in assignedPatientList) { if (patient.patientId == patientId.trim() && patient.docName.toLowerCase() == docName.trim().toLowerCase()) { temp = 1 break; } } if (temp == 1) { var intent = Intent(this@PatientLoginActivity,InfoActivty::class.java) intent.putExtra(PATIENT_ID,patientId) intent.putExtra(DOC_NAME,docName) startActivity(intent) finish() } else { Toast.makeText(this@PatientLoginActivity,"Authentication Failed!!",Toast.LENGTH_SHORT).show() } } } } override fun onStart() { super.onStart() databaseReference.getReference(ASSIGNED_PATIENT_LIST).get().addOnSuccessListener { for (patient in it.children) { Log.d("TAGY",patient.key.toString() + " " + patient.value.toString()) assignedPatientList.add(PatientLoginInfo(patient.key.toString(),patient.value.toString())) } }.addOnFailureListener { Toast.makeText(this@PatientLoginActivity,"Authentication Failed !!",Toast.LENGTH_SHORT).show() } } fun loginAsDoctor(view: View) { startActivity(Intent(this@PatientLoginActivity,DoctorLoginActivity::class.java)) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/HomeFragment.kt
3037044697
package com.example.detectdepression import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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"
Depression.Detection./app/src/main/java/com/example/detectdepression/PatientListRecyclerViewAdapter.kt
417081186
package com.example.detectdepression import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.detectdepression.databinding.PatientListItemBinding import com.example.detectdepression.models.PatientListItemInfo class PatientListRecyclerViewAdapter(var context: Context,var patientList : MutableList<PatientListItemInfo>) : RecyclerView.Adapter<PatientListRecyclerViewAdapter.MyViewHolder>() { class MyViewHolder(var binding : PatientListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data : PatientListItemInfo) { binding.patientListItemInfo = data } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { return MyViewHolder(PatientListItemBinding.inflate(LayoutInflater.from(context),parent,false)) } override fun getItemCount(): Int { return patientList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(patientList[position]) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/TestResultActivity.kt
4250050642
package com.example.detectdepression import android.app.Activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityTestResultBinding class TestResultActivity : AppCompatActivity() { private lateinit var binding : ActivityTestResultBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this@TestResultActivity,R.layout.activity_test_result) } }
Depression.Detection./app/src/main/java/com/example/detectdepression/ObjectiveQuestionsActivity.kt
1856246273
package com.example.detectdepression import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.databinding.DataBindingUtil import com.example.detectdepression.databinding.ActivityObjectiveQuestionsBinding import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ktx.database import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.ktx.Firebase import io.grpc.Server class ObjectiveQuestionsActivity : AppCompatActivity() { private lateinit var firestore : FirebaseFirestore private lateinit var binding : ActivityObjectiveQuestionsBinding private lateinit var database: FirebaseDatabase private lateinit var reference : DatabaseReference private var PATIENT_RESULTS_COLLECTION = "PatientResults" private var QUESTION_NUMBER = 1 private var SCORE = "score" private var score = 0 private var scoreArray = ArrayList<Int>() private var TOTAL_QUESTIONS = 9 private var questions = ArrayList<String>() private var SCORE_ARRAY = "Score Array" private var OBJECTIVE_QUESTIONS = "ObjectiveQuestions" private val PATIENT_ID = "PatientId" private var DOC_NAME = "DoctorName" lateinit var docName : String lateinit var patientId : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_objective_questions) database = Firebase.database firestore = FirebaseFirestore.getInstance() patientId = intent.getStringExtra(PATIENT_ID)!! docName = intent.getStringExtra(DOC_NAME)!! if (questions.size == 0) { loadQuestions() } else { setQuestions() } binding.btnNext.setOnClickListener { btnNext() } binding.btnPrevious.setOnClickListener { btnPrevious() } } private fun btnPrevious() { if(QUESTION_NUMBER == 1) { startActivity(Intent(this@ObjectiveQuestionsActivity,InfoActivty::class.java)) finish() } else { QUESTION_NUMBER-- setQuestions() } } private fun loadQuestions() { reference = database.getReference(OBJECTIVE_QUESTIONS) reference.get().addOnSuccessListener { for (question in it.children) { questions.add(question.value.toString()) scoreArray.add(0) Log.d("TGAY",question.value.toString()) } binding.progressBar2.visibility = View.INVISIBLE binding.constraintLayout.visibility = View.VISIBLE setQuestions() }.addOnFailureListener { Toast.makeText(this@ObjectiveQuestionsActivity,"Oops!! Something went wrong...", Toast.LENGTH_SHORT).show() } } private fun btnNext() { binding.apply { if (options.checkedRadioButtonId == -1) { Toast.makeText(this@ObjectiveQuestionsActivity,"Select one of the above options !!",Toast.LENGTH_SHORT).show() } else { when (options.checkedRadioButtonId) { opt1.id -> { scoreArray[QUESTION_NUMBER-1] = 0 }opt2.id -> { scoreArray[QUESTION_NUMBER-1] = 1 }opt3.id -> { scoreArray[QUESTION_NUMBER-1] = 2 } else -> { scoreArray[QUESTION_NUMBER-1] = 3 } } options.clearCheck() if (QUESTION_NUMBER == TOTAL_QUESTIONS || btnNext.text.toString() == "Submit") { binding.progressBar.progress = 90 //calculate total score for (i in scoreArray) { score += i } Toast.makeText(this@ObjectiveQuestionsActivity, "SCORE : $score", Toast.LENGTH_SHORT).show() //next activity var intent = Intent(this@ObjectiveQuestionsActivity,SubjectiveQuestionsActivity::class.java) intent.putIntegerArrayListExtra(SCORE_ARRAY,scoreArray) intent.putExtra(SCORE,score) intent.putExtra(PATIENT_ID,patientId) startActivity(intent) finish() } else { QUESTION_NUMBER++ setQuestions() } } } } private fun setQuestions() { binding.apply { txtQuestion.text = questions[QUESTION_NUMBER-1] binding.progressBar.progress = (QUESTION_NUMBER-1)*10 if (QUESTION_NUMBER == 1) { binding.btnPrevious.visibility = View.GONE } else { binding.btnPrevious.visibility = View.VISIBLE btnPrevious.text = "Previous" } if (QUESTION_NUMBER == TOTAL_QUESTIONS) { btnNext.text = "Submit" } else { btnNext.text = "Next" } } } }