content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.viewbinding_checkbox 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) } }
binding_and_checkbox/app/src/test/java/com/example/viewbinding_checkbox/ExampleUnitTest.kt
2715223742
package com.example.viewbinding_checkbox import android.content.Intent import android.content.res.ColorStateList import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.core.view.isNotEmpty import com.example.viewbinding_checkbox.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.button.setOnClickListener { if (binding.checkBox.isChecked&& !binding.name.text.isNullOrBlank()){ val intent=Intent(this,MainActivity2::class.java) startActivity(intent) //open new screen }else{ binding.checkBox.buttonTintList= ColorStateList.valueOf(Color.RED) Toast.makeText(this, "please accept the T&C", Toast.LENGTH_SHORT).show() } } } }
binding_and_checkbox/app/src/main/java/com/example/viewbinding_checkbox/MainActivity.kt
1578418791
package com.example.viewbinding_checkbox import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) } }
binding_and_checkbox/app/src/main/java/com/example/viewbinding_checkbox/MainActivity2.kt
2800595059
package com.my.compose 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.my.compose", appContext.packageName) } }
Compose/app/src/androidTest/java/com/my/compose/ExampleInstrumentedTest.kt
3969901256
package com.my.compose 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) } }
Compose/app/src/test/java/com/my/compose/ExampleUnitTest.kt
408267801
package com.my.compose.tutorial001 import android.content.res.Configuration import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface 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.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.my.compose.R import com.my.compose.ui.theme.ComposeTheme data class Message( val author: String, val body: String ) @Composable fun MessageCard( msg: Message ) { // We Keep track if the message is expanded or not in this variable var isExpanded by remember { mutableStateOf(false) } // Add padding around our message Row( modifier = Modifier .padding(all = 8.dp) .fillMaxWidth() .clickable { isExpanded = !isExpanded } ) { Image( painter = painterResource(id = R.drawable.profile), contentDescription = stringResource(id = R.string.contact_profile_picture), modifier = Modifier // Set image size to 40 dp .size(40.dp) // Clip image to be shaped as a circle .clip(CircleShape) .border(2.dp, MaterialTheme.colorScheme.primary, CircleShape) ) // Add a horizontal space between the image and the column Spacer(modifier = Modifier.width(8.dp)) // We toggle the isExpanded variable when we click on this Column Column { Text( text = msg.author, color = MaterialTheme.colorScheme.secondary, style = MaterialTheme.typography.titleSmall ) // Add a vertical space between the author and message texts Spacer(modifier = Modifier.height(4.dp)) // surfaceColor will be updated gradually from one color to the other val surfaceColor by animateColorAsState( if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface, label = "ColorAnimation", ) Surface( shape = MaterialTheme.shapes.small, shadowElevation = 1.dp, // surfaceColor color will be changing gradually from primary to surface color = surfaceColor, // animateContentSize will change the Surface size gradually modifier = Modifier .animateContentSize() .padding(1.dp) ) { Text( text = msg.body, modifier = Modifier.padding(all = 4.dp), // If the message is expanded, we display all its content // otherwise we only display the first line maxLines = if (isExpanded) Int.MAX_VALUE else 1, style = MaterialTheme.typography.bodyMedium ) } } } } @Preview( uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, name = "Light Mode" ) @Preview( uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, name = "Dark Mode" ) @Composable fun MessageCardPreview() { ComposeTheme { Surface { MessageCard( msg = Message("Mahmoud", "Hey, take a look at Jetpack Compose, it's great!") ) } } }
Compose/app/src/main/java/com/my/compose/tutorial001/MessageCard.kt
4180098551
import com.my.compose.tutorial001.Message /** * SampleData for Jetpack Compose Tutorial */ object SampleData { // Sample conversation data val conversationSample = listOf( Message( "Mahmoud", "Test...Test...Test..." ), Message( "Mahmoud", """List of Android versions: |Android KitKat (API 19) |Android Lollipop (API 21) |Android Marshmallow (API 23) |Android Nougat (API 24) |Android Oreo (API 26) |Android Pie (API 28) |Android 10 (API 29) |Android 11 (API 30) |Android 12 (API 31)""".trim() ), Message( "Mahmoud", """I think Kotlin is my favorite programming language. |It's so much fun!""".trim() ), Message( "Mahmoud", "Searching for alternatives to XML layouts..." ), Message( "Mahmoud", """Hey, take a look at Jetpack Compose, it's great! |It's the Android's modern toolkit for building native UI. |It simplifies and accelerates UI development on Android. |Less code, powerful tools, and intuitive Kotlin APIs :)""".trim() ), Message( "Mahmoud", "It's available from API 21+ :)" ), Message( "Mahmoud", "Writing Kotlin for UI seems so natural, Compose where have you been all my life?" ), Message( "Mahmoud", "Android Studio next version's name is Arctic Fox" ), Message( "Mahmoud", "Android Studio Arctic Fox tooling for Compose is top notch ^_^" ), Message( "Mahmoud", "I didn't know you can now run the emulator directly from Android Studio" ), Message( "Mahmoud", "Compose Previews are great to check quickly how a composable layout looks like" ), Message( "Mahmoud", "Previews are also interactive after enabling the experimental setting" ), Message( "Mahmoud", "Have you tried writing build.gradle with KTS?" ), ) }
Compose/app/src/main/java/com/my/compose/tutorial001/SampleData.kt
4225981608
package com.my.compose.tutorial001 import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.my.compose.ui.theme.ComposeTheme @Composable fun Conversation(messages: List<Message>) { LazyColumn { items(messages) { message -> MessageCard(message) } } } @Preview @Composable fun PreviewConversation() { ComposeTheme { Conversation(SampleData.conversationSample) } }
Compose/app/src/main/java/com/my/compose/tutorial001/Conversation.kt
609935847
package com.my.compose.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)
Compose/app/src/main/java/com/my/compose/ui/theme/Color.kt
3497022205
package com.my.compose.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.ui.platform.LocalContext 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 ComposeTheme( 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 } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Compose/app/src/main/java/com/my/compose/ui/theme/Theme.kt
1381460290
package com.my.compose.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 ) */ )
Compose/app/src/main/java/com/my/compose/ui/theme/Type.kt
448668219
package com.my.compose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.my.compose.tutorial001.Conversation import com.my.compose.tutorial001.Message import com.my.compose.tutorial001.MessageCard import com.my.compose.ui.theme.ComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //enableEdgeToEdge() setContent { ComposeTheme { Surface( modifier = Modifier.fillMaxSize() ) { Conversation(SampleData.conversationSample) } } } } }
Compose/app/src/main/java/com/my/compose/MainActivity.kt
1602659865
package com.my.compose // # Summary 001 // - Describe what, not how // - Ul elements are functions // - State controls Ul // - Events control State // # Summary 002 // - Create composable using the @Composable annotation // - It's quick & easy to create composable // - Composable accept parameters // - Use MutableState and remember // - Composable should be side-effect free // # Summary 003 // # Composable can : // - Execute in any order // - Run in parallel // - Be skipped! // - Run frequently
Compose/app/src/main/java/com/my/compose/Summary.kt
2861171994
package com.example.terrestrial 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.terrestrial", appContext.packageName) } }
Capstone-project-2023/Mobile Development/app/src/androidTest/java/com/example/terrestrial/ExampleInstrumentedTest.kt
3046920977
package com.example.terrestrial 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) } }
Capstone-project-2023/Mobile Development/app/src/test/java/com/example/terrestrial/ExampleUnitTest.kt
3175173077
package com.example.terrestrial.ui.recommendation import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.data.response.QuestionItem import com.example.terrestrial.data.auth.Result import com.example.terrestrial.data.auth.UserModel import com.example.terrestrial.ml.TFLiteModel import kotlinx.coroutines.launch class QuestionViewModel(private val repository: UserRepository) : ViewModel() { private val _questions = MutableLiveData<List<QuestionItem?>?>() val questions: LiveData<List<QuestionItem?>?> get() = _questions private val _result = MutableLiveData<String?>() val result: LiveData<String?> get() = _result private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> get() = _isLoading fun getQuestions() { viewModelScope.launch { when (val result = repository.getQuestion()) { is Result.Success -> _questions.value = result.data.data is Result.Error -> {/* handle error */} else -> {} } } } // fun processModelWithAnswers( // desain: Int, // logika: Int, // data: Int, // questionActivity: QuestionActivity // ) { // viewModelScope.launch { // try { // val response = repository.submitAnswers(desain, logika, data) // _modelResult.value = response.prediction // } catch (e: Exception) { // // Handle error if needed // } // } // } // fun processAnswers(desain: Int, logika: Int, data: Int) { // val result = determineResult(desain, logika, data) // } fun processAnswers(desain: Int, logika: Int, data: Int): String { val recommendations = listOf( Triple(7, 0, 0), Triple(6, 1, 0), Triple(6, 0, 1), Triple(5, 1, 1), Triple(4, 2, 1), Triple(4, 1, 2), Triple(4, 3, 0), Triple(4, 0, 3), Triple(3, 3, 1), Triple(3, 1, 3), Triple(3, 2, 2) ) val result = when { recommendations.any { (d, l, da) -> d == desain && l == logika && da == data } -> "Frontend" recommendations.any { (l, d, da) -> l == logika && d == desain && da == data } -> "Backend" else -> "DataScience" } _result.postValue(result) viewModelScope.launch { val userModel = UserModel(isAnswer = true, resultRecommendation = result) repository.saveResultRecommendation(userModel) } return result } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/recommendation/QuestionViewModel.kt
753709216
package com.example.terrestrial.ui.recommendation import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.activity.viewModels import com.example.terrestrial.R import com.example.terrestrial.databinding.ActivityRecommendationClassBinding import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.ui.main.MainActivity class RecommendationResultActivity : AppCompatActivity() { private lateinit var binding: ActivityRecommendationClassBinding private val viewModel by viewModels<QuestionViewModel> { ViewModelFactory.getInstance(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRecommendationClassBinding.inflate(layoutInflater) setContentView(binding.root) Log.e("RecommendationResultActivity", "onCreate is called.") val result = intent.getStringExtra("result") Log.e("RecommendationResultActivity", "Result received from QuestionActivity: $result") binding.tvResult.text = getString(R.string.hore, result) binding.btnNext.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/recommendation/RecommendationResultActivity.kt
1668393514
package com.example.terrestrial.ui.recommendation 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.activity.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.terrestrial.R import com.example.terrestrial.databinding.ActivityQuestionBinding import com.example.terrestrial.ui.ViewModelFactory class QuestionActivity : AppCompatActivity() { private lateinit var questionAdapter: QuestionAdapter private val viewModel by viewModels<QuestionViewModel> { ViewModelFactory.getInstance(this) } private lateinit var binding: ActivityQuestionBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityQuestionBinding.inflate(layoutInflater) setContentView(binding.root) binding.loading.visibility = View.GONE questionAdapter = QuestionAdapter { questionId, answerNumber -> println("Jawaban terpilih untuk pertanyaan $questionId: $answerNumber") } val recyclerView: RecyclerView = findViewById(R.id.rvQuestion) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = questionAdapter observeQuestions() viewModel.getQuestions() binding.submitAnswer.setOnClickListener { binding.loading.visibility = View.VISIBLE val selectedAnswers = questionAdapter.getSelectedAnswers() if (questionAdapter.allQuestionsAnswered()) { val formattedAnswers = formatSelectedAnswers(selectedAnswers) viewModel.processAnswers( formattedAnswers[0], formattedAnswers[1], formattedAnswers[2] ) Log.d("QuestionActivity", "Selected Answers: $formattedAnswers") } else { Toast.makeText(this, "Harap jawab semua pertanyaan", Toast.LENGTH_SHORT).show() } } viewModel.result.observe(this) { result -> Log.e("QuestionActivity","data dari QuestionActivity: $result") val intent = Intent(this, RecommendationResultActivity::class.java) intent.putExtra("result", result) startActivity(intent) } observeLoadingState() } private fun observeLoadingState() { viewModel.isLoading.observe(this) { isLoading -> binding.loading.visibility = if (isLoading) View.VISIBLE else View.GONE } } private fun observeQuestions() { viewModel.questions.observe(this) { questions -> questions?.let { questionAdapter.submitList(it) } } } private fun formatSelectedAnswers(selectedAnswers: Map<Int, String>): List<Int> { val answerCounts = mutableMapOf("A" to 0, "B" to 0, "C" to 0) selectedAnswers.values.forEach { answer -> answerCounts[answer] = answerCounts[answer]?.plus(1) ?: 1 } return answerCounts.values.toList() } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/recommendation/QuestionActivity.kt
3576618649
package com.example.terrestrial.ui.recommendation import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.RadioButton import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.terrestrial.data.response.QuestionItem import com.example.terrestrial.databinding.ItemQuestionBinding class QuestionAdapter( private val onAnswerSelected: (Int, String) -> Unit ) : ListAdapter<QuestionItem, QuestionAdapter.QuestionViewHolder>(QuestionDiffCallback()) { private val selectedAnswers = mutableMapOf<Int, String>() fun getSelectedAnswers(): Map<Int, String> { return selectedAnswers } fun allQuestionsAnswered(): Boolean { return selectedAnswers.size == itemCount } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ItemQuestionBinding.inflate(inflater, parent, false) return QuestionViewHolder(binding, onAnswerSelected, selectedAnswers) } override fun onBindViewHolder(holder: QuestionViewHolder, position: Int) { val question = getItem(position) holder.bind(question, selectedAnswers[question.id] ?: "") } class QuestionViewHolder( private val binding: ItemQuestionBinding, private val onAnswerSelected: (Int, String) -> Unit, private val selectedAnswers: MutableMap<Int, String> ) : RecyclerView.ViewHolder(binding.root) { init { binding.radioGroupOptions.setOnCheckedChangeListener { _, checkedId -> val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val selectedRadioButton = binding.root.findViewById<RadioButton>(checkedId) val answer = when (selectedRadioButton) { binding.radioOption1 -> "A" binding.radioOption2 -> "B" binding.radioOption3 -> "C" else -> "" } onAnswerSelected(position, answer) Log.d("QuestionAdapter", "Jawaban terpilih: $position, $answer") // Perbarui status jawaban terpilih selectedAnswers[position] = answer } } } fun bind(question: QuestionItem, selectedAnswer: String) { binding.tvQuestion.text = question.queText binding.radioOption1.text = question.answer1 binding.radioOption2.text = question.answer2 binding.radioOption3.text = question.answer3 // Perbarui status jawaban terpilih pada tampilan when (selectedAnswer) { "A" -> binding.radioOption1.isChecked = true "B" -> binding.radioOption2.isChecked = true "C" -> binding.radioOption3.isChecked = true else -> { binding.radioOption1.isChecked = false binding.radioOption2.isChecked = false binding.radioOption3.isChecked = false } } } } private class QuestionDiffCallback : DiffUtil.ItemCallback<QuestionItem>() { override fun areItemsTheSame(oldItem: QuestionItem, newItem: QuestionItem): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: QuestionItem, newItem: QuestionItem): Boolean { return oldItem == newItem } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/recommendation/QuestionAdapter.kt
2241411637
package com.example.terrestrial.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.example.terrestrial.R import com.example.terrestrial.data.auth.UserRepository import kotlinx.coroutines.launch import com.example.terrestrial.data.auth.Result import com.example.terrestrial.data.auth.UserModel import com.example.terrestrial.data.response.DataItem class HomeViewModel(private val userRepository: UserRepository) : ViewModel() { private val _courseList = MutableLiveData<List<DataItem>?>() val courseList: MutableLiveData<List<DataItem>?> get() = _courseList private val _recommendCourseList = MutableLiveData<List<DataItem?>>() val recommendCourseList: MutableLiveData<List<DataItem?>> get() = _recommendCourseList private val _profile = MutableLiveData<String>().apply { val drawableResourceId = R.drawable.default_profile value = drawableResourceId.toString() } val profile: LiveData<String> = _profile // private val _searchedCourseList = MutableLiveData<List<DataItem?>?>() // val searchedCourseList: LiveData<List<DataItem?>?> get() = _searchedCourseList fun getSession(): LiveData<UserModel> = userRepository.getLoginSession().asLiveData() fun getAllCourse() { viewModelScope.launch { when (val result = userRepository.getAllCourse()) { is Result.Success -> _courseList.value = result.data?.data as List<DataItem>? is Result.Error -> {/* handle error */} else -> {} } } } fun getRecommendCourse() { viewModelScope.launch { when (val result = userRepository.getRecommendCourse()) { is Result.Success -> _recommendCourseList.value = result.data?.data as List<DataItem>? is Result.Error -> {/* handle error */} else -> {} } } } // fun searchCourse(query: String) { // viewModelScope.launch { // try { // val response = userRepository.searchCourse(query) // if (!response.error!!) { // _searchedCourseList.postValue(response.data) // } else { // // Handle error jika diperlukan // } // } catch (e: Exception) { // // Handle exception jika diperlukan // } // } // } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/home/HomeViewModel.kt
3200075402
package com.example.terrestrial.ui.home import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.terrestrial.data.response.DataItem import com.example.terrestrial.databinding.ItemCourseBinding class CourseAdapter(private val onItemClick: (String) -> Unit) : ListAdapter<DataItem, CourseAdapter.CourseViewHolder>(DiffCallback) { class CourseViewHolder(private val binding: ItemCourseBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(course: DataItem) { Glide.with(itemView).load(course.thumbnail).into(binding.ivItemPhoto) binding.tvTitleKursus.text = course.courseName binding.desc.text = course.courseType } } object DiffCallback : DiffUtil.ItemCallback<DataItem>() { override fun areItemsTheSame(oldItem: DataItem, newItem: DataItem): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: DataItem, newItem: DataItem): Boolean { return oldItem == newItem } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourseViewHolder { val binding = ItemCourseBinding.inflate(LayoutInflater.from(parent.context), parent, false) return CourseViewHolder(binding) } override fun onBindViewHolder(holder: CourseViewHolder, position: Int) { val currentCourse = getItem(position) holder.bind(currentCourse) holder.itemView.setOnClickListener { onItemClick.invoke(currentCourse.id.toString()) } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/home/CourseAdapter.kt
3086153619
package com.example.terrestrial.ui.home import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.terrestrial.R import com.example.terrestrial.databinding.FragmentHomeBinding import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.ui.detail.DetailCourseActivity class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private val homeViewModel by viewModels<HomeViewModel> { ViewModelFactory.getInstance(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) val root: View = binding.root homeViewModel.getSession().observe(viewLifecycleOwner) { user -> binding.tvName.text = user.name binding.tvTag.text = getString(R.string.tag_line) } homeViewModel.profile.observe(viewLifecycleOwner) { imageUrl -> Log.d("ProfileImage", "Image URL: $imageUrl") Glide.with(this) .load(imageUrl) .placeholder(R.drawable.default_profile) .circleCrop() .into(binding.photo) } // Setup RecyclerView for Course val courseRecyclerView: RecyclerView = binding.rvCourse val courseAdapter = CourseAdapter { courseId -> navigateToDetail(courseId) } homeViewModel.courseList.observe(viewLifecycleOwner) { courseAdapter.submitList(it) } courseRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) courseRecyclerView.adapter = courseAdapter // Setup RecyclerView for Recommend Course // val recommendRecyclerView: RecyclerView = binding.rvRecommend // val recommendAdapter = CourseAdapter { courseId -> // navigateToDetail(courseId) // } // // homeViewModel.recommendCourseList.observe(viewLifecycleOwner) { // recommendAdapter.submitList(it) // } // // recommendRecyclerView.layoutManager = // LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) // recommendRecyclerView.adapter = recommendAdapter homeViewModel.getAllCourse() // homeViewModel.getRecommendCourse() return root } private fun navigateToDetail(courseId: String) { val intent = Intent(requireContext(), DetailCourseActivity::class.java) intent.putExtra(DetailCourseActivity.EXTRA_KURSUS_ID, courseId) startActivity(intent) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/home/HomeFragment.kt
2903789001
package com.example.terrestrial.ui import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.ui.detail.DetailCourseViewModel import com.example.terrestrial.ui.home.HomeViewModel import com.example.terrestrial.ui.login.LoginViewModel import com.example.terrestrial.utils.Injection import com.example.terrestrial.ui.main.MainViewModel import com.example.terrestrial.ui.recommendation.QuestionViewModel import com.example.terrestrial.ui.setting.SettingViewModel import com.example.terrestrial.ui.signup.SignupViewModel class ViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return when { modelClass.isAssignableFrom(MainViewModel::class.java) -> { MainViewModel(repository) as T } modelClass.isAssignableFrom(SettingViewModel::class.java) -> { SettingViewModel(repository) as T } modelClass.isAssignableFrom(HomeViewModel::class.java) -> { HomeViewModel(repository) as T } modelClass.isAssignableFrom(SignupViewModel::class.java) -> { SignupViewModel() as T } modelClass.isAssignableFrom(LoginViewModel::class.java) -> { LoginViewModel(repository) as T } modelClass.isAssignableFrom(DetailCourseViewModel::class.java) -> { DetailCourseViewModel(repository) as T } modelClass.isAssignableFrom(QuestionViewModel::class.java) -> { QuestionViewModel(repository) as T } else -> throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.name) } } companion object{ @Volatile private var INSTANCE: ViewModelFactory? = null @JvmStatic fun getInstance(context: Context): ViewModelFactory{ if (INSTANCE == null) { synchronized(ViewModelFactory::class.java){ INSTANCE = ViewModelFactory( Injection.provideRepository(context), ) } } return INSTANCE as ViewModelFactory } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/ViewModelFactory.kt
1052878613
package com.example.terrestrial.ui.signup import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.terrestrial.data.api.ApiConfig import com.example.terrestrial.data.api.ApiService import com.example.terrestrial.data.auth.UserRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class SignupViewModel : ViewModel() { private val apiService: ApiService = ApiConfig.getApiService("") private val _registrationResult = MutableLiveData<Boolean>() val registrationResult: LiveData<Boolean> = _registrationResult private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> = _isLoading fun registerUser(name: String, email: String, password: String) { viewModelScope.launch(Dispatchers.Main) { try { _isLoading.postValue(true) val signupRequest = ApiService.SignupRequest(name, email, password) val response = apiService.signup(signupRequest) val registrationSuccess = response.error == false withContext(Dispatchers.Main) { _registrationResult.value = registrationSuccess _isLoading.value = false } } catch (e: Exception) { withContext(Dispatchers.Main) { _isLoading.value = false _registrationResult.value = false } } finally { _isLoading.value = false } } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/signup/SignupViewModel.kt
1593100652
package com.example.terrestrial.ui.signup import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Intent import android.os.Build import android.os.Bundle import android.util.Patterns import android.view.View import android.view.WindowInsets import android.view.WindowManager import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import com.example.terrestrial.R import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.databinding.ActivitySignupBinding import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.ui.login.LoginActivity import com.example.terrestrial.ui.login.LoginViewModel import com.example.terrestrial.ui.main.MainViewModel class SignupActivity : AppCompatActivity() { private lateinit var binding: ActivitySignupBinding private val viewModel by viewModels<SignupViewModel> { ViewModelFactory.getInstance(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignupBinding.inflate(layoutInflater) setContentView(binding.root) showLoading(false) setupAction() setupAnimation() viewModel.registrationResult.observe(this) { if (it) { showSuccessDialog(binding.emailEditText.text.toString()) } else { showToast(getString(R.string.create_account_failed)) showLoading(false) } } binding.tvLogin.setOnClickListener { val signIn = Intent(this, LoginActivity::class.java) startActivity(signIn) } } private fun setupAction() { binding.signupButton.setOnClickListener { val name = binding.nameEditText.text.toString() val email = binding.emailEditText.text.toString() val password = binding.passwordEditText.text.toString() if (name.isNotEmpty() && email.isNotEmpty() && password.isNotEmpty()) { showLoading(true) registerUser(name, email, password) } else { showToast(getString(R.string.not_empty_form)) } } } private fun setupAnimation() { val nameTextView = ObjectAnimator.ofFloat(binding.nameTextView, View.ALPHA, 1f).setDuration(200) val nameEditTextLayout = ObjectAnimator.ofFloat(binding.nameEditTextLayout, View.ALPHA, 1f).setDuration(200) val emailTextView = ObjectAnimator.ofFloat(binding.emailTextView, View.ALPHA, 1f).setDuration(200) val emailEditTextLayout = ObjectAnimator.ofFloat(binding.emailEditTextLayout, View.ALPHA, 1f).setDuration(200) val passwordTextView = ObjectAnimator.ofFloat(binding.passwordTextView, View.ALPHA, 1f).setDuration(200) val passwordEditTextLayout = ObjectAnimator.ofFloat(binding.passwordEditTextLayout, View.ALPHA, 1f).setDuration(200) val registerButton = ObjectAnimator.ofFloat(binding.signupButton, View.ALPHA, 1f).setDuration(200) val tvLogin = ObjectAnimator.ofFloat(binding.tvquestionLogin, View.ALPHA, 1f).setDuration(200) val login = ObjectAnimator.ofFloat(binding.tvLogin, View.ALPHA, 1f).setDuration(200) val together = AnimatorSet().apply {playTogether(registerButton, tvLogin, login)} AnimatorSet().apply { playSequentially( nameTextView, nameEditTextLayout, emailTextView, emailEditTextLayout, passwordTextView, passwordEditTextLayout, registerButton, login, together ) startDelay = 90 }.start() } private fun registerUser(name: String, email: String, password: String) { if (isValidEmail(email)) { viewModel.registerUser(name, email, password) } else { showToast(getString(R.string.valid_email)) showLoading(false) } } private fun isValidEmail(email: String): Boolean { return Patterns.EMAIL_ADDRESS.matcher(email).matches() } private fun showSuccessDialog(email: String) { if (!isFinishing && !isDestroyed) { AlertDialog.Builder(this).apply { setTitle(getString(R.string.dialog_title_success)) setMessage(" ${getString(R.string.dialog_message_success)}") setPositiveButton(getString(R.string.dialog_button_next)) { _, _ -> finish() } create() show() } } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun showLoading(isLoading: Boolean) { binding.loading.visibility = if (isLoading) View.VISIBLE else View.GONE } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/signup/SignupActivity.kt
569827842
package com.example.terrestrial.ui.detail import androidx.lifecycle.ViewModel import com.example.terrestrial.data.auth.Result import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.data.response.DetailCourseResponse import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow class DetailCourseViewModel(private val repository: UserRepository) : ViewModel() { private val _detailCourse = MutableStateFlow<Result<DetailCourseResponse?>>(Result.Loading) val detailCourse: StateFlow<Result<DetailCourseResponse?>> = _detailCourse.asStateFlow() suspend fun getDetail(id: String) { _detailCourse.value = repository.getDetailCourse(id) } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/detail/DetailCourseViewModel.kt
1632110763
package com.example.terrestrial.ui.detail import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.activity.viewModels import androidx.lifecycle.lifecycleScope import com.bumptech.glide.Glide import com.example.terrestrial.R import com.example.terrestrial.data.response.Data import com.example.terrestrial.databinding.ActivityDetailCourseBinding import com.example.terrestrial.ui.main.MainActivity import com.example.terrestrial.data.auth.Result import com.example.terrestrial.data.response.DetailCourseResponse import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.utils.Injection import kotlinx.coroutines.launch class DetailCourseActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailCourseBinding private val detailCourseViewModel: DetailCourseViewModel by viewModels { ViewModelFactory(Injection.provideRepository(this)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailCourseBinding.inflate(layoutInflater) setContentView(binding.root) val courseId = intent.getStringExtra(EXTRA_KURSUS_ID) if (courseId != null) { lifecycleScope.launch { try { detailCourseViewModel.getDetail(courseId) } catch (e: Exception) { // Handle exceptions if needed } } binding.back.setOnClickListener { moveToMainActivity() } } // Observe the StateFlow to handle the result lifecycleScope.launch { detailCourseViewModel.detailCourse .collect { result -> handleResult(result) } } } private fun handleResult(result: Result<DetailCourseResponse?>) { when (result) { is Result.Success -> { val data = result.data?.data if (data != null) { setData(data) binding.loading.visibility = View.GONE } else { binding.tvDesc.text = getString(R.string.null_data) } } is Result.Error -> { binding.loading.visibility = View.GONE binding.tvDesc.text = getString(R.string.error) } is Result.Loading -> { binding.loading.visibility = View.VISIBLE } } } private fun setData(data: Data) { Glide.with(this) .load(data.thumbnail) .into(binding.ivPic) binding.tvName .text = data.courseName binding.tvDesc.text = data.describe binding.tvLearn.text = data.learning } private fun moveToMainActivity() { startActivity(Intent(this, MainActivity::class.java)) } companion object { const val EXTRA_KURSUS_ID = "extra_kursus_id" } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/detail/DetailCourseActivity.kt
3624586795
package com.example.terrestrial.ui.customview import android.content.Context import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.util.Patterns import com.google.android.material.textfield.TextInputEditText class CustomEditTextEmail : TextInputEditText { constructor(context: Context) : super(context){ init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs){ init() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr){ init() } private fun init(){ addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun afterTextChanged(s: Editable) { val email = s.toString() val isValidEmail = email.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(email).matches() if (isValidEmail){ error = null } else { setError( "Email Must be valid email", null) } } }) } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/customview/CustomEditTextEmail.kt
2123315827
package com.example.terrestrial.ui.customview import android.content.Context import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import com.google.android.material.textfield.TextInputEditText class CustomEditTextPassword : TextInputEditText { constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int ) : super(context, attrs, defStyleAttr) { init() } private fun init() { addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val password = s.toString() if (password.length < 8) { setError("Password tidak boleh kurang dari 8 karakter", null) } else { error = null } } override fun afterTextChanged(s: Editable?) {} }) } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/customview/CustomEditTextPassword.kt
485798324
package com.example.terrestrial.ui.kursuskelas import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.terrestrial.R class kursus_kelas_Activity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_course_class) } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/kursuskelas/Kursus_kelas_Activity.kt
878738510
package com.example.terrestrial.ui.setting import android.content.Intent import android.os.Bundle import android.provider.Settings import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.bumptech.glide.Glide import com.example.terrestrial.R import com.example.terrestrial.databinding.FragmentSettingBinding import com.example.terrestrial.ui.ViewModelFactory class SettingFragment : Fragment() { private var _binding: FragmentSettingBinding? = null private val binding get() = _binding!! private val viewModel: SettingViewModel by viewModels { ViewModelFactory.getInstance(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSettingBinding.inflate(inflater, container, false) val root: View = binding.root viewModel.getSession().observe(viewLifecycleOwner) { user -> binding.name.text = user.name binding.email.text = user.email } viewModel.profile.observe(viewLifecycleOwner) { imageUrl -> Log.d("ProfileImage", "Image URL: $imageUrl") Glide.with(this) .load(imageUrl) .placeholder(R.drawable.default_profile) .circleCrop() .into(binding.photo) } binding.back.setOnClickListener { requireActivity().onBackPressed() } binding.language.setOnClickListener { startActivity(Intent(Settings.ACTION_LOCALE_SETTINGS)) } binding.logout.setOnClickListener { viewModel.logout() } return root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/setting/SettingFragment.kt
1848884181
package com.example.terrestrial.ui.setting import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.example.terrestrial.R import com.example.terrestrial.data.auth.UserModel import com.example.terrestrial.data.auth.UserRepository import kotlinx.coroutines.launch class SettingViewModel(private val repository: UserRepository) : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "Setting" } val text: LiveData<String> = _text private val _name = MutableLiveData<String>().apply { value = "Asep Sutisna" } val name: LiveData<String> = _name private val _email = MutableLiveData<String>().apply { value = "[email protected]" } val email: LiveData<String> = _email private val _profile = MutableLiveData<String>().apply { val drawableResourceId = R.drawable.default_profile value = drawableResourceId.toString() } val profile: LiveData<String> = _profile private val _darkMode = MutableLiveData<Boolean>() val darkMode: LiveData<Boolean> = _darkMode fun logout() { viewModelScope.launch { repository.clearLoginSession() } } fun getSession(): LiveData<UserModel> = repository.getLoginSession().asLiveData() }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/setting/SettingViewModel.kt
2516912461
package com.example.terrestrial.ui.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.data.auth.UserModel import com.example.terrestrial.data.response.LoginResponse import com.example.terrestrial.data.response.SignupResponse import com.example.terrestrial.data.auth.Result import kotlinx.coroutines.launch class MainViewModel(private val userRepository: UserRepository) : ViewModel() { fun getSession(): LiveData<UserModel> = userRepository.getLoginSession().asLiveData() }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/main/MainViewModel.kt
560800387
package com.example.terrestrial.ui.main import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupWithNavController import com.example.terrestrial.R import com.example.terrestrial.databinding.ActivityMainBinding import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.ui.login.LoginActivity import com.example.terrestrial.ui.recommendation.QuestionActivity class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val viewModel by viewModels<MainViewModel> { ViewModelFactory.getInstance(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) viewModel.getSession().observe(this) { user -> if (user.isLogin) { if(user.isAnswer){ val navView: BottomNavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) AppBarConfiguration( setOf( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications ) ) navView.setupWithNavController(navController) } else{ startActivity(Intent(this, QuestionActivity::class.java)) finish() } } else { startActivity(Intent(this, LoginActivity::class.java)) finish() } } } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_activity_main) return navController.navigateUp() || super.onSupportNavigateUp() } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/main/MainActivity.kt
2261028635
package com.example.terrestrial.ui.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import android.util.Log import com.example.terrestrial.data.api.ApiService import com.example.terrestrial.data.auth.UserModel import com.example.terrestrial.data.auth.UserRepository class LoginViewModel(private val repository: UserRepository) : ViewModel() { private val _loginResult = MutableLiveData<Boolean>() val loginResult: LiveData<Boolean> get() = _loginResult private val _isLoading = MutableLiveData<Boolean>() val isLoading: LiveData<Boolean> = _isLoading fun loginUser(email: String, password: String) { viewModelScope.launch { try { _isLoading.postValue(true) val loginRequest = ApiService.LoginRequest(email, password) val response = repository.login(loginRequest) if (response.error == false) { val token = response.loginResult?.token ?: "" val name = response.loginResult?.name ?: "" val emailResult = response.loginResult?.email ?: "" repository.saveLoginSession(UserModel(name, emailResult, token, isLogin = true)) _loginResult.value = true } else { _loginResult.value = false } } catch (e: Exception) { _loginResult.value = false Log.e("TAG", "Error: ${e.message}") } finally { _isLoading.value = false } } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/login/LoginViewModel.kt
3952373287
package com.example.terrestrial.ui.login import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Intent import android.os.Build import android.os.Bundle import android.view.View import android.view.WindowInsets import android.view.WindowManager import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.example.terrestrial.R import com.example.terrestrial.databinding.ActivityLoginBinding import com.example.terrestrial.ui.ViewModelFactory import com.example.terrestrial.ui.main.MainActivity import com.example.terrestrial.ui.signup.SignupActivity class LoginActivity : AppCompatActivity() { private val viewModel by viewModels<LoginViewModel> { ViewModelFactory.getInstance(this) } private lateinit var binding : ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) showLoading(false) binding.tvSignup.setOnClickListener { val signup = Intent(this, SignupActivity::class.java) startActivity(signup) } setupView() setupAction() playAnimation() } private fun setupView() { @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.hide(WindowInsets.Type.statusBars()) } else { window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } supportActionBar?.hide() } private fun setupAction() { binding.loginButton.setOnClickListener { val email = binding.emailEditText.text.toString() val password = binding.passwordEditText.text.toString() showLoading(true) viewModel.loginUser(email, password) viewModel.loginResult.observe(this) { isLogin -> showLoading(false) if (isLogin) { val intent = Intent(this, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } else { showToast(getString(R.string.login_failed)) } } } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun showLoading(isLoading: Boolean) { binding.loading.visibility = if (isLoading) View.VISIBLE else View.GONE } private fun playAnimation() { val loginTextView = ObjectAnimator.ofFloat(binding.titlelogin, View.ALPHA, 1f).setDuration(200) val emailTextView = ObjectAnimator.ofFloat(binding.emailTextView, View.ALPHA, 1f).setDuration(200) val emailEditText = ObjectAnimator.ofFloat(binding.emailEditTextLayout, View.ALPHA, 1f).setDuration(200) val passwordTextView = ObjectAnimator.ofFloat(binding.passwordTextView, View.ALPHA, 1f).setDuration(200) val passwordEditText = ObjectAnimator.ofFloat(binding.passwordEditTextLayout, View.ALPHA, 1f).setDuration(200) val login = ObjectAnimator.ofFloat(binding.loginButton, View.ALPHA, 1f).setDuration(200) val tvSignup = ObjectAnimator.ofFloat(binding.tvquestionSignup, View.ALPHA, 1f).setDuration(300) val signup = ObjectAnimator.ofFloat(binding.tvSignup, View.ALPHA, 1f).setDuration(300) val together = AnimatorSet().apply { playTogether(login, tvSignup, signup) } AnimatorSet().apply { playSequentially( loginTextView, emailTextView, emailEditText, passwordTextView, passwordEditText, login, together ) startDelay = 90 }.start() } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/login/LoginActivity.kt
2129686206
package com.example.terrestrial.ui.upload import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class UploadViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "Coming Soon" } val text: LiveData<String> = _text }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/upload/UploadViewModel.kt
3668727760
package com.example.terrestrial.ui.upload import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.terrestrial.databinding.FragmentUploadBinding class UploadFragment : Fragment() { private var _binding: FragmentUploadBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentUploadBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ui/upload/UploadFragment.kt
2147564510
package com.example.terrestrial.utils object Constant { enum class UserPreferences{ UserUID, UserName, UserEmail, UserToken, UserLastLogin } const val DELAY_SPLASH_SCREEN = 2000L const val preferenceName = "session" const val BASE_URL = "https://db7482add7a47d.lhr.life/api/" const val OUTPUT_SIZE = 0.0 const val KEY_AUTH_PREFERENCES = "auth" const val KEY_STATE_PREFERENCES = "state" }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/utils/Constant.kt
2042717746
package com.example.terrestrial.utils import android.content.Context import com.example.terrestrial.data.api.ApiConfig import com.example.terrestrial.data.auth.UserPreferences import com.example.terrestrial.data.auth.UserRepository import com.example.terrestrial.data.auth.dataStore import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking object Injection { fun provideRepository(context: Context): UserRepository { val pref = UserPreferences.getInstance(context.dataStore) val user = runBlocking { pref.getLoginSession().first() } val apiService = ApiConfig.getApiService( user.token) return UserRepository.getInstance(apiService, pref) } } // fun provideUserRepository(context: Context): UserRepository { // val pref = UserPreferences.getInstance(context.dataStore) // val apiService = ApiConfig.apiInstance // return UserRepository.getInstance(apiService,pref) // } // //// fun provideStoryRepository(): StoryRepository { //// val apiService = ApiConfig.apiInstance //// return StoryRepository.getInstance(apiService) //// }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/utils/Injection.kt
3210804016
package com.example.terrestrial.ml import android.content.Context import org.tensorflow.lite.Interpreter import java.io.FileInputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.FileChannel class TFLiteModel(context: Context, modelPath: String) { private val interpreter: Interpreter init { val modelFile = context.assets.openFd(modelPath) val fileDescriptor = modelFile.fileDescriptor val startOffset = modelFile.startOffset val declaredLength = modelFile.declaredLength val modelByteBuffer = FileInputStream(fileDescriptor).channel .map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength) interpreter = Interpreter(modelByteBuffer) } fun runInference(inputs: IntArray): FloatArray { val inputBuffer = ByteBuffer.allocateDirect(inputs.size * 4) inputBuffer.order(ByteOrder.nativeOrder()) for (input in inputs) { inputBuffer.putInt(input) } val outputBuffer = ByteBuffer.allocateDirect(4 * NUM_CLASSES) outputBuffer.order(ByteOrder.nativeOrder()) interpreter.run(inputBuffer, outputBuffer) val outputArray = FloatArray(NUM_CLASSES) outputBuffer.rewind() outputBuffer.asFloatBuffer().get(outputArray) return outputArray } companion object { private const val NUM_CLASSES = 3 // Adjust based on the number of output classes } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/ml/TFLiteModel.kt
1566510942
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class CourseResponse( @field:SerializedName("data") val data: List<DataItem?>? = null, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) data class DataItem( @field:SerializedName("courseName") val courseName: String? = null, @field:SerializedName("thumbnail") val thumbnail: String? = null, @field:SerializedName("courseType") val courseType: String? = null, @field:SerializedName("id") val id: Int? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/CourseResponse.kt
4116114820
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class QuestionResponse( @field:SerializedName("data") val data: List<QuestionItem?>? = null, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) data class QuestionItem( @field:SerializedName("queText") val queText: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("answer1") val answer1: String? = null, @field:SerializedName("answer2") val answer2: String? = null, @field:SerializedName("answer3") val answer3: String? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/QuestionResponse.kt
1410884277
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class ResponseLogout( @field:SerializedName("data") val data: String? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/ResponseLogout.kt
4098784115
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName class PredictResponse ( @field:SerializedName("loginResult") val prediction: String? = null, )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/PredictResponse.kt
4036609000
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class DetailCourseResponse( @field:SerializedName("data") val data: Data? = null, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) data class Data( @field:SerializedName("thumbnail") val thumbnail: String? = null, @field:SerializedName("courseName") val courseName: String? = null, @field:SerializedName("learning") val learning: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("describe") val describe: String? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/DetailCourseResponse.kt
3983941523
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class LoginResponse( @field:SerializedName("loginResult") val loginResult: LoginResult? = null, @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null ) data class LoginResult( @field:SerializedName("email") val email: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("token") val token: String? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/LoginResponse.kt
3509022087
package com.example.terrestrial.data.response import com.google.gson.annotations.SerializedName data class SignupResponse( @field:SerializedName("error") val error: Boolean? = null, @field:SerializedName("message") val message: String? = null )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/response/SignupResponse.kt
2334254784
package com.example.terrestrial.data.auth sealed class Result<out T> { data class Success<out T>(val data: T) : Result<T>() data class Error(val error: String) : Result<Nothing>() data object Loading : Result<Nothing>() }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/auth/Result.kt
1007356879
package com.example.terrestrial.data.auth import com.example.terrestrial.data.api.ApiConfig import com.example.terrestrial.data.api.ApiService import com.example.terrestrial.data.response.CourseResponse import com.example.terrestrial.data.response.DetailCourseResponse import com.example.terrestrial.data.response.LoginResponse import com.example.terrestrial.data.response.PredictResponse import com.example.terrestrial.data.response.QuestionResponse import com.example.terrestrial.data.response.SignupResponse import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first class UserRepository private constructor( private val apiService: ApiService, private val userPreferences: UserPreferences ) { suspend fun signup(request: ApiService.SignupRequest): SignupResponse { return apiService.signup(request) } suspend fun login(request: ApiService.LoginRequest): LoginResponse { return apiService.login(request) } suspend fun saveLoginSession(user: UserModel) { userPreferences.saveLoginSession(user) } suspend fun saveResultRecommendation(user: UserModel) { userPreferences.saveResultRecommendation(user) } fun getLoginSession(): Flow<UserModel> = userPreferences.getLoginSession() suspend fun clearLoginSession() { userPreferences.clearLoginSession() } suspend fun getAllCourse(): Result<CourseResponse?> { return try { val user = userPreferences.getLoginSession().first() val apiService = ApiConfig.getApiService(user.token) val response = apiService.getAllCourse() Result.Success(response) } catch (e: Exception) { Result.Error(e.message.toString()) } } suspend fun getRecommendCourse(): Result<CourseResponse?> { return try { val user = userPreferences.getLoginSession().first() val apiService = ApiConfig.getApiService(user.token) val recommendClass = user.resultRecommendation val response = apiService.getRecommendCourse(recommendClass) Result.Success(response) } catch (e: Exception) { Result.Error(e.message.toString()) } } suspend fun getDetailCourse(id: String): Result<DetailCourseResponse?> { return try { val user = userPreferences.getLoginSession().first() val apiService = ApiConfig.getApiService(user.token) val response = apiService.getDetailCourse(id) Result.Success(response) } catch (e: Exception) { Result.Error(e.message.toString()) } } // suspend fun searchCourse(query: String): AllCourseResponse { // val user = userPreferences.getLoginSession().first() // val apiService = ApiConfig.getApiService(user.token) // return apiService.searchUser(mapOf("query" to query)) // } suspend fun getQuestion(): Result<QuestionResponse>{ return try { val user = userPreferences.getLoginSession().first() val apiService = ApiConfig.getApiService(user.token) val response = apiService.getQuestion() Result.Success(response) }catch (e: Exception){ Result.Error(e.message.toString()) } } // suspend fun submitAnswers(desain: Int, logika: Int, data: Int): PredictResponse { // val answerRequest = ApiService.AnswerRequest(desain, logika, data) // return apiService.submitAnswers(answerRequest) // } companion object { @Volatile private var instance: UserRepository? = null fun getInstance(apiService: ApiService, userPreferences: UserPreferences): UserRepository = instance ?: synchronized(this) { instance ?: UserRepository(apiService, userPreferences) }.also { instance = it } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/auth/UserRepository.kt
4125949658
package com.example.terrestrial.data.auth data class UserModel( val email: String = "", val name: String = "", val token: String = "", val isLogin: Boolean = false, val isAnswer: Boolean = false, val resultRecommendation: String = "" )
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/auth/UserModel.kt
1007021643
package com.example.terrestrial.data.auth import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.example.terrestrial.utils.Constant import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = Constant.preferenceName) class UserPreferences private constructor(private val dataStore: DataStore<Preferences>) { suspend fun saveLoginSession(user: UserModel) { dataStore.edit { preferences -> preferences[NAME_KEY] = user.name preferences[EMAIL_KEY] = user.email preferences[TOKEN_KEY] = user.token preferences[IS_LOGIN_KEY] = user.isLogin } } suspend fun saveResultRecommendation(user: UserModel) { val existingData = getLoginSession().first() if (existingData.isAnswer != user.isAnswer || existingData.resultRecommendation != user.resultRecommendation) { dataStore.edit { preferences -> preferences[IS_ANSWER_KEY] = user.isAnswer preferences[RESULT_RECOMMENDATION] = user.resultRecommendation } } } fun getLoginSession(): Flow<UserModel> { return dataStore.data.map { prefrences -> UserModel( prefrences[NAME_KEY] ?: "", prefrences[EMAIL_KEY] ?: "", prefrences[TOKEN_KEY] ?: "", prefrences[IS_LOGIN_KEY] ?: false, prefrences[IS_ANSWER_KEY] ?: false, prefrences[RESULT_RECOMMENDATION] ?: "" ) } } suspend fun clearLoginSession() { dataStore.edit { preferences -> preferences.clear() } } companion object { @Volatile private var INSTANCE: UserPreferences? = null private val EMAIL_KEY = stringPreferencesKey("email") private val NAME_KEY = stringPreferencesKey("name") private val TOKEN_KEY = stringPreferencesKey("token") private val IS_LOGIN_KEY = booleanPreferencesKey("isLogin") private val IS_ANSWER_KEY = booleanPreferencesKey("isAnswer") private val RESULT_RECOMMENDATION = stringPreferencesKey("resultRecommendation") fun getInstance(dataStore: DataStore<Preferences>): UserPreferences { return INSTANCE ?: synchronized(this) { val instance = UserPreferences(dataStore) INSTANCE = instance instance } } } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/auth/UserPreferences.kt
1473302973
package com.example.terrestrial.data.api import com.example.terrestrial.BuildConfig import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiConfig { fun getApiService(token: String): ApiService { val loggingInterceptor = if(BuildConfig.DEBUG) { HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) } else { HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE) } val authInterceptor = Interceptor { chain -> val req = chain.request() val requestHeaders = req.newBuilder() .addHeader("Authorization", token) .build() chain.proceed(requestHeaders) } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(authInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(BuildConfig.API_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() return retrofit.create(ApiService::class.java) } }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/api/ApiConfig.kt
3419535968
package com.example.terrestrial.data.api import com.example.terrestrial.data.response.CourseResponse import com.example.terrestrial.data.response.DetailCourseResponse import com.example.terrestrial.data.response.LoginResponse import com.example.terrestrial.data.response.QuestionResponse import com.example.terrestrial.data.response.SignupResponse import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path interface ApiService { data class SignupRequest( val name: String, val email: String, val password: String ) @POST("users/signup") suspend fun signup( @Body request: SignupRequest ): SignupResponse data class LoginRequest( val email: String, val password: String ) @POST("users/login") suspend fun login( @Body request: LoginRequest ): LoginResponse @GET("course") suspend fun getAllCourse(): CourseResponse @GET("course/{recommendClass}") suspend fun getRecommendCourse( @Path("recommendClass") recommendClass: String ): CourseResponse @GET("course/{id}") suspend fun getDetailCourse( @Path("id") id: String ): DetailCourseResponse // @GET("search/course") // fun searchUser( // @QueryMap params: Map<String, String> // ): AllCourseResponse @GET("question") suspend fun getQuestion() : QuestionResponse // data class AnswerRequest( // val desain: Int, // val logika : Int, // val data : Int // ) // // @POST("answers") // suspend fun submitAnswers( // @Body answers: AnswerRequest // ): PredictResponse }
Capstone-project-2023/Mobile Development/app/src/main/java/com/example/terrestrial/data/api/ApiService.kt
2831451686
package com.example.autoinsight 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.autoinsight", appContext.packageName) } }
AutoStrings/autoStrings-app-master/app/src/androidTest/java/com/example/autoinsight/ExampleInstrumentedTest.kt
2526276717
package com.example.autoinsight 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) } }
AutoStrings/autoStrings-app-master/app/src/test/java/com/example/autoinsight/ExampleUnitTest.kt
445082900
package com.example.autoinsight import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.Toast import com.example.autoinsight.DataContactActivity.Companion.a import com.example.autoinsight.DataContactActivity.Companion.b import com.example.autoinsight.DataContactActivity.Companion.c import com.example.autoinsight.DataContactActivity.Companion.d import com.example.autoinsight.DataContactActivity.Companion.e import com.example.autoinsight.DataContactActivity.Companion.f import com.google.firebase.auth.FirebaseAuth class DataPersonalActivity : AppCompatActivity() { val firebaseAuth = FirebaseAuth.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datapersonal) a = this.findViewById(R.id.firstName) b = this.findViewById(R.id.lastName) c = this.findViewById(R.id.houseNo) d = this.findViewById(R.id.city) e = this.findViewById(R.id.state) f = this.findViewById(R.id.pinCode) // Retrieve the mobile and email data from the intent val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val pnextButton = this.findViewById<Button>(R.id.pnextButton) pnextButton.setOnClickListener { if (a.text.toString().isEmpty() || b.text.toString().isEmpty() || c.text.toString() .isEmpty() || d.text.toString().isEmpty() || e.text.toString() .isEmpty() || f.text.toString().isEmpty() ) { Toast.makeText(applicationContext, "Please fill all the mandatory * fields.", Toast.LENGTH_SHORT) .show() } else { val intent = Intent(this, DataCarActivity::class.java).apply { // Pass the UI component data and mobile and email data to DataCarActivity putExtra("firstName", a.text.toString()) putExtra("lastName", b.text.toString()) putExtra("houseNo", c.text.toString()) putExtra("city", d.text.toString()) putExtra("state", e.text.toString()) putExtra("pinCode", f.text.toString()) putExtra("mobile", mobile) putExtra("email", email) } startActivity(intent) } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { firebaseAuth.signOut() val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataPersonalActivity.kt
2859590574
package com.example.autoinsight import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DBHelper(context: Context?) : SQLiteOpenHelper(context, DB_NAME, null, DB_VER) { override fun onCreate(sqLiteDatabase: SQLiteDatabase) { val query = "CREATE TABLE users(mobile VARCHAR(10) PRIMARY KEY, fname TEXT , lname TEXT , houseno TEXT , city TEXT , state TEXT , pincode TEXT , manf TEXT , model TEXT, year TEXT, email TEXT, regno TEXT, fuel TEXT )" sqLiteDatabase.execSQL(query) } override fun onUpgrade(sqLiteDatabase: SQLiteDatabase, i: Int, i1: Int) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS users") onCreate(sqLiteDatabase) } fun addData(mobile: String, fname: String, lname: String, houseno: String, city: String, state: String, pincode: String, manf: String, model: String, year: String, email: String, regno: String, fuel: String): Boolean { val sqLiteDatabase = this.writableDatabase val contentValues = ContentValues() try { contentValues.put("fname", fname) contentValues.put("lname", lname) contentValues.put("houseno", houseno) contentValues.put("city", city) contentValues.put("state", state) contentValues.put("pincode", pincode) contentValues.put("manf", manf) contentValues.put("model", model) contentValues.put("year", year) contentValues.put("mobile", mobile) contentValues.put("email", email) contentValues.put("fuel", fuel) contentValues.put("regno", regno) sqLiteDatabase.insert("users", null,contentValues) return true } catch (e: Exception) { println(e.message) return false } finally { sqLiteDatabase.close() } } companion object { private const val DB_NAME = "users" private const val DB_VER = 1 } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DBHelper.kt
3485079452
package com.example.autoinsight import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.hbb20.CountryCodePicker class WashContactActivity : AppCompatActivity() { val firebaseAuth = FirebaseAuth.getInstance() companion object{ @SuppressLint("StaticFieldLeak") lateinit var a: EditText @SuppressLint("StaticFieldLeak") lateinit var b: EditText @SuppressLint("StaticFieldLeak") lateinit var c: EditText @SuppressLint("StaticFieldLeak") lateinit var d: EditText @SuppressLint("StaticFieldLeak") lateinit var e: EditText @SuppressLint("StaticFieldLeak") lateinit var f: EditText @SuppressLint("StaticFieldLeak") lateinit var g: EditText @SuppressLint("StaticFieldLeak") lateinit var h: EditText @SuppressLint("StaticFieldLeak") lateinit var i: EditText @SuppressLint("StaticFieldLeak") lateinit var j: EditText @SuppressLint("StaticFieldLeak") lateinit var k: EditText lateinit var l: EditText lateinit var m: EditText } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_washcontact) val ccp: CountryCodePicker = this.findViewById(R.id.countryCodeHolder) j = this.findViewById(R.id.mobile) k = this.findViewById(R.id.email) ccp.registerCarrierNumberEditText(j) val verify = this.findViewById<Button>(R.id.verify) verify.setOnClickListener { if (j.text.toString().isEmpty() || k.text.toString().isEmpty()) { Toast.makeText( applicationContext, "Please fill the mandatory * field.", Toast.LENGTH_SHORT ).show() } else if (!isValidEmail(k.text.toString())) { // Show an error message or handle the invalid email condition Toast.makeText( applicationContext, "Invalid email address", Toast.LENGTH_SHORT ).show() } else { val intent = Intent(this, WashPersonalActivity::class.java).apply { putExtra("mobile", j.text.toString()) putExtra("email", k.text.toString()) } startActivity(intent) } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { firebaseAuth.signOut() Toast.makeText(this, "Logout successfully", Toast.LENGTH_SHORT).show() val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } private fun isValidEmail(email: String): Boolean { return email.contains("@") } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/WashContactActivity.kt
4161411844
package com.example.autoinsight import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import java.util.* class RegisterActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth private val db = FirebaseFirestore.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) auth = FirebaseAuth.getInstance() val emailEditText = findViewById<EditText>(R.id.email) val passwordEditText = findViewById<EditText>(R.id.lastNaedsgsrme) val firstNameEditText = findViewById<EditText>(R.id.firstNameuser) val lastNameEditText = findViewById<EditText>(R.id.lastNameuser) val mobileNumberEditText = findViewById<EditText>(R.id.lastName) val registerButton = findViewById<Button>(R.id.registerBtn) val generateButton=findViewById<Button>(R.id.generateButton) val empidUI=findViewById<TextView>(R.id.empid) var empId: String? =null; generateButton.setOnClickListener { val firstName = firstNameEditText.text.toString() val lastName = lastNameEditText.text.toString() // Generate employee ID empId = generateEmployeeId(firstName, lastName) // Set the generated empId to the "empid" TextView empidUI.text = empId } registerButton.setOnClickListener { // Get user input val username = empId?.toLowerCase(Locale.ROOT) val email = emailEditText.text.toString() val password = passwordEditText.text.toString() val firstName = firstNameEditText.text.toString() val lastName = lastNameEditText.text.toString() val mobileNumber = mobileNumberEditText.text.toString() // Register the user with email and password auth.createUserWithEmailAndPassword("[email protected]", password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Registration successful val user = auth.currentUser if (user != null) { // Create a user object with data val userData = hashMapOf( "firstName" to firstName, "lastName" to lastName, "mobileNumber" to mobileNumber, "employeeId" to empId, "emaildId" to email ) // Store user data in Firestore db.collection("users") .document(empId.toString()) .set(userData) .addOnSuccessListener { Log.d(TAG, "User data added to Firestore") Toast.makeText(this, "Registration sucessfull", Toast.LENGTH_SHORT).show() val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) // Redirect to the next activity or perform other actions } .addOnFailureListener { e -> Log.w(TAG, "Error adding user data to Firestore", e) // Handle error } } } else { // Registration failed Log.w(TAG, "User registration failed", task.exception) // Handle registration failure } } } } private fun generateEmployeeId(firstName: String, lastName: String): String { // Generate a random 3-digit code val randomCode = (100..999).random() // Create an employee ID using the first 2 letters of the first name, // the last 2 letters of the last name, and the 3-digit code val empId = firstName.take(2).toUpperCase(Locale.ROOT) + lastName.takeLast(2).toUpperCase(Locale.ROOT) + randomCode.toString() return empId } companion object { private const val TAG = "RegisterActivity" } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/RegisterActivity.kt
2845456177
// CustomDialog.kt package com.example.autoinsight import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.Window import android.widget.Button import android.widget.TextView class CustomDialog(context: Context, private val message: String) : Dialog(context) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.custom_dialog_layout) val messageTextView: TextView = findViewById(R.id.messageTextView) val closeButton: Button = findViewById(R.id.closeButton) messageTextView.text = message closeButton.setOnClickListener { dismiss() } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/CustomDialog.kt
260250272
package com.example.autoinsight import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import android.widget.Button import android.widget.TextView class WashOtpActivity : AppCompatActivity() { private lateinit var resendTextView: TextView private lateinit var countDownTimer: CountDownTimer var resendEnabled: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_washotp) val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") // Toast.makeText(this, mobile.toString(), Toast.LENGTH_SHORT).show() val verify = this.findViewById<Button>(R.id.verify) verify.setOnClickListener { val intent = Intent(this, WashPersonalActivity::class.java).apply { putExtra("mobile", mobile) // Pass the mobile data to DataPersonalActivity putExtra("email", email) // Pass the email data to DataPersonalActivity } startActivity(intent) } resendTextView = findViewById(R.id.resendTextView) startCountdownTimer() } private fun startCountdownTimer() { resendEnabled = false resendTextView.setTextColor(Color.parseColor("#99000000")) countDownTimer = object : CountDownTimer(30000, 1000) { override fun onTick(millisUntilFinished: Long) { val secondsLeft = millisUntilFinished / 1000 resendTextView.setText("Resend OTP ("+secondsLeft+")") } override fun onFinish() { resendEnabled = true resendTextView.setText("Resend OTP") resendTextView.setTextColor(resources.getColor(R.color.blue)) } } countDownTimer.start() } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/WashOtpActivity.kt
2818709451
package com.example.autoinsight import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.ImageView import com.example.autoinsight.WashContactActivity.Companion.a import com.example.autoinsight.WashContactActivity.Companion.b import com.example.autoinsight.WashContactActivity.Companion.c import com.example.autoinsight.WashContactActivity.Companion.d import com.example.autoinsight.WashContactActivity.Companion.e import com.example.autoinsight.WashContactActivity.Companion.f class WashCarActivity : AppCompatActivity() { private val brands = arrayOf( "Tata", "Maruti", "Mahindra & Mahindra", "Hyundai", "Toyota", "Volkswagen", "Honda", "GM/Chevrolet", "BMW", "Mercedes" ) private val modelsMap = mapOf( "Tata" to arrayOf("Indica", "Tiago", "Tigor", "Harrier", "Safari","Nexon","Altroz","Punch","Zest","Nano","Sierra","Hexa","Aria","Sumo","Estate"), "Maruti" to arrayOf("Swift", "Dzire", "Ertiga", "Baleno", "Wagon R", "Alto","Presso","Versa","Eeco","Brezza","Celerio","Ciaz","Ignis","S Cross","XL6","Jumny","Vitara","Invicto","Cresent","Fronx"), "Mahindra & Mahindra" to arrayOf("Scorpio", "Bolero", "XUV500", "KUV100", "XUV300","XUV700","Thar", "Xylo"), "Hyundai" to arrayOf("i10", "i20", "Eon", "Xcent", "Venue", "Tucson", "Creta", "Grand i10", "Accent", "Sonata", "Verna", "Elentra", "Aura", "Alcazar",), "Toyota" to arrayOf("Camry", "Qualis", "Innova - Crysta", "Innova", "Corolla"), "Volkswagen" to arrayOf("Jetta", "Polo", "Atlas", "Golf", "Touareg", "Tiguan"), "Honda" to arrayOf( "Amaze", "City", "Civic", "CR-V", "Accord", "Jazz"), "GM/Chevrolet" to arrayOf("Beat", "Tavera", "Captiva", "Cruze"), "BMW" to arrayOf("X1","X3","X5","X7"), "Mercedes" to arrayOf("C-Class", "GLA", "S-Class", "E-Class", "A-Class", "GLE", "GLC", "GLS", "G-Class"), ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_washcar) /*g = this.findViewById(R.id.manf) h = this.findViewById(R.id.model) i = this.findViewById(R.id.manfYear) l = this.findViewById(R.id.regNo) m = this.findViewById(R.id.fuel)*/ val firstName = intent.getStringExtra("firstName") val lastName = intent.getStringExtra("lastName") val houseNo = intent.getStringExtra("houseNo") val city = intent.getStringExtra("city") val state = intent.getStringExtra("state") val pinCode = intent.getStringExtra("pinCode") val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val brandAutoCompleteTextView = findViewById<AutoCompleteTextView>(R.id.manufacturer) val modelAutoCompleteTextView = findViewById<AutoCompleteTextView>(R.id.car_model) // Populate the brand AutoCompleteTextView val brandAdapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, brands) brandAutoCompleteTextView.setAdapter(brandAdapter) // Set an item click listener for the brand AutoCompleteTextView brandAutoCompleteTextView.setOnItemClickListener { _, _, position, _ -> val selectedBrand = brands[position] val modelsForBrand = modelsMap[selectedBrand] ?: emptyArray() // Populate the model AutoCompleteTextView with models for the selected brand val modelAdapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, modelsForBrand) modelAutoCompleteTextView.setAdapter(modelAdapter) val fuelType = resources.getStringArray(R.array.fuelType) val arrayAdapterFuel: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, fuelType) val fuel = findViewById<AutoCompleteTextView>(R.id.fuel) fuel.setAdapter(arrayAdapterFuel) val carSegment = resources.getStringArray(R.array.carSegment) val arrayAdapterSegment: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, carSegment) val segment = findViewById<AutoCompleteTextView>(R.id.segment) segment.setAdapter(arrayAdapterSegment) val cnextButton = this.findViewById<Button>(R.id.cnextButton) cnextButton.setOnClickListener { val manufacturer = brandAutoCompleteTextView.text.toString() val carModel = modelAutoCompleteTextView.text.toString() val fuelType = fuel.text.toString() val carSegment = segment.text.toString() // Create an intent to start the next activity and pass data as extras val intent = Intent(this, activity_washplans::class.java).apply { putExtra("firstName", firstName) putExtra("lastName", lastName) putExtra("houseNo", houseNo) putExtra("city", city) putExtra("state", state) putExtra("pinCode", pinCode) putExtra("mobile", mobile) putExtra("email", email) putExtra("manufacturer", manufacturer) putExtra("carModel", carModel) putExtra("fuelType", fuelType) putExtra("carSegment", carSegment) } startActivity(intent) } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/WashCarActivity.kt
1273185405
package com.example.autoinsight import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.CountDownTimer import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class DataOtpActivity : AppCompatActivity() { private lateinit var resendTextView: TextView private lateinit var countDownTimer: CountDownTimer var resendEnabled: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dataotp) val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") // Toast.makeText(this, mobile.toString(), Toast.LENGTH_SHORT).show() val verify = this.findViewById<Button>(R.id.verify) verify.setOnClickListener { val intent = Intent(this, DataPersonalActivity::class.java).apply { putExtra("mobile", mobile) // Pass the mobile data to DataPersonalActivity putExtra("email", email) // Pass the email data to DataPersonalActivity } startActivity(intent) } resendTextView = findViewById(R.id.resendTextView) startCountdownTimer() } private fun startCountdownTimer() { resendEnabled = false resendTextView.setTextColor(Color.parseColor("#99000000")) countDownTimer = object : CountDownTimer(30000, 1000) { override fun onTick(millisUntilFinished: Long) { val secondsLeft = millisUntilFinished / 1000 resendTextView.setText("Resend OTP ("+secondsLeft+")") } override fun onFinish() { resendEnabled = true resendTextView.setText("Resend OTP") resendTextView.setTextColor(resources.getColor(R.color.blue)) } } countDownTimer.start() } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataOtpActivity.kt
3969815722
package com.example.autoinsight import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.net.ConnectivityManager import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AlertDialog import com.google.firebase.firestore.FirebaseFirestore class activity_washplans : AppCompatActivity() { private lateinit var myImageViews: Array<ImageView> private lateinit var myButtons: Array<Button> private val normalImageResources = arrayOf( R.drawable.plan1, R.drawable.plan2, R.drawable.plan3, R.drawable.plan4 ) private val clickedImageResources = arrayOf( R.drawable.clickedplan1, R.drawable.clickedplan2, R.drawable.clickedplan3, R.drawable.clickedplan4 ) private var isImageClicked = BooleanArray(4) { false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_washplans) // Initialize arrays for ImageView and Button references myImageViews = arrayOf( findViewById(R.id.imageView3), findViewById(R.id.imageView4), findViewById(R.id.imageView5), findViewById(R.id.imageView6) ) myButtons = arrayOf( findViewById(R.id.button1), findViewById(R.id.button7), findViewById(R.id.button6), findViewById(R.id.button5) ) var proceedButton = findViewById<Button>(R.id.proceedbtn) // Set click listeners for each button and its corresponding ImageView for (i in myButtons.indices) { val imageView = myImageViews[i] val normalImage = normalImageResources[i] val clickedImage = clickedImageResources[i] myButtons[i].setOnClickListener(View.OnClickListener { if (isImageClicked[i]) { // If the same button is clicked again, return it to the initial state isImageClicked[i] = false imageView.setImageResource(normalImage) myButtons[i].setBackgroundResource(R.drawable.round_btn) } else { // Reset the state of all other buttons and images resetButtonsAndImages(i) // Change the image in the corresponding ImageView isImageClicked[i] = true imageView.setImageResource(clickedImage) // Change the Button color based on the flag myButtons[i].setBackgroundResource(R.drawable.btnblue) } when (i) { 0 -> showToast("Plan 499 selected") 1 -> showToast("Plan 699 selected") 2 -> showToast("Plan 799 selected") 3 -> showToast("Plan 999 selected") } }) } proceedButton.setOnClickListener { // Check if the internet is available if (isNetworkAvailable()) { // Extract the selected plan var selectedPlan = "" for (i in myButtons.indices) { if (isImageClicked[i]) { when (i) { 0 -> selectedPlan = "499" 1 -> selectedPlan = "699" 2 -> selectedPlan = "799" 3 -> selectedPlan = "999" } } } // Extract the intented data received from the previous activity val intent = intent val firstName = intent.getStringExtra("firstName") val lastName = intent.getStringExtra("lastName") val houseNo = intent.getStringExtra("houseNo") val city = intent.getStringExtra("city") val state = intent.getStringExtra("state") val pinCode = intent.getStringExtra("pinCode") val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val manufacturer = intent.getStringExtra("manufacturer") val carModel = intent.getStringExtra("carModel") val fuelType = intent.getStringExtra("fuelType") val carSegment = intent.getStringExtra("carSegment") // Store the data in Firestore val db = FirebaseFirestore.getInstance() val currentUserEmail = email // Change this to the user's email val docRef = db.collection("carWashing").document(email.toString()) val userEmail = currentUserEmail val data = hashMapOf( "collectedBy" to userEmail, "firstName" to firstName, "lastName" to lastName, "houseNo" to houseNo, "city" to city, "state" to state, "pinCode" to pinCode, "mobile" to mobile, "email" to email, "manufacturer" to manufacturer, "carModel" to carModel, "fuelType" to fuelType, "carSegment" to carSegment, "selectedPlan" to selectedPlan ) docRef.set(data) .addOnSuccessListener { val intent = Intent(this, PaymentActivity::class.java) intent.putExtra("planSelected", selectedPlan) startActivity(intent) } .addOnFailureListener { showToast("Failed to save data to Firestore") } } else { // Show a dialog or your custom message when internet is not available showNoInternetDialog() } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } private fun resetButtonsAndImages(excludeIndex: Int) { for (i in myButtons.indices) { if (i != excludeIndex) { isImageClicked[i] = false myImageViews[i].setImageResource(normalImageResources[i]) myButtons[i].setBackgroundResource(R.drawable.round_btn) } } } private fun isNetworkAvailable(): Boolean { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun showNoInternetDialog() { val dialog = CustomDialog(this, "Please turn on the internet connection") dialog.show() } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/activity_washplans.kt
2848490809
package com.example.autoinsight import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import org.w3c.dom.Text class PaymentActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) val services = resources.getStringArray(R.array.services) val arrayAdapterAns: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, services) val ans = findViewById<AutoCompleteTextView>(R.id.ans) ans.setAdapter(arrayAdapterAns) val submitButton = this.findViewById<Button>(R.id.submitButton) submitButton.visibility = View.GONE var selectedText = "" ans.setOnItemClickListener { parent, view, position, id -> selectedText = parent.getItemAtPosition(position).toString() if (selectedText == "Yes") { submitButton.visibility = View.VISIBLE } else { selectedText = "No" submitButton.visibility = View.GONE } } var obtainedPlan: String val displayPlan = this.findViewById<TextView>(R.id.displayPlan) obtainedPlan = intent.getStringExtra("planSelected").toString() displayPlan.text = " Your Selected Plan: ₹" + obtainedPlan submitButton.setOnClickListener { // Display a toast message after clicking the submit button showToast("Data saved to Firestore successfully") val toastMessage = "Thankyou" Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show() val intent= Intent(this,SelectActivity::class.java) startActivity(intent) // You can perform additional actions here if needed } } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/PaymentActivity.kt
1872320607
package com.example.autoinsight import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.ImageView import android.widget.LinearLayout import android.widget.Toast import com.example.autoinsight.DataContactActivity.Companion.a import com.example.autoinsight.DataContactActivity.Companion.b import com.example.autoinsight.DataContactActivity.Companion.c import com.example.autoinsight.DataContactActivity.Companion.d import com.example.autoinsight.DataContactActivity.Companion.e import com.example.autoinsight.DataContactActivity.Companion.f import com.example.autoinsight.DataContactActivity.Companion.g import com.example.autoinsight.DataContactActivity.Companion.h import com.example.autoinsight.DataContactActivity.Companion.i import com.example.autoinsight.DataContactActivity.Companion.j import com.example.autoinsight.DataContactActivity.Companion.k import com.example.autoinsight.DataContactActivity.Companion.l import com.example.autoinsight.DataContactActivity.Companion.m class DataStatusActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datastatus) // Retrieve the values passed from DataCarActivity val firstName = intent.getStringExtra("firstName") val lastName = intent.getStringExtra("lastName") val houseNo = intent.getStringExtra("houseNo") val city = intent.getStringExtra("city") val state = intent.getStringExtra("state") val pinCode = intent.getStringExtra("pinCode") val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val manufacturer = intent.getStringExtra("manufacturer") val carModel = intent.getStringExtra("carModel") val fuelType = intent.getStringExtra("fuelType") val carSegment = intent.getStringExtra("carSegment") var selectedText: String? = null val services = resources.getStringArray(R.array.services) val arrayAdapter = ArrayAdapter(this, R.layout.dropdown, services) val serviceDone = findViewById<AutoCompleteTextView>(R.id.serviceDone) serviceDone.setAdapter(arrayAdapter) val doneWhere = resources.getStringArray(R.array.doneWhere) val arrayAdapter1: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, doneWhere) val where = findViewById<AutoCompleteTextView>(R.id.where) where.setAdapter(arrayAdapter1) val scheduledWhen = resources.getStringArray(R.array.scheduledWhen) val arrayAdapter2: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, scheduledWhen) val whenScheduled = findViewById<AutoCompleteTextView>(R.id.whenScheduled) whenScheduled.setAdapter(arrayAdapter2) val doneOften = resources.getStringArray(R.array.doneWhere) val arrayAdapter3: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, doneOften) val often = findViewById<AutoCompleteTextView>(R.id.often) often.setAdapter(arrayAdapter3) val avg = resources.getStringArray(R.array.avg) val arrayAdapter4: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, avg) val avgRunning = findViewById<AutoCompleteTextView>(R.id.avgRunning) avgRunning.setAdapter(arrayAdapter4) val whenlayout = findViewById<LinearLayout>(R.id.whenlayout) val wherelayout = findViewById<LinearLayout>(R.id.wherelayout) serviceDone.setOnItemClickListener { _, _, position, _ -> selectedText = serviceDone.text.toString() if (selectedText == "Yes") { wherelayout.visibility = View.VISIBLE whenlayout.visibility = View.GONE } else { selectedText = "No" whenlayout.visibility = View.VISIBLE wherelayout.visibility = View.GONE } } fun isValidSelection(autoCompleteTextView: AutoCompleteTextView): Boolean { val selectedValue = autoCompleteTextView.text.toString() return selectedValue != "Select your answer" } val snext = this.findViewById<Button>(R.id.snext) snext.setOnClickListener { if (isValidSelection(serviceDone)) { if (selectedText == "Yes") { if (isValidSelection(often) && isValidSelection(avgRunning) && isValidSelection(where)) { val intent = Intent(this, DataFeedbackActivity::class.java).apply { putExtra("firstName", firstName) putExtra("lastName", lastName) putExtra("houseNo", houseNo) putExtra("city", city) putExtra("state", state) putExtra("pinCode", pinCode) putExtra("mobile", mobile) putExtra("email", email) putExtra("manufacturer", manufacturer) putExtra("carModel", carModel) putExtra("fuelType", fuelType) putExtra("carSegment", carSegment) putExtra("serviceDone", selectedText) putExtra("where", where.text.toString()) putExtra("often", often.text.toString()) putExtra("avgRunning", avgRunning.text.toString()) } startActivity(intent) } else { Toast.makeText(this, "Please fill all the mandatory * fields", Toast.LENGTH_SHORT).show() } } else { if (isValidSelection(often) && isValidSelection(avgRunning) && isValidSelection(whenScheduled)) { val intent = Intent(this, DataFeedbackActivity::class.java).apply { putExtra("firstName", firstName) putExtra("lastName", lastName) putExtra("houseNo", houseNo) putExtra("city", city) putExtra("state", state) putExtra("pinCode", pinCode) putExtra("mobile", mobile) putExtra("email", email) putExtra("manufacturer", manufacturer) putExtra("carModel", carModel) putExtra("fuelType", fuelType) putExtra("carSegment", carSegment) putExtra("serviceDone", selectedText) putExtra("often", often.text.toString()) putExtra("avgRunning", avgRunning.text.toString()) putExtra("whenScheduled", whenScheduled.text.toString()) } startActivity(intent) } else { Toast.makeText(this, "Please fill all the mandatory * fields", Toast.LENGTH_SHORT).show() } } } else { Toast.makeText(this, "Please fill all the mandatory * fields", Toast.LENGTH_SHORT).show() } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataStatusActivity.kt
1322490822
package com.example.autoinsight import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import com.example.autoinsight.WashContactActivity.Companion.a import com.example.autoinsight.WashContactActivity.Companion.b import com.example.autoinsight.WashContactActivity.Companion.c import com.example.autoinsight.WashContactActivity.Companion.d import com.example.autoinsight.WashContactActivity.Companion.e import com.example.autoinsight.WashContactActivity.Companion.f import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class WashPersonalActivity : AppCompatActivity() { val firebaseAuth = FirebaseAuth.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datapersonal) a = this.findViewById(R.id.firstName) b = this.findViewById(R.id.lastName) c = this.findViewById(R.id.houseNo) d = this.findViewById(R.id.city) e = this.findViewById(R.id.state) f = this.findViewById(R.id.pinCode) // Retrieve the mobile and email data from the intent val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val pnextButton = this.findViewById<Button>(R.id.pnextButton) pnextButton.setOnClickListener { if (a.text.toString().isEmpty() || b.text.toString().isEmpty() || c.text.toString() .isEmpty() || d.text.toString().isEmpty() || e.text.toString() .isEmpty() || f.text.toString().isEmpty() ) { Toast.makeText(applicationContext, "Please fill all the mandatory * fields.", Toast.LENGTH_SHORT) .show() } else { val intent = Intent(this, WashCarActivity::class.java).apply { // Pass the UI component data and mobile and email data to DataCarActivity putExtra("firstName", a.text.toString()) putExtra("lastName", b.text.toString()) putExtra("houseNo", c.text.toString()) putExtra("city", d.text.toString()) putExtra("state", e.text.toString()) putExtra("pinCode",f.text.toString()) putExtra("mobile", mobile) putExtra("email", email) } startActivity(intent) } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { firebaseAuth.signOut() val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/WashPersonalActivity.kt
3919238470
/*package com.example.autoinsight import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView class WashPlanActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_washplan) val planList = resources.getStringArray(R.array.planList) val arrayAdapterPlan: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, planList) val plan = findViewById<AutoCompleteTextView>(R.id.plan) plan.setAdapter(arrayAdapterPlan) } }*/
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/WashPlanActivity.kt
3617837321
package com.example.autoinsight import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.hbb20.CountryCodePicker class DataContactActivity : AppCompatActivity() { val firebaseAuth = FirebaseAuth.getInstance() companion object{ @SuppressLint("StaticFieldLeak") lateinit var a: EditText @SuppressLint("StaticFieldLeak") lateinit var b: EditText @SuppressLint("StaticFieldLeak") lateinit var c: EditText @SuppressLint("StaticFieldLeak") lateinit var d: EditText @SuppressLint("StaticFieldLeak") lateinit var e: EditText @SuppressLint("StaticFieldLeak") lateinit var f: EditText @SuppressLint("StaticFieldLeak") lateinit var g: EditText @SuppressLint("StaticFieldLeak") lateinit var h: EditText @SuppressLint("StaticFieldLeak") lateinit var i: EditText @SuppressLint("StaticFieldLeak") lateinit var j: EditText @SuppressLint("StaticFieldLeak") lateinit var k: EditText lateinit var l: EditText lateinit var m: EditText } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datacontact) val ccp: CountryCodePicker = this.findViewById(R.id.countryCodeHolder) j = this.findViewById(R.id.mobile) k = this.findViewById(R.id.email) ccp.registerCarrierNumberEditText(j) val verify = this.findViewById<Button>(R.id.verify) verify.setOnClickListener { if (j.text.toString().isEmpty() || k.text.toString().isEmpty()) { Toast.makeText( applicationContext, "Please fill the mandatory * field.", Toast.LENGTH_SHORT ).show() } else if (!isValidEmail(k.text.toString())) { // Show an error message or handle the invalid email condition Toast.makeText( applicationContext, "Invalid email address", Toast.LENGTH_SHORT ).show() } else { val intent = Intent(this, DataPersonalActivity::class.java).apply { putExtra("mobile", j.text.toString()) putExtra("email", k.text.toString()) } startActivity(intent) } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { firebaseAuth.signOut() Toast.makeText(this, "Logout successfully", Toast.LENGTH_SHORT).show() val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } private fun isValidEmail(email: String): Boolean { return email.contains("@") } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataContactActivity.kt
3671144464
package com.example.autoinsight import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore class DataFeedbackActivity : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datafeedback) val services = resources.getStringArray(R.array.services) val arrayAdapterAns: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, services) val ans = findViewById<AutoCompleteTextView>(R.id.ans) ans.setAdapter(arrayAdapterAns) val fnameyes = findViewById<EditText>(R.id.fnameyes) val lnameyes = findViewById<EditText>(R.id.lnameyes) fnameyes.visibility = View.GONE lnameyes.visibility = View.GONE val edit1 = findViewById<EditText>(R.id.edit1) val edit2 = findViewById<EditText>(R.id.edit2) val auth = FirebaseAuth.getInstance() val currentUser = auth.currentUser if (currentUser == null) { // Handle the case where the user is not logged in or authentication fails // You may want to redirect the user to the login screen or perform some other action. return } val userEmail = currentUser.email // Retrieve the values passed from DataStatusActivity val firstName = intent.getStringExtra("firstName") val lastName = intent.getStringExtra("lastName") val houseNo = intent.getStringExtra("houseNo") val city = intent.getStringExtra("city") val state = intent.getStringExtra("state") val pinCode = intent.getStringExtra("pinCode") val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val manufacturer = intent.getStringExtra("manufacturer") val carModel = intent.getStringExtra("carModel") val fuelType = intent.getStringExtra("fuelType") val carSegment = intent.getStringExtra("carSegment") val serviceDone = intent.getStringExtra("serviceDone") val often = intent.getStringExtra("often") val avgRunning = intent.getStringExtra("avgRunning") val fnext = this.findViewById<Button>(R.id.submit) var selectedText = "" ans.setOnItemClickListener { parent, view, position, id -> selectedText = parent.getItemAtPosition(position).toString() if (selectedText == "Yes") { fnameyes.visibility = View.VISIBLE lnameyes.visibility = View.VISIBLE } else { selectedText = "No" fnameyes.visibility = View.GONE lnameyes.visibility = View.GONE } } fnext.setOnClickListener { // Firestore instance val db = FirebaseFirestore.getInstance() // Firestore collection reference val dataCollection = db.collection("datacollection") val currentUserDoc = dataCollection.document(email.toString() ?: "unknown_email") // Create a HashMap to store all the data val userData = hashMapOf( "collectedBy" to userEmail, "firstName" to firstName, "lastName" to lastName, "houseNo" to houseNo, "city" to city, "state" to state, "pinCode" to pinCode, "mobile" to mobile, "email" to email, "manufacturer" to manufacturer, "carModel" to carModel, "fuelType" to fuelType, "carSegment" to carSegment, "serviceDone" to serviceDone, "often" to often, "avgRunning" to avgRunning, "answer" to selectedText, // Store selectedText "fNameYes" to if (selectedText == "Yes") fnameyes.text.toString() else "", "lNameYes" to if (selectedText == "Yes") lnameyes.text.toString() else "", "Reasons behind selecting service center" to edit1.text.toString(), "edit2" to edit2.text.toString() ) // Add the user data (HashMap) to Firestore currentUserDoc.set(userData) .addOnSuccessListener { // Data saved successfully Toast.makeText(this, "Data saved to Firestore", Toast.LENGTH_SHORT).show() // Navigate to SelectActivity val intent = Intent(this, SelectActivity::class.java) startActivity(intent) } .addOnFailureListener { // Handle the error Toast.makeText(this, "Error: ${it.message}", Toast.LENGTH_SHORT).show() } } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataFeedbackActivity.kt
1540086397
package com.example.autoinsight import android.content.Intent import android.os.Bundle import android.text.InputType import android.text.InputType.TYPE_CLASS_TEXT import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD import android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import java.util.Locale class LoginActivity : AppCompatActivity() { private lateinit var passwordEditText: EditText private lateinit var showHide: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) showHide = findViewById<ImageView>(R.id.showHide) // val emailEditText = findViewById<EditText>(R.id.firstName) // Assuming this is the email input field passwordEditText = this.findViewById(R.id.passWord) showHide.setOnClickListener{ togglePasswordVisibility() } val loginButton = findViewById<Button>(R.id.loginButton) loginButton.setOnClickListener { val email = emailEditText.text.toString() val password = passwordEditText.text.toString() loginUser(email, password) } val register = findViewById<TextView>(R.id.register) register.setOnClickListener { val intent = Intent(this, RegisterActivity::class.java) startActivity(intent) } } private fun togglePasswordVisibility() { if (passwordEditText.inputType == (TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD)) { passwordEditText.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_VISIBLE_PASSWORD showHide.setImageResource(R.drawable.ic_show_eye) } else { passwordEditText.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD showHide.setImageResource(R.drawable.ic_hide_eye) } } private fun loginUser(email: String, password: String) { val auth = FirebaseAuth.getInstance() val loweremail=email?.toLowerCase(Locale.ROOT) val emailusername= "[email protected]" auth.signInWithEmailAndPassword(emailusername, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Login was successful val user = auth.currentUser Toast.makeText(this, loweremail.toString()+" Login successfully", Toast.LENGTH_SHORT).show() val intent = Intent(this, SelectActivity::class.java) startActivity(intent) } else { // Login failed // Handle login failure, show an error message, etc. } } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/LoginActivity.kt
114900216
// SplashActivity.kt package com.example.autoinsight import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.WindowManager import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth @Suppress("DEPRECATION") @SuppressLint("CustomSplashScreen") class SplashActivity : AppCompatActivity() { private lateinit var topAnim: Animation private lateinit var bottomAnim: Animation private lateinit var splashLogo: ImageView private lateinit var autoStringsLogo: ImageView private var splashScreen: Int = 5000 private lateinit var firebaseAuth: FirebaseAuth private var networkReceiver: NetworkReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_splash) topAnim = AnimationUtils.loadAnimation(this, R.anim.top_animation) bottomAnim = AnimationUtils.loadAnimation(this, R.anim.bottom_animation) splashLogo = this.findViewById(R.id.splashLogo) autoStringsLogo = this.findViewById(R.id.autoStringsLogo) splashLogo.animation = topAnim autoStringsLogo.animation = bottomAnim firebaseAuth = FirebaseAuth.getInstance() // Check internet connectivity if (isNetworkAvailable()) { // Check if a user is already authenticated using Firebase if (firebaseAuth.currentUser != null) { // If a user is logged in, navigate to SelectActivity val intent = Intent(this, SelectActivity::class.java) startActivity(intent) finish() } else { // If not logged in, proceed to LoginActivity after the splash screen delay val r = Runnable { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } Handler(Looper.getMainLooper()).postDelayed(r, splashScreen.toLong()) } } else { // Show custom dialog for no internet showNoInternetDialog() } // Register the network receiver to monitor network changes networkReceiver = NetworkReceiver() registerReceiver(networkReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) } override fun onDestroy() { super.onDestroy() // Unregister the network receiver to avoid memory leaks unregisterReceiver(networkReceiver) } private fun isNetworkAvailable(): Boolean { val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } private fun showNoInternetDialog() { val dialog = CustomDialog(this, "Please turn on the internet connection") dialog.show() } inner class NetworkReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (isNetworkAvailable()) { if (firebaseAuth.currentUser != null) { // If a user is logged in, navigate to SelectActivity val intent = Intent(context, SelectActivity::class.java) startActivity(intent) finish() } else { // If not logged in, proceed to LoginActivity after the splash screen delay val r = Runnable { val intent = Intent(context, LoginActivity::class.java) startActivity(intent) finish() } Handler(Looper.getMainLooper()).postDelayed(r, splashScreen.toLong()) } } } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/SplashActivity.kt
667534068
package com.example.autoinsight import android.content.Intent import android.os.Bundle import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.autoinsight.DataContactActivity.Companion.g import com.example.autoinsight.DataContactActivity.Companion.h import com.example.autoinsight.DataContactActivity.Companion.i import com.example.autoinsight.DataContactActivity.Companion.l import com.example.autoinsight.DataContactActivity.Companion.m class DataCarActivity : AppCompatActivity() { private val brands = arrayOf( "Tata", "Maruti", "Mahindra & Mahindra", "Hyundai", "Toyota", "Volkswagen", "Honda", "GM/Chevrolet", "BMW", "Mercedes" ) private val modelsMap = mapOf( "Tata" to arrayOf("Indica", "Tiago", "Tigor", "Harrier", "Safari","Nexon","Altroz","Punch","Zest","Nano","Sierra","Hexa","Aria","Sumo","Estate"), "Maruti" to arrayOf("Swift", "Dzire", "Ertiga", "Baleno", "Wagon R", "Alto","Presso","Versa","Eeco","Brezza","Celerio","Ciaz","Ignis","S Cross","XL6","Jumny","Vitara","Invicto","Cresent","Fronx"), "Mahindra & Mahindra" to arrayOf("Scorpio", "Bolero", "XUV500", "KUV100", "XUV300","XUV700","Thar", "Xylo"), "Hyundai" to arrayOf("i10", "i20", "Eon", "Xcent", "Venue", "Tucson", "Creta", "Grand i10", "Accent", "Sonata", "Verna", "Elentra", "Aura", "Alcazar",), "Toyota" to arrayOf("Camry", "Qualis", "Innova - Crysta", "Innova", "Corolla"), "Volkswagen" to arrayOf("Jetta", "Polo", "Atlas", "Golf", "Touareg", "Tiguan"), "Honda" to arrayOf( "Amaze", "City", "Civic", "CR-V", "Accord", "Jazz"), "GM/Chevrolet" to arrayOf("Beat", "Tavera", "Captiva", "Cruze"), "BMW" to arrayOf("X1","X3","X5","X7"), "Mercedes" to arrayOf("C-Class", "GLA", "S-Class", "E-Class", "A-Class", "GLE", "GLC", "GLS", "G-Class"), ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_datacar) /*g = this.findViewById(R.id.manf) h = this.findViewById(R.id.model) i = this.findViewById(R.id.manfYear) l = this.findViewById(R.id.regNo) m = this.findViewById(R.id.fuel)*/ val firstName = intent.getStringExtra("firstName") val lastName = intent.getStringExtra("lastName") val houseNo = intent.getStringExtra("houseNo") val city = intent.getStringExtra("city") val state = intent.getStringExtra("state") val pinCode = intent.getStringExtra("pinCode") val mobile = intent.getStringExtra("mobile") val email = intent.getStringExtra("email") val brandAutoCompleteTextView = findViewById<AutoCompleteTextView>(R.id.manufacturer) val modelAutoCompleteTextView = findViewById<AutoCompleteTextView>(R.id.car_model) // Populate the brand AutoCompleteTextView val brandAdapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, brands) brandAutoCompleteTextView.setAdapter(brandAdapter) // Set an item click listener for the brand AutoCompleteTextView brandAutoCompleteTextView.setOnItemClickListener { _, _, position, _ -> val selectedBrand = brands[position] val modelsForBrand = modelsMap[selectedBrand] ?: emptyArray() // Populate the model AutoCompleteTextView with models for the selected brand val modelAdapter = ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, modelsForBrand) modelAutoCompleteTextView.setAdapter(modelAdapter) val fuelType = resources.getStringArray(R.array.fuelType) val arrayAdapterFuel: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, fuelType) val fuel = findViewById<AutoCompleteTextView>(R.id.fuel) fuel.setAdapter(arrayAdapterFuel) val carSegment = resources.getStringArray(R.array.carSegment) val arrayAdapterSegment: ArrayAdapter<String> = ArrayAdapter(this, R.layout.dropdown, carSegment) val segment = findViewById<AutoCompleteTextView>(R.id.segment) segment.setAdapter(arrayAdapterSegment) val cnextButton = this.findViewById<Button>(R.id.cnextButton) cnextButton.setOnClickListener { val manufacturer = brandAutoCompleteTextView.text.toString() val carModel = modelAutoCompleteTextView.text.toString() val fuelType = fuel.text.toString() val carSegment = segment.text.toString() // Create an intent to start the next activity and pass data as extras val intent = Intent(this, DataStatusActivity::class.java).apply { putExtra("firstName", firstName) putExtra("lastName", lastName) putExtra("houseNo", houseNo) putExtra("city", city) putExtra("state", state) putExtra("pinCode", pinCode) putExtra("mobile", mobile) putExtra("email", email) putExtra("manufacturer", manufacturer) putExtra("carModel", carModel) putExtra("fuelType", fuelType) putExtra("carSegment", carSegment) } startActivity(intent) } val logout = this.findViewById<ImageView>(R.id.logout) logout.setOnClickListener { val intent = Intent(this, LoginActivity::class.java).apply { } startActivity(intent) } } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/DataCarActivity.kt
3901460556
package com.example.autoinsight import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class SelectActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_select) val dataCollection = this.findViewById<Button>(R.id.dataCollectionBtn) dataCollection.setOnClickListener { val intent = Intent(this, DataContactActivity::class.java).apply { } startActivity(intent) } val carWashing = this.findViewById<Button>(R.id.carWashingBtn) carWashing.setOnClickListener { val intent = Intent(this, WashContactActivity::class.java).apply { } startActivity(intent) } } }
AutoStrings/autoStrings-app-master/app/src/main/java/com/example/autoinsight/SelectActivity.kt
3826353990
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.happybirthday.ui.theme import androidx.compose.ui.graphics.Color val light_primary = Color(0xFFD0BCFF) val light_secondary = Color(0xFFCCC2DC) val light_tertiary = Color(0xFFEFB8C8) val dark_primary = Color(0xFF6650a4) val dark_secondary = Color(0xFF625b71) val dark_tertiary = Color(0xFF7D5260)
AtividadePam-Img/app/src/main/java/com/example/happybirthday/ui/theme/Color.kt
3593561967
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.happybirthday.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 = dark_primary, secondary = dark_secondary, tertiary = dark_tertiary ) private val LightColorScheme = lightColorScheme( primary = light_primary, secondary = light_secondary, tertiary = light_tertiary ) @Composable fun HappyBirthdayTheme( 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 ) }
AtividadePam-Img/app/src/main/java/com/example/happybirthday/ui/theme/Theme.kt
3207257769
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.happybirthday.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 ) )
AtividadePam-Img/app/src/main/java/com/example/happybirthday/ui/theme/Type.kt
1904458271
package com.example.happybirthday import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.happybirthday.ui.theme.HappyBirthdayTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { HappyBirthdayTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { GreetingImage( stringResource(R.string.happy_birthday_text), stringResource(R.string.signature_text) ) } } } } } @Composable fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) { Column( verticalArrangement = Arrangement.Center, modifier = modifier ) { Text( text = message, fontSize = 75.sp, lineHeight = 105.sp, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 16.dp) ) Text( text = from, fontSize = 36.sp, modifier = Modifier .padding(top = 16.dp) .padding(end = 16.dp) .align(alignment = Alignment.End) ) } } @Composable fun GreetingImage(message: String, from: String, modifier: Modifier = Modifier) { Box(modifier) { Image( painter = painterResource(id = R.drawable.tec), contentDescription = null, contentScale = ContentScale.Crop, alpha = 0.5F ) GreetingText( message = message, from = from, modifier = Modifier .fillMaxSize() .padding(8.dp) ) } } @Preview(showBackground = false) @Composable private fun BirthdayCardPreview() { HappyBirthdayTheme { GreetingImage( stringResource(R.string.happy_birthday_text), stringResource(R.string.signature_text) ) } }
AtividadePam-Img/app/src/main/java/com/example/happybirthday/MainActivity.kt
2630874096
package com.example.qqquotes 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.qqquotes", appContext.packageName) } }
codsoft_2/app/src/androidTest/java/com/example/qqquotes/ExampleInstrumentedTest.kt
62232588
package com.example.qqquotes 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) } }
codsoft_2/app/src/test/java/com/example/qqquotes/ExampleUnitTest.kt
102822291
package com.example.qqquotes import android.annotation.SuppressLint import android.content.ContentValues import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.os.Bundle import android.provider.MediaStore import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import java.io.ByteArrayOutputStream class FavoritesActivity : AppCompatActivity() { private lateinit var toolBar: androidx.appcompat.widget.Toolbar private val db: QuoteDB by lazy { QuoteDB.getDB(this) } @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) toolBar = findViewById(R.id.toolBar) setSupportActionBar(toolBar) supportActionBar?.title = "Favorite Quotes" supportActionBar?.setDisplayHomeAsUpEnabled(true) val quotes: java.util.ArrayList<String>? = intent.getStringArrayListExtra("Quotes") val fav = db.quoteDao().allQuotes // Favourite list (Local copy) from DB to check if it is favourite or not val favL = ArrayList<Quote>() for (i in fav) { if (i.fav) favL.add(i) } val btnShare: ImageView = findViewById(R.id.im_quote_share) val btnShareImg: ImageView = findViewById(R.id.im_quote_share_img) val btnFav: ImageView = findViewById(R.id.im_quote_like) val tvQuote: TextView = findViewById(R.id.tv_quote) val cv: ConstraintLayout = findViewById(R.id.cv) val btnReStyle: ImageView = findViewById(R.id.im_quote_restyle) val btnReColor: ImageView = findViewById(R.id.im_quote_recolor) btnReStyle.setOnClickListener { MainActivity.randomStyles(tvQuote) } btnReColor.setOnClickListener { cv.setBackgroundColor(MainActivity.generateRandomColor()) } btnReStyle.performClick() btnReColor.performClick() btnShareImg.setOnClickListener { // Hide buttons btnFav.visibility = View.GONE btnShare.visibility = View.GONE btnReStyle.visibility = View.GONE btnReColor.visibility = View.GONE btnShareImg.visibility = View.GONE val ll: LinearLayout = findViewById(R.id.ll) val layoutParams = ll.layoutParams // Change layout parameters to WRAP_CONTENT layoutParams?.let { it.height = ViewGroup.LayoutParams.WRAP_CONTENT ll.layoutParams = it } // Listen for layout changes ll.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // Ensure we remove the layout listener to prevent it from being called multiple times ll.viewTreeObserver.removeOnGlobalLayoutListener(this) // Capture the bitmap after layout changes val bitmap = Bitmap.createBitmap(ll.width, ll.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) ll.draw(canvas) val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes) // Save the bitmap to a file val contentResolver = applicationContext.contentResolver val contentValues = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, "TitleFav") put(MediaStore.Images.Media.MIME_TYPE, "image/png") } val uri = contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues ) uri?.let { contentResolver.openOutputStream(it)?.use { outputStream -> outputStream.write(bytes.toByteArray()) } } // Share the bitmap using Intent.ACTION_SEND val shareIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_STREAM, uri) type = "image/png" } startActivity(Intent.createChooser(shareIntent, "Share Quote as Image")) // Restore original layout params (MATCH_PARENT) layoutParams?.let { it.height = ViewGroup.LayoutParams.MATCH_PARENT ll.layoutParams = it } // Restore buttons visibility btnShare.visibility = View.VISIBLE btnReStyle.visibility = View.VISIBLE btnReColor.visibility = View.VISIBLE btnShareImg.visibility = View.VISIBLE if (favL.isNotEmpty()) btnFav.visibility = View.VISIBLE } }) // Request a layout pass to ensure that layout changes take effect ll.requestLayout() } btnShare.setOnClickListener { val iShare = Intent(Intent.ACTION_SEND) iShare.setType("text/plain") iShare.putExtra(Intent.EXTRA_TEXT, tvQuote.text.toString()) startActivity(Intent.createChooser(iShare, "Share quote via")) } if (favL.isNotEmpty()) { var curr = 0 var curIndex = favL[curr].id val liked = R.drawable.ic_heart_black_24dp val unLike = R.drawable.ic_heart_outline_24dp tvQuote.text = quotes?.get(curIndex) cv.setOnTouchListener(object : OnSwipeTouchListener(this@FavoritesActivity) { override fun onDoubleClick() { btnFav.performClick() } }) if (favL.size > 1) cv.setOnTouchListener(object : OnSwipeTouchListener(this@FavoritesActivity) { override fun onDoubleClick() { btnFav.performClick() } override fun onSwipeLeft() { if (--curr < 0) curr = favL.size - 1 curIndex = favL[curr].id val chkFav: Boolean? = db.quoteDao().chkFav(curIndex) if ((chkFav != null) && !chkFav) { btnFav.setImageResource(unLike) btnFav.tag = "unlike" } else { btnFav.setImageResource(liked) btnFav.tag = "like" } tvQuote.text = quotes?.get(curIndex) } override fun onSwipeRight() { if (++curr >= favL.size) curr = 0 curIndex = favL[curr].id tvQuote.text = quotes?.get(curIndex) val chkFav: Boolean? = db.quoteDao().chkFav(curIndex) if ((chkFav != null) && !chkFav) { btnFav.setImageResource(unLike) btnFav.tag = "unlike" } else { btnFav.setImageResource(liked) btnFav.tag = "like" } } override fun onSwipe() { btnReStyle.performClick() btnReColor.performClick() } }) val chkFav: Boolean? = db.quoteDao().chkFav(curIndex) if ((chkFav != null) && chkFav) { btnFav.setImageResource(liked) btnFav.tag = "like" } btnFav.visibility = View.VISIBLE btnFav.setOnClickListener { if (btnFav.tag == "like") { btnFav.setImageResource(unLike) btnFav.tag = "unlike" db.quoteDao().favQuote(Quote(curIndex, false)) } else { btnFav.setImageResource(liked) btnFav.tag = "like" db.quoteDao().favQuote(Quote(curIndex, true)) } } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { super.onBackPressedDispatcher.onBackPressed() return super.onOptionsItemSelected(item) } }
codsoft_2/app/src/main/java/com/example/qqquotes/FavoritesActivity.kt
1443139685
package com.example.qqquotes import android.annotation.SuppressLint import android.app.AlertDialog import android.content.ContentValues import android.content.Intent import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import java.io.ByteArrayOutputStream import java.util.stream.IntStream.range class MainActivity : AppCompatActivity() { private val quotes: ArrayList<String> = arrayListOf( "Swipe for Quotes! \nDouble Tap to favorite! \nShare any Quote by clicking on the share icon! \nChange the look with options on bottom right-side!", "Strive for progress, not perfection.", "Every accomplishment starts with the decision to try.", "Believe you can and you're halfway there.", "In the middle of difficulty lies opportunity.", "Success is not final, failure is not fatal: It is the courage to continue that counts.", "The only way to do great work is to love what you do.", "Action is the foundational key to all success.", "The best way to predict the future is to create it.", "Success is walking from failure to failure with no loss of enthusiasm.", "Dream big and dare to fail.", "Don't watch the clock; do what it does. Keep going.", "The only limit to our realization of tomorrow will be our doubts of today.", "Opportunities don't happen, you create them.", "The secret of getting ahead is getting started.", "If you want to achieve greatness, stop asking for permission.", "Your limitation—it's only your imagination.", "Push yourself because no one else is going to do it for you.", "Great things never come from comfort zones.", "Dream it. Wish it. Do it.", "Success doesn't just find you. You have to go out and get it.", "The harder you work for something, the greater you'll feel when you achieve it.", "Dream bigger. Do bigger.", "Don't stop when you're tired. Stop when you're done.", "Wake up with determination. Go to bed with satisfaction.", "Do something today that your future self will thank you for.", "Little things make big days.", "It's going to be hard, but hard does not mean impossible.", "Don't wait for opportunity. Create it.", "Sometimes we're tested not to show our weaknesses, but to discover our strengths.", "The key to success is to focus on goals, not obstacles.", "Dream it. Believe it. Build it.", "Wake up with determination. Sleep with satisfaction.", "The only limit is your mind.", "Prove them wrong.", "Do it with passion or not at all.", "Do your best and forget the rest.", "The journey of a thousand miles begins with one step.", "It's not about perfect. It's about effort.", "You are capable of more than you know.", "Believe you can and you're halfway there.", "One day or day one. You decide.", "The only way to do great work is to love what you do.", "Strive for progress, not perfection.", "You are enough.", "The harder you work, the luckier you get.", "Believe in yourself and all that you are.", "You don't have to be great to start, but you have to start to be great.", "Success is not the key to happiness. Happiness is the key to success.", "Do what you love, and the money will follow.", "Believe in yourself and you will be unstoppable.", "Success is not just about making money. It's about making a difference.", "Your attitude determines your direction.", "Hard work beats talent when talent doesn't work hard.", "If it doesn't challenge you, it won't change you.", "The only time you should ever look back is to see how far you've come.", "The difference between ordinary and extraordinary is that little extra.", "You are stronger than you think.", "Success is stumbling from failure to failure with no loss of enthusiasm.", "You are never too old to set another goal or to dream a new dream.", "A year from now you may wish you had started today.", "The only person you should try to be better than is the person you were yesterday.", "Don't count the days, make the days count.", "The best way to predict the future is to create it.", "The only limit to our realization of tomorrow will be our doubts of today.", "Success is the sum of small efforts repeated day in and day out.", "The future belongs to those who believe in the beauty of their dreams.", "Life is 10% what happens to us and 90% how we react to it.", "The best revenge is massive success.", "The way to get started is to quit talking and begin doing.", "Whatever you are, be a good one.", "Don't stop until you're proud.", "Your only limit is you.", "Don't wait for opportunity. Create it.", "The only thing that stands between you and your dream is the will to try and the belief that it is actually possible.", "Great things never come from comfort zones.", "A successful man is one who can lay a firm foundation with the bricks others have thrown at him.", "It always seems impossible until it is done.", "What you get by achieving your goals is not as important as what you become by achieving your goals.", "The only place where success comes before work is in the dictionary.", "Success is not in what you have, but who you are.", "Don't watch the clock; do what it does. Keep going.", "Don't let yesterday take up too much of today.", "The only way to do great work is to love what you do.", "The best revenge is massive success.", "Opportunities don't happen, you create them.", "Well done is better than well said.", "You don't have to be great to start, but you have to start to be great.", "The future belongs to those who believe in the beauty of their dreams.", "Don't count the days, make the days count.", "The only limit to our realization of tomorrow will be our doubts of today.", "The journey of a thousand miles begins with one step.", "You are never too old to set another goal or to dream a new dream.", "The only person you should try to be better than is the person you were yesterday.", "Believe you can and you're halfway there.", "Success is not the key to happiness. Happiness is the key to success.", "Action is the foundational key to all success.", "The only way to do great work is to love what you do.", "Strive for progress, not perfection.", "You miss 100% of the shots you don't take.", "Believe in yourself and all that you are.", "Sometimes, the quality of sadness is more poignant than the quality of happiness.", "In the silence of solitude, we often find the true quality of our existence.", "Quality is often overshadowed by the weight of mediocrity.", "Amidst the chaos of life, we search for the quality of peace.", "The quality of our sorrow reveals the depth of our love.", "In the darkness of despair, we discover the quality of our resilience.", "The quality of our regrets often surpasses the quality of our achievements.", "Lost in the shadows, we yearn for the quality of light.", "In the echo of loneliness, we measure the quality of our connections.", "Amidst the ruins of shattered dreams, we seek the quality of hope.", "The quality of our tears speaks volumes about the depth of our pain.", "In the silence of suffering, we find the true quality of our strength.", "The quality of our existence is often defined by the depth of our scars.", "In the depths of despair, we search for the quality of redemption.", "The quality of life is sometimes measured by the depth of our sorrows.", "Amidst the ruins of broken promises, we search for the quality of trust.", "In the chill of solitude, we long for the quality of warmth.", "The quality of our struggles reveals the depth of our character.", "Lost in the wilderness of uncertainty, we yearn for the quality of direction.", "In the shadows of doubt, we seek the quality of certainty.", "The quality of our fears often outweighs the quality of our hopes.", "Amidst the chaos of confusion, we search for the quality of clarity.", "In the labyrinth of despair, we seek the quality of purpose.", "The quality of our nightmares mirrors the darkness within our souls.", "In the void of emptiness, we yearn for the quality of fulfillment.", "Lost in the mists of memory, we search for the quality of remembrance.", "In the silence of grief, we find the true quality of our tears.", "The quality of our failures often shapes the trajectory of our lives.", "Amidst the wreckage of shattered dreams, we search for the quality of resilience.", "In the depths of despair, we discover the quality of our humanity.", "The quality of our pain often exceeds the capacity of our endurance.", "Lost in the labyrinth of regret, we yearn for the quality of forgiveness.", "In the echoes of abandonment, we seek the quality of acceptance.", "The quality of our solitude reveals the depth of our introspection.", "Amidst the storm of chaos, we search for the quality of serenity.", "In the darkness of despair, we find the true quality of our courage.", "The quality of our solitude often mirrors the depth of our introspection.", "Lost in the wilderness of despair, we yearn for the quality of hope.", "In the depths of sorrow, we seek the quality of solace.", "The quality of our losses often shapes the course of our lives.", "Amidst the wreckage of shattered dreams, we search for the quality of resilience.", "In the silence of grief, we find the true quality of our strength.", "The quality of our struggles often reveals the depth of our resilience.", "Lost in the darkness of despair, we yearn for the quality of light.", "In the depths of sorrow, we seek the quality of healing.", "The quality of our pain often exceeds the capacity of our understanding.", "Amidst the storm of chaos, we search for the quality of peace.", "In the silence of solitude, we find the true quality of our essence.", "The quality of our solitude often mirrors the depth of our introspection.", "Lost in the wilderness of despair, we yearn for the quality of hope.", "In the depths of sorrow, we seek the quality of solace.", "The quality of our losses often shapes the course of our lives.", "Amidst the wreckage of shattered dreams, we search for the quality of resilience.", "In the silence of grief, we find the true quality of our strength.", "The quality of our struggles often reveals the depth of our resilience.", "Lost in the darkness of despair, we yearn for the quality of light.", "In the depths of sorrow, we seek the quality of healing.", "The quality of our pain often exceeds the capacity of our understanding.", "Amidst the storm of chaos, we search for the quality of peace.", "In the silence of solitude, we find the true quality of our essence.", "The quality of our solitude often mirrors the depth of our introspection.", "Lost in the wilderness of despair, we yearn for the quality of hope.", "In the depths of sorrow, we seek the quality of solace.", "The quality of our losses often shapes the course of our lives.", "Amidst the wreckage of shattered dreams, we search for the quality of resilience.", "In the silence of grief, we find the true quality of our strength.", "The quality of our struggles often reveals the depth of our resilience.", "Lost in the darkness of despair, we yearn for the quality of light.", "In the depths of sorrow, we seek the quality of healing.", "The quality of our pain often exceeds the capacity of our understanding.", "Amidst the storm of chaos, we search for the quality of peace.", "In the silence of solitude, we find the true quality of our essence.", "The quality of our solitude often mirrors the depth of our introspection.", "Lost in the wilderness of despair, we yearn for the quality of hope.", "In the depths of sorrow, we seek the quality of solace.", "The quality of our losses often shapes the course of our lives.", "Amidst the wreckage of shattered dreams, we search for the quality of resilience.", "In the silence of grief, we find the true quality of our strength.", "The quality of our struggles often reveals the depth of our resilience.", "Lost in the darkness of despair, we yearn for the quality of light.", "In the depths of sorrow, we seek the quality of healing.", "The quality of our pain often exceeds the capacity of our understanding.", "Amidst the storm of chaos, we search for the quality of peace.", "In the silence of solitude, we find the true quality of our essence.", "The quality of our solitude often mirrors the depth of our introspection.", "Quality is like underwear; you only notice it when it's not there.", "I'm not lazy; I'm just in energy-saving mode.", "I'm not clumsy; I'm just embracing my inner gracefulness.", "Quality is like Wi-Fi, you only miss it when it's gone.", "I'm not arguing; I'm just explaining why I'm right.", "Quality is like humor; you can't force it.", "I'm not a procrastinator; I'm just on a prolonged coffee break.", "I'm not short; I'm just concentrated awesome.", "Quality is like a fine wine; it gets better with age.", "I'm not a control freak; I just know what you should be doing.", "I'm not a morning person; I'm a coffee enthusiast.", "Quality is like duct tape; it fixes almost anything.", "I'm not late; I'm just fashionably challenged by time.", "I'm not forgetful; I'm just creating suspense.", "Quality is like chocolate; it makes everything better.", "I'm not a mess; I'm just a colorful masterpiece in progress.", "I'm not old; I'm just a vintage classic.", "Quality is like pizza; even when it's bad, it's still pretty good.", "I'm not stubborn; my way is just better.", "I'm not indecisive; I'm just exploring all my options.", "Quality is like karma; what goes around, comes around.", "I'm not weird; I'm just limited edition.", "I'm not multitasking; I'm just inefficiently efficient.", "I'm not lazy; I'm just conserving energy for future endeavors.", "Quality is like music; it's all about the rhythm.", "I'm not clumsy; the floor just hates me.", "I'm not a control freak; I just have better ideas.", "I'm not disorganized; I'm creatively chaotic.", "Quality is like a good joke; it's all about the delivery.", "I'm not messy; I'm just creatively untidy.", "I'm not a perfectionist; I'm just very particular.", "Quality is like a hug; it's comforting and always appreciated.", "I'm not procrastinating; I'm just prioritizing leisure time.", "I'm not lost; I'm just taking the scenic route.", "I'm not addicted to chocolate; I'm committed to it.", "Quality is like a smile; it's contagious.", "I'm not talking to myself; I'm having a private conversation with my inner genius.", "I'm not a quitter; I'm just strategically surrendering.", "I'm not ignoring you; I'm just giving you the silent treatment.", "Quality is like a good joke; it's all about the timing.", "I'm not antisocial; I'm selectively social.", "I'm not a hoarder; I'm a collector of memories.", "I'm not overthinking; I'm just exploring every possible outcome.", "I'm not impatient; I'm just very enthusiastic about instant gratification.", "Quality is like a good cup of tea; it's soothing for the soul.", "I'm not avoiding responsibility; I'm just delegating it to someone else.", "I'm not a procrastinator; I'm just on a deadline-driven adrenaline rush.", "I'm not forgetful; I'm just selectively remembering.", "Quality is like good manners; it never goes out of style.", "I'm not a night owl; I'm just nocturnally inclined.", "I'm not a control freak; I'm just very persuasive.", "I'm not nosy; I'm just highly interested in your business.", "I'm not a pessimist; I'm just an optimist with experience.", "I'm not ignoring you; I'm just giving you the gift of absence.", "I'm not a klutz; I'm just auditioning for a slapstick comedy.", "I'm not a couch potato; I'm a leisure enthusiast.", "I'm not avoiding work; I'm just enhancing my procrastination skills.", "I'm not grumpy; I'm just embracing my inner grouch.", "I'm not a know-it-all; I'm just highly knowledgeable.", "I'm not high maintenance; I'm just low tolerance for mediocrity.", "I'm not a drama queen; I'm a melodrama enthusiast.", "I'm not antisocial; I'm just pro-solitude.", "I'm not a morning person; I'm a nocturnal warrior.", "I'm not paranoid; I'm just highly alert.", "I'm not ignoring you; I'm just practicing selective hearing.", "I'm not a scatterbrain; I'm just creatively spontaneous.", "I'm not avoiding exercise; I'm just procrastinating sweat.", "I'm not a shopaholic; I'm just financially enthusiastic.", "I'm not a snob; I'm just highly selective.", "I'm not a hypochondriac; I'm just healthily cautious.", "I'm not a control freak; I'm just a quality enthusiast.", "I'm not a procrastinator; I'm just a deadline enthusiast.", "I'm not a morning person; I'm just allergic to mornings.", "I'm not a social butterfly; I'm a conversation connoisseur.", "I'm not indecisive; I'm just exploring all possibilities.", "I'm not a klutz; I'm just auditioning for a slapstick comedy.", "I'm not a couch potato; I'm a leisure enthusiast.", "I'm not avoiding work; I'm just enhancing my procrastination skills.", "I'm not grumpy; I'm just embracing my inner grouch.", "I'm not a know-it-all; I'm just highly knowledgeable.", "I'm not high maintenance; I'm just low tolerance for mediocrity.", "I'm not a drama queen; I'm a melodrama enthusiast.", "I'm not antisocial; I'm just pro-solitude.", "I'm not a morning person; I'm a nocturnal warrior.", "I'm not paranoid; I'm just highly alert.", "I'm not ignoring you; I'm just practicing selective hearing.", "I'm not a scatterbrain; I'm just creatively spontaneous.", "I'm not avoiding exercise; I'm just procrastinating sweat.", "I'm not a shopaholic; I'm just financially enthusiastic.", "I'm not a snob; I'm just highly selective.", "I'm not lazy, I'm just on energy-saving mode.", "I'm not arguing, I'm just explaining why I'm right.", "I'm not clumsy, it's just the floor hates me, the table and chairs are bullies, and the walls get in my way.", "I'm not short, I'm just concentrated awesome.", "I'm not addicted to chocolate, we're just in a committed relationship.", "I'm not a complete idiot, some parts are missing.", "I'm not a morning person. I'm a coffee person.", "I'm not fat, I'm just easy to see.", "I'm not late, everyone else is just early.", "I'm not random, I just have many thoughts." ) private var quoteNum: Int = 0 private lateinit var toolBar: androidx.appcompat.widget.Toolbar private val liked = R.drawable.ic_heart_black_24dp private val unLike = R.drawable.ic_heart_outline_24dp private val db: QuoteDB by lazy { QuoteDB.getDB(this) } @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) toolBar = findViewById(R.id.toolBar) setSupportActionBar(toolBar) supportActionBar?.title = "Quick Quality QuoteS App" val cv: ConstraintLayout = findViewById(R.id.cv) val tvQuote: TextView = findViewById(R.id.tv_quote) val btnReStyle: ImageView = findViewById(R.id.im_quote_restyle) val btnReColor: ImageView = findViewById(R.id.im_quote_recolor) val btnFav: ImageView = findViewById(R.id.im_quote_like) val btnShareImg: ImageView = findViewById(R.id.im_quote_share_img) val btnShare: ImageView = findViewById(R.id.im_quote_share) var fav = db.quoteDao().allQuotes if (fav.isEmpty()){ tvQuote.text = quotes[0] for (i in range(0, quotes.size)) db.quoteDao().addQuote(Quote(false)) } else { tvQuote.text = getRandom() if (db.quoteDao().chkFav(quoteNum)) { btnFav.setImageResource(liked) btnFav.tag = "like" } else { btnFav.setImageResource(unLike) btnFav.tag = "unlike" } btnReStyle.performClick() btnReColor.performClick() } cv.setOnTouchListener(object : OnSwipeTouchListener(this@MainActivity) { override fun onSwipe() { tvQuote.text = getRandom() if (db.quoteDao().chkFav(quoteNum)) { btnFav.setImageResource(liked) btnFav.tag = "like" } else { btnFav.setImageResource(unLike) btnFav.tag = "unlike" } btnReColor.performClick() val s = (0..3).random() for (i in 0..s) btnReStyle.performClick() } override fun onDoubleClick() { btnFav.performClick() } }) btnFav.visibility = View.VISIBLE btnReStyle.setOnClickListener { randomStyles(tvQuote) } btnReColor.setOnClickListener { cv.setBackgroundColor(generateRandomColor()) } btnShareImg.setOnClickListener { // Hide buttons btnFav.visibility = View.GONE btnShare.visibility = View.GONE btnShareImg.visibility = View.GONE btnReStyle.visibility = View.GONE btnReColor.visibility = View.GONE val ll: LinearLayout = findViewById(R.id.ll) val layoutParams = ll.layoutParams // Change layout parameters to WRAP_CONTENT layoutParams?.let { it.height = ViewGroup.LayoutParams.WRAP_CONTENT ll.layoutParams = it } // Listen for layout changes ll.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // Ensure we remove the layout listener to prevent it from being called multiple times ll.viewTreeObserver.removeOnGlobalLayoutListener(this) // Capture the bitmap after layout changes val bitmap = Bitmap.createBitmap(ll.width, ll.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) ll.draw(canvas) val bytes = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes) // Save the bitmap to a file val contentResolver = applicationContext.contentResolver val contentValues = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, "TitleMain") put(MediaStore.Images.Media.MIME_TYPE, "image/png") } val uri = contentResolver.insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues ) uri?.let { contentResolver.openOutputStream(it)?.use { outputStream -> outputStream.write(bytes.toByteArray()) } } // Share the bitmap using Intent.ACTION_SEND val shareIntent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_STREAM, uri) type = "image/png" } startActivity(Intent.createChooser(shareIntent, "Share Quote as Image")) // Restore original layout params (MATCH_PARENT) layoutParams?.let { it.height = ViewGroup.LayoutParams.MATCH_PARENT ll.layoutParams = it } // Restore buttons visibility btnShare.visibility = View.VISIBLE btnShareImg.visibility = View.VISIBLE btnFav.visibility = View.VISIBLE btnReStyle.visibility = View.VISIBLE btnReColor.visibility = View.VISIBLE } }) // Request a layout pass to ensure that layout changes take effect ll.requestLayout() } btnShare.setOnClickListener { val iShare = Intent(Intent.ACTION_SEND) iShare.setType("text/plain") iShare.putExtra(Intent.EXTRA_TEXT, tvQuote.text.toString()) startActivity(Intent.createChooser(iShare, "Share quote via")) } if ((fav.isNotEmpty()) && db.quoteDao().chkFav(quoteNum)) btnFav.setImageResource(liked) btnFav.setOnClickListener { if (btnFav.tag == "like") { btnFav.setImageResource(unLike) btnFav.tag = "unlike" db.quoteDao().favQuote(Quote(quoteNum, false)) } else { // if (quoteNum == 0) return@setOnClickListener btnFav.setImageResource(liked) btnFav.tag = "like" db.quoteDao().favQuote(Quote(quoteNum, true)) } fav = db.quoteDao().allQuotes } val onBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { val backDialog: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity) backDialog.setTitle("Close Quick Quality QuoteS App?") backDialog.setIcon(R.drawable.baseline_exit_to_app_24) backDialog.setMessage("Are you sure you want to exit?") backDialog.setPositiveButton("Yes") { dialog, _ -> dialog.dismiss() finish() } backDialog.setNegativeButton("No") { dialog, _ -> dialog.dismiss() } backDialog.show() } } onBackPressedDispatcher.addCallback(onBackPressedCallback) } private fun getRandom(): String { quoteNum = (0 until quotes.size).random() return quotes[quoteNum] } override fun onResume() { val fav = db.quoteDao().allQuotes val btnFav: ImageView = findViewById(R.id.im_quote_like) val chkFav: Boolean? = db.quoteDao().chkFav(quoteNum) if ((fav.isNotEmpty()) && (chkFav != null && chkFav)) { btnFav.setImageResource(liked) btnFav.tag = "like" } else if (fav != null) { btnFav.setImageResource(unLike) btnFav.tag = "unlike" } super.onResume() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.opt_toolbar, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.btn_fav -> { val iNext = Intent(this, FavoritesActivity::class.java) iNext.putStringArrayListExtra("Quotes", quotes) startActivity(iNext) } } return super.onOptionsItemSelected(item) } companion object { fun randomStyles(tvQuote: TextView) { var num: Int = tvQuote.typeface.style if ((++num) == 4) num = 1 val rCAPS = Math.random() > 0.3 && Math.random() < 0.6 tvQuote.isAllCaps = rCAPS when (num) { 1 -> tvQuote.setTypeface(null, Typeface.BOLD) 2 -> tvQuote.setTypeface(null, Typeface.ITALIC) 3 -> tvQuote.setTypeface(null, Typeface.BOLD_ITALIC) } } fun generateRandomColor(): Int { val alpha = 75 // Generate random RGB color val r = (0..255).random() val g = (0..255).random() val b = (0..255).random() // Combine alpha and RGB values to create the color return Color.argb(alpha, r, g, b) } } }
codsoft_2/app/src/main/java/com/example/qqquotes/MainActivity.kt
3060684901
package com.example.qqquotes import android.content.Context import android.view.GestureDetector import android.view.MotionEvent import android.view.View import kotlin.math.abs open class OnSwipeTouchListener(context: Context) : View.OnTouchListener { private val gestureDetector: GestureDetector companion object { private const val SWIPE_THRESHOLD = 100 private const val SWIPE_VELOCITY_THRESHOLD = 100 } init { gestureDetector = GestureDetector(context, GestureListener()) } override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { view.performClick() return gestureDetector.onTouchEvent(motionEvent) } private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { return true } override fun onDoubleTap(e: MotionEvent): Boolean { onDoubleClick() return super.onDoubleTap(e) } override fun onFling( e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { if (e1 == null) return false val diffX = e2.x - e1.x val diffY = e2.y - e1.y if (abs(diffX) > abs(diffY) && abs(diffX) > SWIPE_THRESHOLD && abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight() } else { onSwipeLeft() } onSwipe() return true } return false } } open fun onDoubleClick() {} open fun onSwipe() {} open fun onSwipeRight() {} open fun onSwipeLeft() {} }
codsoft_2/app/src/main/java/com/example/qqquotes/gestureDetector.kt
3692354197
package com.example.assignment1 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.assignment1", appContext.packageName) } }
MAD_Assignments/Assignment_1/app/src/androidTest/java/com/example/assignment1/ExampleInstrumentedTest.kt
1807440260
package com.example.assignment1 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) } }
MAD_Assignments/Assignment_1/app/src/test/java/com/example/assignment1/ExampleUnitTest.kt
786327860
package com.example.assignment1 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.ImageView import android.widget.TextView import kotlin.random.Random var randomInt = Random.nextInt(0,100) class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val myButton: Button = findViewById(R.id.button) val buttonSHow: Button= findViewById(R.id.button2) buttonSHow.setOnClickListener { // Code to be executed when the button is clicked setContentView(R.layout.assignmnet2) val hatCheckBox = findViewById<CheckBox>(R.id.hatcheckBox4) val eyesBrowsCheckBox = findViewById<CheckBox>(R.id.eyebrowscheckBox5) val eyesCheckBox = findViewById<CheckBox>(R.id.eyescheckBox9) val noseCheckBox = findViewById<CheckBox>(R.id.nosecheckBox6) val mustacheCheckBox = findViewById<CheckBox>(R.id.mustachecheckBox7) val armsCheckBox = findViewById<CheckBox>(R.id.armscheckBox8) val shoesCheckBox = findViewById<CheckBox>(R.id.shoescheckBox13) val mouthCheckBox = findViewById<CheckBox>(R.id.mouthcheckBox11) val glassCheckBox = findViewById<CheckBox>(R.id.GlassescheckBox10) val earCheckBox = findViewById<CheckBox>(R.id.earscheckBox12) hatCheckBox.isChecked = true eyesBrowsCheckBox.isChecked = true eyesCheckBox.isChecked= true noseCheckBox.isChecked = true mustacheCheckBox.isChecked = true armsCheckBox.isChecked = true shoesCheckBox.isChecked = true mouthCheckBox.isChecked = true glassCheckBox.isChecked = true earCheckBox.isChecked = true hatCheckBox.setOnCheckedChangeListener { _, isChecked -> val hat = findViewById<ImageView>(R.id.hats) if (isChecked) { hat.visibility = View.VISIBLE } else { hat.visibility = View.GONE } } noseCheckBox.setOnCheckedChangeListener { _, isChecked -> val nose = findViewById<ImageView>(R.id.nose) if (isChecked) { nose.visibility = View.VISIBLE } else { nose.visibility = View.GONE } } eyesCheckBox.setOnCheckedChangeListener { _, isChecked -> val eyes = findViewById<ImageView>(R.id.eyes) if (isChecked) { eyes.visibility = View.VISIBLE } else { eyes.visibility = View.GONE } } eyesBrowsCheckBox.setOnCheckedChangeListener { _, isChecked -> val eyebrow = findViewById<ImageView>(R.id.eyebrows) if (isChecked) { eyebrow.visibility = View.VISIBLE } else { eyebrow.visibility = View.GONE } } glassCheckBox.setOnCheckedChangeListener { _, isChecked -> val glasses = findViewById<ImageView>(R.id.glasses) if (isChecked) { glasses.visibility = View.VISIBLE } else { glasses.visibility = View.GONE } } mouthCheckBox.setOnCheckedChangeListener { _, isChecked -> val mouth = findViewById<ImageView>(R.id.mouth) if (isChecked) { mouth.visibility = View.VISIBLE } else { mouth.visibility = View.GONE } } mustacheCheckBox.setOnCheckedChangeListener { _, isChecked -> val mustache = findViewById<ImageView>(R.id.mustache) if (isChecked) { mustache.visibility = View.VISIBLE } else { mustache.visibility = View.GONE } } earCheckBox.setOnCheckedChangeListener { _, isChecked -> val ears = findViewById<ImageView>(R.id.ears) if (isChecked) { ears.visibility = View.VISIBLE } else { ears.visibility = View.GONE } } armsCheckBox.setOnCheckedChangeListener { _, isChecked -> val arm = findViewById<ImageView>(R.id.hands) if (isChecked) { arm.visibility = View.VISIBLE } else { arm.visibility = View.GONE } } shoesCheckBox.setOnCheckedChangeListener { _, isChecked -> val shoe = findViewById<ImageView>(R.id.shoes) if (isChecked) { shoe.visibility = View.VISIBLE } else { shoe.visibility = View.GONE } } } myButton.setOnClickListener { // Code to be executed when the button is clicked Validate() } } fun Validate(){ val inputText : EditText = findViewById(R.id.Text) val editText =findViewById<TextView>(R.id.TextVeiw) val input= Integer.parseInt(inputText.text.toString()) if (input > randomInt){ editText.text="your guess i Too HIgh $randomInt" } else if (input < randomInt) editText.text="your guess i Low $randomInt" else{ editText.text="ohh Hurrah U guessed it correctly Now Number is Changed" randomInt = Random.nextInt() } } }
MAD_Assignments/Assignment_1/app/src/main/java/com/example/assignment1/MainActivity.kt
3156943624
package com.example.assignment1 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import kotlin.random.Random class Task2 : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { } }
MAD_Assignments/Assignment_1/app/src/main/java/com/example/assignment1/Task2.kt
1020466971
package com.example.lab3 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.lab3", appContext.packageName) } }
MAD_Assignments/Lab_3/app/src/androidTest/java/com/example/lab3/ExampleInstrumentedTest.kt
2655181882
package com.example.lab3 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) } }
MAD_Assignments/Lab_3/app/src/test/java/com/example/lab3/ExampleUnitTest.kt
3387524120
package com.example.lab3.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)
MAD_Assignments/Lab_3/app/src/main/java/com/example/lab3/ui/theme/Color.kt
34021530
package com.example.lab3.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 Lab3Theme( 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 ) }
MAD_Assignments/Lab_3/app/src/main/java/com/example/lab3/ui/theme/Theme.kt
2406599819
package com.example.lab3.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 ) */ )
MAD_Assignments/Lab_3/app/src/main/java/com/example/lab3/ui/theme/Type.kt
219338867
package com.example.lab3 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Star import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.lab3.ui.theme.Lab3Theme import androidx.compose.material3.Icon import androidx.compose.runtime.* class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Lab3Theme { // A surface container using the 'background' color from the theme val navController = rememberNavController() val navController = rememberNavController() friendsRatingApp() } } } } @Composable fun friendsRatingApp() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "friends") { composable("friends"){ friends(navController) } composable("detailsActivity"){ detailsActivity() } } } @Composable fun lab3Activity2() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "login") { composable("login"){ logIn(navController = navController) } composable("register"){ register(navController = navController) } } } val questions = listOf( "1. What callbacks are called when an app is first launched?", "2. What callbacks occur when home is pressed?", "3. What callbacks occur when an app is restart from the launcher?", "4. What callbacks occur when the device rotated?" ) @Composable fun activity1(navController:NavController) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(20.dp,0.dp,0.dp,20.dp) ) { for(question in questions) { Card(Modifier.padding(8.dp)) { Text( text = question, fontSize = 20.sp, fontFamily = androidx.compose.ui.text.font.FontFamily.SansSerif, fontStyle = FontStyle.Italic, fontWeight = FontWeight.Bold ) } } } } @Composable fun logIn(navController: NavController) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize(1f) ) { OutlinedTextField( value = "Email", onValueChange = {}, modifier = Modifier .padding(0.dp,20.dp,0.dp,0.dp) ) OutlinedTextField( value = "Password", onValueChange = {}, modifier = Modifier .padding(0.dp,20.dp,0.dp,0.dp) ) OutlinedButton( onClick = { /*TODO*/ }, modifier = Modifier .padding(0.dp,30.dp,0.dp,0.dp) ) { Text( text = "Log In", ) } Text( text = "Not a member? Register here", color = Color.Blue, modifier = Modifier .clickable { navController.navigate("register") } .padding(0.dp, 40.dp, 0.dp, 0.dp) ) } } @Composable fun register(navController: NavController) { Column( verticalArrangement =Arrangement.Center, horizontalAlignment =Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize(1f) ) { OutlinedTextField(value = "", onValueChange = {}, label = { Text(text = "Full Name")},modifier = Modifier.padding(0.dp,10.dp,0.dp,0.dp)) OutlinedTextField(value = "", onValueChange = {}, label = { Text(text = "Email")},modifier = Modifier.padding(0.dp,10.dp,0.dp,0.dp)) OutlinedTextField(value = "", onValueChange = {}, label = { Text(text = "Password")},modifier = Modifier.padding(0.dp,10.dp,0.dp,0.dp)) Button(onClick = {}, modifier = Modifier .padding(0.dp, 40.dp, 0.dp, 0.dp) .fillMaxWidth(.7f) ){ Text(text = "REGISTER") } Text( text = "Already registered! Log In", modifier = Modifier .padding(0.dp, 40.dp, 0.dp, 0.dp) .clickable { navController.navigate("login") } , color = Color.White, fontSize = 20.sp ) } } data class Image(val imageId:Int, val name:String) val ImageList = listOf<Image>( Image(imageId = R.drawable.rchel, name = "Rachel"), Image(imageId = R.drawable.ross, name = "Ross"), Image(imageId = R.drawable.rossgeller, name = "Ross Geller"), Image(imageId = R.drawable.monica_geller, name = "Monica Geller"), Image(imageId = R.drawable.square_monica, name = "Square Geller"), Image(imageId = R.drawable.men3, name = "Men"), ) @OptIn(ExperimentalMaterial3Api::class) @Composable fun friends(navController: NavController) { Column( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(10.dp,10.dp) ) { Text( text ="Friends", fontStyle = FontStyle.Normal, fontWeight = FontWeight.Bold, fontSize = 50.sp ) Text(text = "Click on a character to rate his acting,") LazyVerticalGrid( columns = GridCells.Fixed(2), // modifier = Modifier.background(Color.Cyan) ){ items(ImageList){ (image,name)-> Column( verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .shadow(elevation = 1.dp) ) { Box( modifier = Modifier .padding(2.dp) .clickable { navController.navigate("detailsActivity")} ) { Image( painter = painterResource(id = image), contentDescription = name, contentScale = ContentScale.Crop, modifier = Modifier .size(200.dp, 200.dp) //.fillMaxWidth(.5f) .clip(MaterialTheme.shapes.medium) .padding(12.dp) ) } Text(text = name) Spacer(modifier = Modifier.height(8.dp)) } } } } } @Composable fun detailsActivity() { Column( verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize(1f) .background(Color.Cyan) ) { RatingBar() ImageCard( ) } } @Composable fun RatingBar() { var rating by remember { mutableStateOf(0) } Row( modifier = Modifier .fillMaxWidth() .padding(16.dp) .background(MaterialTheme.colorScheme.background) ) { repeat(5) { index -> val isFilled = index < rating val starIcon = if (isFilled) Icons.Default.Star else Icons.Default.Star Icon( imageVector = starIcon, contentDescription = null, modifier = Modifier .clickable { rating = index + 1 } .padding(4.dp) .size(36.dp) ) } } } @Composable fun ImageCard() { val imgId = 2 Box( modifier = Modifier .background(Color.Blue) ) { Image( painter = painterResource(id = imgId), contentDescription = null, ) Text(text ="Cool Friend") } } @Preview(showBackground = true, showSystemUi = true) @Composable fun GreetingPreview() { Lab3Theme { } }
MAD_Assignments/Lab_3/app/src/main/java/com/example/lab3/MainActivity.kt
906424532
package com.example.mad_lab_2 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.mad_lab_2", appContext.packageName) } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/androidTest/java/com/example/mad_lab_2/ExampleInstrumentedTest.kt
20690829
package com.example.mad_lab_2 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) } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/test/java/com/example/mad_lab_2/ExampleUnitTest.kt
2633245849
package com.example.mad_lab_2.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)
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/ui/theme/Color.kt
3523181551
package com.example.mad_lab_2.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 MAD_LAB_2Theme( 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 ) }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/ui/theme/Theme.kt
3532656291
package com.example.mad_lab_2.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 ) */ )
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/ui/theme/Type.kt
1029074238
package com.example.mad_lab_2 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.ScrollableDefaults import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyGridScope import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AssistChip import androidx.compose.material3.BottomAppBar import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults.topAppBarColors import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mad_lab_2.ui.theme.MAD_LAB_2Theme import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Settings class TaskFour : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MAD_LAB_2Theme { // A surface container using the 'background' color from the theme ScaffloadExample() } } } } @OptIn(ExperimentalMaterial3Api::class) @Preview(showBackground = true) @Composable fun ScaffloadExample(){ Scaffold ( // modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { TopAppBar( colors = topAppBarColors( Color(0xFF6200EE), ), title = { Text(text = "Lazy Grid Layout", color = Color.White, fontSize = 20.sp) }, navigationIcon = { Icon(Icons.Filled.ArrowBack, contentDescription = "", tint = Color.White) }, actions = { Icon(Icons.Filled.Menu, contentDescription = "", tint = Color.White) } ) }, ) { it -> Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(it) ){ // add lazy grid layout here LazyVerticalGrid( columns = GridCells.Adaptive(minSize = 150.dp) ) { items(20) { LazyGridExample() } } } } } @Composable fun LazyGridExample() { Card(modifier = Modifier.padding(8.dp)) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Image( painter = painterResource(id = R.drawable.noshads_image), contentDescription = "android image", modifier = Modifier.size(width = 300.dp, height = 100.dp), ) Text(text = "Noshad Ali", fontSize = 15.sp, modifier = Modifier.padding(8.dp)) } } }
MAD_Assignments/Lab_2/JetpackCompose-Lab-02-main/app/src/main/java/com/example/mad_lab_2/Task04.kt
3043771696