content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.practice
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)
}
} | myfirstrepoproject/app/src/test/java/com/example/practice/ExampleUnitTest.kt | 2403705594 |
package com.example.practice.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) | myfirstrepoproject/app/src/main/java/com/example/practice/ui/theme/Color.kt | 3247879662 |
package com.example.practice.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 PracticeTheme(
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
)
} | myfirstrepoproject/app/src/main/java/com/example/practice/ui/theme/Theme.kt | 1103443755 |
package com.example.practice.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
)
*/
) | myfirstrepoproject/app/src/main/java/com/example/practice/ui/theme/Type.kt | 3633633737 |
package com.example.practice
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.material3.Button
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.runtime.remember
//import android.os.Bundle
//import androidx.activity.ComponentActivity
//import androidx.activity.compose.setContent
//import androidx.compose.material3.Text
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.ElevatedButton
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
//import androidx.compose.foundation.Image
//import androidx.compose.ui.res.painterResource
//import androidx.compose.foundation.layout.Spacer
//import androidx.compose.foundation.layout.fillMaxSize
//import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
//import androidx.compose.foundation.layout.width
//import androidx.compose.foundation.layout.size
//import androidx.compose.foundation.shape.CircleShape
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
//import androidx.compose.foundation.border
//import androidx.compose.material3.MaterialTheme
//import androidx.compose.material3.Surface
import com.example.practice.ui.theme.PracticeTheme
//
//
//class MainActivity: ComponentActivity() {
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContent {
// PracticeTheme {
// Surface(modifier = Modifier.fillMaxSize()) {
// MessageCard(Message("Android", "Jetpack Compose"))
// }
// }
// }
// }
//}
//
//data class Message(val author: String, val body: String)
//
//@Composable
//fun MessageCard(msg: Message) {
// // Add padding around our message
// Row(modifier = Modifier.padding(all = 8.dp)) {
// Image(
// painter = painterResource(R.drawable.androidpractice),
// contentDescription = "Contact profile picture",
// modifier = Modifier
// .size(40.dp)
// .clip(CircleShape)
// .border(1.5.dp, MaterialTheme.colorScheme.secondary)
// )
//
//
// // Add a horizontal space between the image and the column
// Spacer(modifier = Modifier.width(8.dp))
//
// Column {
// Text(text = msg.author,
// color = MaterialTheme.colorScheme.primary,
// style = MaterialTheme.typography.titleSmall
// )
//
// Spacer(modifier = Modifier.height(4.dp))
// Surface(shape = MaterialTheme.shapes.medium, shadowElevation = 1.dp) {
// Text(
// text = msg.body,
// modifier = Modifier.padding(all = 4.dp),
// style = MaterialTheme.typography.bodyMedium
// )
// }
// }
// }
//}
//
//@Preview
//@Composable
//fun PreviewMessageCard() {
// Surface {
// MessageCard(
// msg = Message("Lexi", "Take a look at Jetpack Compose, it's great!")
// )
// }
// }
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PracticeTheme {
MyApp()
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
var expanded by rememberSaveable{mutableStateOf(false)}
val extrapadding by animateDpAsState(targetValue = if (expanded) 48.dp else 0.dp,
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
Surface(color = MaterialTheme.colorScheme.primary,
modifier = modifier.padding(vertical = 4.dp, horizontal = 8.dp)) {
Row(modifier = Modifier.padding(24.dp)) {
Column(modifier = Modifier
.weight(1f)
.padding(bottom = extrapadding.coerceAtLeast(0.dp))) {
Text(text = "Hello ")
Text(text = name)
}
ElevatedButton(onClick = {expanded = !expanded}) {
Text(if (expanded) "Show less" else "Show more")
}
}
}
}
@Preview(showBackground = true, widthDp = 1080/2, heightDp = 2408/2)
@Composable
fun GreetingPreview() {
PracticeTheme {
MyApp(modifier = Modifier.fillMaxSize())
}
}
@Composable
fun MyApp(modifier: Modifier = Modifier, ){
var shouldShowOnboarding by rememberSaveable {mutableStateOf(true)}
if (shouldShowOnboarding){
OnboardingScreen(onContinueClicked = {shouldShowOnboarding = false})
} else {
Greetings()
}
}
@Composable
private fun Greetings(modifier: Modifier = Modifier,
names: List<String> = List(1000){"$it"}) {
LazyColumn(modifier = modifier.padding(vertical = 4.dp)){
items(items=names) {
name -> Greeting(name = name)
}
}
}
@Composable
fun OnboardingScreen(
onContinueClicked: () -> Unit,
modifier: Modifier = Modifier) {
Column(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Welcome to the basics Codelab!")
Button(
modifier = modifier.padding(vertical = 24.dp),
onClick = onContinueClicked
) {
Text("continue")
}
}
}
@Preview(showBackground = true, widthDp = 1080/2, heightDp = 2408/2)
@Composable
fun OnboardingPreview() {
PracticeTheme {
OnboardingScreen(onContinueClicked = {})
}
}
@Preview
@Composable
fun MyAppPreview() {
PracticeTheme {
MyApp()
}
} | myfirstrepoproject/app/src/main/java/com/example/practice/MainActivity.kt | 1591216491 |
package com.pepito.partypalpro
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.pepito.partypalpro", appContext.packageName)
}
} | PartyPal-Pro/app/src/androidTest/java/com/pepito/partypalpro/ExampleInstrumentedTest.kt | 1591366530 |
package com.pepito.partypalpro
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)
}
} | PartyPal-Pro/app/src/test/java/com/pepito/partypalpro/ExampleUnitTest.kt | 1019090754 |
package com.pepito.partypalpro
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import com.pepito.partypalpro.databinding.ActivityAddAguestBinding
import com.pepito.partypalpro.storage.AppDatabase
import com.pepito.partypalpro.storage.Guest
import com.pepito.partypalpro.storage.GuestDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class AddAGuestActivity : AppCompatActivity() {
private lateinit var binding: ActivityAddAguestBinding
private lateinit var guestDao: GuestDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAddAguestBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize the Room database
val database = AppDatabase.getInstance(this)
guestDao = database.guestDao()
val addButton: Button = binding.buttonAddGuest
addButton.setOnClickListener {
addGuest()
}
// Set up ArrayAdapter for the Spinner using the array resource
val spinnerArrayAdapter = ArrayAdapter.createFromResource(
this,
R.array.rsvp_statuses,
android.R.layout.simple_spinner_dropdown_item
)
binding.spinnerRSVP.adapter = spinnerArrayAdapter
}
private fun addGuest() {
val name = binding.editTextName.text.toString()
val email = binding.editTextEmail.text.toString()
val rsvpStatus = binding.spinnerRSVP.selectedItem.toString()
if (name.isNotBlank() && email.isNotBlank()) {
val guest = Guest(name = name, email = email, rsvpStatus = rsvpStatus)
// Use a coroutine to perform the database operation on a background thread
CoroutineScope(Dispatchers.IO).launch {
val insertedId = guestDao.addGuest(guest)
// Check if the insertion was successful
if (insertedId > 0) {
// Insertion successful, log it
Log.d("AddGuestActivity", "Guest added successfully with ID: $insertedId")
// Optionally, you can handle it further or finish the activity
runOnUiThread {
Toast.makeText(
this@AddAGuestActivity,
"Guest added successfully",
Toast.LENGTH_SHORT
).show()
finish()
}
} else {
// Insertion failed, log it
Log.e("AddGuestActivity", "Failed to add guest to the database")
runOnUiThread {
Toast.makeText(this@AddAGuestActivity, "Failed to add guest", Toast.LENGTH_SHORT)
.show()
}
}
}
} else {
// Handle invalid input
Toast.makeText(this, "Name and email are required", Toast.LENGTH_SHORT).show()
}
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/AddAGuestActivity.kt | 2402912483 |
package com.pepito.partypalpro
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.pepito.partypalpro.databinding.ActivityMainBinding
import com.pepito.partypalpro.recycleradapter.GuestAdapter
import com.pepito.partypalpro.storage.AppDatabase
import com.pepito.partypalpro.storage.GuestDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var guestDao: GuestDao
private lateinit var guestAdapter: GuestAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize the Room database
val database = AppDatabase.getInstance(this)
guestDao = database.guestDao()
// Set up RecyclerView
guestAdapter = GuestAdapter(this, emptyList())
binding.guestRecyclerView.layoutManager = LinearLayoutManager(this)
binding.guestRecyclerView.adapter = guestAdapter
// Set up BottomNavigationView
binding.bottomNavigationView.setOnItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.guest -> {
// Handle the guest item click (if needed)
true
}
R.id.task -> {
// Redirect to ToDoListActivity when the "Task" item is clicked
startActivity(Intent(this, ToDoListActivity::class.java))
true
}
else -> false
}
}
// Load data from the Room database using Coroutines
loadDataFromDatabase()
}
override fun onResume() {
super.onResume()
loadDataFromDatabase()
}
private fun loadDataFromDatabase() {
CoroutineScope(Dispatchers.Main).launch {
val guests = guestDao.getAllGuests()
// Update the adapter with the new data
guestAdapter.setData(guests)
// Update the visibility of textViewNoGuest based on the data size
binding.textViewNoGuest.visibility = if (guests.isEmpty()) View.VISIBLE else View.GONE
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menuItemAddGuest -> {
startActivity(Intent(this, AddAGuestActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/MainActivity.kt | 2878382706 |
package com.pepito.partypalpro
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.pepito.partypalpro.databinding.ActivityGuestDetailBinding
import com.pepito.partypalpro.storage.AppDatabase
import com.pepito.partypalpro.storage.GuestDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class GuestDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityGuestDetailBinding
private lateinit var guestDao: GuestDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGuestDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize the Room database
val database = AppDatabase.getInstance(this)
guestDao = database.guestDao()
// Get the guest ID from the intent
val guestId = intent.getLongExtra("guestId", -1)
if (guestId != -1L) {
// Use Coroutines to retrieve the guest details from the database
CoroutineScope(Dispatchers.Main).launch {
val guest = guestDao.getGuestById(guestId)
// Populate the views with guest details
binding.editTextName.setText(guest?.name)
binding.editTextEmail.setText(guest?.email)
// Set the selection for the spinner based on the guest's RSVP status
val statusArray = resources.getStringArray(R.array.rsvp_statuses)
val statusIndex = statusArray.indexOf(guest?.rsvpStatus)
if (statusIndex != -1) {
binding.spinnerRSVP.setSelection(statusIndex)
}
}
}
// Set up click listeners for update and delete buttons
binding.buttonDeleteGuest.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
// Get the guest ID from the intent
val guestIdVal = intent.getLongExtra("guestId", -1)
if (guestId != -1L) {
// Use Coroutines to delete the guest from the database
guestDao.deleteGuestById(guestIdVal)
// Optionally, you can navigate back to the main activity or perform other actions
finish()
}
}
}
binding.buttonUpdateGuest.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
// Get the guest ID from the intent
val guestIdVal = intent.getLongExtra("guestId", -1)
if (guestId != -1L) {
// Use Coroutines to retrieve the guest details from the database
val guest = guestDao.getGuestById(guestIdVal)
// Update guest details with the new values
guest?.name = binding.editTextName.text.toString()
guest?.email = binding.editTextEmail.text.toString()
guest?.rsvpStatus = binding.spinnerRSVP.selectedItem.toString()
// Use Coroutines to update the guest in the database
guest?.let {
guestDao.updateGuest(it)
// Optionally, you can navigate back to the main activity or perform other actions
finish()
}
}
}
}
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/GuestDetailActivity.kt | 190170471 |
package com.pepito.partypalpro
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.format.DateFormat
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.pepito.partypalpro.alarm.AlarmReceiver
import com.pepito.partypalpro.databinding.ActivityTaskDetailBinding
import com.pepito.partypalpro.storage.AppDatabase
import com.pepito.partypalpro.storage.TaskDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Locale
class TaskDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityTaskDetailBinding
private lateinit var taskDao: TaskDao
private var taskId: Long = -1
private var isReminderSet = false
private var reminderHour = 0
private var reminderMinute = 0
private lateinit var alarmManager: AlarmManager
private lateinit var pendingIntent: PendingIntent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityTaskDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize the Room database
val database = AppDatabase.getInstance(this)
taskDao = database.taskDao()
// Get the task ID from the intent
taskId = intent.getLongExtra("taskId", -1)
if (taskId != -1L) {
// Use Coroutines to retrieve the task details from the database
CoroutineScope(Dispatchers.Main).launch {
val task = taskDao.getTaskById(taskId)
// Populate the views with task details
binding.editTaskName.setText(task?.taskName)
binding.editTextTaskDesc.setText(task?.taskDescription)
// Set the switch state based on the saved state in the Task model
binding.switchSetReminder.isChecked = task?.isReminderSet ?: false
isReminderSet = task?.isReminderSet ?: false
if (!isReminderSet){
binding.textViewReminderTime.text = getString(R.string.no_time_set)
}
else{
reminderHour = task?.reminderHour ?: 0
reminderMinute = task?.reminderMinute ?: 0
val setupTime = formatTime(reminderHour, reminderMinute)
binding.textViewReminderTime.text = getString(R.string.reminder_message, setupTime)
}
}
}
// Set up click listeners for update and delete buttons
binding.buttonDeleteTask.setOnClickListener {
// Handle delete action here
deleteTask()
}
binding.buttonUpdateTask.setOnClickListener {
// Handle update action here
updateTask()
}
binding.switchSetReminder.setOnCheckedChangeListener { _, isChecked ->
isReminderSet = isChecked
if (!isReminderSet){
binding.textViewReminderTime.text = getString(R.string.no_time_set)
cancelAlarm()
Toast.makeText(this, "Please press update button to apply changes.", Toast.LENGTH_LONG).show()
}
}
binding.setAlarmButton.setOnClickListener {
showTimePickerDialog()
}
alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
}
@SuppressLint("ScheduleExactAlarm")
private fun setAlarm() {
if (isReminderSet) {
val currentTime = Calendar.getInstance()
val alarmTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, reminderHour)
set(Calendar.MINUTE, reminderMinute)
set(Calendar.SECOND, 0)
}
// Check if the selected time is in the future
if (alarmTime.after(currentTime)) {
val intent = Intent(this, AlarmReceiver::class.java)
intent.putExtra("taskName", binding.editTaskName.text.toString())
pendingIntent = PendingIntent.getBroadcast(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// For devices running Android M (API 23) and above
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
alarmTime.timeInMillis,
pendingIntent
)
} else {
// For devices running Android L (API 21) to K (API 19)
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
alarmTime.timeInMillis,
pendingIntent
)
}
}
}
}
private fun deleteTask() {
CoroutineScope(Dispatchers.IO).launch {
// Delete the task from the Room database
taskDao.deleteTaskById(taskId)
// Notify the user if needed
// ...
// Finish the activity (optional: navigate back to ToDoListActivity)
finish()
}
Toast.makeText(this, "Task has been removed.", Toast.LENGTH_LONG).show()
}
private fun updateTask() {
val updatedTaskName = binding.editTaskName.text.toString()
val updatedTaskDesc = binding.editTextTaskDesc.text.toString()
if (updatedTaskName.isNotBlank()) {
CoroutineScope(Dispatchers.IO).launch {
// Retrieve the existing task from the Room database
val existingTask = taskDao.getTaskById(taskId)
// Update the task details
existingTask?.let {
it.taskName = updatedTaskName
it.taskDescription = updatedTaskDesc
it.isReminderSet = isReminderSet
it.reminderHour = reminderHour
it.reminderMinute = reminderMinute
// Keep the existing status and isChecked, do not update them here
// The status and isChecked will be updated in the RecyclerView in ToDoListActivity
// Update the entire task in the Room database
taskDao.updateTask(it)
}
// Call setAlarm to schedule the alarm
setAlarm()
// Finish the activity (optional: navigate back to ToDoListActivity)
finish()
}
Toast.makeText(this, "Task update successful", Toast.LENGTH_LONG).show()
} else {
// Show an error message or handle empty task name
// ...
}
}
private fun showTimePickerDialog() {
val currentTime = Calendar.getInstance()
val hour = currentTime.get(Calendar.HOUR_OF_DAY)
val minute = currentTime.get(Calendar.MINUTE)
val timePickerDialog = TimePickerDialog(
this,
{ _, selectedHour, selectedMinute ->
onTimeSet(selectedHour, selectedMinute)
},
hour,
minute,
DateFormat.is24HourFormat(this)
)
timePickerDialog.show()
}
private fun onTimeSet(hourOfDay: Int, minute: Int) {
reminderHour = hourOfDay
reminderMinute = minute
// Format the time
val formattedTime = formatTime(hourOfDay, minute)
// Set the text using the resource string with a placeholder
binding.textViewReminderTime.text = getString(R.string.reminder_message, formattedTime)
}
private fun formatTime(hourOfDay: Int, minute: Int): String {
val is24HourFormat = DateFormat.is24HourFormat(this)
val formattedHour = if (is24HourFormat) {
String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute)
} else {
// Convert 24-hour format to 12-hour format
val amPm = if (hourOfDay < 12) "AM" else "PM"
val formattedHour12 = if (hourOfDay % 12 == 0) 12 else hourOfDay % 12
String.format(Locale.getDefault(), "%02d:%02d %s", formattedHour12, minute, amPm)
}
return formattedHour
}
private fun cancelAlarm() {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
this,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
alarmManager.cancel(pendingIntent)
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/TaskDetailActivity.kt | 3743436145 |
package com.pepito.partypalpro.recycleradapter
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.pepito.partypalpro.GuestDetailActivity
import com.pepito.partypalpro.R
import com.pepito.partypalpro.databinding.ItemGuestBinding
import com.pepito.partypalpro.storage.Guest
class GuestAdapter(private val context: Context, private var guestList: List<Guest>) :
RecyclerView.Adapter<GuestAdapter.GuestViewHolder>() {
class GuestViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = ItemGuestBinding.bind(itemView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GuestViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_guest, parent, false)
return GuestViewHolder(itemView)
}
override fun onBindViewHolder(holder: GuestViewHolder, position: Int) {
val currentGuest = guestList[position]
holder.binding.textViewName.text = currentGuest.name
holder.binding.textViewRSVP.text = currentGuest.rsvpStatus
// Set onClickListener to handle item click
holder.itemView.setOnClickListener {
// Start GuestDetailActivity with the selected guest's ID
val intent = Intent(context, GuestDetailActivity::class.java)
intent.putExtra("guestId", currentGuest.id) // Pass the guest's ID to GuestDetailActivity
context.startActivity(intent)
}
}
override fun getItemCount() = guestList.size
@SuppressLint("NotifyDataSetChanged")
fun setData(newList: List<Guest>) {
guestList = newList
notifyDataSetChanged()
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/recycleradapter/GuestAdapter.kt | 274354803 |
package com.pepito.partypalpro.recycleradapter
// TaskAdapter.kt
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.pepito.partypalpro.R
import com.pepito.partypalpro.databinding.ItemTaskBinding
import com.pepito.partypalpro.storage.Task
import com.pepito.partypalpro.storage.TaskDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class TaskAdapter(
private var taskList: List<Task>,
private val onItemClick: (Task) -> Unit,
private val taskDao: TaskDao // Pass the TaskDao as a parameter
) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {
class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = ItemTaskBinding.bind(itemView)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false)
return TaskViewHolder(itemView)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val currentTask = taskList[position]
holder.binding.textViewTaskName.text = currentTask.taskName
holder.binding.checkBoxTask.isChecked = currentTask.taskStatus == "Completed"
// Update badgeTaskStatus TextView based on taskStatus
holder.binding.badgeTaskStatus.text = currentTask.taskStatus
holder.binding.badgeTaskStatus.setBackgroundResource(
if (currentTask.taskStatus == "Completed") R.color.colorBadgeCompleted
else R.color.colorBadgeOngoing
)
holder.binding.checkBoxTask.setOnCheckedChangeListener { _, isChecked ->
val status = if (isChecked) "Completed" else "On going"
// Only update if the status has changed
if (currentTask.taskStatus != status) {
holder.binding.badgeTaskStatus.text = status
holder.binding.badgeTaskStatus.setBackgroundResource(
if (isChecked) R.color.colorBadgeCompleted else R.color.colorBadgeOngoing
)
// Update the status in the Task entity and call the DAO method to persist the change
currentTask.taskStatus = status
CoroutineScope(Dispatchers.IO).launch {
taskDao.updateTask(currentTask)
}
}
}
// Set click listener for the item view
holder.itemView.setOnClickListener {
onItemClick(currentTask)
}
}
override fun getItemCount() = taskList.size
@SuppressLint("NotifyDataSetChanged")
fun setData(newList: List<Task>) {
taskList = newList
notifyDataSetChanged()
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/recycleradapter/TaskAdapter.kt | 100714265 |
package com.pepito.partypalpro.storage
import androidx.room.Entity
import androidx.room.PrimaryKey
// Guest.kt
@Entity(tableName = "guests")
data class Guest(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
var name: String,
var email: String,
var rsvpStatus: String
)
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/storage/Guest.kt | 1142195285 |
package com.pepito.partypalpro.storage
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
// AppDatabase.kt
@Database(entities = [Guest::class, Task::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun guestDao(): GuestDao
abstract fun taskDao(): TaskDao
companion object {
private const val DATABASE_NAME = "party_pal_database"
@Volatile
private var INSTANCE: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
DATABASE_NAME
).build()
INSTANCE = instance
instance
}
}
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/storage/AppDatabase.kt | 1306093020 |
// Task.kt
package com.pepito.partypalpro.storage
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "tasks")
data class Task(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
var taskName: String,
var taskDescription: String,
var taskStatus: String,
var isChecked: Boolean = false,
var isReminderSet: Boolean = false,
var reminderHour: Int = 0,
var reminderMinute: Int = 0
)
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/storage/Task.kt | 2381116146 |
// TaskDao.kt
package com.pepito.partypalpro.storage
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface TaskDao {
@Insert
suspend fun addTask(task: Task): Long
@Query("SELECT * FROM tasks")
suspend fun getAllTasksDirect(): List<Task>
@Query("SELECT * FROM tasks WHERE id = :taskId")
suspend fun getTaskById(taskId: Long): Task?
@Update
suspend fun updateTask(task: Task)
@Query("DELETE FROM tasks WHERE id = :taskId")
suspend fun deleteTaskById(taskId: Long)
// Add other necessary queries or updates
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/storage/TaskDao.kt | 692990174 |
package com.pepito.partypalpro.storage
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
// GuestDao.kt
@Dao
interface GuestDao {
@Insert
suspend fun addGuest(guest: Guest): Long
@Query("SELECT * FROM guests")
suspend fun getAllGuests(): List<Guest>
@Query("SELECT * FROM guests WHERE id = :guestId")
suspend fun getGuestById(guestId: Long): Guest?
@Query("DELETE FROM guests WHERE id = :guestId")
suspend fun deleteGuestById(guestId: Long)
@Update
suspend fun updateGuest(guest: Guest)
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/storage/GuestDao.kt | 367045599 |
package com.pepito.partypalpro.alarm
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.pepito.partypalpro.R
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// Handle the alarm here
val taskName = intent?.getStringExtra("taskName")
// You can show a notification, play a sound, etc.
// For simplicity, let's just show a toast
Toast.makeText(context, "Alarm for task: $taskName", Toast.LENGTH_LONG).show()
showNotification(context, taskName)
playNotificationSound(context)
}
private fun playNotificationSound(context: Context?) {
// You can customize the sound by providing a URI or use a default sound
val notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val ringtone = RingtoneManager.getRingtone(context, notificationSoundUri)
ringtone.play()
}
@SuppressLint("MissingPermission")
private fun showNotification(context: Context?, taskName: String?) {
createNotificationChannel(context)
val builder = NotificationCompat.Builder(context!!, "default_channel")
.setSmallIcon(R.drawable.task_icon)
.setContentTitle("Task Reminder")
.setContentText("Don't forget to do: $taskName")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(context)) {
notify(1, builder.build())
}
}
private fun createNotificationChannel(context: Context?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Default Channel"
val descriptionText = "Default Notification Channel"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("default_channel", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/alarm/AlarmReceiver.kt | 4272449831 |
package com.pepito.partypalpro
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.pepito.partypalpro.databinding.ActivityToDoListBinding
import com.pepito.partypalpro.recycleradapter.TaskAdapter
import com.pepito.partypalpro.storage.AppDatabase
import com.pepito.partypalpro.storage.Task
import com.pepito.partypalpro.storage.TaskDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ToDoListActivity : AppCompatActivity() {
private lateinit var binding: ActivityToDoListBinding
private lateinit var taskDao: TaskDao
private lateinit var taskAdapter: TaskAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityToDoListBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize the Room database
val database = AppDatabase.getInstance(this)
taskDao = database.taskDao()
// Set up RecyclerView.
taskAdapter = TaskAdapter(emptyList(), this::openTaskDetailActivity, taskDao)
binding.guestRecyclerView.adapter = taskAdapter
binding.guestRecyclerView.layoutManager = LinearLayoutManager(this)
// Set up click listener for the "Add Task" button
binding.buttonAddTask.setOnClickListener {
addTask()
}
// Set up BottomNavigationView
binding.bottomNavigationView.setOnItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.guest -> {
// Redirect to MainActivity when the "Guest" item is clicked
startActivity(Intent(this, MainActivity::class.java))
true
}
R.id.task -> {
// Handle necessary actions
true
}
else -> false
}
}
// Explicitly set the selected item to "Task"
binding.bottomNavigationView.selectedItemId = R.id.task
// Load existing tasks from the Room database
loadTasks()
}
override fun onResume() {
super.onResume()
loadTasks()
}
private fun loadTasks() {
CoroutineScope(Dispatchers.Main).launch {
// Retrieve tasks directly without observing changes
val tasks = taskDao.getAllTasksDirect()
// Log the task statuses
tasks.forEach { task ->
Log.d("TaskAdapter", "Task status from database: ${task.taskStatus}")
}
// Update the adapter with the retrieved tasks
taskAdapter.setData(tasks)
// Update the visibility of textViewEmptyList based on the data size
binding.textViewEmptyList.visibility = if (tasks.isEmpty()) View.VISIBLE else View.GONE
}
}
private fun addTask() {
val taskName = binding.editTextTaskName.text.toString()
val taskDescription = binding.editTextTask.text.toString()
if (taskName.isNotBlank()) {
val newTask = Task(taskName = taskName, taskDescription = taskDescription, taskStatus = "On going")
CoroutineScope(Dispatchers.IO).launch {
// Add the new task to the Room database
taskDao.addTask(newTask)
// Fetch tasks again from the database after adding a new task
loadTasks()
}
// Clear the input fields after adding a task
binding.editTextTaskName.text.clear()
binding.editTextTask.text.clear()
}
}
private fun openTaskDetailActivity(task: Task) {
// Start TaskDetailActivity with the selected task's details
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("taskId", task.id) // Pass the task's ID to TaskDetailActivity
startActivity(intent)
}
}
| PartyPal-Pro/app/src/main/java/com/pepito/partypalpro/ToDoListActivity.kt | 2523717606 |
package th.ac.kku.cis.ShoppingCart
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("th.ac.kku.cis.ShoppingCart", appContext.packageName)
}
} | shoppincart/app/src/androidTest/java/th/ac/kku/cis/ShoppingCart/ExampleInstrumentedTest.kt | 505357659 |
package th.ac.kku.cis.ShoppingCart
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)
}
} | shoppincart/app/src/test/java/th/ac/kku/cis/ShoppingCart/ExampleUnitTest.kt | 2509081964 |
package th.ac.kku.cis.ShoppingCart.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) | shoppincart/app/src/main/java/th/ac/kku/cis/ShoppingCart/ui/theme/Color.kt | 3913373327 |
package th.ac.kku.cis.ShoppingCart.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 ShoppingCartTheme(
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
)
} | shoppincart/app/src/main/java/th/ac/kku/cis/ShoppingCart/ui/theme/Theme.kt | 2785415922 |
package th.ac.kku.cis.ShoppingCart.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
)
*/
) | shoppincart/app/src/main/java/th/ac/kku/cis/ShoppingCart/ui/theme/Type.kt | 4177434507 |
package th.ac.kku.cis.ShoppingCart
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.Card
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.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import th.ac.kku.cis.ShoppingCart.ui.theme.ShoppingCartTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ShoppingCartTheme {
ShoppingCartApp()
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun ShoppingCartApp() {
var data = remember { mutableStateListOf<String>() }
var isShowDialog = remember {
mutableStateOf(false)
}
var newItemName by remember {
mutableStateOf("")
}
if (isShowDialog.value) {
InputDialog(
itemName = newItemName,
onCancel = {
isShowDialog.value = false
},
onAddButtonClick = { newItem ->
data.add(newItem)
isShowDialog.value = false
}
)
}
Scaffold(
topBar = {
TopAppBar(
title = { Text("Shopping Cart")},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = Color.LightGray,
titleContentColor = Color.Magenta
))
},
floatingActionButton = {
FloatingActionButton(
onClick = { isShowDialog.value = true },
containerColor = Color.Magenta) {
Icon(Icons.Filled.Add,
"Add new Items",
tint = Color.White)
}
}
){
LazyColumn(modifier = Modifier.padding(it)) {
items(data) {item ->
CartItem(item)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun InputDialog(
itemName: String,
onCancel: () -> Unit,
onAddButtonClick: (String) -> Unit
) {
Dialog(
onDismissRequest = onCancel,
) {
var textValue by remember {
mutableStateOf(itemName)
}
Card(
shape = RoundedCornerShape(8.dp)
) {
Column(
modifier = Modifier.padding(10.dp)
) {
TextField(
value = textValue,
onValueChange = { textValue = it },
label = { Text("Itemname") }
)
TextButton(onClick = { onAddButtonClick(textValue) }) {
Text("Add")
}
}
}
}
}
@Composable
private fun CartItem(itemname:String) {
var amount : Int by remember { mutableStateOf(0) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
){
Text(
"$itemname",
modifier = Modifier
.weight(1f)
.padding(start = 10.dp)
)
IconButton(onClick = { amount-- }) {
Icon(Icons.Filled.ArrowBack,
"Decrease")
}
Text(
"$amount",
)
IconButton(onClick = { amount++ }) {
Icon(Icons.Filled.ArrowForward,
"Increase")
}
}
}
@Preview(showBackground = true)
@Composable
fun Preview(){
ShoppingCartApp()
}
| shoppincart/app/src/main/java/th/ac/kku/cis/ShoppingCart/MainActivity.kt | 2463833051 |
package com.raywenderlich.podplay
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.raywenderlich.podplay", appContext.packageName)
}
} | PodPlay/app/src/androidTest/java/com/raywenderlich/podplay/ExampleInstrumentedTest.kt | 1851158168 |
package com.raywenderlich.podplay
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)
}
} | PodPlay/app/src/test/java/com/raywenderlich/podplay/ExampleUnitTest.kt | 3675633448 |
package com.raywenderlich.podplay.ui
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.work.*
import com.raywenderlich.podplay.R
import com.raywenderlich.podplay.adapter.PodcastListAdapter
import com.raywenderlich.podplay.adapter.PodcastListAdapter.PodcastListAdapterListener
import com.raywenderlich.podplay.databinding.ActivityPodcastBinding
import com.raywenderlich.podplay.repository.ItunesRepo
import com.raywenderlich.podplay.repository.PodcastRepo
import com.raywenderlich.podplay.service.ItunesService
import com.raywenderlich.podplay.service.RssFeedService
import com.raywenderlich.podplay.ui.PodcastDetailsFragment.OnPodcastDetailsListener
import com.raywenderlich.podplay.viewmodel.PodcastViewModel
import com.raywenderlich.podplay.viewmodel.SearchViewModel
import com.raywenderlich.podplay.worker.EpisodeUpdateWorker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
class PodcastActivity : AppCompatActivity(), PodcastListAdapterListener,
OnPodcastDetailsListener {
private val searchViewModel by viewModels<SearchViewModel>()
private val podcastViewModel by viewModels<PodcastViewModel>()
private lateinit var podcastListAdapter: PodcastListAdapter
private lateinit var searchMenuItem: MenuItem
private lateinit var databinding: ActivityPodcastBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
databinding = ActivityPodcastBinding.inflate(layoutInflater)
setContentView(databinding.root)
setupToolbar()
setupViewModels()
updateControls()
setupPodcastListView()
handleIntent(intent)
addBackStackListener()
scheduleJobs()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu_search, menu)
searchMenuItem = menu.findItem(R.id.search_item)
val searchView = searchMenuItem.actionView as SearchView
searchMenuItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
showSubscribedPodcasts()
return true
}
})
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
if (supportFragmentManager.backStackEntryCount > 0) {
databinding.podcastRecyclerView.visibility = View.INVISIBLE
}
if (databinding.podcastRecyclerView.visibility == View.INVISIBLE) {
searchMenuItem.isVisible = false
}
return true
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
override fun onShowDetails(podcastSummaryViewData: SearchViewModel.PodcastSummaryViewData) {
podcastSummaryViewData.feedUrl ?: return
showProgressBar()
podcastViewModel.viewModelScope.launch (context = Dispatchers.Main) {
podcastViewModel.getPodcast(podcastSummaryViewData)
hideProgressBar()
showDetailsFragment()
}
}
private fun scheduleJobs() {
val constraints: Constraints = Constraints.Builder().apply {
setRequiredNetworkType(NetworkType.CONNECTED)
setRequiresCharging(true)
}.build()
val request = PeriodicWorkRequestBuilder<EpisodeUpdateWorker>(
1, TimeUnit.HOURS)
.setConstraints(constraints)
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(TAG_EPISODE_UPDATE_JOB,
ExistingPeriodicWorkPolicy.REPLACE, request)
}
private fun showSubscribedPodcasts() {
val podcasts = podcastViewModel.getPodcasts()?.value
if (podcasts != null) {
databinding.toolbar.title = getString(R.string.subscribed_podcasts)
podcastListAdapter.setSearchData(podcasts)
}
}
private fun performSearch(term: String) {
showProgressBar()
GlobalScope.launch {
val results = searchViewModel.searchPodcasts(term)
withContext(Dispatchers.Main) {
hideProgressBar()
databinding.toolbar.title = term
podcastListAdapter.setSearchData(results)
}
}
}
private fun handleIntent(intent: Intent) {
if (Intent.ACTION_SEARCH == intent.action) {
val query = intent.getStringExtra(SearchManager.QUERY) ?: return
performSearch(query)
}
val podcastFeedUrl = intent.getStringExtra(EpisodeUpdateWorker.EXTRA_FEED_URL)
if (podcastFeedUrl != null) {
podcastViewModel.viewModelScope.launch {
val podcastSummaryViewData = podcastViewModel.setActivePodcast(podcastFeedUrl)
podcastSummaryViewData?.let { podcastSummaryView -> onShowDetails(podcastSummaryView) }
}
}
}
private fun setupToolbar() {
setSupportActionBar(databinding.toolbar)
}
private fun setupViewModels() {
val service = ItunesService.instance
searchViewModel.iTunesRepo = ItunesRepo(service)
val rssService = RssFeedService.instance
podcastViewModel.podcastRepo = PodcastRepo(rssService, podcastViewModel.podcastDao)
}
private fun setupPodcastListView() {
podcastViewModel.getPodcasts()?.observe(this, {
if (it != null) {
showSubscribedPodcasts()
}
})
}
private fun addBackStackListener() {
supportFragmentManager.addOnBackStackChangedListener {
if (supportFragmentManager.backStackEntryCount == 0) {
databinding.podcastRecyclerView.visibility = View.VISIBLE
}
}
}
private fun updateControls() {
databinding.podcastRecyclerView.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(this)
databinding.podcastRecyclerView.layoutManager = layoutManager
val dividerItemDecoration = DividerItemDecoration(databinding.podcastRecyclerView.context,
layoutManager.orientation)
databinding.podcastRecyclerView.addItemDecoration(dividerItemDecoration)
podcastListAdapter = PodcastListAdapter(null, this, this)
databinding.podcastRecyclerView.adapter = podcastListAdapter
}
private fun showDetailsFragment() {
val podcastDetailsFragment = createPodcastDetailsFragment()
supportFragmentManager.beginTransaction().add(R.id.podcastDetailsContainer,
podcastDetailsFragment, TAG_DETAILS_FRAGMENT).addToBackStack("DetailsFragment").commit()
databinding.podcastRecyclerView.visibility = View.INVISIBLE
searchMenuItem.isVisible = false
}
private fun showPlayerFragment() {
val episodePlayerFragment = createEpisodePlayerFragment()
supportFragmentManager.beginTransaction().replace(R.id.podcastDetailsContainer,
episodePlayerFragment, TAG_PLAYER_FRAGMENT).addToBackStack("PlayerFragment").commit()
databinding.podcastRecyclerView.visibility = View.INVISIBLE
searchMenuItem.isVisible = false
}
private fun createEpisodePlayerFragment(): EpisodePlayerFragment {
var episodePlayerFragment = supportFragmentManager.findFragmentByTag(TAG_PLAYER_FRAGMENT) as
EpisodePlayerFragment?
if (episodePlayerFragment == null) {
episodePlayerFragment = EpisodePlayerFragment.newInstance()
}
return episodePlayerFragment
}
private fun createPodcastDetailsFragment(): PodcastDetailsFragment {
var podcastDetailsFragment = supportFragmentManager.findFragmentByTag(TAG_DETAILS_FRAGMENT) as PodcastDetailsFragment?
if (podcastDetailsFragment == null) {
podcastDetailsFragment = PodcastDetailsFragment.newInstance()
}
return podcastDetailsFragment
}
private fun showProgressBar() {
databinding.progressBar.visibility = View.VISIBLE
}
private fun hideProgressBar() {
databinding.progressBar.visibility = View.INVISIBLE
}
companion object {
private const val TAG_DETAILS_FRAGMENT = "DetailsFragment"
private const val TAG_EPISODE_UPDATE_JOB = "com.raywenderlich.podplay.episodes"
private const val TAG_PLAYER_FRAGMENT = "PlayerFragment"
}
override fun onSubscribe() {
podcastViewModel.saveActivePodcast()
supportFragmentManager.popBackStack()
}
override fun onUnsubscribe() {
podcastViewModel.deleteActivePodcast()
supportFragmentManager.popBackStack()
}
override fun onShowEpisodePlayer(episodeViewData: PodcastViewModel.EpisodeViewData) {
podcastViewModel.activeEpisodeViewData = episodeViewData
showPlayerFragment()
}
}
| PodPlay/app/src/main/java/ui/PodcastActivity.kt | 1113673111 |
package com.raywenderlich.podplay.ui
import android.content.Context
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.raywenderlich.podplay.R
import com.raywenderlich.podplay.adapter.EpisodeListAdapter
import com.raywenderlich.podplay.databinding.FragmentPodcastDetailsBinding
import com.raywenderlich.podplay.viewmodel.PodcastViewModel
class PodcastDetailsFragment : Fragment(), EpisodeListAdapter.EpisodeListAdapterListener {
private val podcastViewModel: PodcastViewModel by activityViewModels()
private lateinit var databinding: FragmentPodcastDetailsBinding
private lateinit var episodeListAdapter: EpisodeListAdapter
private var listener: OnPodcastDetailsListener? = null
companion object {
fun newInstance(): PodcastDetailsFragment {
return PodcastDetailsFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
databinding = FragmentPodcastDetailsBinding.inflate(inflater, container, false)
return databinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
podcastViewModel.podcastLiveData.observe(viewLifecycleOwner, { viewData ->
if (viewData != null) {
databinding.feedTitleTextView.text = viewData.feedTitle
databinding.feedDescTextView.text = viewData.feedDesc
activity?.let { activity ->
Glide.with(activity).load(viewData.imageUrl).into(databinding.feedImageView)
}
// 1
databinding.feedDescTextView.movementMethod = ScrollingMovementMethod()
// 2
databinding.episodeRecyclerView.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(activity)
databinding.episodeRecyclerView.layoutManager = layoutManager
val dividerItemDecoration = DividerItemDecoration(
databinding.episodeRecyclerView.context, layoutManager.orientation)
databinding.episodeRecyclerView.addItemDecoration(dividerItemDecoration)
// 3
episodeListAdapter = EpisodeListAdapter(viewData.episodes, this)
databinding.episodeRecyclerView.adapter = episodeListAdapter
activity?.invalidateOptionsMenu()
}
})
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnPodcastDetailsListener) {
listener = context
} else {
throw RuntimeException(context.toString() +
" must implement OnPodcastDetailsListener")
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_details, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_feed_action -> {
if (item.title == getString(R.string.unsubscribe)) {
listener?.onUnsubscribe()
} else {
listener?.onSubscribe()
}
true
}
else ->
super.onOptionsItemSelected(item)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
podcastViewModel.podcastLiveData.observe(viewLifecycleOwner, { podcast ->
if (podcast != null) {
menu.findItem(R.id.menu_feed_action).title = if (podcast.subscribed)
getString(R.string.unsubscribe) else getString(R.string.subscribe)
}
})
super.onPrepareOptionsMenu(menu)
}
interface OnPodcastDetailsListener {
fun onSubscribe()
fun onUnsubscribe()
fun onShowEpisodePlayer(episodeViewData: PodcastViewModel.EpisodeViewData)
}
override fun onSelectedEpisode(episodeViewData: PodcastViewModel.EpisodeViewData) {
listener?.onShowEpisodePlayer(episodeViewData)
}
}
| PodPlay/app/src/main/java/ui/PodcastDetailsFragment.kt | 3181390847 |
package com.raywenderlich.podplay.ui
import android.animation.ValueAnimator
import android.content.ComponentName
import android.content.Context
import android.graphics.Color
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.text.format.DateUtils
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import com.bumptech.glide.Glide
import com.raywenderlich.podplay.databinding.FragmentEpisodePlayerBinding
import com.raywenderlich.podplay.service.PodplayMediaCallback
import com.raywenderlich.podplay.service.PodplayMediaCallback.Companion.CMD_CHANGESPEED
import com.raywenderlich.podplay.service.PodplayMediaCallback.Companion.CMD_EXTRA_SPEED
import com.raywenderlich.podplay.service.PodplayMediaService
import com.raywenderlich.podplay.util.HtmlUtils
import com.raywenderlich.podplay.viewmodel.PodcastViewModel
class EpisodePlayerFragment : Fragment() {
private lateinit var databinding: FragmentEpisodePlayerBinding
private val podcastViewModel: PodcastViewModel by activityViewModels()
private lateinit var mediaBrowser: MediaBrowserCompat
private var mediaControllerCallback: MediaControllerCallback? = null
private var playerSpeed: Float = 1.0f
private var episodeDuration: Long = 0
private var draggingScrubber: Boolean = false
private var progressAnimator: ValueAnimator? = null
private var mediaSession: MediaSessionCompat? = null
private var mediaPlayer: MediaPlayer? = null
private var isVideo: Boolean = false
private var playOnPrepare: Boolean = false
companion object {
fun newInstance(): EpisodePlayerFragment {
return EpisodePlayerFragment()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isVideo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
podcastViewModel.activeEpisodeViewData?.isVideo ?: false
} else {
false
}
if (!isVideo) {
initMediaBrowser()
}
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View {
databinding = FragmentEpisodePlayerBinding.inflate(inflater, container, false)
return databinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupControls()
if (isVideo) {
initMediaSession()
initVideoPlayer()
}
updateControls()
}
override fun onStart() {
super.onStart()
if (!isVideo) {
if (mediaBrowser.isConnected) {
val fragmentActivity = activity as FragmentActivity
if (MediaControllerCompat.getMediaController(fragmentActivity) == null) {
registerMediaController(mediaBrowser.sessionToken)
}
updateControlsFromController()
} else {
mediaBrowser.connect()
}
}
}
override fun onStop() {
super.onStop()
progressAnimator?.cancel()
val fragmentActivity = activity as FragmentActivity
if (MediaControllerCompat.getMediaController(fragmentActivity) != null) {
mediaControllerCallback?.let {
MediaControllerCompat.getMediaController(fragmentActivity)
.unregisterCallback(it)
}
}
if (isVideo) {
mediaPlayer?.setDisplay(null)
}
if (!fragmentActivity.isChangingConfigurations) {
mediaPlayer?.release()
mediaPlayer = null
}
}
private fun setupControls() {
databinding.playToggleButton.setOnClickListener {
togglePlayPause()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
databinding.speedButton.setOnClickListener {
changeSpeed()
}
} else {
databinding.speedButton.visibility = View.INVISIBLE
}
databinding.forwardButton.setOnClickListener {
seekBy(30)
}
databinding.replayButton.setOnClickListener {
seekBy(-10)
}
// 1
databinding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
// 2
databinding.currentTimeTextView.text = DateUtils.formatElapsedTime((progress / 1000).toLong())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
// 3
draggingScrubber = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
// 4
draggingScrubber = false
// 5
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
if (controller.playbackState != null) {
// 6
controller.transportControls.seekTo(seekBar.progress.toLong())
} else {
// 7
seekBar.progress = 0
}
}
})
}
private fun setupVideoUI() {
databinding.episodeDescTextView.visibility = View.INVISIBLE
databinding.headerView.visibility = View.INVISIBLE
val activity = activity as AppCompatActivity
activity.supportActionBar?.hide()
databinding.playerControls.setBackgroundColor(Color.argb(255 / 2, 0, 0, 0))
}
private fun updateControlsFromController() {
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
if (controller != null) {
val metadata = controller.metadata
if (metadata != null) {
handleStateChange(controller.playbackState.state,
controller.playbackState.position, playerSpeed)
updateControlsFromMetadata(controller.metadata)
}
}
}
private fun initVideoPlayer() {
databinding.videoSurfaceView.visibility = View.VISIBLE
val surfaceHolder = databinding.videoSurfaceView.holder
surfaceHolder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
initMediaPlayer()
mediaPlayer?.setDisplay(holder)
}
override fun surfaceChanged(var1: SurfaceHolder, var2: Int, var3: Int, var4: Int) {
}
override fun surfaceDestroyed(var1: SurfaceHolder) {
}
})
}
private fun initMediaPlayer() {
if (mediaPlayer == null) {
// 1
mediaPlayer = MediaPlayer()
mediaPlayer?.let { mediaPlayer ->
// 2
mediaPlayer.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
)
// 3
mediaPlayer.setDataSource(podcastViewModel.activeEpisodeViewData?.mediaUrl)
// 4
mediaPlayer.setOnPreparedListener {
// 5
val fragmentActivity = activity as FragmentActivity
mediaSession?.let { mediaSession ->
val episodeMediaCallback = PodplayMediaCallback(fragmentActivity, mediaSession, it)
mediaSession.setCallback(episodeMediaCallback)
}
// 6
setSurfaceSize()
// 7
if (playOnPrepare) {
togglePlayPause()
}
}
// 8
mediaPlayer.prepareAsync()
}
} else {
// 9
setSurfaceSize()
}
}
private fun initMediaSession() {
if (mediaSession == null) {
mediaSession = MediaSessionCompat(activity as Context, "EpisodePlayerFragment")
mediaSession?.setMediaButtonReceiver(null)
}
mediaSession?.let {
registerMediaController(it.sessionToken)
}
}
private fun setSurfaceSize() {
val mediaPlayer = mediaPlayer ?: return
val videoWidth = mediaPlayer.videoWidth
val videoHeight = mediaPlayer.videoHeight
val parent = databinding.videoSurfaceView.parent as View
val containerWidth = parent.width
val containerHeight = parent.height
val layoutAspectRatio = containerWidth.toFloat() / containerHeight
val videoAspectRatio = videoWidth.toFloat() / videoHeight
val layoutParams = databinding.videoSurfaceView.layoutParams
if (videoAspectRatio > layoutAspectRatio) {
layoutParams.height = (containerWidth / videoAspectRatio).toInt()
} else {
layoutParams.width = (containerHeight * videoAspectRatio).toInt()
}
databinding.videoSurfaceView.layoutParams = layoutParams
}
private fun animateScrubber(progress: Int, speed: Float) {
val timeRemaining = ((episodeDuration - progress) / speed).toInt()
if (timeRemaining < 0) {
return
}
progressAnimator = ValueAnimator.ofInt(
progress, episodeDuration.toInt())
progressAnimator?.let { animator ->
animator.duration = timeRemaining.toLong()
animator.interpolator = LinearInterpolator()
animator.addUpdateListener {
if (draggingScrubber) {
animator.cancel()
} else {
databinding.seekBar.progress = animator.animatedValue as Int
}
}
animator.start()
}
}
private fun updateControlsFromMetadata(metadata: MediaMetadataCompat) {
episodeDuration = metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION)
databinding.endTimeTextView.text = DateUtils.formatElapsedTime((episodeDuration / 1000))
databinding.seekBar.max = episodeDuration.toInt()
}
private fun changeSpeed() {
playerSpeed += 0.25f
if (playerSpeed > 2.0f) {
playerSpeed = 0.75f
}
val bundle = Bundle()
bundle.putFloat(CMD_EXTRA_SPEED, playerSpeed)
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
controller.sendCommand(CMD_CHANGESPEED, bundle, null)
val speedButtonText = "${playerSpeed}x"
databinding.speedButton.text = speedButtonText
}
private fun seekBy(seconds: Int) {
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
val newPosition = controller.playbackState.position + seconds * 1000
controller.transportControls.seekTo(newPosition)
}
private fun handleStateChange(state: Int, position: Long, speed: Float) {
progressAnimator?.let {
it.cancel()
progressAnimator = null
}
val isPlaying = state == PlaybackStateCompat.STATE_PLAYING
databinding.playToggleButton.isActivated = isPlaying
val progress = position.toInt()
databinding.seekBar.progress = progress
val speedButtonText = "${playerSpeed}x"
databinding.speedButton.text = speedButtonText
if (isPlaying) {
if (isVideo) {
setupVideoUI()
}
animateScrubber(progress, speed)
}
}
private fun updateControls() {
// 1
databinding.episodeTitleTextView.text = podcastViewModel.activeEpisodeViewData?.title
// 2
val htmlDesc = podcastViewModel.activeEpisodeViewData?.description ?: ""
val descSpan = HtmlUtils.htmlToSpannable(htmlDesc)
databinding.episodeDescTextView.text = descSpan
databinding.episodeDescTextView.movementMethod = ScrollingMovementMethod()
// 3
val fragmentActivity = activity as FragmentActivity
Glide.with(fragmentActivity)
.load(podcastViewModel.podcastLiveData.value?.imageUrl)
.into(databinding.episodeImageView)
val speedButtonText = "${playerSpeed}x"
databinding.speedButton.text = speedButtonText
mediaPlayer?.let {
updateControlsFromController()
}
}
private fun startPlaying(episodeViewData: PodcastViewModel.EpisodeViewData) {
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
val viewData = podcastViewModel.podcastLiveData
val bundle = Bundle()
bundle.putString(MediaMetadataCompat.METADATA_KEY_TITLE, episodeViewData.title)
bundle.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, viewData.value?.feedTitle)
bundle.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, viewData.value?.imageUrl)
controller.transportControls.playFromUri(Uri.parse(episodeViewData.mediaUrl), bundle)
}
private fun togglePlayPause() {
playOnPrepare = true
val fragmentActivity = activity as FragmentActivity
val controller = MediaControllerCompat.getMediaController(fragmentActivity)
if (controller.playbackState != null) {
if (controller.playbackState.state == PlaybackStateCompat.STATE_PLAYING) {
controller.transportControls.pause()
} else {
podcastViewModel.activeEpisodeViewData?.let { startPlaying(it) }
}
} else {
podcastViewModel.activeEpisodeViewData?.let { startPlaying(it) }
}
}
private fun registerMediaController(token: MediaSessionCompat.Token) {
val mediaController = MediaControllerCompat(activity, token)
val fragmentActivity = activity as FragmentActivity
MediaControllerCompat.setMediaController(fragmentActivity, mediaController)
mediaControllerCallback = MediaControllerCallback()
mediaController.registerCallback(mediaControllerCallback!!)
}
private fun initMediaBrowser() {
val fragmentActivity = activity as FragmentActivity
mediaBrowser = MediaBrowserCompat(fragmentActivity,
ComponentName(fragmentActivity, PodplayMediaService::class.java),
MediaBrowserCallBacks(),
null)
}
inner class MediaBrowserCallBacks : MediaBrowserCompat.ConnectionCallback() {
override fun onConnected() {
super.onConnected()
registerMediaController(mediaBrowser.sessionToken)
updateControlsFromController()
}
override fun onConnectionSuspended() {
super.onConnectionSuspended()
println("onConnectionSuspended")
}
override fun onConnectionFailed() {
super.onConnectionFailed()
println("onConnectionFailed")
}
}
inner class MediaControllerCallback : MediaControllerCompat.Callback() {
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
super.onMetadataChanged(metadata)
metadata?.let { updateControlsFromMetadata(it) }
}
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
val currentState = state ?: return
handleStateChange(currentState.state, currentState.position, currentState.playbackSpeed)
}
}
} | PodPlay/app/src/main/java/ui/EpisodePlayerFragment.kt | 878838995 |
package com.raywenderlich.podplay.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.raywenderlich.podplay.repository.ItunesRepo
import com.raywenderlich.podplay.service.PodcastResponse
import com.raywenderlich.podplay.util.DateUtils
class SearchViewModel(application: Application) : AndroidViewModel(application) {
var iTunesRepo: ItunesRepo? = null
data class PodcastSummaryViewData(
var name: String? = "",
var lastUpdated: String? = "",
var imageUrl: String? = "",
var feedUrl: String? = "")
private fun itunesPodcastToPodcastSummaryView(
itunesPodcast: PodcastResponse.ItunesPodcast):
PodcastSummaryViewData {
return PodcastSummaryViewData(
itunesPodcast.collectionCensoredName,
DateUtils.jsonDateToShortDate(itunesPodcast.releaseDate),
itunesPodcast.artworkUrl100,
itunesPodcast.feedUrl)
}
suspend fun searchPodcasts(term: String): List<PodcastSummaryViewData> {
val results = iTunesRepo?.searchByTerm(term)
if (results != null && results.isSuccessful) {
val podcasts = results.body()?.results
if (!podcasts.isNullOrEmpty()) {
return podcasts.map { podcast ->
itunesPodcastToPodcastSummaryView(podcast)
}
}
}
return emptyList()
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/viewmodel/SearchViewModel.kt | 3274107631 |
package com.raywenderlich.podplay.viewmodel
import android.app.Application
import androidx.lifecycle.*
import com.raywenderlich.podplay.db.PodPlayDatabase
import com.raywenderlich.podplay.db.PodcastDao
import com.raywenderlich.podplay.model.Episode
import com.raywenderlich.podplay.model.Podcast
import com.raywenderlich.podplay.repository.PodcastRepo
import com.raywenderlich.podplay.util.DateUtils
import com.raywenderlich.podplay.viewmodel.SearchViewModel.PodcastSummaryViewData
import java.util.*
class PodcastViewModel(application: Application) : AndroidViewModel(application) {
var podcastRepo: PodcastRepo? = null
private val _podcastLiveData = MutableLiveData<PodcastViewData?>()
val podcastLiveData: LiveData<PodcastViewData?> = _podcastLiveData
var livePodcastSummaryData: LiveData<List<PodcastSummaryViewData>>? = null
var activeEpisodeViewData: EpisodeViewData? = null
val podcastDao: PodcastDao = PodPlayDatabase
.getInstance(application, viewModelScope)
.podcastDao()
private var activePodcast: Podcast? = null
suspend fun setActivePodcast(feedUrl: String): PodcastSummaryViewData? {
val repo = podcastRepo ?: return null
val podcast = repo.getPodcast(feedUrl)
return if (podcast == null) {
null
} else {
_podcastLiveData.value = podcastToPodcastView(podcast)
activePodcast = podcast
podcastToSummaryView(podcast)
}
}
suspend fun getPodcast(podcastSummaryViewData: PodcastSummaryViewData) {
podcastSummaryViewData.feedUrl?.let { url ->
podcastRepo?.getPodcast(url)?.let {
it.feedTitle = podcastSummaryViewData.name ?: ""
it.imageUrl = podcastSummaryViewData.imageUrl ?: ""
_podcastLiveData.value = podcastToPodcastView(it)
activePodcast = it
} ?: run {
_podcastLiveData.value = null
}
} ?: run {
_podcastLiveData.value = null
}
}
fun getPodcasts(): LiveData<List<PodcastSummaryViewData>>? {
val repo = podcastRepo ?: return null
// 1
if (livePodcastSummaryData == null) {
// 2
val liveData = repo.getAll()
// 3
livePodcastSummaryData = liveData.map { podcastList ->
podcastList.map { podcast ->
podcastToSummaryView(podcast)
}
}
}
// 4
return livePodcastSummaryData
}
fun saveActivePodcast() {
val repo = podcastRepo ?: return
activePodcast?.let {
repo.save(it)
}
}
private fun podcastToPodcastView(podcast: Podcast): PodcastViewData {
return PodcastViewData(
podcast.id != null,
podcast.feedTitle,
podcast.feedUrl,
podcast.feedDesc,
podcast.imageUrl,
episodesToEpisodesView(podcast.episodes)
)
}
private fun podcastToSummaryView(podcast: Podcast):
PodcastSummaryViewData {
return PodcastSummaryViewData(
podcast.feedTitle,
DateUtils.dateToShortDate(podcast.lastUpdated),
podcast.imageUrl,
podcast.feedUrl)
}
private fun episodesToEpisodesView(episodes: List<Episode>): List<EpisodeViewData> {
return episodes.map {
val isVideo = it.mimeType.startsWith("video")
EpisodeViewData(it.guid, it.title, it.description, it.mediaUrl, it.releaseDate, it.duration, isVideo)
}
}
fun deleteActivePodcast() {
val repo = podcastRepo ?: return
activePodcast?.let {
repo.delete(it)
}
}
data class PodcastViewData(var subscribed: Boolean = false,
var feedTitle: String? = "",
var feedUrl: String? = "",
var feedDesc: String? = "",
var imageUrl: String? = "",
var episodes: List<EpisodeViewData>)
data class EpisodeViewData(var guid: String? = "",
var title: String? = "",
var description: String? = "",
var mediaUrl: String? = "",
var releaseDate: Date? = null,
var duration: String? = "",
var isVideo: Boolean = false)
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/viewmodel/PodcastViewModel.kt | 3520854399 |
package com.raywenderlich.podplay.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) | PodPlay/app/src/main/java/com/raywenderlich/podplay/ui/theme/Color.kt | 261895102 |
package com.raywenderlich.podplay.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 PodPlayTheme(
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
)
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/ui/theme/Theme.kt | 4096813383 |
package com.raywenderlich.podplay.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
)
*/
) | PodPlay/app/src/main/java/com/raywenderlich/podplay/ui/theme/Type.kt | 2311202623 |
package com.raywenderlich.podplay.repository
import com.raywenderlich.podplay.service.ItunesService
class ItunesRepo(private val itunesService: ItunesService) {
suspend fun searchByTerm(term: String) = itunesService.searchPodcastByTerm(term)
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/repository/ItunesRepo.kt | 686272266 |
package com.raywenderlich.podplay.repository
import androidx.lifecycle.LiveData
import com.raywenderlich.podplay.db.PodcastDao
import com.raywenderlich.podplay.model.Episode
import com.raywenderlich.podplay.model.Podcast
import com.raywenderlich.podplay.service.RssFeedResponse
import com.raywenderlich.podplay.service.RssFeedService
import com.raywenderlich.podplay.util.DateUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class PodcastRepo(private var feedService: RssFeedService,
private var podcastDao: PodcastDao) {
suspend fun getPodcast(feedUrl: String): Podcast? {
val podcastLocal = podcastDao.loadPodcast(feedUrl)
if (podcastLocal != null) {
podcastLocal.id?.let {
podcastLocal.episodes = podcastDao.loadEpisodes(it)
return podcastLocal
}
}
var podcast: Podcast? = null
val feedResponse = feedService.getFeed(feedUrl)
if (feedResponse != null) {
podcast = rssResponseToPodcast(feedUrl, "", feedResponse)
}
return podcast
}
private fun rssItemsToEpisodes(episodeResponses: List<RssFeedResponse.EpisodeResponse>): List<Episode> {
return episodeResponses.map {
Episode(
it.guid ?: "",
null,
it.title ?: "",
it.description ?: "",
it.url ?: "",
it.type ?: "",
DateUtils.xmlDateToDate(it.pubDate),
it.duration ?: ""
)
}
}
private fun rssResponseToPodcast(
feedUrl: String, imageUrl: String, rssResponse: RssFeedResponse
): Podcast? {
// 1
val items = rssResponse.episodes ?: return null
// 2
val description = if (rssResponse.description == "")
rssResponse.summary else rssResponse.description
// 3
return Podcast(null, feedUrl, rssResponse.title, description, imageUrl,
rssResponse.lastUpdated, episodes = rssItemsToEpisodes(items))
}
fun save(podcast: Podcast) {
GlobalScope.launch {
val podcastId = podcastDao.insertPodcast(podcast)
for (episode in podcast.episodes) {
episode.podcastId = podcastId
podcastDao.insertEpisode(episode)
}
}
}
fun delete(podcast: Podcast) {
GlobalScope.launch {
podcastDao.deletePodcast(podcast)
}
}
fun getAll(): LiveData<List<Podcast>> {
return podcastDao.loadPodcasts()
}
suspend fun updatePodcastEpisodes() : MutableList<PodcastUpdateInfo> {
// 1
val updatedPodcasts: MutableList<PodcastUpdateInfo> = mutableListOf()
// 2
val podcasts = podcastDao.loadPodcastsStatic()
// 3
for (podcast in podcasts) {
// 4
val newEpisodes = getNewEpisodes(podcast)
// 5
if (newEpisodes.count() > 0) {
podcast.id?.let {
saveNewEpisodes(it, newEpisodes)
updatedPodcasts.add(PodcastUpdateInfo(podcast.feedUrl, podcast.feedTitle, newEpisodes.count()))
}
}
}
// 6
return updatedPodcasts
}
private suspend fun getNewEpisodes(localPodcast: Podcast): List<Episode> {
// 1
val response = feedService.getFeed(localPodcast.feedUrl)
if (response != null) {
// 2
val remotePodcast = rssResponseToPodcast(localPodcast.feedUrl, localPodcast.imageUrl, response)
remotePodcast?.let {
// 3
val localEpisodes = podcastDao.loadEpisodes(localPodcast.id!!)
// 4
return remotePodcast.episodes.filter { episode ->
localEpisodes.find { episode.guid == it.guid } == null
}
}
}
// 6
return listOf()
}
private fun saveNewEpisodes(podcastId: Long, episodes: List<Episode>) {
GlobalScope.launch {
for (episode in episodes) {
episode.podcastId = podcastId
podcastDao.insertEpisode(episode)
}
}
}
class PodcastUpdateInfo(val feedUrl: String, val name: String, val newCount: Int)
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/repository/PodcastRepo.kt | 1250806167 |
package com.raywenderlich.podplay
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.raywenderlich.podplay.ui.theme.PodPlayTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
PodPlayTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
PodPlayTheme {
Greeting("Android")
}
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/MainActivity.kt | 2467121606 |
package com.raywenderlich.podplay.util
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
object DateUtils {
fun jsonDateToShortDate(jsonDate: String?): String {
if (jsonDate == null) {
return "-"
}
val inFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
val date = inFormat.parse(jsonDate) ?: return "-"
val outputFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault())
return outputFormat.format(date)
}
fun xmlDateToDate(dateString: String?): Date {
val date = dateString ?: return Date()
val inFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.getDefault())
return inFormat.parse(date) ?: Date()
}
fun dateToShortDate(date: Date): String {
val outputFormat = DateFormat.getDateInstance(
DateFormat.SHORT, Locale.getDefault())
return outputFormat.format(date)
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/util/DateUtils.kt | 196256575 |
package com.raywenderlich.podplay.util
import android.os.Build
import android.text.Html
import android.text.Spanned
object HtmlUtils {
fun htmlToSpannable(htmlDesc: String): Spanned {
// 1
var newHtmlDesc = htmlDesc.replace("\n".toRegex(), "")
newHtmlDesc = newHtmlDesc.replace("(<(/)img>)|(<img.+?>)".
toRegex(), "")
// 2
val descSpan: Spanned
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
descSpan = Html.fromHtml(newHtmlDesc, Html.FROM_HTML_MODE_LEGACY)
} else {
@Suppress("DEPRECATION")
descSpan = Html.fromHtml(newHtmlDesc)
}
return descSpan
}
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/util/HtmlUtils.kt | 4007303181 |
package com.raywenderlich.podplay.adapter
import android.app.Activity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.raywenderlich.podplay.databinding.SearchItemBinding
import com.raywenderlich.podplay.viewmodel.SearchViewModel.PodcastSummaryViewData
class PodcastListAdapter(
private var podcastSummaryViewList: List<PodcastSummaryViewData>?,
private val podcastListAdapterListener: PodcastListAdapterListener,
private val parentActivity: Activity
) : RecyclerView.Adapter<PodcastListAdapter.ViewHolder>() {
interface PodcastListAdapterListener {
fun onShowDetails(podcastSummaryViewData: PodcastSummaryViewData)
}
inner class ViewHolder(
databinding: SearchItemBinding,
private val podcastListAdapterListener: PodcastListAdapterListener
) : RecyclerView.ViewHolder(databinding.root) {
var podcastSummaryViewData: PodcastSummaryViewData? = null
val nameTextView: TextView = databinding.podcastNameTextView
val lastUpdatedTextView: TextView = databinding.podcastLastUpdatedTextView
val podcastImageView: ImageView = databinding.podcastImage
init {
databinding.searchItem.setOnClickListener {
podcastSummaryViewData?.let {
podcastListAdapterListener.onShowDetails(it)
}
}
}
}
fun setSearchData(podcastSummaryViewData: List<PodcastSummaryViewData>) {
podcastSummaryViewList = podcastSummaryViewData
this.notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PodcastListAdapter.ViewHolder {
return ViewHolder(
SearchItemBinding.inflate(LayoutInflater.from(parent.context), parent, false),
podcastListAdapterListener
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val searchViewList = podcastSummaryViewList ?: return
val searchView = searchViewList[position]
holder.podcastSummaryViewData = searchView
holder.nameTextView.text = searchView.name
holder.lastUpdatedTextView.text = searchView.lastUpdated
Glide.with(parentActivity).load(searchView.imageUrl).into(holder.podcastImageView)
}
override fun getItemCount(): Int {
return podcastSummaryViewList?.size ?: 0
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/adapter/PodcastListAdapter.kt | 280179049 |
package com.raywenderlich.podplay.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.raywenderlich.podplay.databinding.EpisodeItemBinding
import com.raywenderlich.podplay.util.DateUtils
import com.raywenderlich.podplay.util.HtmlUtils
import com.raywenderlich.podplay.viewmodel.PodcastViewModel
class EpisodeListAdapter(
private var episodeViewList: List<PodcastViewModel.EpisodeViewData>?,
private val episodeListAdapterListener: EpisodeListAdapterListener) :
RecyclerView.Adapter<EpisodeListAdapter.ViewHolder>() {
interface EpisodeListAdapterListener {
fun onSelectedEpisode(episodeViewData: PodcastViewModel.EpisodeViewData)
}
inner class ViewHolder(
databinding: EpisodeItemBinding,
val episodeListAdapterListener: EpisodeListAdapterListener
) : RecyclerView.ViewHolder(databinding.root) {
init {
databinding.root.setOnClickListener {
episodeViewData?.let {
episodeListAdapterListener.onSelectedEpisode(it)
}
}
}
var episodeViewData: PodcastViewModel.EpisodeViewData? = null
val titleTextView: TextView = databinding.titleView
val descTextView: TextView = databinding.descView
val durationTextView: TextView = databinding.durationView
val releaseDateTextView: TextView = databinding.releaseDateView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EpisodeListAdapter.ViewHolder {
return ViewHolder(EpisodeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false), episodeListAdapterListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val episodeViewList = episodeViewList ?: return
val episodeView = episodeViewList[position]
holder.episodeViewData = episodeView
holder.titleTextView.text = episodeView.title
holder.descTextView.text = HtmlUtils.htmlToSpannable(episodeView.description ?: "")
holder.durationTextView.text = episodeView.duration
holder.releaseDateTextView.text = episodeView.releaseDate?.let {
DateUtils.dateToShortDate(it)
}
}
override fun getItemCount(): Int {
return episodeViewList?.size ?: 0
}
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/adapter/EpisodeListAdapter.kt | 3272381537 |
package com.raywenderlich.podplay.model
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import java.util.*
@Entity(
foreignKeys = [
ForeignKey(
entity = Podcast::class,
parentColumns = ["id"],
childColumns = ["podcastId"],
onDelete = ForeignKey.CASCADE)
],
indices = [Index("podcastId")]
)
data class Episode (
@PrimaryKey var guid: String = "",
var podcastId: Long? = null,
var title: String = "",
var description: String = "",
var mediaUrl: String = "",
var mimeType: String = "",
var releaseDate: Date = Date(),
var duration: String = ""
)
| PodPlay/app/src/main/java/com/raywenderlich/podplay/model/Episode.kt | 1956333740 |
package com.raywenderlich.podplay.model
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import java.util.*
@Entity
data class Podcast(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
var feedUrl: String = "",
var feedTitle: String = "",
var feedDesc: String = "",
var imageUrl: String = "",
var lastUpdated: Date = Date(),
@Ignore
var episodes: List<Episode> = listOf()
)
| PodPlay/app/src/main/java/com/raywenderlich/podplay/model/Podcast.kt | 696207335 |
package com.raywenderlich.podplay.db
import android.content.Context
import androidx.room.*
import com.raywenderlich.podplay.model.Episode
import com.raywenderlich.podplay.model.Podcast
import kotlinx.coroutines.CoroutineScope
import java.util.*
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return if (value == null) null else Date(value)
}
@TypeConverter
fun toTimestamp(date: Date?): Long? {
return (date?.time)
}
}
// 1
@Database(entities = [Podcast::class, Episode::class], version = 1)
@TypeConverters(Converters::class)
abstract class PodPlayDatabase : RoomDatabase() {
// 2
abstract fun podcastDao(): PodcastDao
// 3
companion object {
// 4
@Volatile
private var INSTANCE: PodPlayDatabase? = null
// 5
fun getInstance(context: Context, coroutineScope: CoroutineScope): PodPlayDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
// 6
synchronized(this) {
val instance = Room.databaseBuilder(context.applicationContext,
PodPlayDatabase::class.java,
"PodPlayer")
.build()
INSTANCE = instance
// 7
return instance
}
}
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/db/PodPlayDatabase.kt | 2156423111 |
package com.raywenderlich.podplay.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query
import com.raywenderlich.podplay.model.Episode
import com.raywenderlich.podplay.model.Podcast
@Dao
interface PodcastDao {
@Query("SELECT * FROM Podcast ORDER BY FeedTitle")
fun loadPodcasts(): LiveData<List<Podcast>>
@Query("SELECT * FROM Podcast ORDER BY FeedTitle")
suspend fun loadPodcastsStatic(): List<Podcast>
@Query("SELECT * FROM Episode WHERE podcastId = :podcastId ORDER BY releaseDate DESC")
suspend fun loadEpisodes(podcastId: Long): List<Episode>
@Query("SELECT * FROM Podcast WHERE feedUrl = :url")
suspend fun loadPodcast(url: String): Podcast?
@Insert(onConflict = REPLACE)
suspend fun insertPodcast(podcast: Podcast): Long
@Insert(onConflict = REPLACE)
suspend fun insertEpisode(episode: Episode): Long
@Delete
suspend fun deletePodcast(podcast: Podcast)
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/db/PodcastDao.kt | 3323787360 |
package com.raywenderlich.podplay.service
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFocusRequest
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.ResultReceiver
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
class PodplayMediaCallback(
val context: Context,
val mediaSession: MediaSessionCompat,
var mediaPlayer: MediaPlayer? = null
) : MediaSessionCompat.Callback() {
var listener: PodplayMediaListener? = null
private var mediaUri: Uri? = null
private var newMedia: Boolean = false
private var mediaExtras: Bundle? = null
private var focusRequest: AudioFocusRequest? = null
private var mediaNeedsPrepare: Boolean = false
override fun onCommand(command: String?, extras: Bundle?,
cb: ResultReceiver?) {
super.onCommand(command, extras, cb)
when (command) {
CMD_CHANGESPEED -> extras?.let { changeSpeed(it) }
}
}
override fun onPlayFromUri(uri: Uri?, extras: Bundle?) {
super.onPlayFromUri(uri, extras)
if (mediaUri == uri) {
newMedia = false
mediaExtras = null
} else {
mediaExtras = extras
setNewMedia(uri)
}
onPlay()
}
override fun onPlay() {
super.onPlay()
if (ensureAudioFocus()) {
mediaSession.isActive = true
initializeMediaPlayer()
prepareMedia()
startPlaying()
}
}
override fun onStop() {
super.onStop()
stopPlaying()
}
override fun onPause() {
super.onPause()
pausePlaying()
}
override fun onSeekTo(pos: Long) {
super.onSeekTo(pos)
mediaPlayer?.seekTo(pos.toInt())
val playbackState: PlaybackStateCompat? = mediaSession.controller.playbackState
if (playbackState != null) {
setState(playbackState.state)
} else {
setState(PlaybackStateCompat.STATE_PAUSED)
}
}
private fun setNewMedia(uri: Uri?) {
newMedia = true
mediaUri = uri
}
private fun ensureAudioFocus(): Boolean {
val audioManager = this.context.getSystemService(
Context.AUDIO_SERVICE) as AudioManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).run {
setAudioAttributes(AudioAttributes.Builder().run {
setUsage(AudioAttributes.USAGE_MEDIA)
setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
build()
})
build()
}
this.focusRequest = focusRequest
val result = audioManager.requestAudioFocus(focusRequest)
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
} else {
val result = audioManager.requestAudioFocus(null,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN)
return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}
}
private fun removeAudioFocus() {
val audioManager = this.context.getSystemService(
Context.AUDIO_SERVICE) as AudioManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
focusRequest?.let {
audioManager.abandonAudioFocusRequest(it)
}
} else {
audioManager.abandonAudioFocus(null)
}
}
private fun initializeMediaPlayer() {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer()
mediaPlayer!!.setOnCompletionListener{
setState(PlaybackStateCompat.STATE_PAUSED)
}
mediaNeedsPrepare = true
}
}
private fun changeSpeed(extras: Bundle) {
var playbackState = PlaybackStateCompat.STATE_PAUSED
if (mediaSession.controller.playbackState != null) {
playbackState = mediaSession.controller.playbackState.state
}
setState(playbackState, extras.getFloat(CMD_EXTRA_SPEED))
}
private fun setState(state: Int, newSpeed: Float? = null) {
var position: Long = -1
mediaPlayer?.let {
position = it.currentPosition.toLong()
}
var speed = 1.0f
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
speed = newSpeed ?: (mediaPlayer?.playbackParams?.speed ?: 1.0f)
mediaPlayer?.let { mediaPlayer ->
try {
mediaPlayer.playbackParams = mediaPlayer.playbackParams.setSpeed(speed)
}
catch (e: Exception) {
mediaPlayer.reset()
mediaUri?.let { mediaUri ->
mediaPlayer.setDataSource(context, mediaUri)
}
mediaPlayer.prepare()
mediaPlayer.playbackParams = mediaPlayer.playbackParams.setSpeed(speed)
mediaPlayer.seekTo(position.toInt())
if (state == PlaybackStateCompat.STATE_PLAYING) {
mediaPlayer.start()
}
}
}
}
val playbackState = PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY or
PlaybackStateCompat.ACTION_STOP or
PlaybackStateCompat.ACTION_PLAY_PAUSE or
PlaybackStateCompat.ACTION_PAUSE)
.setState(state, position, speed)
.build()
mediaSession.setPlaybackState(playbackState)
if (state == PlaybackStateCompat.STATE_PAUSED ||
state == PlaybackStateCompat.STATE_PLAYING) {
listener?.onStateChanged()
}
}
private fun prepareMedia() {
if (newMedia) {
newMedia = false
mediaPlayer?.let { mediaPlayer ->
mediaUri?.let { mediaUri ->
if (mediaNeedsPrepare) {
mediaPlayer.reset()
mediaPlayer.setDataSource(context, mediaUri)
mediaPlayer.prepare()
}
mediaExtras?.let { mediaExtras ->
mediaSession.setMetadata(MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_TITLE,
mediaExtras.getString(MediaMetadataCompat.METADATA_KEY_TITLE))
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,
mediaExtras.getString(MediaMetadataCompat.METADATA_KEY_ARTIST))
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI,
mediaExtras.getString(
MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI))
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION,
mediaPlayer.duration.toLong())
.build())
}
}
}
}
}
private fun startPlaying() {
mediaPlayer?.let { mediaPlayer ->
if (!mediaPlayer.isPlaying) {
mediaPlayer.start()
setState(PlaybackStateCompat.STATE_PLAYING)
}
}
}
private fun pausePlaying() {
removeAudioFocus()
mediaPlayer?.let { mediaPlayer ->
if (mediaPlayer.isPlaying) {
mediaPlayer.pause()
setState(PlaybackStateCompat.STATE_PAUSED)
}
}
listener?.onPausePlaying()
}
private fun stopPlaying() {
removeAudioFocus()
mediaSession.isActive = false
mediaPlayer?.let { mediaPlayer ->
if (mediaPlayer.isPlaying) {
mediaPlayer.stop()
setState(PlaybackStateCompat.STATE_STOPPED)
}
}
listener?.onStopPlaying()
}
interface PodplayMediaListener {
fun onStateChanged()
fun onStopPlaying()
fun onPausePlaying()
}
companion object {
const val CMD_CHANGESPEED = "change_speed"
const val CMD_EXTRA_SPEED = "speed"
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/service/PodplayMediaCallback.kt | 968108794 |
package com.raywenderlich.podplay.service
data class PodcastResponse(
val resultCount: Int,
val results: List<ItunesPodcast>) {
data class ItunesPodcast(
val collectionCensoredName: String,
val feedUrl: String,
val artworkUrl100: String,
val releaseDate: String
)
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/service/PodcastResponse.kt | 1632136021 |
package com.raywenderlich.podplay.service
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
interface ItunesService {
@GET("/search?media=podcast")
suspend fun searchPodcastByTerm(@Query("term") term: String): Response<PodcastResponse>
companion object {
val instance: ItunesService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://itunes.apple.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(ItunesService::class.java)
}
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/service/ItunesService.kt | 3199761553 |
package com.raywenderlich.podplay.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.media.MediaBrowserServiceCompat
import androidx.media.session.MediaButtonReceiver
import com.raywenderlich.podplay.R
import com.raywenderlich.podplay.service.PodplayMediaCallback.PodplayMediaListener
import com.raywenderlich.podplay.ui.PodcastActivity
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.net.URL
class PodplayMediaService : MediaBrowserServiceCompat(), PodplayMediaListener {
private lateinit var mediaSession: MediaSessionCompat
override fun onStateChanged() {
displayNotification()
}
override fun onStopPlaying() {
stopSelf()
stopForeground(true)
}
override fun onPausePlaying() {
stopForeground(false)
}
override fun onCreate() {
super.onCreate()
createMediaSession()
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
mediaSession.controller.transportControls.stop()
}
override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
// To be implemented
println("onLoadChildren called")
if (parentId == PODPLAY_EMPTY_ROOT_MEDIA_ID) {
result.sendResult(null)
}
}
override fun onGetRoot(clientPackageName: String,
clientUid: Int, rootHints: Bundle?): BrowserRoot {
return BrowserRoot(
PODPLAY_EMPTY_ROOT_MEDIA_ID, null)
}
private fun createMediaSession() {
mediaSession = MediaSessionCompat(this, "PodplayMediaService")
sessionToken = mediaSession.sessionToken
val callback = PodplayMediaCallback(this, mediaSession)
callback.listener = this
mediaSession.setCallback(callback)
}
private fun getPausePlayActions():
Pair<NotificationCompat.Action, NotificationCompat.Action> {
val pauseAction = NotificationCompat.Action(
R.drawable.ic_pause_white, getString(R.string.pause),
MediaButtonReceiver.buildMediaButtonPendingIntent(this,
PlaybackStateCompat.ACTION_PAUSE))
val playAction = NotificationCompat.Action(
R.drawable.ic_play_arrow_white, getString(R.string.play),
MediaButtonReceiver.buildMediaButtonPendingIntent(this,
PlaybackStateCompat.ACTION_PLAY))
return Pair(pauseAction, playAction)
}
private fun isPlaying() =
mediaSession.controller.playbackState != null &&
mediaSession.controller.playbackState.state ==
PlaybackStateCompat.STATE_PLAYING
private fun getNotificationIntent(): PendingIntent {
val openActivityIntent = Intent(this, PodcastActivity::class.java)
openActivityIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
return PendingIntent.getActivity(
this@PodplayMediaService, 0, openActivityIntent,
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (notificationManager.getNotificationChannel(PLAYER_CHANNEL_ID) == null) {
val channel = NotificationChannel(PLAYER_CHANNEL_ID, "Player",
NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
}
}
private fun createNotification(mediaDescription: MediaDescriptionCompat,
bitmap: Bitmap?): Notification {
val notificationIntent = getNotificationIntent()
val (pauseAction, playAction) = getPausePlayActions()
val notification = NotificationCompat.Builder(
this@PodplayMediaService, PLAYER_CHANNEL_ID)
notification
.setContentTitle(mediaDescription.title)
.setContentText(mediaDescription.subtitle)
.setLargeIcon(bitmap)
.setContentIntent(notificationIntent)
.setDeleteIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(this,
PlaybackStateCompat.ACTION_STOP))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_episode_icon)
.addAction(if (isPlaying()) pauseAction else playAction)
.setStyle(
androidx.media.app.NotificationCompat.MediaStyle()
.setMediaSession(mediaSession.sessionToken)
.setShowActionsInCompactView(0)
.setShowCancelButton(true)
.setCancelButtonIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(this,
PlaybackStateCompat.ACTION_STOP)))
return notification.build()
}
private fun displayNotification() {
if (mediaSession.controller.metadata == null) {
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
val mediaDescription = mediaSession.controller.metadata.description
GlobalScope.launch {
val iconUrl = URL(mediaDescription.iconUri.toString())
val bitmap = BitmapFactory.decodeStream(iconUrl.openStream())
val notification = createNotification(mediaDescription, bitmap)
ContextCompat.startForegroundService(
this@PodplayMediaService,
Intent(this@PodplayMediaService, PodplayMediaService::class.java))
startForeground(NOTIFICATION_ID, notification)
}
}
companion object {
private const val PODPLAY_EMPTY_ROOT_MEDIA_ID = "podplay_empty_root_media_id"
private const val PLAYER_CHANNEL_ID = "podplay_player_channel"
private const val NOTIFICATION_ID = 1
}
}
| PodPlay/app/src/main/java/com/raywenderlich/podplay/service/PodplayMediaService.kt | 582212021 |
package com.raywenderlich.podplay.service
import com.raywenderlich.podplay.BuildConfig
import com.raywenderlich.podplay.util.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.w3c.dom.Node
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Url
import java.util.concurrent.TimeUnit
import javax.xml.parsers.DocumentBuilderFactory
class RssFeedService private constructor() {
suspend fun getFeed(xmlFileURL: String): RssFeedResponse? {
val service: FeedService
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
if (BuildConfig.DEBUG) {
client.addInterceptor(interceptor)
}
client.build()
val retrofit = Retrofit.Builder()
.baseUrl("${xmlFileURL.split("?")[0]}/")
.build()
service = retrofit.create(FeedService::class.java)
try {
val result = service.getFeed(xmlFileURL)
if (result.code() >= 400) {
println("server error, ${result.code()}, ${result.errorBody()}")
return null
} else {
var rssFeedResponse: RssFeedResponse?
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
withContext(Dispatchers.IO) {
val doc = dBuilder.parse(result.body()?.byteStream())
val rss = RssFeedResponse(episodes = mutableListOf())
domToRssFeedResponse(doc, rss)
println(rss)
rssFeedResponse = rss
}
return rssFeedResponse
}
} catch (t: Throwable) {
println("error, ${t.localizedMessage}")
}
return null
}
private fun domToRssFeedResponse(node: Node, rssFeedResponse: RssFeedResponse) {
if (node.nodeType == Node.ELEMENT_NODE) {
val nodeName = node.nodeName
val parentName = node.parentNode.nodeName
// 1
val grandParentName = node.parentNode.parentNode?.nodeName ?: ""
// 2
if (parentName == "item" && grandParentName == "channel") {
// 3
val currentItem = rssFeedResponse.episodes?.last()
if (currentItem != null) {
// 4
when (nodeName) {
"title" -> currentItem.title = node.textContent
"description" -> currentItem.description = node.textContent
"itunes:duration" -> currentItem.duration = node.textContent
"guid" -> currentItem.guid = node.textContent
"pubDate" -> currentItem.pubDate = node.textContent
"link" -> currentItem.link = node.textContent
"enclosure" -> {
currentItem.url = node.attributes.getNamedItem("url")
.textContent
currentItem.type = node.attributes.getNamedItem("type")
.textContent
}
}
}
}
if (parentName == "channel") {
when (nodeName) {
"title" -> rssFeedResponse.title = node.textContent
"description" -> rssFeedResponse.description = node.textContent
"itunes:summary" -> rssFeedResponse.summary = node.textContent
"item" -> rssFeedResponse.episodes?.add(RssFeedResponse.EpisodeResponse())
"pubDate" -> rssFeedResponse.lastUpdated =
DateUtils.xmlDateToDate(node.textContent)
}
}
}
val nodeList = node.childNodes
for (i in 0 until nodeList.length) {
val childNode = nodeList.item(i)
domToRssFeedResponse(childNode, rssFeedResponse)
}
}
companion object {
val instance: RssFeedService by lazy {
RssFeedService()
}
}
}
interface FeedService {
@Headers(
"Content-Type: application/xml; charset=utf-8",
"Accept: application/xml"
)
@GET
suspend fun getFeed(@Url xmlFileURL: String): Response<ResponseBody>
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/service/RssFeedService.kt | 2178039762 |
package com.raywenderlich.podplay.service
import java.util.*
data class RssFeedResponse(
var title: String = "",
var description: String = "",
var summary: String = "",
var lastUpdated: Date = Date(),
var episodes: MutableList<EpisodeResponse>? = null
) {
data class EpisodeResponse(
var title: String? = null,
var link: String? = null,
var description: String? = null,
var guid: String? = null,
var pubDate: String? = null,
var duration: String? = null,
var url: String? = null,
var type: String? = null
)
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/service/RssFeedResponse.kt | 3481442028 |
package com.raywenderlich.podplay.worker
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.raywenderlich.podplay.R
import com.raywenderlich.podplay.db.PodPlayDatabase
import com.raywenderlich.podplay.repository.PodcastRepo
import com.raywenderlich.podplay.service.RssFeedService
import com.raywenderlich.podplay.ui.PodcastActivity
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
class EpisodeUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = coroutineScope {
val job = async { val db = PodPlayDatabase.getInstance(applicationContext, this)
val repo = PodcastRepo(RssFeedService.instance, db.podcastDao())
val podcastUpdates = repo.updatePodcastEpisodes()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
for (podcastUpdate in podcastUpdates) {
displayNotification(podcastUpdate)
}
}
job.await()
Result.success()
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (notificationManager.getNotificationChannel(EPISODE_CHANNEL_ID) == null) {
val channel = NotificationChannel(EPISODE_CHANNEL_ID, "Episodes", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
}
private fun displayNotification(podcastInfo: PodcastRepo.PodcastUpdateInfo) {
val contentIntent = Intent(applicationContext, PodcastActivity::class.java)
contentIntent.putExtra(EXTRA_FEED_URL, podcastInfo.feedUrl)
val pendingContentIntent = PendingIntent.getActivity(applicationContext, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(applicationContext, EPISODE_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_episode_icon)
.setContentTitle(applicationContext.getString(R.string.episode_notification_title))
.setContentText(applicationContext.getString(R.string.episode_notification_text, podcastInfo.newCount, podcastInfo.name))
.setNumber(podcastInfo.newCount)
.setAutoCancel(true)
.setContentIntent(pendingContentIntent)
.build()
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(podcastInfo.name, 0, notification)
}
companion object {
const val EPISODE_CHANNEL_ID = "podplay_episodes_channel"
const val EXTRA_FEED_URL = "PodcastFeedUrl"
}
} | PodPlay/app/src/main/java/com/raywenderlich/podplay/worker/EpisodeUpdateWorker.kt | 1964076845 |
package abhishek.pathak.composetesting
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performScrollTo
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ListUITest {
@get:Rule
val composeRule = createComposeRule()
val stateList = mutableStateListOf<String>()
@Before
fun setUp(){
stateList.add("One")
stateList.add("Two")
stateList.add("Three")
stateList.add("Four")
stateList.add("Five")
composeRule.setContent {
ListUI(list = stateList)
}
}
@Test
fun testList() {
// check all items displayed
stateList.forEach { content ->
composeRule
.onNodeWithText(content).assertExists()
}
}
@Test
fun testScrollOfList(){
// check scroll
composeRule
.onNodeWithText("Five").performScrollTo()
composeRule
.onNodeWithText("Five").assertIsDisplayed()
// remove item and assert not displayed
stateList.remove("Four")
composeRule
.onNodeWithText("Four").assertDoesNotExist()
// add item and assert displayed
stateList.add("Six")
composeRule
.onNodeWithText("Six").assertIsDisplayed()
}
} | ComposeTestingDemo/app/src/androidTest/java/abhishek/pathak/composetesting/ListUITest.kt | 2087856912 |
package abhishek.pathak.composetesting
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("abhishek.pathak.composetesting", appContext.packageName)
}
} | ComposeTestingDemo/app/src/androidTest/java/abhishek/pathak/composetesting/ExampleInstrumentedTest.kt | 3452738572 |
package abhishek.pathak.composetesting
import abhishek.pathak.composetesting.ui.theme.ComposeTestingTheme
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class WelcomeUITest {
@get:Rule
val rule = createComposeRule()
@Before
fun setUp() {
rule.setContent {
ComposeTestingTheme {
WelcomeScreen()
}
}
}
@Test
fun checkWeatherContinueButtonExistsOrNot() {
rule.onNodeWithText("Continue").assertExists()
rule.onNodeWithText("Continue").performClick()
}
} | ComposeTestingDemo/app/src/androidTest/java/abhishek/pathak/composetesting/WelcomeUITest.kt | 3174226859 |
package abhishek.pathak.composetesting
import abhishek.pathak.composetesting.ui.theme.ComposeTestingTheme
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LoginUITest {
@get:Rule
val rule = createComposeRule()
private lateinit var email: SemanticsNodeInteraction
private lateinit var password: SemanticsNodeInteraction
private lateinit var loginButton: SemanticsNodeInteraction
private lateinit var loginLabel: SemanticsNodeInteraction
@Before
fun setUp() {
rule.setContent {
ComposeTestingTheme {
LoginScreen {}
}
}
with(rule) {
email = onNodeWithTag("email")
password = onNodeWithTag("password")
loginButton = onNodeWithTag("LoginButton")
loginLabel = onNodeWithTag("LoginLabel")
}
}
@Test
fun verifyAllViewsAreExists() {
with(rule) {
email.assertExists()
password.assertExists()
loginLabel.assertExists()
loginButton.assertExists()
}
}
@Test
fun verifyEmailAddressValidation() {
with(email) {
performTextInput(VALID_EMAIL)
assert(hasText(VALID_EMAIL))
assertTrue(!isEmailValid.value)
assertTrue(emailErrMsg.value == "")
performTextClearance()
}
}
@Test
fun verifyEmailAddressValidationWithInvalidInput() {
val invalidEmail = "myofficework"
with(email) {
performTextInput(invalidEmail)
assert(hasText(invalidEmail))
assertNotEquals(VALID_EMAIL, hasText(invalidEmail))
performTextClearance()
}
}
@Test
fun verifyConfirmPasswordValidationWithValidInput() {
val input = "123456"
with(password) {
performTextInput(input)
assert(hasText(input))
assertTrue(!isConfirmPasswordInvalid.value)
assertTrue(emailErrMsg.value == "")
performTextClearance()
}
}
@Test
fun loginUser() {
email.performTextInput("[email protected]")
password.performTextInput("12345678")
loginButton.performClick()
}
private companion object {
const val VALID_EMAIL = "[email protected]"
}
}
| ComposeTestingDemo/app/src/androidTest/java/abhishek/pathak/composetesting/LoginUITest.kt | 719888044 |
package abhishek.pathak.composetesting
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RegistrationKtTest {
@get:Rule
val composeTestRule = createComposeRule()
@Before
fun setup() {
composeTestRule.setContent {
RegistrationForm {
}
}
}
@Test
fun verifyAllViewExits() {
composeTestRule.apply {
onNodeWithText("Username").assertExists()
onNodeWithText("Email").assertExists()
onNodeWithText("Mobile Number").assertExists()
onNodeWithText("Password").assertExists()
onNodeWithText("Confirm Password").assertExists()
}
}
@Test
fun verifyEmailValidationWithValidEmail() {
val validEmail = "[email protected]"
composeTestRule.onNodeWithText("Email").apply {
performTextInput(validEmail)
assert(hasText(validEmail))
assertTrue(!isEmailValid.value)
assertTrue(emailErrMsg.value == "")
performTextClearance()
}
}
@Test
fun verifyEmailValidationWithInvalidEmail() {
val invalidEmail = "invalidEmail"
val errorMsg = "Input proper email id"
composeTestRule.onNodeWithText("Email").apply {
performTextInput(invalidEmail)
assert(hasText(invalidEmail))
assertTrue(isEmailValid.value)
assertTrue(errorMsg == emailErrMsg.value)
performTextClearance()
}
}
@Test
fun verifyConfirmPasswordValidationWithValidPassword() {
val validConfirmPassword = ""
val errorMsg = ""
composeTestRule.onNodeWithText("Confirm Password").apply {
performTextInput(validConfirmPassword)
assert(hasText(validConfirmPassword))
Assert.assertFalse(isConfirmPasswordInvalid.value)
assertTrue(errorMsg == "")
performTextClearance()
}
}
@Test
fun verifyConfirmPasswordValidationWithInvalidPassword() {
val validConfirmPassword = "password"
val errorMsg = "Password is not matched"
composeTestRule.onNodeWithText("Confirm Password").apply {
performTextInput(validConfirmPassword)
assert(hasText(validConfirmPassword))
assertTrue(isConfirmPasswordInvalid.value)
assertTrue(errorMsg == "Password is not matched")
performTextClearance()
}
}
@Test
fun verifyButtonClick() {
val userName = "user"
val email = "[email protected]"
val mobile = "123-456-789"
val password = "password"
val confirmPassword = "password"
composeTestRule.onNodeWithText("Username")
.performTextInput(userName)
composeTestRule.onNodeWithText("Email")
.performTextInput(email)
composeTestRule.onNodeWithText("Mobile Number")
.performTextInput(mobile)
composeTestRule.onNodeWithText("Password")
.performTextInput(password)
composeTestRule.onNodeWithText("Confirm Password")
.performTextInput(confirmPassword)
composeTestRule.onNodeWithTag("RegisterButton").performClick()
assertTrue(email.isNotEmpty())
assertTrue(password.isNotEmpty())
}
} | ComposeTestingDemo/app/src/androidTest/java/abhishek/pathak/composetesting/RegistrationUITest.kt | 4097034779 |
package abhishek.pathak.composetesting
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)
}
} | ComposeTestingDemo/app/src/test/java/abhishek/pathak/composetesting/ExampleUnitTest.kt | 3203089232 |
package abhishek.pathak.composetesting.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) | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/ui/theme/Color.kt | 2802107909 |
package abhishek.pathak.composetesting.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 ComposeTestingTheme(
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
)
} | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/ui/theme/Theme.kt | 4062166535 |
package abhishek.pathak.composetesting.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
)
*/
) | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/ui/theme/Type.kt | 53561090 |
package abhishek.pathak.composetesting
import abhishek.pathak.composetesting.ui.theme.ComposeTestingTheme
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTestingTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
// WelcomeScreen()
RegistrationForm {}
}
}
}
}
}
| ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/MainActivity.kt | 2747566299 |
package abhishek.pathak.composetesting
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun WelcomeScreen() {
Box(modifier = Modifier.fillMaxSize()) {
Button(onClick = { }) {
Text(text = "Continue")
Text(text = "Continue")
Text(text = "Continue")
}
}
} | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/WelcomeUI.kt | 3025648095 |
package abhishek.pathak.composetesting
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.OutlinedTextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Preview
@Composable
private fun LoginScreenUIPrev() {
LoginScreen{}
}
@Composable
fun LoginScreen( onLogin: () -> Unit) {
var email by remember { mutableStateOf(TextFieldValue()) }
var password by remember { mutableStateOf(TextFieldValue()) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Login",
fontSize = 32.sp,
color = Color.Blue,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold,
modifier = Modifier.testTag("LoginLabel")
)
SpacerSmallLogin()
EmailTextField(email) { email = it }
SpacerSmallLogin()
PasswordTextField(password) { password = it }
SpacerSmallLogin()
SimpleTextButton("Login") {
}
}
}
@Composable
fun EmailTextField(email: TextFieldValue, onEmailChange: (TextFieldValue) -> Unit) {
OutlinedTextField(
value = email,
leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "emailIcon") },
onValueChange = { onEmailChange(it) },
label = { Text(text = "Email") },
modifier = Modifier.testTag("email")
)
}
@Composable
fun PasswordTextField(password: TextFieldValue, onPasswordChange: (TextFieldValue) -> Unit) {
OutlinedTextField(
value = password,
leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "lockIcon") },
onValueChange = { onPasswordChange(it) },
label = { Text(text = "Password") },
modifier = Modifier.testTag("password")
)
}
@Composable
fun SimpleTextButton(buttonMessage: String, onClick: () -> Unit) {
Button(
onClick = { onClick() },
modifier = Modifier.testTag("LoginButton"),
colors = ButtonDefaults.buttonColors(Color.Blue)
) {
Text(text = buttonMessage, color = Color.White)
}
}
@Composable
fun SpacerSmallLogin() {
Spacer(modifier = Modifier.padding(4.dp))
}
fun showToastLogin(context: Context, string: String) {
Toast.makeText(context, string, Toast.LENGTH_SHORT).show()
}
@Composable
fun showToastMessageLogin(context: Context, message: String) {
showToastLogin(context, message)
}
fun showLongToastLogin(context: Context, string: String) {
Toast.makeText(context, string, Toast.LENGTH_LONG).show()
}
| ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/Login.kt | 2498044704 |
package abhishek.pathak.composetesting
import abhishek.pathak.composetesting.ValidateRegistration.isValidRegistrationInput
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Preview
@Composable
fun RegistrationPreview() {
RegistrationForm {
}
}
@Composable
fun RegistrationForm(
onRegister: () -> Unit
) {
Box(
Modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.testTag("RegisterLabel"),
text = "Register",
fontSize = 32.sp,
color = Color.Blue,
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold
)
SpacerSmall()
//username
UserTextField()
SpacerSmall()
//email input field
EmailTextField()
SpacerSmall()
//
TextFieldWithNumbers()
SpacerSmall()
//password input field
PasswordTextField()
SpacerSmall()
//confirm password input field
ConfirmPasswordTextField()
SpacerSmall()
//register button
SimpleTextButton("Register", modifier = Modifier.testTag("RegisterButton")) {
onRegister
}
}
}
}
fun buttonClick(context: Context) {
if (isValidRegistrationInput(
username = username.value,
password = password,
confirmPassword = confirmPassword
)
) {
Log.d("TAG", username.value)
Log.d("TAG", password)
Log.d("TAG", confirmPassword)
showToast(context = context, context.getString(R.string.registration_success))
} else {
showLongToast(context = context, context.getString(R.string.registration_fail))
}
}
fun showToast(context: Context, string: String) {
Toast.makeText(context, string, Toast.LENGTH_SHORT).show()
}
fun showLongToast(context: Context, string: String) {
Toast.makeText(context, string, Toast.LENGTH_LONG).show()
}
@Composable
fun SimpleTextButton(
buttonMessage: String,
modifier: Modifier = Modifier,
textModifier: Modifier = Modifier,
enabled: Boolean = true,
buttonColors: ButtonColors = ButtonDefaults.buttonColors(),
textColor: Color = Color.Unspecified,
fontWeight: FontWeight? = null,
onClick: () -> Unit
) {
Button(
onClick = { onClick() },
modifier,
enabled = enabled,
colors = buttonColors
) {
Text(
text = buttonMessage,
modifier = textModifier,
color = textColor,
fontWeight = fontWeight
)
}
}
@Composable
fun SpacerSmall() {
Spacer(modifier = Modifier.padding(4.dp))
}
@Composable
fun RegisterButton() {
val context = LocalContext.current
Button(
onClick = { buttonClick(context = context) },
shape = RoundedCornerShape(20.dp)
) {
Text(text = "Register", fontSize = 16.sp)
}
}
@Composable
fun UserTextField() {
OutlinedTextField(
value = username.value,
leadingIcon = { Icon(imageVector = Icons.Default.Person, contentDescription = "userIcon") },
onValueChange = { username.value = it },
label = { Text(text = "Username") },
modifier = Modifier.testTag("username")
)
}
@Composable
fun EmailTextField() {
OutlinedTextField(
value = email.value,
leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "emailIcon") },
onValueChange = {
email.value = it
validateEmail(email = it)
},
isError = isEmailValid.value,
label = { Text(text = "Email") },
modifier = Modifier.testTag("email")
)
}
@Composable
fun ConfirmPasswordTextField() {
OutlinedTextField(
value = confirmPassword,
leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "lockIcon") },
onValueChange = {
confirmPassword = it
validConfirmPassword(password = password, confirmPassword = confirmPassword)
},
isError = isConfirmPasswordInvalid.value,
label = { Text(text = "Confirm Password") },
modifier = Modifier.testTag("confirmPassword")
)
}
@Composable
fun InputFields() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
SimpleTextField()
Spacer(modifier = Modifier.padding(4.dp))
LabelAndPlaceHolder()
Spacer(modifier = Modifier.padding(4.dp))
OutlineTextField()
Spacer(modifier = Modifier.padding(4.dp))
TextFieldWithIcons()
Spacer(modifier = Modifier.padding(4.dp))
PasswordTextField()
Spacer(modifier = Modifier.padding(4.dp))
TextFieldWithNumbers()
}
}
@Composable
fun SimpleTextField() {
var text by remember { mutableStateOf(TextFieldValue("")) }
TextField(value = text, onValueChange = { newText ->
text = newText
})
}
@Composable
fun LabelAndPlaceHolder() {
var text by remember { mutableStateOf(TextFieldValue("")) }
TextField(value = text, onValueChange = { text = it },
label = { Text(text = "Username") },
placeholder = { Text(text = "username") }
)
}
@Composable
fun OutlineTextField() {
var text by remember { mutableStateOf(TextFieldValue("")) }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text(text = "Enter Your Name") }
)
}
@Composable
fun TextFieldWithIcons() {
var text by remember { mutableStateOf(TextFieldValue("")) }
OutlinedTextField(
value = text,
leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = "emailIcon") },
onValueChange = { text = it },
label = { Text(text = "Email") }
)
}
@Composable
fun TextFieldWithNumbers() {
var text by remember { mutableStateOf(TextFieldValue("")) }
OutlinedTextField(
value = text,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
onValueChange = { text = it },
leadingIcon = { Icon(imageVector = Icons.Default.Phone, contentDescription = "phoneIcon") },
label = { Text(text = "Mobile Number") },
modifier = Modifier.testTag("mobile")
)
}
@Composable
private fun PasswordTextField() {
val showPassword by remember {
mutableStateOf(false)
}
OutlinedTextField(
value = password,
leadingIcon = { Icon(imageVector = Icons.Default.Lock, contentDescription = "lockIcon") },
onValueChange = { password = it },
label = { Text(text = "Password") },
modifier = Modifier.testTag("password")
)
}
fun validateEmail(email: String) {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
isEmailValid.value = true
emailErrMsg.value = "Input proper email id"
} else {
isEmailValid.value = false
emailErrMsg.value = ""
}
}
fun validConfirmPassword(password: String, confirmPassword: String) {
if (password != confirmPassword) {
isConfirmPasswordInvalid.value = true
emailErrMsg.value = "Password is not matched"
} else {
isConfirmPasswordInvalid.value = false
emailErrMsg.value = ""
}
}
var regUser: RegisterUser = RegisterUser()
var username: MutableState<String> = mutableStateOf(regUser.name)
var password: String by mutableStateOf("")
var confirmPassword: String by mutableStateOf("")
var isConfirmPasswordInvalid: MutableState<Boolean> = mutableStateOf(false)
var email: MutableState<String> = mutableStateOf(regUser.email)
var isEmailValid: MutableState<Boolean> = mutableStateOf(false)
var emailErrMsg: MutableState<String> = mutableStateOf("")
data class RegisterUser(
var name: String = "",
var email: String = "",
var password: String = "",
var confirmPassword: String = ""
)
| ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/Registration.kt | 3298346468 |
package abhishek.pathak.composetesting
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun ListUI(list: SnapshotStateList<String>) {
LazyColumn {
items(list) { item ->
Box(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.background(Color.Cyan, RoundedCornerShape(10.dp))
) {
Text(text = item, modifier = Modifier.padding(10.dp).align(Alignment.Center))
}
}
}
} | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/ListUI.kt | 2575188128 |
package abhishek.pathak.composetesting
object ValidateRegistration {
private val existingUsers = listOf("Alex","Ethan","Jeremy","Ryan")
fun isValidRegistrationInput(
username : String,
password : String,
confirmPassword: String
) : Boolean {
if(username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) return false
if (username in existingUsers) return false
if (password != confirmPassword) return false
if (password.count { it.isDigit()} < 6) return false
return true
}
} | ComposeTestingDemo/app/src/main/java/abhishek/pathak/composetesting/ValidateRegistration.kt | 79812746 |
package tn.mpdam1.myapplication_jeuxtri
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("tn.mpdam1.myapplication_jeuxtri", appContext.packageName)
}
} | tri/app/src/androidTest/java/tn/mpdam1/myapplication_jeuxtri/ExampleInstrumentedTest.kt | 16721910 |
package tn.mpdam1.myapplication_jeuxtri
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)
}
} | tri/app/src/test/java/tn/mpdam1/myapplication_jeuxtri/ExampleUnitTest.kt | 73040617 |
package tn.mpdam1.myapplication_jeuxtri
import android.content.ClipData
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
import android.view.*
import android.widget.Button
import android.widget.Chronometer
import android.widget.TextView
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
private val numbers = mutableListOf<Int>()
private var startTime: Long = 0
private var lastClickedNumber: TextView? = null
private var initialPosition: Int = 0
private var initialText: String = ""
private var isValiderButtonEnabled: Boolean = false
private val draggedNumbers = mutableListOf<Int>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Generate 5 random numbers
for (i in 1..5) {
numbers.add(Random.nextInt(1, 100))
}
// Display welcome message and random numbers
val welcomeText: TextView = findViewById(R.id.welcomeText)
val number1: TextView = findViewById(R.id.number1)
val number2: TextView = findViewById(R.id.number2)
val number3: TextView = findViewById(R.id.number3)
val number4: TextView = findViewById(R.id.number4)
val number5: TextView = findViewById(R.id.number5)
val placeholder1: TextView = findViewById(R.id.placeholder1)
val placeholder2: TextView = findViewById(R.id.placeholder2)
val placeholder3: TextView = findViewById(R.id.placeholder3)
val placeholder4: TextView = findViewById(R.id.placeholder4)
val placeholder5: TextView = findViewById(R.id.placeholder5)
val validerButton: Button = findViewById(R.id.validerButton)
welcomeText.text = "Welcome to the App!"
number1.text = numbers[0].toString()
number2.text = numbers[1].toString()
number3.text = numbers[2].toString()
number4.text = numbers[3].toString()
number5.text = numbers[4].toString()
// Set initial text for placeholders
placeholder1.text = ""
placeholder2.text = ""
placeholder3.text = ""
placeholder4.text = ""
placeholder5.text = ""
// Start the timer
startTimer()
// Set up double click listeners for numbers
setDoubleClickListenerForNumber(number1)
setDoubleClickListenerForNumber(number2)
setDoubleClickListenerForNumber(number3)
setDoubleClickListenerForNumber(number4)
setDoubleClickListenerForNumber(number5)
// Set up click listeners for placeholders
setClickListenerForPlaceholder(placeholder1, validerButton)
setClickListenerForPlaceholder(placeholder2, validerButton)
setClickListenerForPlaceholder(placeholder3, validerButton)
setClickListenerForPlaceholder(placeholder4, validerButton)
setClickListenerForPlaceholder(placeholder5, validerButton)
// Set click listener for the Valider button
validerButton.setOnClickListener {
if (isValiderButtonEnabled) {
if (checkOrder()) {
// If the order is correct, launch GoodJobActivity
val intent = Intent(this@MainActivity, GoodJobActivity::class.java)
startActivity(intent)
} else {
// If the order is incorrect, launch GameOverActivity
val intent = Intent(this@MainActivity, GameOverActivity::class.java)
startActivity(intent)
}
}
}
}
private fun setDoubleClickListenerForNumber(number: TextView) {
number.setOnClickListener {
if (lastClickedNumber == number && SystemClock.elapsedRealtime() - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
// Double-click action
initialPosition = numbers.indexOf(number.text.toString().toInt())
initialText = number.text.toString()
number.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val dragData = ClipData.newPlainText("", "")
val shadowBuilder = View.DragShadowBuilder(number)
// Set a tag to identify the dragged view
number.tag = "NUMBER"
number.startDrag(dragData, shadowBuilder, number, 0)
number.visibility = View.INVISIBLE
true
}
else -> false
}
}
} else {
// Single-click action
lastClickTime = SystemClock.elapsedRealtime()
lastClickedNumber = number
}
}
}
private fun setClickListenerForPlaceholder(placeholder: TextView, validerButton: Button) {
var lastClickTimePlaceholder: Long = 0
var lastClickedNumberForPlaceholder: TextView? = null
placeholder.setOnClickListener {
// Click action
lastClickedNumberForPlaceholder?.let { number ->
if (placeholder.text.isNotEmpty()) {
// Return the text to its initial position
val initialNumber = numbers[initialPosition].toString()
placeholder.text = initialNumber
// Clear the text of the original view (number)
number.text = ""
// Make the original view visible again
number.visibility = View.VISIBLE
draggedNumbers.remove(number.text.toString().toInt())
lastClickedNumberForPlaceholder = null
} else {
// Set the text of the placeholder to the dropped text
placeholder.text = number.text
// Clear the text of the dropped view (number)
number.text = ""
// Make the dropped view visible again
number.visibility = View.VISIBLE
draggedNumbers.add(placeholder.text.toString().toInt())
lastClickedNumberForPlaceholder = null
// Check if all placeholders have a number
isValiderButtonEnabled = areAllPlaceholdersFilled()
validerButton.isEnabled = isValiderButtonEnabled
}
}
}
// Double click on a placeholder to return the text to its initial position in the number
placeholder.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
if (event.eventTime - event.downTime < DOUBLE_CLICK_TIME_DELTA) {
// Double-click action
if (lastClickedNumberForPlaceholder == null || lastClickedNumberForPlaceholder == lastClickedNumber) {
lastClickedNumberForPlaceholder = lastClickedNumber
lastClickTimePlaceholder = SystemClock.elapsedRealtime()
}
true
} else {
false
}
}
MotionEvent.ACTION_UP -> {
if (event.eventTime - event.downTime < DOUBLE_CLICK_TIME_DELTA) {
// Double-click action
if (lastClickedNumberForPlaceholder == lastClickedNumber && SystemClock.elapsedRealtime() - lastClickTimePlaceholder < DOUBLE_CLICK_TIME_DELTA) {
lastClickedNumberForPlaceholder?.let { number ->
// Return the text to its initial position in the number
val initialNumber = numbers[initialPosition].toString()
placeholder.text = initialNumber
// Clear the text of the original view (number)
number.text = ""
// Make the original view visible again
number.visibility = View.VISIBLE
lastClickedNumberForPlaceholder = null
}
}
true
} else {
false
}
}
else -> false
}
}
}
private fun areAllPlaceholdersFilled(): Boolean {
val placeholder1: TextView = findViewById(R.id.placeholder1)
val placeholder2: TextView = findViewById(R.id.placeholder2)
val placeholder3: TextView = findViewById(R.id.placeholder3)
val placeholder4: TextView = findViewById(R.id.placeholder4)
val placeholder5: TextView = findViewById(R.id.placeholder5)
return (
placeholder1.text.isNotEmpty() &&
placeholder2.text.isNotEmpty() &&
placeholder3.text.isNotEmpty() &&
placeholder4.text.isNotEmpty() &&
placeholder5.text.isNotEmpty()
)
}
private fun checkOrder(): Boolean {
val sortedNumbers = draggedNumbers.sorted()
// Check if the sorted numbers match the expected order
return (
sortedNumbers[0] == 1 &&
sortedNumbers[1] == 2 &&
sortedNumbers[2] == 3 &&
sortedNumbers[3] == 4 &&
sortedNumbers[4] == 5
)
}
private fun startTimer() {
// Start the chronometer
val chronometer: Chronometer = findViewById(R.id.chronometer)
startTime = SystemClock.elapsedRealtime()
chronometer.base = startTime
chronometer.start()
}
companion object {
private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 // milliseconds
private var lastClickTime: Long = 0
}
} | tri/app/src/main/java/tn/mpdam1/myapplication_jeuxtri/MainActivity.kt | 1661899103 |
package tn.mpdam1.myapplication_jeuxtri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class GameOverActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game_over)
}
} | tri/app/src/main/java/tn/mpdam1/myapplication_jeuxtri/GameOverActivity.kt | 1514883954 |
package tn.mpdam1.myapplication_jeuxtri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class GoodJobActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_good_job)
}
} | tri/app/src/main/java/tn/mpdam1/myapplication_jeuxtri/GoodJobActivity.kt | 3159133674 |
package com.example.wellnessresolutions
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.wellnessresolutions", appContext.packageName)
}
} | WWCodeHackathon2023/src/androidTest/java/com/example/wellnessresolutions/ExampleInstrumentedTest.kt | 140628044 |
package com.example.wellnessresolutions
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)
}
} | WWCodeHackathon2023/src/test/java/com/example/wellnessresolutions/ExampleUnitTest.kt | 1057504607 |
package com.example.wellnessresolutions
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import android.Manifest
import android.view.View
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread.sleep(3000)
installSplashScreen()
setContentView(R.layout.activity_main)
// Check for the permission
if (!activityRecognitionPermissionApproved()) {
// Request the permission
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),
PERMISSION_REQUEST_ACTIVITY_RECOGNITION
)
}
}
// Reviews Activity Recognition permission checking.
//Source: https://developer.android.com/codelabs/android-sleep-api#2
private fun activityRecognitionPermissionApproved(): Boolean {
return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACTIVITY_RECOGNITION
)
}
companion object {
private const val PERMISSION_REQUEST_ACTIVITY_RECOGNITION = 1
}
} | WWCodeHackathon2023/src/main/java/com/example/wellnessresolutions/MainActivity.kt | 2798044915 |
package com.proyecto.findteacherapp
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.proyecto.findteacherapp", appContext.packageName)
}
} | Find_Teacher_App/app/src/androidTest/java/com/proyecto/findteacherapp/ExampleInstrumentedTest.kt | 3649844812 |
package com.proyecto.findteacherapp
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)
}
} | Find_Teacher_App/app/src/test/java/com/proyecto/findteacherapp/ExampleUnitTest.kt | 3204186963 |
package com.proyecto.findteacherapp
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.proyecto.findteacherapp.includes.MiToolbar
class AccionesAdministrador : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_acciones_administrador)
MiToolbar.show(this, "Acciones Administrador", false)
val FotoAdmin = findViewById<LinearLayout>(R.id.FotoAdmin)
val AnuncioAdmin = findViewById<LinearLayout>(R.id.AnuncioAdmin)
FotoAdmin.setOnClickListener {
val intent = Intent(this@AccionesAdministrador, CrearFoto::class.java)
startActivity(intent)
}
AnuncioAdmin.setOnClickListener {
val intent = Intent(this@AccionesAdministrador, CrearAnuncio::class.java)
startActivity(intent)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_admin, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.Salir) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Advertencia")
builder.setMessage("¿Desea cerrar sesión?")
builder.setPositiveButton("Aceptar", DialogInterface.OnClickListener { dialog, which ->
FirebaseAuth.getInstance().signOut()
val intent = Intent(this, InicioSesion::class.java)
startActivity(intent)
})
builder.setNegativeButton("Cancelar", DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "Acción Cancelada", Toast.LENGTH_SHORT).show()
})
builder.show()
}
return super.onOptionsItemSelected(item)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/AccionesAdministrador.kt | 2542514753 |
package com.proyecto.findteacherapp
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
setContentView(R.layout.activity_main)
val animacion1 = AnimationUtils.loadAnimation(this, R.anim.desplazamiento_arriba)
val animacion2 = AnimationUtils.loadAnimation(this, R.anim.desplazamiento_abajo)
val imageView = findViewById<ImageView>(R.id.img_logo)
val textView = findViewById<TextView>(R.id.textView_logo)
imageView.animation = animacion1
textView.animation = animacion2
Handler().postDelayed({
val intent = Intent(this@MainActivity, VentanaPrincipal::class.java)
startActivity(intent)
finish()
}, 2000)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/MainActivity.kt | 955456978 |
package com.proyecto.findteacherapp
import android.content.Intent
import android.content.SharedPreferences
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
class InicioSesion : AppCompatActivity() {
private lateinit var UsuarioEditText: EditText
private lateinit var ContaseñaEditText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_inicio_sesion)
val volver = findViewById<ImageView>(R.id.volver)
UsuarioEditText = findViewById(R.id.UsuarioEditText)
ContaseñaEditText = findViewById(R.id.ContaseñaEditText)
val BotonInicioSesion = findViewById<Button>(R.id.BotonInicioSesion)
volver.setOnClickListener {
val intent = Intent(this@InicioSesion, VentanaPrincipal::class.java)
startActivity(intent)
finish()
}
BotonInicioSesion.setOnClickListener {
IniciarSesion()
}
}
private fun IniciarSesion(){
val preferences: SharedPreferences
preferences = getSharedPreferences("typeUser", MODE_PRIVATE)
val editor = preferences.edit()
if(!UsuarioEditText.text.toString().isEmpty() && !ContaseñaEditText.text.toString().isEmpty()){
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(UsuarioEditText.text.toString(), ContaseñaEditText.text.toString())
.addOnCompleteListener {
if (it.isSuccessful){
val intent = Intent(this@InicioSesion, AccionesAdministrador::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
editor.putString("user", "Administrador")
editor.apply()
startActivity(intent)
finish()
}else {
Toast.makeText(this, "Este usuario no esta registrado", Toast.LENGTH_SHORT).show()
}
}
}else{
Toast.makeText(this, "Debe ingresar la información completa para continuar", Toast.LENGTH_SHORT).show()
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/InicioSesion.kt | 813910417 |
package com.proyecto.findteacherapp.includes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.proyecto.findteacherapp.R
object MiToolbar {
fun show(activity: AppCompatActivity, titulo: String?, upButton: Boolean) {
val Toolbar = activity.findViewById<Toolbar>(R.id.toolbar)
activity.setSupportActionBar(Toolbar)
activity.supportActionBar!!.title = titulo
activity.supportActionBar!!.setDisplayHomeAsUpEnabled(upButton)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/includes/MiToolbar.kt | 1309319889 |
package com.proyecto.findteacherapp
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.squareup.picasso.Picasso
class DetallesAnuncio : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detalles_anuncio)
val AtrasDetallesAnuncio = findViewById<ImageView>(R.id.AtrasDetallesAnuncio)
val TxtNombreDetallesAnuncio = findViewById<TextView>(R.id.TxtNombreDetallesAnuncio)
val TxtUbicacionDetallesAnuncio = findViewById<TextView>(R.id.TxtUbicacionDetallesAnuncio)
val TxtAsignaturaDetallesAnuncio = findViewById<TextView>(R.id.TxtAsignaturaDetallesAnuncio)
val TxtInformacionDetallesAnuncio = findViewById<TextView>(R.id.TxtInformacionDetallesAnuncio)
val ImgDocenteDetallesAnuncio = findViewById<ImageView>(R.id.ImgDocenteDetallesAnuncio)
val TxtTelefonoDetallesAnuncio = findViewById<TextView>(R.id.TxtTelefonoDetallesAnuncio)
val AccionNumeroDetallesAnuncio = findViewById<LinearLayout>(R.id.AccionNumeroDetallesAnuncio)
var Id: String? = intent.getStringExtra("Id")
var Nombre: String? = intent.getStringExtra("Nombre")
var Telefono: String? = intent.getStringExtra("Telefono")
var Informacion: String? = intent.getStringExtra("Informacion")
var Ciudad: String? = intent.getStringExtra("Ciudad")
var Asignatura: String? = intent.getStringExtra("Asignatura")
var Url: String? = intent.getStringExtra("Url")
AtrasDetallesAnuncio.setOnClickListener {
val intent = Intent(this@DetallesAnuncio, VentanaPrincipal::class.java)
startActivity(intent)
finish()
}
TxtNombreDetallesAnuncio.setText(Nombre)
TxtUbicacionDetallesAnuncio.setText(Ciudad)
TxtInformacionDetallesAnuncio.setText(Informacion)
TxtAsignaturaDetallesAnuncio.setText(Asignatura)
TxtTelefonoDetallesAnuncio.setText(Telefono)
Picasso.get().load(Url).into(ImgDocenteDetallesAnuncio)
AccionNumeroDetallesAnuncio.setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://api.whatsapp.com/send?phone=+57$Telefono")
startActivity(intent)
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/DetallesAnuncio.kt | 3077476285 |
package com.proyecto.findteacherapp.Adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.proyecto.findteacherapp.DetallesAnuncio
import com.proyecto.findteacherapp.Model.AnuncioModel
import com.proyecto.findteacherapp.R
import com.squareup.picasso.Picasso
class AnuncioAdapter (
private val SitioLista : ArrayList<AnuncioModel>)
: RecyclerView.Adapter<AnuncioAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.perfil_fragment, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val lista = SitioLista[position]
holder.Id.text = lista.Id
holder.Asignatura.text = lista.Asignatura
holder.Ciudad.text = lista.Ciudad
holder.Informacion.text = lista.Informacion
holder.Nombre.text = lista.Nombre
holder.Telefono.text = lista.Telefono
Picasso.get().load(lista.Url).into(holder.Url)
holder.Seleccionar.setOnClickListener{
val intent = Intent(holder.Seleccionar.context, DetallesAnuncio::class.java)
intent.putExtra("Id", lista.Id)
intent.putExtra("Nombre", lista.Nombre)
intent.putExtra("Telefono", lista.Telefono)
intent.putExtra("Informacion", lista.Informacion)
intent.putExtra("Ciudad", lista.Ciudad)
intent.putExtra("Asignatura", lista.Asignatura)
intent.putExtra("Url", lista.Url)
holder.Seleccionar.context.startActivity(intent)
}
}
override fun getItemCount(): Int {
return SitioLista.size
}
class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
val Asignatura : TextView = itemView.findViewById(R.id.TxtAsignatura)
val Ciudad : TextView = itemView.findViewById(R.id.TxtUbicacionDocente)
val Id : TextView = itemView.findViewById(R.id.TxtId)
val Informacion : TextView = itemView.findViewById(R.id.TxtInformacion)
val Nombre : TextView = itemView.findViewById(R.id.TxtNombreDocente)
val Telefono : TextView = itemView.findViewById(R.id.TxtTelefonoDocente)
val Url : ImageView = itemView.findViewById(R.id.ImagenPerfil)
val Seleccionar : LinearLayout = itemView.findViewById(R.id.SeleccionPerfil)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/Adapter/AnuncioAdapter.kt | 2794822896 |
package com.proyecto.findteacherapp.Adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.proyecto.findteacherapp.DetallesFotografia
import com.proyecto.findteacherapp.Model.FotografiasModel
import com.proyecto.findteacherapp.R
import com.squareup.picasso.Picasso
class FotografiasAdapter (
private val FotografiasLista: ArrayList<FotografiasModel>)
: RecyclerView.Adapter<FotografiasAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.fotografias_item, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val lista = FotografiasLista[position]
Picasso.get().load(lista.Url).into(holder.ImagenPromocional)
holder.IdImg.text = lista.Id
holder.ImagenPromocional.setOnClickListener {
val intent = Intent(holder.ImagenPromocional.context, DetallesFotografia::class.java)
intent.putExtra("Url", lista.Url)
intent.putExtra("Id", lista.Id)
holder.ImagenPromocional.context.startActivity(intent)
}
}
override fun getItemCount(): Int {
return FotografiasLista.size
}
class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
val ImagenPromocional : ImageView = itemView.findViewById(R.id.ImgPromoItem)
val IdImg : TextView = itemView.findViewById(R.id.idurl)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/Adapter/FotografiasAdapter.kt | 3473398389 |
package com.proyecto.findteacherapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.proyecto.findteacherapp.Adapter.FotografiasAdapter
import com.proyecto.findteacherapp.Model.FotografiasModel
class CrearFoto : AppCompatActivity() {
private lateinit var BotonAtrasImagenes: ImageView
private lateinit var AccionAgregarImagen: ImageView
private lateinit var AccionAgregarText: TextView
private lateinit var RecyclerFotos: RecyclerView
private lateinit var reference: DatabaseReference
private lateinit var lista : ArrayList <FotografiasModel>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crear_foto)
BotonAtrasImagenes = findViewById(R.id.BotonAtrasImagenes)
AccionAgregarImagen = findViewById(R.id.AccionAgregarImagen)
AccionAgregarText = findViewById(R.id.AccionAgregarText)
RecyclerFotos = findViewById(R.id.RecyclerFotos)
RecyclerFotos.layoutManager = LinearLayoutManager(this)
RecyclerFotos.setHasFixedSize(true)
RecyclerFotos.visibility = View.GONE
lista = arrayListOf<FotografiasModel>()
reference = FirebaseDatabase.getInstance().getReference("ImagenesPromocionales")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(FotografiasModel::class.java)
lista.add(data!!)
}
val Adapter = FotografiasAdapter(lista)
RecyclerFotos.adapter = Adapter
RecyclerFotos.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
}
})
BotonAtrasImagenes.setOnClickListener {
val intent = Intent(this@CrearFoto, AccionesAdministrador::class.java)
startActivity(intent)
finish()
}
AccionAgregarText.setOnClickListener {
val intent = Intent(this@CrearFoto, AgregarFotografias::class.java)
startActivity(intent)
}
AccionAgregarImagen.setOnClickListener {
val intent = Intent(this@CrearFoto, AgregarFotografias::class.java)
startActivity(intent)
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/CrearFoto.kt | 3401711053 |
package com.proyecto.findteacherapp
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.Toast
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.squareup.picasso.Picasso
class DetallesFotografia : AppCompatActivity() {
private lateinit var reference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detalles_fotografia)
reference = FirebaseDatabase.getInstance().getReference("ImagenesPromocionales")
val AtrasImgPromoDetalles = findViewById<ImageView>(R.id.AtrasImgPromoDetalles)
val ImgDetallesPromo = findViewById<ImageView>(R.id.ImgDetallesPromo)
val BorrarImgDetalles = findViewById<ImageView>(R.id.BorrarImgDetalles)
var url: String? = intent.getStringExtra("Url")
var id: String? = intent.getStringExtra("Id")
Picasso.get().load(url).into(ImgDetallesPromo)
AtrasImgPromoDetalles.setOnClickListener {
val intent = Intent(this@DetallesFotografia, CrearFoto::class.java)
startActivity(intent)
finish()
}
BorrarImgDetalles.setOnClickListener {
val builder = AlertDialog.Builder(this)
builder.setTitle("Advertencia")
builder.setMessage("¿Esta seguro que desea eliminar esta imagen?")
builder.setPositiveButton("Aceptar", DialogInterface.OnClickListener { dialog, which ->
reference.child(id.toString()).removeValue().addOnCompleteListener{
Toast.makeText(this, "Se ha eliminado la imagen", Toast.LENGTH_SHORT).show()
val intent = Intent(this@DetallesFotografia, CrearFoto::class.java)
startActivity(intent)
finish()
}.addOnFailureListener{
Toast.makeText(this, "Error añ eliminar la imagen", Toast.LENGTH_SHORT).show()
}
})
builder.setNegativeButton("Cancelar", DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "Acción Cancelada", Toast.LENGTH_SHORT).show()
})
builder.show()
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/DetallesFotografia.kt | 1304886432 |
package com.proyecto.findteacherapp
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
class CrearAnuncio : AppCompatActivity() {
private lateinit var ImgAnuncio: ImageView
private lateinit var UrlFoto: TextView
private lateinit var EditTextNombre: EditText
private lateinit var EditTextNumeroTelefonico: EditText
private lateinit var TextCiudad: AutoCompleteTextView
private lateinit var TextAsignatura: AutoCompleteTextView
private lateinit var EditTextInformacion: EditText
private lateinit var reference: DatabaseReference
private lateinit var reference1: DatabaseReference
private val mStorageRef = FirebaseStorage.getInstance().reference
private val TAG = "FirebaseStorageManager"
companion object{
const val REQUEST_FROM_CAMERA = 1001
const val REQUEST_FROM_GALERY = 1002
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_crear_anuncio)
reference = FirebaseDatabase.getInstance().getReference().child("Anuncio")
ImgAnuncio = findViewById(R.id.ImgAnuncio)
val AtrasCrearAnuncio = findViewById<ImageView>(R.id.AtrasCrearAnuncio)
val SeleccionGaleria = findViewById<LinearLayout>(R.id.SeleccionGaleria)
val SeleccionCamara = findViewById<LinearLayout>(R.id.SeleccionCamara)
EditTextNombre = findViewById(R.id.EditTextNombre)
EditTextNumeroTelefonico = findViewById(R.id.EditTextNumeroTelefonico)
TextCiudad = findViewById(R.id.TextCiudad)
TextAsignatura = findViewById(R.id.TextAsignatura)
EditTextInformacion = findViewById(R.id.EditTextInformacion)
val SubirInformacion = findViewById<Button>(R.id.SubirInformacion)
UrlFoto = findViewById(R.id.UrlFoto)
val items = listOf("Chiquinquirá","Quipama","Briceño", "Caldas", "La Uvita", "Jenesano",
"Muzo", "San Pablo de Borbur", "Saboya", "La Victoria", "Tasco",
"Pauna", "San Miguel de Sema", "Coper", "Buenavista", "San Mateo",
"Maripi", "Otanche", "Tununguá", "Úmbita", "Toca")
val adapter = ArrayAdapter(this, R.layout.list_item,items)
val items1 = listOf("Matematicas", "Idiomas", "Deportes", "Arte", "Geografia")
val adapter1 = ArrayAdapter(this, R.layout.list_item,items1)
TextCiudad.setAdapter(adapter)
TextAsignatura.setAdapter(adapter1)
TextCiudad.onItemClickListener = AdapterView.OnItemClickListener {
parent, view, position, id ->
val itemSelected = parent.getItemAtPosition(position)
Toast.makeText(this,"Item: $itemSelected",Toast.LENGTH_SHORT).show()
}
TextAsignatura.onItemClickListener = AdapterView.OnItemClickListener {
parent, view, position, id ->
val itemSelected = parent.getItemAtPosition(position)
Toast.makeText(this,"Item: $itemSelected",Toast.LENGTH_SHORT).show()
}
val con = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = con.activeNetworkInfo
AtrasCrearAnuncio.setOnClickListener {
val intent = Intent(this@CrearAnuncio, AccionesAdministrador::class.java)
startActivity(intent)
finish()
}
SeleccionGaleria.setOnClickListener {
AbrirGaleria()
}
SeleccionCamara.setOnClickListener {
TomarFoto()
}
SubirInformacion.setOnClickListener {
if(networkInfo!=null && networkInfo.isConnected){
SubirInformacion()
}else{
Toast.makeText(this,"No hay conexión a internet\nVerifique el acceso a internet e intente nuevamente",Toast.LENGTH_LONG).show()
}
}
}
private fun AbrirGaleria(){
ImagePicker.with(this).galleryOnly()
.crop()
.start(AgregarFotografias.REQUEST_FROM_GALERY)
}
private fun TomarFoto(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(AgregarFotografias.REQUEST_FROM_CAMERA)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK){
when (requestCode){
AgregarFotografias.REQUEST_FROM_CAMERA -> {
ImgAnuncio.setImageURI(data!!.data)
uploadImage(this, data.data!!)
}
AgregarFotografias.REQUEST_FROM_GALERY -> {
ImgAnuncio.setImageURI(data!!.data)
uploadImage(this, data.data!!)
}
}
}
}
private fun uploadImage(mContext: Context, imageURI: Uri){
val ImagenFileName = "FotoAnuncio ${System.currentTimeMillis()}"
val uploadTask = mStorageRef.child(ImagenFileName).putFile(imageURI)
uploadTask.addOnSuccessListener {
Log.e(TAG, "Imagen cargada con éxito")
val DescargarUrlImagen = mStorageRef.child(ImagenFileName).downloadUrl
DescargarUrlImagen.addOnSuccessListener {
UrlFoto.setText("$it")
}.addOnFailureListener{
Toast.makeText(this, "No se pudo cargar la Url de la imagen", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener{
Log.e(TAG, "Carga de imagen fallida ${it.printStackTrace()}")
}
}
private fun SubirInformacion(){
val Id = reference.push().key!!
val Imagen = UrlFoto.text.toString()
val Nombre = EditTextNombre.text.toString()
val Telefono = EditTextNumeroTelefonico.text.toString()
val Ciudad = TextCiudad.text.toString()
val Asignatura = TextAsignatura.text.toString()
val Informacion = EditTextInformacion.text.toString()
val map: MutableMap<String, Any> = HashMap()
map["Id"] = Id
map["Url"] = Imagen
map["Nombre"] = Nombre
map["Telefono"] = Telefono
map["Ciudad"] = Ciudad
map["Asignatura"] = Asignatura
map["Informacion"] = Informacion
if(Asignatura.equals("Matematicas")){
reference1 = FirebaseDatabase.getInstance().getReference().child("Matematicas")
reference1.child(Id).setValue(map)
}else if(Asignatura.equals("Idiomas")){
reference1 = FirebaseDatabase.getInstance().getReference().child("Idiomas")
reference1.child(Id).setValue(map)
}else if(Asignatura.equals("Deportes")){
reference1 = FirebaseDatabase.getInstance().getReference().child("Deportes")
reference1.child(Id).setValue(map)
}else if(Asignatura.equals("Arte")){
reference1 = FirebaseDatabase.getInstance().getReference().child("Arte")
reference1.child(Id).setValue(map)
}else if(Asignatura.equals("Geografia")){
reference1 = FirebaseDatabase.getInstance().getReference().child("Geografia")
reference1.child(Id).setValue(map)
}
if(Imagen != "" && Nombre != "" && Telefono != "" && Ciudad != "" && Informacion != ""){
reference.child(Id).setValue(map).addOnCompleteListener {
Toast.makeText(this, "Se ha creado un nuevo anuncio", Toast.LENGTH_SHORT).show()
finish()
}.addOnFailureListener{
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this, "Ingrese los datos requeridos para continuar", Toast.LENGTH_SHORT).show()
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/CrearAnuncio.kt | 2184688126 |
package com.proyecto.findteacherapp.Model
data class AnuncioModel(
val Asignatura: String? = null,
var Ciudad: String? = null,
var Id: String? = null,
var Informacion: String? = null,
var Nombre: String? = null,
var Telefono: String? = null,
var Url: String? = null
) | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/Model/AnuncioModel.kt | 3145644581 |
package com.proyecto.findteacherapp.Model
data class FotografiasModel (
var Url: String? = null,
var Id: String? = null,
) | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/Model/FotografiasModel.kt | 3880333854 |
package com.proyecto.findteacherapp
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.LinearLayout
import android.widget.SearchView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.denzcoskun.imageslider.ImageSlider
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.models.SlideModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.proyecto.findteacherapp.Adapter.AnuncioAdapter
import com.proyecto.findteacherapp.Model.AnuncioModel
import com.proyecto.findteacherapp.includes.MiToolbar
import java.util.ArrayList
class VentanaPrincipal : AppCompatActivity() {
private lateinit var lista : ArrayList <AnuncioModel>
private lateinit var reference: DatabaseReference
private lateinit var rv_anuncios: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ventana_principal)
MiToolbar.show(this, "Find Teacher App", false)
val sv_profesor = findViewById<androidx.appcompat.widget.SearchView>(R.id.sv_profesor)
rv_anuncios = findViewById(R.id.rv_anuncios)
val imageSlider = findViewById<ImageSlider>(R.id.imageSlider)
val AccionMatematicas = findViewById<LinearLayout>(R.id.AccionMatematicas)
val AccionIdiomas = findViewById<LinearLayout>(R.id.AccionIdiomas)
val AccionDeporte = findViewById<LinearLayout>(R.id.AccionDeporte)
val AccionArte = findViewById<LinearLayout>(R.id.AccionArte)
val AccionGeografias = findViewById<LinearLayout>(R.id.AccionGeografias)
reference = FirebaseDatabase.getInstance().getReference("Anuncio")
val imageList = ArrayList<SlideModel>()
rv_anuncios.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
rv_anuncios.setHasFixedSize(true)
lista = arrayListOf<AnuncioModel>()
///////////////////Imagenes Promocionales/////////////////////////
FirebaseDatabase.getInstance().reference.child("ImagenesPromocionales")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (data in snapshot.children) {
imageList.add(SlideModel(data.child("Url").value.toString(), ScaleTypes.FIT))
imageSlider.setImageList(imageList, ScaleTypes.FIT)
}
}
override fun onCancelled(error: DatabaseError) {}
})
///////////////////Matematicas/////////////////////////
AccionMatematicas.setOnClickListener {
val intent = Intent(this, AccionAreaConocimiento::class.java)
intent.putExtra("Dato", "Matematicas")
startActivity(intent)
finish()
}
///////////////////Idiomas/////////////////////////
AccionIdiomas.setOnClickListener {
val intent = Intent(this, AccionAreaConocimiento::class.java)
intent.putExtra("Dato", "Idiomas")
startActivity(intent)
finish()
}
///////////////////Deportes/////////////////////////
AccionDeporte.setOnClickListener {
val intent = Intent(this, AccionAreaConocimiento::class.java)
intent.putExtra("Dato", "Deportes")
startActivity(intent)
finish()
}
///////////////////Arte/////////////////////////
AccionArte.setOnClickListener {
val intent = Intent(this, AccionAreaConocimiento::class.java)
intent.putExtra("Dato", "Arte")
startActivity(intent)
finish()
}
///////////////////Geografia/////////////////////////
AccionGeografias.setOnClickListener {
val intent = Intent(this, AccionAreaConocimiento::class.java)
intent.putExtra("Dato", "Geografia")
startActivity(intent)
finish()
}
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
rv_anuncios.adapter = Adapter
rv_anuncios.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
sv_profesor.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(s: String): Boolean {
buscar(s)
return true
}
})
}
private fun buscar(s: String) {
val milista = ArrayList<AnuncioModel>()
for (obj in lista) {
if (obj.Nombre?.lowercase()?.contains(s.lowercase()) == true){
milista.add(obj)
}
}
val adapter = AnuncioAdapter(milista)
rv_anuncios.setAdapter(adapter)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.InicioSesion) {
val intent = Intent(this@VentanaPrincipal, InicioSesion::class.java)
startActivity(intent)
}
return super.onOptionsItemSelected(item)
}
override fun onStart() {
super.onStart()
val preferences: SharedPreferences
preferences = getSharedPreferences("typeUser", MODE_PRIVATE)
if (FirebaseAuth.getInstance().getCurrentUser() != null){
val user = preferences.getString("user", "")
if (user.equals("Administrador")){
val intent = Intent(this, AccionesAdministrador::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
}
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/VentanaPrincipal.kt | 4129257614 |
package com.proyecto.findteacherapp
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.SearchView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.proyecto.findteacherapp.Adapter.AnuncioAdapter
import com.proyecto.findteacherapp.Model.AnuncioModel
class AccionAreaConocimiento : AppCompatActivity() {
private lateinit var lista : ArrayList<AnuncioModel>
private lateinit var reference: DatabaseReference
private lateinit var RecyclerAreaC: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_accion_area_conocimiento)
val AtrasAccionesA = findViewById<ImageView>(R.id.AtrasAccionesA)
val ImgFondoMate = findViewById<View>(R.id.ImgFondoMate)
val ImgFondoIdiomas = findViewById<View>(R.id.ImgFondoIdiomas)
val ImgFondoDeportes = findViewById<View>(R.id.ImgFondoDeportes)
val ImgFondoArte = findViewById<View>(R.id.ImgFondoArte)
val ImgFondoGeografia = findViewById<View>(R.id.ImgFondoGeografia)
val ImgMate = findViewById<ImageView>(R.id.ImgMate)
val ImgIdiomas = findViewById<ImageView>(R.id.ImgIdiomas)
val ImgDeportes = findViewById<ImageView>(R.id.ImgDeportes)
val ImgArte = findViewById<ImageView>(R.id.ImgArte)
val ImgGeografia = findViewById<ImageView>(R.id.ImgGeografia)
val TxtAC = findViewById<TextView>(R.id.TxtAC)
RecyclerAreaC = findViewById(R.id.RecyclerAreaC)
val sv_area_conocimiento_anuncio = findViewById<
androidx.appcompat.widget.SearchView>(R.id.sv_area_conocimiento_anuncio)
reference = FirebaseDatabase.getInstance().getReference("Anuncio")
var Area: String? = intent.getStringExtra("Dato")
RecyclerAreaC.layoutManager = LinearLayoutManager(this)
RecyclerAreaC.setHasFixedSize(true)
lista = arrayListOf<AnuncioModel>()
AtrasAccionesA.setOnClickListener {
val intent = Intent(this@AccionAreaConocimiento, VentanaPrincipal::class.java)
startActivity(intent)
finish()
}
if(Area.equals("Matematicas")){
ImgMate.visibility = View.VISIBLE
ImgFondoMate.visibility = View.VISIBLE
TxtAC.setText("Matematicas")
reference = FirebaseDatabase.getInstance().getReference("Matematicas")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
RecyclerAreaC.adapter = Adapter
RecyclerAreaC.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
else if(Area.equals("Idiomas")){
ImgIdiomas.visibility = View.VISIBLE
ImgFondoIdiomas.visibility = View.VISIBLE
TxtAC.setText("Idiomas")
reference = FirebaseDatabase.getInstance().getReference("Idiomas")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
RecyclerAreaC.adapter = Adapter
RecyclerAreaC.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
else if(Area.equals("Deportes")){
ImgDeportes.visibility = View.VISIBLE
ImgFondoDeportes.visibility = View.VISIBLE
TxtAC.setText("Deportes")
reference = FirebaseDatabase.getInstance().getReference("Deportes")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
RecyclerAreaC.adapter = Adapter
RecyclerAreaC.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
else if(Area.equals("Arte")){
ImgArte.visibility = View.VISIBLE
ImgFondoArte.visibility = View.VISIBLE
TxtAC.setText("Arte")
reference = FirebaseDatabase.getInstance().getReference("Arte")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
RecyclerAreaC.adapter = Adapter
RecyclerAreaC.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
else if(Area.equals("Geografia")){
ImgGeografia.visibility = View.VISIBLE
ImgFondoGeografia.visibility = View.VISIBLE
TxtAC.setText("Geografia")
reference = FirebaseDatabase.getInstance().getReference("Geografia")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
lista.clear()
if (snapshot.exists()){
for (Snap in snapshot.children){
val data = Snap.getValue(AnuncioModel::class.java)
lista.add(data!!)
}
val Adapter = AnuncioAdapter(lista)
RecyclerAreaC.adapter = Adapter
RecyclerAreaC.visibility = View.VISIBLE
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
sv_area_conocimiento_anuncio.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(s: String): Boolean {
buscar(s)
return true
}
})
}
private fun buscar(s: String) {
val milista = java.util.ArrayList<AnuncioModel>()
for (obj in lista) {
if (obj.Nombre?.lowercase()?.contains(s.lowercase()) == true){
milista.add(obj)
}
}
val adapter = AnuncioAdapter(milista)
RecyclerAreaC.setAdapter(adapter)
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/AccionAreaConocimiento.kt | 4123399642 |
package com.proyecto.findteacherapp
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.github.dhaval2404.imagepicker.ImagePicker
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
class AgregarFotografias : AppCompatActivity() {
private lateinit var BotonAtras: ImageView
private lateinit var BotonSeleccionarImagen: Button
private lateinit var BotonTomarFoto: Button
private lateinit var Fotografia: ImageView
private lateinit var UrlFoto: TextView
private lateinit var SubirFoto: Button
private lateinit var reference: DatabaseReference
private val mStorageRef = FirebaseStorage.getInstance().reference
private val TAG = "FirebaseStorageManager"
companion object{
const val REQUEST_FROM_CAMERA = 1001
const val REQUEST_FROM_GALERY = 1002
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_agregar_fotografias)
reference = FirebaseDatabase.getInstance().getReference().child("ImagenesPromocionales")
BotonAtras = findViewById(R.id.BotonAtrasCrearFoto)
BotonSeleccionarImagen = findViewById(R.id.BotonSelecionarImagen)
BotonTomarFoto = findViewById(R.id.BotonTomarFotoPromocional)
Fotografia = findViewById(R.id.Img_fotografia)
UrlFoto = findViewById(R.id.UrlFoto)
SubirFoto = findViewById(R.id.SubirFotoFirebase)
BotonAtras.setOnClickListener {
val intent = Intent(this@AgregarFotografias, CrearFoto::class.java)
startActivity(intent)
finish()
}
BotonSeleccionarImagen.setOnClickListener {
AbrirGaleria()
}
BotonTomarFoto.setOnClickListener {
TomarFoto()
}
SubirFoto.setOnClickListener {
SubirImagen()
}
}
private fun AbrirGaleria(){
ImagePicker.with(this).galleryOnly()
.crop()
.start(AgregarFotografias.REQUEST_FROM_GALERY)
}
private fun TomarFoto(){
ImagePicker.with(this).cameraOnly()
.crop()
.start(AgregarFotografias.REQUEST_FROM_CAMERA)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK){
when (requestCode){
AgregarFotografias.REQUEST_FROM_CAMERA -> {
Fotografia.setImageURI(data!!.data)
uploadImage(this, data.data!!)
}
AgregarFotografias.REQUEST_FROM_GALERY -> {
Fotografia.setImageURI(data!!.data)
uploadImage(this, data.data!!)
}
}
}
}
private fun uploadImage(mContext: Context, imageURI: Uri){
val ImagenFileName = "ImagenesAnuncios ${System.currentTimeMillis()}"
val uploadTask = mStorageRef.child(ImagenFileName).putFile(imageURI)
uploadTask.addOnSuccessListener {
Log.e(TAG, "Imagen cargada con éxito")
val DescargarUrlImagen = mStorageRef.child(ImagenFileName).downloadUrl
DescargarUrlImagen.addOnSuccessListener {
UrlFoto.setText("$it")
}.addOnFailureListener{
Toast.makeText(this, "No se pudo cargar la Url de la imagen", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener{
Log.e(TAG, "Carga de imagen fallida ${it.printStackTrace()}")
}
}
private fun SubirImagen(){
val Imagen = UrlFoto.text.toString()
val Id = reference.push().key!!
val map: MutableMap<String, Any> = HashMap()
map["Url"] = Imagen
map["Id"] = Id
if (!Imagen.isEmpty()){
reference.child(Id).setValue(map).addOnCompleteListener{
Toast.makeText(this, "Se ha creado una imagen promocional", Toast.LENGTH_SHORT).show()
finish()
}.addOnFailureListener{
Toast.makeText(this, "Error al subir la imagen", Toast.LENGTH_SHORT).show()
}
}else{
Toast.makeText(this, "Debe ingresar la imagen", Toast.LENGTH_SHORT).show()
}
}
} | Find_Teacher_App/app/src/main/java/com/proyecto/findteacherapp/AgregarFotografias.kt | 1985902935 |
package com.example.internalstorage
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.internalstorage", appContext.packageName)
}
} | InternalStorage/app/src/androidTest/java/com/example/internalstorage/ExampleInstrumentedTest.kt | 4257508620 |
package com.example.internalstorage
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)
}
} | InternalStorage/app/src/test/java/com/example/internalstorage/ExampleUnitTest.kt | 4293668290 |
package com.example.internalstorage.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) | InternalStorage/app/src/main/java/com/example/internalstorage/ui/theme/Color.kt | 3393466750 |
package com.example.internalstorage.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 InternalStorageTheme(
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
)
} | InternalStorage/app/src/main/java/com/example/internalstorage/ui/theme/Theme.kt | 2516010078 |
package com.example.internalstorage.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
)
*/
) | InternalStorage/app/src/main/java/com/example/internalstorage/ui/theme/Type.kt | 578518277 |
package com.example.internalstorage
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.internalstorage.ui.theme.InternalStorageTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import androidx.compose.material3.Text
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
InternalStorageTheme {
val textState = remember {
mutableStateOf("")
}
val context = LocalContext.current
val scope = rememberCoroutineScope()
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = textState.value)
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = {
scope.launch {
textState.value = readFile(context)
}
}) {
Text(text = "Read")
}
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = {
scope.launch {
save(context)
}
}) {
Text(text = "Save")
}
}
}
}
}
}
private suspend fun save(context: Context) {
val text = "В небе свет предвечерних огней.\n" +
"Чувства снова, как прежде, огнисты.\n" +
"Небеса всё синей и синей,\n" +
"Облачка, как барашки, волнисты."
withContext(Dispatchers.IO) {
context.openFileOutput("test.txt", Context.MODE_PRIVATE).use {
it.write(text.toByteArray())
}
}
}
private suspend fun readFile(context: Context) = withContext(Dispatchers.IO) {
try {
context.openFileInput("test.txt").bufferedReader().useLines { lines ->
lines.fold("") { acc, s ->
"$acc\n$s"
}
}
} catch (e: IOException) {
e.printStackTrace()
"Error: File not found!"
}
} | InternalStorage/app/src/main/java/com/example/internalstorage/MainActivity.kt | 1815390301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.