content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.hallserviceapp
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
class AddDiningActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
AddDiningScreen()
}
}
}
}
}
@Composable
fun AddDiningScreen() {
var imageUri by remember { mutableStateOf<Uri?>(null) }
var addDiningName by remember { mutableStateOf("") }
var price by remember { mutableStateOf("") }
var time by remember { mutableStateOf("") }
var date by remember { mutableStateOf("") }
val context = LocalContext.current
val storageReference = FirebaseStorage.getInstance().reference
val databaseReference = Firebase.database.reference
val lightBlue = Color(0xFF8FABE7) // Light blue color 0xFF8FABE7
var showDialog by remember { mutableStateOf(false) }
var isLoading by remember { mutableStateOf(false) } // Loading state
Surface(
modifier = Modifier
.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
// Add the background image
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAll("Add Dining Food")
Spacer(modifier = Modifier.size(40.dp))
LazyColumn {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
LoadImageAD { uri ->
imageUri = uri
}
Spacer(modifier = Modifier.width(40.dp))
ShowImageAD(imageUri)
}
// Show selected image
OutlinedTextField(
value = addDiningName,
onValueChange = { addDiningName = it },
label = { Text("Food Name",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = price,
onValueChange = { price = it },
label = { Text("Price",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = time,
onValueChange = { time = it },
label = { Text("Time",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
Spacer(modifier = Modifier.size(16.dp))
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
Button(
onClick = {
// Validate authority information
if (addDiningName.isNotEmpty() && price.isNotEmpty() &&
time.isNotEmpty() && imageUri != null
) {
showDialog = true
isLoading = true
addDiningToFirebase(
context,
imageUri,
addDiningName,
price,
time,
date,
storageReference,
databaseReference
)
//isLoading = false
//showDialog = false
} else {
Toast.makeText(
context,
"Please fill all fields and select an image",
Toast.LENGTH_SHORT
).show()
}
},
modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth()
) {
Text("Upload Food Information")
}
if (showDialog) {
AlertDialog(
onDismissRequest = {
showDialog = false
isLoading = false
},
title = {
Text("Uploading")
},
text = {
Text("Uploading... Please wait")
},
confirmButton = {
TextButton(
onClick = {
showDialog = false
isLoading = false
}
) {
Text("Dismiss")
}
}
)
}
}
}
}
}
}
@Composable
fun LoadImageAD(
onImageSelected: (Uri) -> Unit
) {
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent()
) { uri ->
uri?.let {
onImageSelected(it)
}
}
Box(
modifier = Modifier
.size(80.dp)
.clickable {
launcher.launch("image/*")
}
.background(Color(0xFFFBF9FC), RoundedCornerShape(8.dp)),
contentAlignment = Alignment.Center
) {
Image(
imageVector = Icons.Default.Add,
contentDescription = "Plus Icon",
modifier = Modifier
.size(60.dp)
)
}
}
@Composable
fun ShowImageAD(imageUri: Uri?) {
if (imageUri != null) {
// Show the selected image
Image(
painter = rememberImagePainter(imageUri),
contentDescription = null,
modifier = Modifier
.size(150.dp)
.padding(vertical = 8.dp)
.clip(shape = RoundedCornerShape(8.dp))
)
}
}
fun addDiningToFirebase(
context: Context,
imageUri: Uri?,
addDiningName: String,
price: String,
time: String,
date: String,
storageReference: StorageReference,
databaseReference: DatabaseReference
) {
imageUri?.let { uri ->
val imageRef = storageReference.child("images/${UUID.randomUUID()}")
imageRef.putFile(uri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
// Create Authority object
val diningFoods = DiningFood(
addDiningName,
price,
time,
date,
imageUrl
)
// Push Authority object to Firebase Database
databaseReference.child("DiningFoods").push().setValue(diningFoods)
.addOnSuccessListener {
Toast.makeText(
context,
"Food information uploaded successfully",
Toast.LENGTH_SHORT
).show()
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload Food information",
Toast.LENGTH_SHORT
).show()
}
}
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload image",
Toast.LENGTH_SHORT
).show()
}
}
}
data class DiningFood(
val addDiningName: String = "",
val price: String = "",
val time: String = "",
val date: String = "",
val imageUrl: String = ""
)
@Preview(showBackground = true)
@Composable
fun AddDiningScreenPreview() {
HallServiceAppTheme {
AddDiningScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/AddDiningActivity.kt
|
1133631891
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class CanteenActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CanteenScreen()
}
}
}
}
}
@Composable
fun CanteenScreen() {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize(),
//.background(Color(0xFF8FABE7)), // Custom background color
//.padding(8.dp),
//horizontalAlignment = Alignment.CenterHorizontally
verticalArrangement = Arrangement.Top,
) {
Headlineee("Canteen") // You can reuse the HeaderSection from DiningActivity or create a new one
MealSection("Breakfast", "8:00 am", "Khichuri - Egg - Dal")
MealSection("Lunch", "12:30 pm", "Chicken, Dal, Fish, Egg, Vegetable, Murighanto")
MealSection("Dinner", "8:00 pm", "Chicken, Dal, Fish, Egg, Vegetable, Murighanto")
SpecialMealSection("Special Meal", "10:00 pm", "Chicken-Khichuri")
SpecialSection("Every Friday - Special biryani")
}
}
}
@Composable
fun SpecialMealSection(specialMealName: String, time: String, description: String) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.background(Color.LightGray, shape = RoundedCornerShape(10.dp))
.padding(16.dp)
) {
Text(
text = "$specialMealName: $time",
style = MaterialTheme.typography.bodyMedium,
color = Color.Black
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = description,
style = MaterialTheme.typography.headlineSmall,
color = Color.DarkGray
)
}
}
// Preview
@Preview(showBackground = true)
@Composable
fun CanteenScreenPreview() {
CanteenScreen()
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/CanteenActivity.kt
|
3806846477
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class UpdateStudentActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
UpdateStudentScreen()
}
}
}
}
}
@Composable
fun UpdateStudentScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val gray = Color(0xFFBA6FBD)
val green = Color(0xFF43B83A)
val yellow = Color(0xFFC5B685)
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize(),
//.background(lightBlue, shape = RoundedCornerShape(10.dp)),
horizontalAlignment = Alignment . CenterHorizontally,
verticalArrangement = Arrangement.Top,
) {
Spacer(modifier = Modifier.height(30.dp)) // For spacing
HeaderSectionAll("Delete Information")
Spacer(modifier = Modifier.height(100.dp)) // For spacing
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = "Delete Student",
color = Color.White,
fontSize = 20.sp,
modifier = Modifier
.width(150.dp)
.background(Color.Gray, RoundedCornerShape(15.dp))
.padding(12.dp)
.clickable {
context.startActivity(
Intent(
context,
DeleteStudentActivity::class.java
)
) // Change to the desired activity
}
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(50.dp)) // For spacing
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = "Delete Offices",
color = Color.White,
fontSize = 20.sp,
modifier = Modifier
.width(150.dp)
.background(Color.Gray, RoundedCornerShape(15.dp))
.padding(12.dp)
.clickable {
context.startActivity(
Intent(
context,
DeleteOfficesActivity::class.java
)
) // Change to the desired activity
}
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(50.dp)) // For spacing
Box(
contentAlignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = "Delete Authority",
color = Color.White,
fontSize = 20.sp,
modifier = Modifier
.width(150.dp)
.background(Color.Gray, RoundedCornerShape(15.dp))
.padding(12.dp)
.clickable {
context.startActivity(
Intent(
context,
DeleteAuthorityActivity::class.java
)
) // Change to the desired activity
}
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun UpdateStudentPreview() {
HallServiceAppTheme {
UpdateStudentScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteInformation.kt
|
76269056
|
package com.example.hallserviceapp
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class ComplaintsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FirebaseApp.initializeApp(this)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ComplaintsScreen()
}
}
}
}
}
@Composable
fun ComplaintsScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
Headlineee("Complaints")
WriteSection()
}
}
}
@Composable
fun WriteSection() {
val yellow = Color(0xFFC5B685)
var titleState by remember { mutableStateOf(TextFieldValue("Enter complaint title")) }
var textState by remember { mutableStateOf(TextFieldValue("Type your complaint here")) }
val context = LocalContext.current
var isUploading by remember { mutableStateOf(false) }
val lightBlue = Color(0xFF8FABE7) // Light blue color
// UI arrangements for title and text input
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
//.background(lightBlue, shape = RoundedCornerShape(10.dp))
.padding(4.dp)
) {
InputTitle(titleState, "Enter complaint title") { titleState = it }
Spacer(modifier = Modifier.height(8.dp))
InputField(textState, "Write your complaint here") { textState = it }
Spacer(modifier = Modifier.height(16.dp))
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Button(onClick = {
textState = TextFieldValue("")
titleState = TextFieldValue("")
}) {
Text("Clear")
}
Button(onClick = {
if (isUserLoggedIn()) {
isUploading = true // Set the state to loading
submitComplaint(context, titleState.text, textState.text) { success ->
if (success) {
titleState = TextFieldValue("")
textState = TextFieldValue("")
}
isUploading = false // Reset the loading state
}
} else {
Toast.makeText(context, "Please log in to submit a complaint", Toast.LENGTH_LONG).show()
}
}) {
Text("Submit")
}
if (isUploading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
}
}
}
fun isUserLoggedIn(): Boolean {
val currentUser = FirebaseAuth.getInstance().currentUser
return currentUser != null
}
@Composable
fun InputTitle(
state: TextFieldValue,
placeholder: String,
onValueChange: (TextFieldValue) -> Unit
) {
// TextField UI modifications
TextField(
value = state,
onValueChange = onValueChange,
placeholder = { Text(placeholder) },
modifier = Modifier
.fillMaxWidth()
.height(65.dp)
.padding(4.dp)
.background(Color.White, shape = MaterialTheme.shapes.medium)
)
}
@Composable
fun InputField(
state: TextFieldValue,
placeholder: String,
onValueChange: (TextFieldValue) -> Unit
) {
// TextField UI modifications
TextField(
value = state,
onValueChange = onValueChange,
placeholder = { Text(placeholder) },
modifier = Modifier
.fillMaxWidth()
.height(350.dp)
.padding(4.dp)
.background(Color.White, shape = MaterialTheme.shapes.medium)
)
}
fun submitComplaint(context: Context, title: String, complaintText: String, onCompletion: (Boolean) -> Unit) {
val auth = FirebaseAuth.getInstance()
val userId = auth.currentUser?.uid
if (userId == null) {
Toast.makeText(context, "Please log in to submit a complaint", Toast.LENGTH_LONG).show()
onCompletion(false)
return
}
val database = Firebase.database
val complaintsRef = database.getReference("complaints")
val complaintId = complaintsRef.push().key
val complaint = Complaint(userId, title, complaintText) // Date is set in the constructor
complaintsRef.child(complaintId!!).setValue(complaint)
.addOnSuccessListener {
Toast.makeText(context, "Complaint submitted successfully", Toast.LENGTH_SHORT).show()
onCompletion(true)
}
.addOnFailureListener {
Toast.makeText(context, "Failed to submit complaint", Toast.LENGTH_SHORT).show()
onCompletion(false)
}
}
data class Complaint(val userId: String, val title: String, val text: String, val date: String) {
// Primary constructor
constructor(userId: String, title: String, text: String) : this(
userId,
title,
text,
SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
)
}
@Preview(showBackground = true)
@Composable
fun ComplaintsScreenPreview() {
HallServiceAppTheme {
ComplaintsScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ComplaintsActivity.kt
|
419118714
|
package com.example.hallserviceapp
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.UUID
class UpdateAuthorityActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
UpdateAuthorityScreen()
}
}
}
}
}
@Composable
fun UpdateAuthorityScreen() {
var imageUri by remember { mutableStateOf<Uri?>(null) }
var authorityName by remember { mutableStateOf("") }
var designation by remember { mutableStateOf("") }
var phoneNumber by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
val context = LocalContext.current
val storageReference = FirebaseStorage.getInstance().reference
val databaseReference = Firebase.database.reference
val lightBlue = Color(0xFF8FABE7) // Light blue color 0xFF8FABE7
var showDialog by remember { mutableStateOf(false) }
var isLoading by remember { mutableStateOf(false) } // Loading state
Surface(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAll("Add Authority")
Spacer(modifier = Modifier.size(16.dp))
LazyColumn {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
LoadImage { uri ->
imageUri = uri
}
Spacer(modifier = Modifier.width(40.dp))
ShowImage(imageUri)
}
// Show selected image
OutlinedTextField(
value = authorityName,
onValueChange = { authorityName = it },
label = { Text("Name",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = designation,
onValueChange = { designation = it },
label = { Text("Designation",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Email",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = phoneNumber,
onValueChange = { phoneNumber = it },
label = { Text("Phone Number",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
// Similar OutlinedTextField for other authority fields
Spacer(modifier = Modifier.size(16.dp))
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
Button(
onClick = {
// Validate authority information
if (authorityName.isNotEmpty() && designation.isNotEmpty() &&
phoneNumber.isNotEmpty() && email.isNotEmpty() && imageUri != null
) {
showDialog = true
isLoading = true
uploadAuthorityToFirebase(
context,
imageUri,
authorityName,
designation,
phoneNumber,
email,
storageReference,
databaseReference
)
//showDialog = false
} else {
Toast.makeText(
context,
"Please fill all fields and select an image",
Toast.LENGTH_SHORT
).show()
}
},
modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth()
) {
Text("Upload Authority Information")
}
if (showDialog) {
AlertDialog(
onDismissRequest = {
showDialog = false
isLoading = false
},
title = {
Text("Uploading")
},
text = {
Text("Uploading... Please wait")
},
confirmButton = {
TextButton(
onClick = {
showDialog = false
isLoading = false
}
) {
Text("Dismiss")
}
}
)
}
}
}
}
}
}
@Composable
fun LoadImage(
onImageSelected: (Uri) -> Unit
) {
var uri by remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent()
) { uri ->
uri?.let {
onImageSelected(it)
}
}
Box(
modifier = Modifier
.size(80.dp)
.clickable {
launcher.launch("image/*")
}
.background(Color(0xFFFBF9FC), RoundedCornerShape(8.dp)),
contentAlignment = Alignment.Center
) {
Image(
imageVector = Icons.Default.Add,
contentDescription = "Plus Icon",
modifier = Modifier
.size(60.dp)
)
}
}
@Composable
fun ShowImage(imageUri: Uri?) {
if (imageUri != null) {
// Show the selected image
Image(
painter = rememberImagePainter(imageUri),
contentDescription = null,
modifier = Modifier
.size(150.dp)
.padding(vertical = 8.dp)
.clip(shape = RoundedCornerShape(8.dp))
)
}
}
fun uploadAuthorityToFirebase(
context: Context,
imageUri: Uri?,
authorityName: String,
designation: String,
phoneNumber: String,
email: String,
storageReference: StorageReference,
databaseReference: DatabaseReference
) {
imageUri?.let { uri ->
val imageRef = storageReference.child("images/${UUID.randomUUID()}")
imageRef.putFile(uri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
// Create Authority object
val authority = Authority(
authorityName,
designation,
email,
phoneNumber,
imageUrl
)
// Push Authority object to Firebase Database
databaseReference.child("authorities").push().setValue(authority)
.addOnSuccessListener {
Toast.makeText(
context,
"Authority information uploaded successfully",
Toast.LENGTH_SHORT
).show()
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload authority information",
Toast.LENGTH_SHORT
).show()
}
}
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload image",
Toast.LENGTH_SHORT
).show()
}
}
}
data class Authority(
val name: String,
val designation: String,
val email: String,
val phoneNumber: String,
val imageUrl: String
)
@Preview(showBackground = true)
@Composable
fun UpdateAuthorityPreview() {
HallServiceAppTheme {
UpdateAuthorityScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/UpdateAuthorityActivity.kt
|
2053038152
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class DeleteStudentActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DeleteStudentScreen()
}
}
}
}
}
@Composable
fun DeleteStudentScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
var registrationNumber by remember { mutableStateOf("") }
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
HeaderSectionAlii("Student Information")
//SearchSection()
DeleteStudentSections(registrationNumber = registrationNumber) // Pass the registration number to filter the list
}
}
}
@Composable
fun HeaderSectionAlii(headlinee : String) {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = headlinee,
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Image(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = "arrow",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
UpdateStudentActivity::class.java
)
) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Composable
fun DeleteStudentSections(registrationNumber: String) {
val database = FirebaseDatabase.getInstance().getReference("students")
var studentList by remember { mutableStateOf(listOf<Student>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
studentList = snapshot.children.mapNotNull { it.getValue(Student::class.java)?.copy(id = it.key ?: "") }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
CircularProgressIndicator()
} else if (isError) {
Text("Error loading student information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(studentList) { student ->
if (student.registrationNumber == registrationNumber || registrationNumber.isEmpty()) {
StudentItemWithDelete(student){ studentId->
database.child(studentId).removeValue()
}
}
}
}
}
}
@Composable
fun StudentItemWithDelete(student: Student, onDelete: (String) -> Unit) {
val context = LocalContext.current
Card(modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(student.imageUrl)
Image(
painter = painter,
contentDescription = "Student Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Name: ${student.name}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Registration Number: ${student.registrationNumber}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Department: ${student.department}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Hometown: ${student.hometown}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Phone Number: ${student.phoneNumber}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
val database = FirebaseDatabase.getInstance().getReference("students")
Button(onClick = { onDelete(student.id) }) {
Text("Delete")
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DeleteStudentPreview() {
HallServiceAppTheme {
DeleteStudentScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteStudentActivity.kt
|
4193810184
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Divider
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class SportsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
SportsScreen()
}
}
}
}
}
@Composable
fun SportsScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val gray = Color(0xFFFFFFFF)
val green = Color(0xFF43B83A)
val yellow = Color(0xFF504B50)
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
verticalArrangement = Arrangement.Top,
) {
Headlineee("Sports")
Spacer(modifier = Modifier.height(30.dp))
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.background(gray, shape = RoundedCornerShape(10.dp))
//.padding(16.dp)
) {
Text(
text = "Available item list",
fontSize = 20.sp,
color = Color.Black,
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
textAlign = TextAlign.Right
)
Divider( // Add a divider line between student items
color = Color.Black,
thickness = 3.dp,
modifier = Modifier
.padding(8.dp)
.padding(horizontal = 10.dp)
)
Text(
text = "Room no : 101",
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.padding(vertical = 5.dp)
.padding(horizontal = 18.dp)
//.align(Alignment.CenterHorizontally)
//.background(gray)
)
Divider( // Add a divider line between student items
color = yellow,
thickness = 3.dp,
modifier = Modifier
.width(170.dp)
.padding(8.dp)
.padding(horizontal = 10.dp)
)
Spacer(modifier = Modifier.height(20.dp))
Column(
modifier = Modifier
//.background(gray, shape = RoundedCornerShape(10.dp))
.padding(horizontal = 20.dp)
) {
Text(text = "* Football", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Cricket ball and stamp", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Dart", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Handball", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Racquetbal", fontSize = 24.sp)
// Add more items as needed
}
Spacer(modifier = Modifier.height(70.dp))
}
}
}
}
@Preview(showBackground = true)
@Composable
fun SportsScreenPreview() {
HallServiceAppTheme {
SportsScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/SportsActivity.kt
|
3739564002
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class AdminActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
AdminScreen()
}
}
}
}
@Composable
fun AdminScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAd()
Spacer(modifier = Modifier.height(30.dp))
LazyColumn {
//item { }
item { ChangeOptionT("Complains/Notice") }
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
){
ChangeOption("Read Complaints", R.drawable.complainttt,"ReadComplaintsActivity")
}
}
item { Spacer(modifier = Modifier.height(10.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
){
ChangeOption("Upload Notice", R.drawable.notice,"UploadNoticeActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("Delete Notice", R.drawable.delete_notice,"DeleteNoticeActivity")
}
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item { ChangeOptionT("Food") }
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
){
ChangeOption("ADD Dining Food", R.drawable.dyningfood,"AddDiningActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("ADD Canteen Food", R.drawable.foodd,"AddCanteenActivity")
}
}
}
item { Spacer(modifier = Modifier.height(10.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
){
ChangeOption("Delete Dining Food", R.drawable.dyningfood,"DeleteDiningActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("Delete Canteen Food", R.drawable.foodd,"DeleteCanteenActivity")
}
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item { ChangeOptionT("Student/Authority") }
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
) {
ChangeOption("Add Student", R.drawable.student_p,"StudentActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("Add Authority", R.drawable.authoriy_p,"UpdateAuthorityActivity")
}
}
}
item { Spacer(modifier = Modifier.height(10.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
) {
ChangeOption("Add Office", R.drawable.office_worker,"UpdateOfficeActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("Delete Information", R.drawable.icon_account_circle,"DeleteInformation")
}
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item { ChangeOptionT("User") }
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.padding(horizontal = 10.dp)
) {
ChangeOption("Add User", R.drawable.placeholder_a,"AddUserActivity")
//Spacer(modifier = Modifier.height(30.dp))
ChangeOption("Delete User", R.drawable.placeholder,"DeleteUser")
}
}
item { Spacer(modifier = Modifier.height(10.dp)) }
item {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
) {
ChangeOption("Reset Password", R.drawable.resetpassword,"SignUpActivity")
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
}
}
}
}
}
@Composable
fun HeaderSectionAd() {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = "Admin Section",
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.background(Color.White, shape = MaterialTheme.shapes.medium)
.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
Image(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = "Headline",
modifier = Modifier
.clickable {context.startActivity(Intent(context,FrontAdminActivity::class.java)) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Absolute.Right
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = "User",
style = MaterialTheme.typography.headlineSmall,
color = Color.White,
fontSize = 18.sp,
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
.clickable {
context.startActivity(
Intent(
context,
UserActivity::class.java
)
) // Change to the desired activity
}
)
}
}
}
@Composable
fun ChangeOptionT(text: String) {
Card(
modifier = Modifier.fillMaxWidth(),
elevation = 4.dp
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.padding(16.dp)
) {
Text(text = text, style = MaterialTheme.typography.bodyLarge)
}
}
}
@Composable
fun ChangeOption(text: String, iconResId: Int, actName : String) {
val context = LocalContext.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(140.dp)
.height(140.dp)
.padding(10.dp)
) {
Image(
painter = painterResource(id = iconResId),
contentDescription = "Sports",
modifier = Modifier
.clickable {
val intent = when (actName) {
"ReadComplaintsActivity" -> Intent(context, ReadComplaintsActivity::class.java)
"UploadNoticeActivity" -> Intent(context, UploadNoticeActivity::class.java)
"DeleteNoticeActivity" -> Intent(context, DeleteNoticeActivity::class.java)
"StudentActivity" -> Intent(context, StudentActivity::class.java)
"AddUserActivity" -> Intent(context, AddUserActivity::class.java)
"DeleteInformation" -> Intent(context, UpdateStudentActivity::class.java)
"UpdateOfficeActivity" -> Intent(context, UpdateOfficeActivity::class.java)
"UpdateAuthorityActivity" -> Intent(context, UpdateAuthorityActivity::class.java)
"SignUpActivity" -> Intent(context, SignUpActivity::class.java)
"DeleteUser" -> Intent(context, RemoveUserActivity::class.java)
"AddDiningActivity" -> Intent(context, AddDiningActivity::class.java)
"DeleteDiningActivity" -> Intent(context, DeleteDiningActivity::class.java)
"AddCanteenActivity" -> Intent(context, AddCanteenActivity::class.java)
"DeleteCanteenActivity" -> Intent(context, DeleteCanteenActivity::class.java)
else -> return@clickable
}
context.startActivity(intent)
}
.width(70.dp)
.height(60.dp)
)
Text(
text = text,
fontSize = 15.sp,
textAlign = TextAlign.Center,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
@Preview(showBackground = true)
@Composable
fun AdminScreenPreview() {
HallServiceAppTheme {
AdminScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/AdminActivity.kt
|
1878363604
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.auth.FirebaseAuth
class SignUpActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
SignUpScreen()
}
}
}
}
@Composable
fun SignUpScreen() {
// State variables to hold user input
var email by remember { mutableStateOf("") }
// Replace with your drawable resource
val imageResource = R.drawable.icon_account_circle
Surface(
modifier = Modifier.fillMaxSize(),
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
verticalArrangement = Arrangement.Top,
modifier = Modifier
//.background(lightBlue)
.fillMaxSize()
.padding(16.dp)
) {
val context = LocalContext.current
Spacer(modifier = Modifier.height(15.dp))
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier.fillMaxSize()
) {
Image(
painter = painterResource(id = imageResource),
contentDescription = "User Icon",
modifier = Modifier.size(150.dp)
)
Spacer(modifier = Modifier.height(10.dp))
Text(
text = "Want to reset Password?",
color = Color.White,
fontSize = 25.sp,
modifier = Modifier
.padding(vertical = 16.dp)
.fillMaxWidth()
.height(50.dp),
//.background(color = Color(138, 103, 168, 255)),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Enter your email",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
if (email == "") {
Toast.makeText(context, "Please Enter Email", Toast.LENGTH_SHORT)
.show()
} else {
val auth = FirebaseAuth.getInstance()
auth.sendPasswordResetEmail(email)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
context,
"Password reset email sent",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
context,
"Failed to send reset email",
Toast.LENGTH_SHORT
).show()
}
}
}
// Handle password reset
},
modifier = Modifier.fillMaxWidth()
) {
Text("Reset Password")
}
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun SignUpScreenPreview() {
HallServiceAppTheme {
SignUpScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ReSignUpActivity.kt
|
483090001
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class ShopActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ShopScreen()
}
}
}
}
}
@Composable
fun ShopScreen() {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
.fillMaxWidth()
.height(450.dp)
//.background(Color(0xFF8FABE7)) // Custom background color
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Headlineee("Food Shop") // You can reuse the HeaderSection from DiningActivity or create a new one
ItemSection("Coffee", "Freshly brewed coffee")
ItemSection("Sandwich", "Chicken and salad sandwich")
ItemSection("Cake", "Variety of cakes available")
// Add more items as needed
}
}
}
@Composable
fun ItemSection(itemName: String, description: String) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.background(Color.LightGray, shape = RoundedCornerShape(10.dp))
.padding(16.dp)
) {
Text(
text = itemName,
fontSize = 20.sp,
color = Color.Black
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = description,
fontSize = 16.sp,
color = Color.DarkGray
)
}
}
// Reuse the HeaderSection from DiningActivity or create a new one as needed.
@Preview(showBackground = true)
@Composable
fun ShopScreenPreview() {
ShopScreen()
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ShopActivity.kt
|
1017457148
|
package com.example.hallserviceapp
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.UUID
class StudentActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
StudentsScreen()
}
}
}
}
}
@Composable
fun StudentsScreen() {
var studentName by remember { mutableStateOf("") }
var registrationNumber by remember { mutableStateOf("") }
var department by remember { mutableStateOf("") }
var hometown by remember { mutableStateOf("") }
var phoneNumber by remember { mutableStateOf("") }
var imageUri by remember { mutableStateOf<Uri?>(null) }
val context = LocalContext.current
val storageReference = FirebaseStorage.getInstance().reference
val databaseReference = Firebase.database.reference
val lightBlue = Color(0xFF8FABE7)
var showDialog by remember { mutableStateOf(false) }
var isLoading by remember { mutableStateOf(false) } // Loading state
Surface(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAll("Add Student")
Spacer(modifier = Modifier.size(16.dp))
LazyColumn {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
LoadImage { uri ->
imageUri = uri
}
Spacer(modifier = Modifier.width(40.dp))
ShowImage(imageUri)
}
OutlinedTextField(
value = studentName,
onValueChange = { studentName = it },
label = { Text("Student Name",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = registrationNumber,
onValueChange = { registrationNumber = it },
label = { Text("Registration Number",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = department,
onValueChange = { department = it },
label = { Text("Department",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = hometown,
onValueChange = { hometown = it },
label = { Text("Hometown",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = phoneNumber,
onValueChange = { phoneNumber = it },
label = { Text("Phone Number",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.size(16.dp))
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
Button(
onClick = {
if (studentName.isNotEmpty() && registrationNumber.isNotEmpty() &&
department.isNotEmpty() && hometown.isNotEmpty() && phoneNumber.isNotEmpty() && imageUri != null
) {
showDialog = true
isLoading = true
uploadStudentToFirebase(
context,
studentName,
registrationNumber,
department,
hometown,
phoneNumber,
imageUri,
storageReference,
databaseReference
)
} else {
Toast.makeText(
context,
"Please fill all fields and select an image",
Toast.LENGTH_SHORT
).show()
}
},
modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth()
) {
Text("Add Student Information")
}
if (showDialog) {
AlertDialog(
onDismissRequest = {
showDialog = false
isLoading = false
},
title = {
Text("Uploading")
},
text = {
Text("Uploading... Please wait")
},
confirmButton = {
TextButton(
onClick = {
showDialog = false
isLoading = false
}
) {
Text("Dismiss")
}
}
)
}
}
}
}
}
}
fun uploadStudentToFirebase(
context: Context,
studentName: String,
registrationNumber: String,
department: String,
hometown: String,
phoneNumber: String,
imageUri: Uri?,
storageReference: StorageReference,
databaseReference: DatabaseReference
) {
imageUri?.let { uri ->
val imageRef = storageReference.child("images/${UUID.randomUUID()}")
imageRef.putFile(uri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
val studentId = UUID.randomUUID().toString()
val student = Students(
name = studentName,
registrationNumber = registrationNumber,
department = department,
hometown = hometown,
phoneNumber = phoneNumber,
imageUrl = imageUrl
)
databaseReference.child("students").child(studentId).setValue(student)
.addOnSuccessListener {
Toast.makeText(
context,
"Student information uploaded successfully",
Toast.LENGTH_SHORT
).show()
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload student information",
Toast.LENGTH_SHORT
).show()
}
}
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload image",
Toast.LENGTH_SHORT
).show()
}
}
}
data class Students(
val name: String,
val registrationNumber: String,
val department: String,
val hometown: String,
val phoneNumber: String,
val imageUrl: String
)
@Preview(showBackground = true)
@Composable
fun StudentsScreenPreview() {
HallServiceAppTheme {
StudentsScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/UpStudentActivity.kt
|
1178810423
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class DiningActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DiningScreen()
}
}
}
}
}
@Composable
fun DiningScreen() {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(Color(0xFF8FABE7)) // Background color of the entire screen
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Headlineee("Dining")
MealSection("Breakfast", "8:00 am", "Khichuri - Egg - Dal")
MealSection("Lunch", "12:30 pm", "Chicken, Fish, Egg, Vegetable, Murighanto, Dal")
MealSection("Dinner", "8:00 pm", "Chicken, Fish, Egg, Vegetable, Murighanto, Dal")
SpecialSection("Every Friday special biryani are available")
}
}
}
@Composable
fun MealSection(mealName: String, time: String, menu: String) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.background(Color.LightGray, shape = RoundedCornerShape(10.dp))
.padding(16.dp)
) {
Text(
text = "$mealName: $time",
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = menu,
style = MaterialTheme.typography.titleMedium
)
}
}
@Composable
fun SpecialSection(specialInfo: String) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.background(Color.LightGray, shape = RoundedCornerShape(10.dp))
.padding(16.dp)
) {
Text(
text = specialInfo,
style = MaterialTheme.typography.titleMedium
//style = MaterialTheme.typography.headlineSmall,
//textAlign = TextAlign.Center,
//color = Color.Black
)
}
}
@Preview(showBackground = true)
@Composable
fun DiningScreenPreview() {
DiningScreen()
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DiningActivity.kt
|
2552677277
|
package com.example.hallserviceapp
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidUserException
class RemoveUserActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DeleteUserContent() // Pass the context to DeleteUserContent
}
}
}
}
}
@Composable
fun DeleteUserContent() { // Receive context as a parameter
val lightBlue = Color(0xFF8FABE7) // Light blue color
val emailState = remember { mutableStateOf(TextFieldValue()) }
var showingProgressDialog by remember { mutableStateOf(false) }
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
HeaderSectionAll("Remove User")
Spacer(modifier = Modifier.height(170.dp))
// Input field to enter user's email
TextField(
value = emailState.value,
onValueChange = { emailState.value = it },
label = { Text("Enter user's email") },
modifier = Modifier.fillMaxWidth().padding(8.dp)
)
Spacer(modifier = Modifier.height(16.dp))
val context = LocalContext.current
// Button to remove user
Button(
onClick = {
val email = emailState.value.text
showingProgressDialog = false
removeUserByEmail(context, email) { // Pass context to removeUserByEmail
showingProgressDialog = false
}
},
modifier = Modifier.fillMaxWidth().padding(8.dp)
) {
Text("Remove User")
}
}
}
if (showingProgressDialog) {
ProgressDialog(context).apply {
setMessage("Removing user...")
setCancelable(false)
}.show()
}
}
private fun removeUserByEmail(context: Context, email: String, onComplete: () -> Unit) {
val auth = FirebaseAuth.getInstance()
val user = auth.currentUser
// Check if the user is authenticated
if (user != null) {
// Check if the provided email matches the current user's email
if (user.email == email) {
// User is attempting to remove themselves. Provide an error message or handle accordingly.
// You can't remove yourself programmatically due to security reasons.
// This is just an example, handle the scenario appropriately based on your application logic.
Toast.makeText(context, "You cannot remove yourself", Toast.LENGTH_SHORT).show()
} else {
// User is an admin or authorized to remove users
auth.fetchSignInMethodsForEmail(email).addOnCompleteListener { task ->
if (task.isSuccessful) {
val result = task.result?.signInMethods ?: emptyList<String>()
if (result.isNotEmpty()) {
// The user exists, proceed to delete
auth.signInWithEmailAndPassword(email, "aDummyPassword") // Use any dummy password
.addOnCompleteListener { signInTask ->
if (signInTask.isSuccessful) {
// Successfully signed in, delete the user
val currentUser = auth.currentUser
currentUser?.delete()?.addOnCompleteListener { deleteTask ->
if (deleteTask.isSuccessful) {
// User deleted successfully
onComplete.invoke()
Toast.makeText(context, "User removed successfully", Toast.LENGTH_SHORT).show()
} else {
// Failed to delete user
Toast.makeText(context, "Failed to remove user", Toast.LENGTH_SHORT).show()
}
}
} else {
// Failed to sign in with email and dummy password
Toast.makeText(context, "Failed to sign in", Toast.LENGTH_SHORT).show()
}
}
}
else {
// User does not exist with the provided email
if (task.exception is FirebaseAuthInvalidUserException) {
// User does not exist with the provided email
Toast.makeText(context, "User does not exist", Toast.LENGTH_SHORT).show()
} else {
// Other errors
Toast.makeText(context, "Failed to fetch user information", Toast.LENGTH_SHORT).show()
}
}
}
else {
// Task to fetch sign-in methods failed
Toast.makeText(context, "Failed to fetch sign-in methods", Toast.LENGTH_SHORT).show()
}
}
}
}
else {
// User is not authenticated
Toast.makeText(context, "User is not authenticated", Toast.LENGTH_SHORT).show()
}
}
@Preview(showBackground = true)
@Composable
fun DeleteUserPreview() {
HallServiceAppTheme {
DeleteUserContent()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/RemoveUserActivity.kt
|
2943674659
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class AuthorityActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
AuthorityScreen()
}
}
}
}
}
@Composable
fun AuthorityScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
Headlineee("Authority Information")
// SearchSection()
AuthorityInformationSection()
}
}
}
@Composable
fun Headlineee(headlinee : String) {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = headlinee,
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Image(
painter = painterResource(id = R.drawable.headline),
contentDescription = "Headline",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
UserActivity::class.java
)
) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Composable
fun AuthorityInformationSection() {
val database = FirebaseDatabase.getInstance().getReference("authorities")
var authorityList by remember { mutableStateOf(listOf<Authoritys>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
authorityList = snapshot.children.mapNotNull { it.getValue(Authoritys::class.java) }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
//CircularProgressIndicator()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Loading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
} else if (isError) {
Text("Error loading authority information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(authorityList) { authority ->
AuthorityItem(authority)
}
}
}
}
@Composable
fun StudentItem1(student: Student) {
val gree = Color(0xFF36A2D8)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
//.background(Color.White) ,// Set a white background color for the card
//elevation = 4.dp // Add elevation for a shadow effect
) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(student.imageUrl)
Image(
painter = painter,
contentDescription = "Student Image",
modifier = Modifier
.size(80.dp)
.clip(CircleShape) // Clip the image to a circle shape
)
Spacer(modifier = Modifier.width(16.dp))
Column(
modifier = Modifier.weight(1f)
) {
Text(
text = student.name,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
color = Color(0xFF3D82D5)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Registration: ${student.registrationNumber}",
style = MaterialTheme.typography.bodyMedium,
color = Color.Black
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Department: ${student.department}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Hometown: ${student.hometown}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Phone: ${student.phoneNumber}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Room No: ...",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
}
}
Divider( // Add a divider line between student items
color = Color.Black,
thickness = 2.dp,
modifier = Modifier.padding(vertical = 8.dp)
)
}
}
}
@Composable
fun AuthorityItem(authority: Authoritys) {
val gree = Color(0xFF36A2D8)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(authority.imageUrl)
Image(
painter = painter,
contentDescription = "Authority Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
.clip(CircleShape)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Name: ${authority.name}",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
color = Color(0xFF3D82D5)
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "Designation: ${authority.designation}",
style = MaterialTheme.typography.bodyMedium,
color = Color.Black
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Email: ${authority.email}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Phone Number: ${authority.phoneNumber}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
}
}
Divider( // Add a divider line between student items
color = Color.Black,
thickness = 2.dp,
modifier = Modifier.padding(vertical = 8.dp)
)
}
}
@Composable
fun AuthorityItem2(authority: Authoritys) {
Card(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(authority.imageUrl)
Image(
painter = painter,
contentDescription = "Authority Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Name: ${authority.name}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Designation: ${authority.designation}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Email: ${authority.email}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Phone Number: ${authority.phoneNumber}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
// Add more details or actions for each authority item here
}
}
}
}
data class Authoritys(
val id: String = "",
val designation: String = "",
val email: String = "",
val imageUrl: String = "",
val name: String = "",
val phoneNumber: String = ""
)
@Preview(showBackground = true)
@Composable
fun AuthorityScreenPreview() {
HallServiceAppTheme {
AuthorityScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/AuthorityActivity.kt
|
2480359376
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class UserActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
UserScreen()
}
}
}
}
}
@Composable
fun UserScreen() {
Surface(
modifier = Modifier.fillMaxSize(),
//color = MaterialTheme.colorScheme.background
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
//.background(lightBlue) // Set the background color here
.padding(30.dp)
) {
Head("Mujtaba Ali Hall")
Spacer(modifier = Modifier.height(20.dp))
Row1()
//Spacer(modifier = Modifier.height(16.dp))
Row2()
//Spacer(modifier = Modifier.height(16.dp))
Row3()
//Spacer(modifier = Modifier.height(16.dp))
Row4()
//Spacer(modifier = Modifier.height(16.dp))
Row5()
}
}
}
}
@Composable
fun Head(headlinee : String) {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(16.dp))
Text(
text = headlinee,
fontSize = 24.sp,
modifier = Modifier.padding(8.dp)
.fillMaxWidth(),
//.width(200.dp),
textAlign = TextAlign.Center,
color = Color.White
)
}
Image(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = "arrow",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, LoginActivity::class.java)) // Change to the desired activity
}
.padding(vertical = 10.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Composable
fun Row1() {
val context = LocalContext.current
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center // Center the items
) {
// Authority Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.government),
contentDescription = "Authority",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, AuthorityActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Authority",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
Spacer(modifier = Modifier.width(8.dp)) // Reduce the width of the Spacer
// Notice Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.notice),
contentDescription = "Notice",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, NoticeActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Notice",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
}
@Composable
fun Row2() {
val context = LocalContext.current
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center // Center the items
) {
// Office Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.officess),
contentDescription = "Office",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, OfficeActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Office",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
Spacer(modifier = Modifier.width(16.dp))
// Complaints Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.complaintss),
contentDescription = "Complaints",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, ComplaintsActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Complaints",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
}
@Composable
fun Row3() {
val context = LocalContext.current
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center // Center the items
) {
// Students Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.studentss),
contentDescription = "Students",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, StudentsInformationActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Students",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
Spacer(modifier = Modifier.width(16.dp))
// Contacts Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.contactss),
contentDescription = "Contacts",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, ContactsActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Contacts",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
}
@Composable
fun Row4() {
val context = LocalContext.current
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center // Center the items
) {
// Food Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.foodd),
contentDescription = "Food",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, FoodActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Food",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
Spacer(modifier = Modifier.width(16.dp))
// Services Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.servicess),
contentDescription = "Services",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, ServicesActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Services",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
}
@Composable
fun Row5() {
val context = LocalContext.current
Row(
modifier = Modifier.fillMaxWidth(),
//horizontalArrangement = Arrangement.SpaceBetween
horizontalArrangement = Arrangement.Center // Center the items
) {
// Sports Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.sportss),
contentDescription = "Sports",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, SportsActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Sports",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
Spacer(modifier = Modifier.width(16.dp))
// Medicine Column
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(130.dp)
) {
Image(
painter = painterResource(id = R.drawable.medicinss),
contentDescription = "Medicine",
modifier = Modifier
.clickable {
context.startActivity(Intent(context, MedicineActivity::class.java)) // Change to the desired activity
}
.width(80.dp)
.height(70.dp)
)
Text(
text = "Medicine",
fontSize = 18.sp,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
}
@Preview(showBackground = true)
@Composable
fun UserScreenPreview() {
HallServiceAppTheme {
UserScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/UserActivity.kt
|
3003778762
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class ReadDiningActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ReadDiningScreen()
}
}
}
}
}
@Composable
fun ReadDiningScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
Headlineee("Food For Today")
ReadDiningSection()
}
}
}
@Composable
fun ReadDiningSection() {
val database = FirebaseDatabase.getInstance().getReference("DiningFoods")
var readDiningList by remember { mutableStateOf(listOf<DiningFoods>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
readDiningList = snapshot.children.mapNotNull { it.getValue(DiningFoods::class.java) }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
//CircularProgressIndicator()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Loading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
} else if (isError) {
Text("Error loading Food information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(readDiningList) { diningFood ->
DiningFoodItem(diningFood)
}
}
}
}
@Composable
fun DiningFoodItem(diningFood: DiningFoods) {
Card(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
val lightGold = Color(0xFFC4BFB0)
val lightGoldB = Color(0xFFEBE6C1)
val painter: Painter = rememberImagePainter(diningFood.imageUrl)
Column(modifier = Modifier.padding(16.dp)
.background(lightGold, shape = RoundedCornerShape(10.dp))
.padding(12.dp),
) {
Text(text = "Date: ${diningFood.date}",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Time: ${diningFood.time}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "FoodName: ${diningFood.addDiningName}",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "price: ${diningFood.price}",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
}
//Spacer(modifier = Modifier.width(14.dp))
Image(
painter = painter,
contentDescription = "Food Image",
modifier = Modifier
.size(140.dp)
.padding(20.dp)
)
}
}
}
data class DiningFoods(
val id: String = "",
val addDiningName: String = "",
val price: String = "",
val date: String = "",
val time: String = "",
val imageUrl: String = ""
)
@Preview(showBackground = true)
@Composable
fun ReadDiningScreenPreview() {
HallServiceAppTheme {
ReadDiningScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ReadDiningActivity.kt
|
3446006573
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class OfficeActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
OfficeScreen()
}
}
}
}
}
@Composable
fun OfficeScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
HeaderSectionOffices()
// SearchSection()
OfficeInformationSection()
}
}
}
@Composable
fun HeaderSectionOffices() {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = "Office Information",
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Image(
painter = painterResource(id = R.drawable.headline),
contentDescription = "Headline",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
UserActivity::class.java
)
) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Composable
fun OfficeInformationSection() {
val database = FirebaseDatabase.getInstance().getReference("offices")
var officeList by remember { mutableStateOf(listOf<Office>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
officeList = snapshot.children.mapNotNull { it.getValue(Office::class.java) }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
//CircularProgressIndicator()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Loading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
} else if (isError) {
Text("Error loading office information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(officeList) { office ->
OfficeItem(office)
}
}
}
}
@Composable
fun OfficeItem(office: Office) {
val gree = Color(0xFF36A2D8)
Card(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(office.imageUrl)
Image(
painter = painter,
contentDescription = "Office Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
.clip(CircleShape)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Name: ${office.name}",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
color = Color(0xFF3D82D5)
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "Designation: ${office.designation}",
style = MaterialTheme.typography.bodyMedium,
color = Color.Black
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Email: ${office.email}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Phone Number: ${office.phoneNumber}",
style = MaterialTheme.typography.bodyMedium,
color = gree
)
}
}
Divider( // Add a divider line between student items
color = Color.Black,
thickness = 2.dp,
modifier = Modifier.padding(vertical = 8.dp)
)
}
}
data class Office(
val id: String = "",
val designation: String = "",
val email: String = "",
val imageUrl: String = "",
val name: String = "",
val phoneNumber: String = ""
)
@Preview(showBackground = true)
@Composable
fun OfficeScreenPreview() {
HallServiceAppTheme {
OfficeScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/OfficeActivity.kt
|
4005808982
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class DeleteDiningActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DeleteDiningScreen()
}
}
}
}
}
@Composable
fun DeleteDiningScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
HeaderSectionAll("Delete Food")
DeleteDiningSections() // Pass the registration number to filter the list
}
}
}
@Composable
fun DeleteDiningSections() {
val database = FirebaseDatabase.getInstance().getReference("DiningFoods")
var diningFoodsList by remember { mutableStateOf(listOf<DiningFoods>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
diningFoodsList = snapshot.children.mapNotNull { it.getValue(DiningFoods::class.java)?.copy(id = it.key ?: "") }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
CircularProgressIndicator()
} else if (isError) {
Text("Error loading Food information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(diningFoodsList) { diningFood ->
DiningFoodItemWithDelete(diningFood){ diningFoodId->
database.child(diningFoodId).removeValue()
}
}
}
}
}
@Composable
fun DiningFoodItemWithDelete(canteenFood: DiningFoods, onDelete: (String) -> Unit) {
val context = LocalContext.current
Card(modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(canteenFood.imageUrl)
Image(
painter = painter,
contentDescription = "Dining Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Date: ${canteenFood.date}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Time: ${canteenFood.time}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "FoodName: ${canteenFood.addDiningName}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Price: ${canteenFood.price}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Button(onClick = { onDelete(canteenFood.id) }) {
Text("Delete")
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DeleteDiningPreview() {
HallServiceAppTheme {
DeleteDiningScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteDiningActivity.kt
|
709495487
|
package com.example.hallserviceapp
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class NoticeFileTextActivity : ComponentActivity() {
private lateinit var selectPdfContract: ActivityResultLauncher<String>
private var pdfUri by mutableStateOf<Uri?>(null)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
selectPdfContract = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
if (uri != null) {
pdfUri = uri
} else {
Toast.makeText(this, "File selection was cancelled", Toast.LENGTH_SHORT).show()
}
}
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
NoticeFileText(pdfUri, { selectPdfFile() }, { newUri -> pdfUri = newUri })
}
}
}
}
private fun selectPdfFile() {
selectPdfContract.launch("application/pdf")
}
}
@Composable
fun NoticeFileText(
pdfUri: Uri?,
onSelectPdf: () -> Unit,
onPdfUriChange: (Uri?) -> Unit
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val context = LocalContext.current
var titleState by remember { mutableStateOf(TextFieldValue()) }
var isUploading by remember { mutableStateOf(false) }
val gray = Color(0xFFE7E3E7)
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
HeaderSectionNFT()
Spacer(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.background(Color.Gray)
.border(2.dp, Color.Black)
.clickable(onClick = onSelectPdf)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Select File",
tint = Color.White,
modifier = Modifier
.size(48.dp)
.align(Alignment.Center)
)
}
Spacer(modifier = Modifier.height(15.dp))
Text(
text = "Select PDF File",
color = Color.Black,
fontSize = 25.sp,
modifier = Modifier
.background(gray, shape = RoundedCornerShape(18.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(15.dp))
TextField(
value = titleState,
onValueChange = { titleState = it },
label = { Text("Enter Title") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
if (titleState.text.isNotBlank() && pdfUri != null) {
isUploading = true
uploadPdfFile(context, titleState.text, pdfUri!!) { success ->
if (success) {
titleState = TextFieldValue("")
onPdfUriChange(null) // Reset pdfUri after upload
}
isUploading = false
}
} else {
Toast.makeText(context, "Please fill all fields", Toast.LENGTH_LONG).show()
}
},
modifier = Modifier.fillMaxWidth()
) {
Text("Submit Notice")
}
if (isUploading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
}
}
}
fun uploadPdfFile(context: Context, title: String, pdfUri: Uri, onCompletion: (Boolean) -> Unit) {
val auth = FirebaseAuth.getInstance()
val userId = auth.currentUser?.uid
val database = Firebase.database
val noticesRef = database.getReference("notices")
val noticeId = noticesRef.push().key ?: return
val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val currentDate = dateFormat.format(Date())
val notice = NoticeF(userId.orEmpty(), title, pdfUri.toString(), currentDate)
noticesRef.child(noticeId).setValue(notice)
.addOnSuccessListener {
Toast.makeText(context, "Notice submitted successfully", Toast.LENGTH_SHORT).show()
onCompletion(true)
}
.addOnFailureListener {
Toast.makeText(context, "Failed to submit notice", Toast.LENGTH_SHORT).show()
onCompletion(false)
}
}
data class NoticeF(
val userId: String,
val title: String,
val pdfUri: String,
val date: String
)
@Composable
fun HeaderSectionNFT() {
val gray = Color(0xFFBA6FBD)
val yellow = Color(0xFF40E48A)
val context = LocalContext.current
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.Top
) {
Image(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = "headline",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
UploadNoticeActivity::class.java
)
)
}
.padding(end = 10.dp)
.size(width = 100.dp, height = 40.dp)
)
Text(
text = "FileNotice",
color = Color.Black,
fontSize = 25.sp,
modifier = Modifier
.background(yellow, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
}
@Preview(showBackground = true)
@Composable
fun NoticeFileTextPreview() {
HallServiceAppTheme {
// Provide dummy Uri? and functions for the preview
NoticeFileText(
pdfUri = null, // Dummy Uri, you can put null for the preview
onSelectPdf = {}, // Dummy function for selecting PDF
onPdfUriChange = {} // Dummy function for handling Uri change
)
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/NoticeFileTextActivity.kt
|
3080856919
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class DynamicFoodActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
DynamicFoodScreen()
}
}
}
}
@Composable
fun DynamicFoodScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
LazyColumn {
item { HeaderSectionAdM() }
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Row(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
//horizontalArrangement = Arrangement.Center // Center the items
) {
ChangeOptionM(
"ADD Dining Food",
R.drawable.dyningfood,
"AddDiningActivity"
)
ChangeOptionM(
"Delete Dining Food",
R.drawable.dyningfood,
"DeleteDiningActivity"
)
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
Row(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
//horizontalArrangement = Arrangement.Center // Center the items
) {
ChangeOptionM(
"ADD Canteen Food",
R.drawable.foodd,
"AddCanteenActivity"
)
ChangeOptionM(
"Delete Canteen Food",
R.drawable.foodd,
"DeleteCanteenActivity"
)
}
}
item { Spacer(modifier = Modifier.height(30.dp)) }
}
}
}
}
}
@Composable
fun ChangeOptionM(text: String, iconResId: Int, actName : String) {
val context = LocalContext.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.width(140.dp)
.height(140.dp)
.padding(10.dp)
) {
Image(
painter = painterResource(id = iconResId),
contentDescription = "Sports",
modifier = Modifier
.clickable {
val intent = when (actName) {
"AddDiningActivity" -> Intent(context, AddDiningActivity::class.java)
"DeleteDiningActivity" -> Intent(context, DeleteDiningActivity::class.java)
"AddCanteenActivity" -> Intent(context, AddCanteenActivity::class.java)
"DeleteCanteenActivity" -> Intent(context, DeleteCanteenActivity::class.java)
else -> return@clickable
}
context.startActivity(intent)
}
.width(70.dp)
.height(60.dp)
)
Text(
text = text,
fontSize = 15.sp,
textAlign = TextAlign.Center,
modifier = Modifier.padding(8.dp),
color = Color.White
)
}
}
@Composable
fun HeaderSectionAdM() {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = "Food Section",
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier
.background(Color.White, shape = MaterialTheme.shapes.medium)
.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
}
}
@Preview(showBackground = true)
@Composable
fun DynamicFoodScreenPreview() {
HallServiceAppTheme {
DynamicFoodScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DynamicFoodActivity.kt
|
816487022
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class DeleteOfficesActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DeleteOfficeScreen()
}
}
}
}
}
@Composable
fun DeleteOfficeScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
HeaderSectionAlii("Office Information")
DeleteOfficeSections() // Pass the registration number to filter the list
}
}
}
@Composable
fun DeleteOfficeSections() {
val database = FirebaseDatabase.getInstance().getReference("offices")
var officesList by remember { mutableStateOf(listOf<Office>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
officesList = snapshot.children.mapNotNull { it.getValue(Office::class.java)?.copy(id = it.key ?: "") }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
CircularProgressIndicator()
} else if (isError) {
Text("Error loading Office information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(officesList) { offices ->
OfficesItemWithDelete(offices){ officeId->
database.child(officeId).removeValue()
}
}
}
}
}
@Composable
fun OfficesItemWithDelete(office: Office, onDelete: (String) -> Unit) {
val context = LocalContext.current
Card(modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
val painter: Painter = rememberImagePainter(office.imageUrl)
Image(
painter = painter,
contentDescription = "Office Image",
modifier = Modifier
.size(80.dp)
.padding(start = 8.dp)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Name: ${office.name}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Designation: ${office.designation}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Email: ${office.email}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Phone Number: ${office.phoneNumber}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(4.dp))
Button(onClick = { onDelete(office.id) }) {
Text("Delete")
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DeleteOfficePreview() {
HallServiceAppTheme {
DeleteOfficeScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/DeleteOfficesActivity.kt
|
1605776834
|
package com.example.hallserviceapp
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class ContactsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ContactsScreen()
}
}
}
}
}
@Composable
fun ContactsScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Headlineee("Contacts")
Spacer(modifier = Modifier.height(30.dp))
LazyColumn(
modifier = Modifier.fillMaxWidth(),
contentPadding = PaddingValues(vertical = 8.dp)
) {
item {
ContactItemView("Varsity Emergency Helpline", "01739-36852")
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
ContactItemView("Ambulance Helpline, Sylhet", "01789-782332")
}
item { Spacer(modifier = Modifier.height(30.dp)) }
item {
ContactItemView("Fire Service Station, Sylhet", "01730-336644")
}
item { Spacer(modifier = Modifier.height(30.dp)) }
}
}
}
}
}
@Composable
fun ContactItemView(name: String, number: String) {
val context = LocalContext.current
Card(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 16.dp),
backgroundColor = Color.White,
shape = RoundedCornerShape(16.dp),
elevation = 8.dp
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
// Contact Name
Text(
text = name,
fontSize = 18.sp,
modifier = Modifier
.width(160.dp),
color = Color.Black,
fontWeight = FontWeight.Bold
)
// Contact Number
Text(
text = number,
fontSize = 16.sp,
color = Color.Gray,
modifier = Modifier
.clickable {
// Handle the phone call action here
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$number"))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
.padding(start = 16.dp)
)
}
}
}
@Preview(showBackground = true)
@Composable
fun ContactsScreenPreview() {
HallServiceAppTheme {
ContactsScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ContactsActivity.kt
|
247770646
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.auth.FirebaseAuth
class FrontAdminActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
FrontAdminScreen()
}
}
}
}
}
@Composable
fun FrontAdminScreen() {
val auth = FirebaseAuth.getInstance()
var isLoading by remember { mutableStateOf(false) } // Loading state
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val context = LocalContext.current
val imageResource = R.drawable.icon_account_circle
Surface(
modifier = Modifier.fillMaxSize(),
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic5), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
//.background(lightBlue)
.fillMaxSize()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(30.dp))
Image(
painter = painterResource(id = imageResource),
contentDescription = null,
modifier = Modifier.size(160.dp)
)
Spacer(modifier = Modifier.height(40.dp))
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Email",
color = Color.White // Set label text color to white
) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password",
color = Color.White // Set label text color to white
) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
if ((username == "")||(password == "")){
Toast.makeText(context, "Please give Email & password", Toast.LENGTH_SHORT).show()
}
else {
// Check if the email is the admin email
if (username == "[email protected]" || username == "[email protected]"|| username == "[email protected]") {
isLoading = true
auth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener { task ->
isLoading = false // Hide progress indicator
if (task.isSuccessful) {
if(username == "[email protected]" ){
context.startActivity(Intent(context, AdminActivity::class.java))
}
else if(username == "[email protected]" ){
context.startActivity(Intent(context, DynamicFoodActivity::class.java))
}
else if(username == "[email protected]" ) {
context.startActivity(Intent(context, DynamicFoodActivity::class.java))
}
else {
context.startActivity(Intent(context, FrontAdminActivity::class.java))
}
//context.startActivity(Intent(context, AdminActivity::class.java))
} else {
Toast.makeText(context, "Login failed", Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(context, "Admin login only", Toast.LENGTH_SHORT).show()
}
}
},
modifier = Modifier.fillMaxWidth()
) {
Text("Login")
}
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
CircularProgressIndicator()
Text(
text = "Login... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun FrontAdminScreenPreview() {
HallServiceAppTheme {
FrontAdminScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/FrontAdminActivity.kt
|
1785462798
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class ReadComplaintsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
ReadComplaintsScreen()
}
}
}
}
@Composable
fun ReadComplaintsScreen() {
val database = FirebaseDatabase.getInstance().getReference("complaints")
var complaintsList by remember { mutableStateOf(listOf<ComplaintSs>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.orderByChild("date").addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
complaintsList = snapshot.children.mapNotNull { it.getValue(ComplaintSs::class.java)?.copy(id = it.key ?: "") }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue, shape = RoundedCornerShape(10.dp))
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAll("Read Complaints")
Spacer(modifier = Modifier.height(20.dp))
//HeaderSection()
if (isLoading) {
CircularProgressIndicator()
} else if (isError) {
Text("Error loading complaints.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize().padding(16.dp)) {
items(complaintsList) { complaint ->
ComplaintItem(complaint) { complaintId ->
database.child(complaintId).removeValue()
}
}
}
}
}
}
}
@Composable
fun HeaderSectionAll(headlinee : String) {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = headlinee,
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Image(
painter = painterResource(id = R.drawable.arrow_back),
contentDescription = "arrow",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
AdminActivity::class.java
)
) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Composable
fun ComplaintItem(complaint: ComplaintSs, onDelete: (String) -> Unit) {
Card(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Date: ${complaint.date}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(8.dp))
//Text(text = "User ID: ${complaint.userId}", style = MaterialTheme.typography.bodySmall)
//Spacer(modifier = Modifier.height(8.dp))
Text(text = "Title: ${complaint.title}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Description: ${complaint.text}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
Button(onClick = { onDelete(complaint.id) }) {
Text("Delete")
}
}
}
}
}
data class ComplaintSs(
val id: String = "",
val userId: String = "",
val title: String = "",
val text: String = "",
val date: String = ""
)
@Preview(showBackground = true)
@Composable
fun ReadComplaintsPreview() {
HallServiceAppTheme {
ReadComplaintsScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ReadComplaintsActivity.kt
|
2408650128
|
package com.example.hallserviceapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class ReadCanteenActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
ReadCanteenScreen()
}
}
}
}
}
@Composable
fun ReadCanteenScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
Headlineee("Food For Today")
ReadCanteenSection()
}
}
}
@Composable
fun ReadCanteenSection() {
val database = FirebaseDatabase.getInstance().getReference("CanteenFoods") // Corrected database reference
var readCanteenList by remember { mutableStateOf(listOf<CanteenFoods>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
readCanteenList = snapshot.children.mapNotNull { it.getValue(CanteenFoods::class.java) }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
//CircularProgressIndicator()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Loading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
} else if (isError) {
Text("Error loading Food information.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(readCanteenList) { canteenFood ->
CanteenFoodItem(canteenFood)
}
}
}
}
@Composable
fun CanteenFoodItem(canteenFood: CanteenFoods) {
Card(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
val lightGold = Color(0xFFC4BFB0)
val lightGoldB = Color(0xFFEBE6C1)
val painter: Painter = rememberImagePainter(canteenFood.imageUrl)
Column(modifier = Modifier.padding(16.dp)
.background(lightGold, shape = RoundedCornerShape(10.dp))
.padding(12.dp),
) {
Text(text = "Date: ${canteenFood.date}", style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Time: ${canteenFood.time}", style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "FoodName: ${canteenFood.addCanteenName}", style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "price: ${canteenFood.price}", style = MaterialTheme.typography.bodySmall,
modifier = Modifier
.background(lightGoldB, shape = RoundedCornerShape(10.dp))
.padding(6.dp)
)
Spacer(modifier = Modifier.height(4.dp))
}
//Spacer(modifier = Modifier.width(14.dp))
Image(
painter = painter,
contentDescription = "Food Image",
modifier = Modifier
.size(140.dp)
.padding(20.dp)
)
}
}
}
data class CanteenFoods(
val id: String = "",
val addCanteenName: String = "",
val price: String = "",
val date: String = "",
val time: String = "",
val imageUrl: String = ""
)
@Preview(showBackground = true)
@Composable
fun ReadCanteenScreenPreview() {
HallServiceAppTheme {
ReadCanteenScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ReadCanteenActivity.kt
|
1864290837
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
LoginScreen()
}
}
}
}
@Composable
fun LoginScreen() {
val auth = FirebaseAuth.getInstance()
var isLoading by remember { mutableStateOf(false) } // Loading state
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val context = LocalContext.current
val imageResource = R.drawable.icon_account_circle
Surface(
modifier = Modifier.fillMaxSize(),
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic5), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
//.background(lightBlue)
.fillMaxSize()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(30.dp))
Image(
painter = painterResource(id = imageResource),
contentDescription = null,
modifier = Modifier.size(160.dp)
)
Spacer(modifier = Modifier.height(40.dp))
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Email/Username",
color = Color.White // Set label text color to white
) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password",
color = Color.White // Set label text color to white
) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(30.dp))
Button(
onClick = {
if ((username == "")||(password == "")){
Toast.makeText(context, "Please give Email & password", Toast.LENGTH_SHORT).show()
}
else {
isLoading = true
auth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener { task ->
isLoading = false // Hide progress indicator
if (task.isSuccessful) {
context.startActivity(Intent(context, UserActivity::class.java))
} else {
Toast.makeText(context, "Login failed", Toast.LENGTH_SHORT).show()
}
}
}
},
modifier = Modifier.fillMaxWidth()
) {
Text("Login / Sign In")
}
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
CircularProgressIndicator()
Text(
text = "Login... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
Spacer(modifier = Modifier.height(20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center // Center the items
) {
Text(
text = "Don't have account? Contact with Authority.",
color = Color.White,
fontSize = 16.sp,
modifier = Modifier.clickable {
}
.padding(vertical = 16.dp)
)
}
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "Reset Password?",
color = Color.Blue,
fontSize = 16.sp,
modifier = Modifier
.clickable {
context.startActivity(Intent(context, ResetPasswordActivity::class.java))
}
.padding(vertical = 16.dp)
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun LoginScreenPreview() {
HallServiceAppTheme {
LoginScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/LoginActivity.kt
|
4250536007
|
package com.example.hallserviceapp
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.UUID
class UpdateOfficeActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.White
) {
UpdateOfficeScreen()
}
}
}
}
}
@Composable
fun UpdateOfficeScreen() {
var imageUri by remember { mutableStateOf<Uri?>(null) }
var officeName by remember { mutableStateOf("") }
var designation by remember { mutableStateOf("") }
var phoneNumber by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
val context = LocalContext.current
val storageReference = FirebaseStorage.getInstance().reference
val databaseReference = Firebase.database.reference
val lightBlue = Color(0xFF8FABE7) // Light blue color
var isLoading by remember { mutableStateOf(false) } // Loading state
var showDialog by remember { mutableStateOf(false) }
Surface(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
HeaderSectionAll("Add Office")
Spacer(modifier = Modifier.size(16.dp))
LazyColumn {
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
LoadImage { uri ->
imageUri = uri
}
Spacer(modifier = Modifier.width(40.dp))
ShowImage(imageUri)
}
OutlinedTextField(
value = officeName,
onValueChange = { officeName = it },
label = { Text("Name",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = designation,
onValueChange = { designation = it },
label = { Text("Designation",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Email",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
OutlinedTextField(
value = phoneNumber,
onValueChange = { phoneNumber = it },
label = { Text("Phone Number",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.size(16.dp))
if (isLoading) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Uploading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
}
Button(
onClick = {
if (officeName.isNotEmpty() && designation.isNotEmpty() &&
phoneNumber.isNotEmpty() && email.isNotEmpty() && imageUri != null
) {
showDialog = true
isLoading = true
uploadOfficeToFirebase(
context,
imageUri,
officeName,
designation,
phoneNumber,
email,
storageReference,
databaseReference
)
} else {
Toast.makeText(
context,
"Please fill all fields and select an image",
Toast.LENGTH_SHORT
).show()
}
},
modifier = Modifier.align(Alignment.CenterHorizontally).fillMaxWidth()
) {
Text("Upload Office Information")
}
if (showDialog) {
AlertDialog(
onDismissRequest = {
showDialog = false
isLoading = false
},
title = {
Text("Uploading")
},
text = {
Text("Uploading... Please wait")
},
confirmButton = {
TextButton(
onClick = {
showDialog = false
isLoading = false
}
) {
Text("Dismiss")
}
}
)
}
}
}
}
}
}
fun uploadOfficeToFirebase(
context: Context,
imageUri: Uri?,
officeName: String,
designation: String,
phoneNumber: String,
email: String,
storageReference: StorageReference,
databaseReference: DatabaseReference
) {
imageUri?.let { uri ->
val imageRef = storageReference.child("images/${UUID.randomUUID()}")
imageRef.putFile(uri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
val office = Offices(
officeName,
designation,
email,
phoneNumber,
imageUrl
)
databaseReference.child("offices").push().setValue(office)
.addOnSuccessListener {
Toast.makeText(
context,
"Office information uploaded successfully",
Toast.LENGTH_SHORT
).show()
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload office information",
Toast.LENGTH_SHORT
).show()
}
}
}
.addOnFailureListener {
Toast.makeText(
context,
"Failed to upload image",
Toast.LENGTH_SHORT
).show()
}
}
}
data class Offices(
val name: String,
val designation: String,
val email: String,
val phoneNumber: String,
val imageUrl: String // URL of the uploaded image
)
@Preview(showBackground = true)
@Composable
fun UpdateOfficePreview() {
HallServiceAppTheme {
UpdateOfficeScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/UpdateOfficeActivity.kt
|
3327115303
|
package com.example.hallserviceapp
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.firebase.auth.EmailAuthProvider
import com.google.firebase.auth.FirebaseAuth
class ResetPasswordActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ResetPasswordScreen()
}
}
}
@Composable
fun ResetPasswordScreen() {
val auth = FirebaseAuth.getInstance()
var email by remember { mutableStateOf("") }
var oldPassword by remember { mutableStateOf("") }
var newPassword by remember { mutableStateOf("") }
var confirmPassword by remember { mutableStateOf("") }
Surface(
modifier = Modifier.fillMaxSize(),
) {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic5), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
//.background(lightBlue)
.fillMaxSize()
.padding(16.dp)
) {
Spacer(modifier = Modifier.height(40.dp))
Image(
painter = painterResource(id = R.drawable.icon_account_circle),
contentDescription = null,
modifier = Modifier.size(130.dp)
)
Spacer(modifier = Modifier.height(40.dp))
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text("Enter your email",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = oldPassword,
onValueChange = { oldPassword = it },
label = { Text("Enter old password",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = newPassword,
onValueChange = { newPassword = it },
label = { Text("Enter new password",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
OutlinedTextField(
value = confirmPassword,
onValueChange = { confirmPassword = it },
label = { Text("Re-type new password",
color = Color.White // Set label text color to white
) },
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(color = Color.White) // Set text color to white
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
if(email == "" || oldPassword == "" || newPassword == "" || confirmPassword == ""){
Toast.makeText(context, "Please fill up all ", Toast.LENGTH_SHORT).show()
}else{
val user = auth.currentUser
if (user != null && user.email != null) {
val credential = EmailAuthProvider.getCredential(user.email!!, oldPassword)
user.reauthenticate(credential)
.addOnCompleteListener { reauthTask ->
if (reauthTask.isSuccessful) {
if (newPassword == confirmPassword) {
user.updatePassword(newPassword)
.addOnCompleteListener { updateTask ->
if (updateTask.isSuccessful) {
Toast.makeText(
context,
"Password updated successfully",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
context,
"Failed to update password",
Toast.LENGTH_SHORT
).show()
}
}
} else {
Toast.makeText(context, "New passwords do not match", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(context, "Re-Authentication failed", Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(context, "User not found or email not set", Toast.LENGTH_SHORT).show()
}
}
},
modifier = Modifier.fillMaxWidth()
) {
Text("Update Password")
}
Spacer(modifier = Modifier.height(20.dp))
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ResetPasswordScreenPreview() {
ResetPasswordScreen()
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/ResetPasswordActivity.kt
|
1483325717
|
package com.example.hallserviceapp
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
class NoticeActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
NoticeScreen()
}
}
}
}
}
@Composable
fun NoticeScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp)
) {
Headlineee("Notice")
//SearchSection()
NoticeSection()
}
}
}
data class NoticeNN(
val id: String = "",
val title: String = "",
val date: String = "",
val text: String = "",
val pdfUri: String = "" // Assuming notices have a PDF URL
)
@Composable
fun NoticeSection() {
val database = FirebaseDatabase.getInstance().getReference("notices")
var noticeList by remember { mutableStateOf(listOf<NoticeNN>()) }
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
LaunchedEffect(key1 = Unit) {
database.orderByChild("date").addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
isLoading = false
noticeList = snapshot.children.mapNotNull { it.getValue(NoticeNN::class.java)?.copy(id = it.key ?: "") }
}
override fun onCancelled(error: DatabaseError) {
isLoading = false
isError = true
}
})
}
if (isLoading) {
//CircularProgressIndicator()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
Text(
text = "Loading... Please wait",
style = MaterialTheme.typography.titleSmall,
color = Color.Gray
)
}
} else if (isError) {
Text("Error loading notices.")
} else {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(noticeList) { notice ->
NoticeItem(notice)
}
}
}
}
@Composable
fun NoticeItem(notice: NoticeNN) {
Card(modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp)) {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = "Date: ${notice.date}", style = MaterialTheme.typography.bodySmall)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "Title: ${notice.title}", style = MaterialTheme.typography.titleMedium)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "Description: ${notice.text}", style = MaterialTheme.typography.bodyMedium)
// Add more details or actions for each notice item here
//Text(text = "File: ${notice.pdfUri}", style = MaterialTheme.typography.bodyMedium)
Spacer(modifier = Modifier.height(4.dp))
if (notice.pdfUri.isNotEmpty()) { // Check if PDF URI is not empty
val context = LocalContext.current
Button(onClick = {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(notice.pdfUri)
context.startActivity(intent)
}) {
Text(text = "View PDF")
}
Spacer(modifier = Modifier.height(4.dp))
Button(onClick = {
// Define a file path to save the PDF
val destinationPath = context.getExternalFilesDir(null)?.absolutePath + "/DownloadedFile.pdf"
// Download the file
downloadFile(notice.pdfUri, destinationPath)
}) {
Text(text = "Download PDF")
}
} else {
//Text(text = "PDF URL is empty", style = MaterialTheme.typography.bodyMedium)
}
}
}
}
fun downloadFile(fileUrl: String, destinationFilePath: String) {
try {
val url = URL(fileUrl)
val connection = url.openConnection() as HttpURLConnection
connection.connect()
val inputStream: InputStream = connection.inputStream
val fileOutputStream = FileOutputStream(File(destinationFilePath))
val buffer = ByteArray(1024)
var len1: Int
while (inputStream.read(buffer).also { len1 = it } != -1) {
fileOutputStream.write(buffer, 0, len1)
}
fileOutputStream.close()
inputStream.close()
} catch (e: Exception) {
e.printStackTrace() // Log the exception for debugging purposes
}
}
@Preview(showBackground = true)
@Composable
fun NoticePreview() {
HallServiceAppTheme {
NoticeScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/NoticeActivity.kt
|
3333146156
|
package com.example.hallserviceapp
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.hallserviceapp.ui.theme.HallServiceAppTheme
class MedicineActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
HallServiceAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MedicineScreen()
}
}
}
}
}
@Composable
fun MedicineScreen() {
val lightBlue = Color(0xFF8FABE7) // Light blue color
val gray = Color(0xFF504B50)
val green = Color(0xFF43B83A)
val yellow = Color(0xFFC5B685)
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
) {
// Add the background image
Image(
painter = painterResource(id = R.drawable.bgpic4), // Replace with your image resource
contentDescription = null, // Content description can be null for decorative images
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.FillBounds // Scale the image to fill the bounds
)
Column(
modifier = Modifier
.fillMaxSize()
//.background(lightBlue)
.padding(16.dp),
verticalArrangement = Arrangement.Top,
) {
Headlineee("Medicine")
Spacer(modifier = Modifier.height(30.dp))
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.background(Color.White, shape = RoundedCornerShape(10.dp))
//.padding(16.dp)
) {
Text(
text = "Available medicine list:",
fontSize = 20.sp,
color = Color.Black,
modifier = Modifier
.fillMaxWidth()
.padding(15.dp),
textAlign = TextAlign.Right
)
Divider( // Add a divider line between student items
color = Color.Black,
thickness = 3.dp,
modifier = Modifier
.padding(8.dp)
.padding(horizontal = 10.dp)
)
Text(
text = "Room no : 101",
color = Color.Black,
fontSize = 20.sp,
modifier = Modifier
.padding(vertical = 5.dp)
.padding(horizontal = 18.dp)
//.align(Alignment.CenterHorizontally)
//.background(gray)
)
Divider( // Add a divider line between student items
color = gray,
thickness = 3.dp,
modifier = Modifier
.width(170.dp)
.padding(8.dp)
.padding(horizontal = 10.dp)
)
Spacer(modifier = Modifier.height(20.dp))
Column(
modifier = Modifier
//.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(16.dp)
) {
Text(text = "* First aid kits", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Napa Extra Tablet", fontSize = 24.sp)
Spacer(modifier = Modifier.height(8.dp))
Text(text = "* Histacin", fontSize = 24.sp)
// Add more medicines as needed
}
Spacer(modifier = Modifier.height(70.dp))
}
}
}
}
@Composable
fun Headlineeee(headlinee : String) {
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Spacer(modifier = Modifier.width(35.dp)) // For spacing
Text(
text = headlinee,
color = Color.White,
fontSize = 20.sp,
modifier = Modifier
//.background(Color.White, shape = RoundedCornerShape(10.dp))
.padding(10.dp)
.clip(RoundedCornerShape(8.dp)),
textAlign = TextAlign.Center
)
}
Image(
painter = painterResource(id = R.drawable.headline),
contentDescription = "Headline",
modifier = Modifier
.clickable {
context.startActivity(
Intent(
context,
UserActivity::class.java
)
) // Change to the desired activity
}
.padding(vertical = 10.dp)
//.padding(top = 4.dp)
.size(50.dp)
.padding(9.dp)
)
}
}
@Preview(showBackground = true)
@Composable
fun MedicineScreenPreview() {
HallServiceAppTheme {
MedicineScreen()
}
}
|
HallService--App/app/src/main/java/com/example/hallserviceapp/MedicineActivity.kt
|
4143483071
|
package com.busal.finals.moviewatchlist
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.busal.finals.myapplication", appContext.packageName)
}
}
|
Movie-Watchlist/app/src/androidTest/java/com/busal/finals/moviewatchlist/ExampleInstrumentedTest.kt
|
1306243613
|
package com.busal.finals.moviewatchlist
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)
}
}
|
Movie-Watchlist/app/src/test/java/com/busal/finals/moviewatchlist/ExampleUnitTest.kt
|
2160948100
|
package com.busal.finals.moviewatchlist
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [FilterFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class FilterFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_filter, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FilterFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
FilterFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/FilterFragment.kt
|
2951714033
|
package com.busal.finals.moviewatchlist.models
data class MovieDetails (
val id: Int,
val poster: String,
val type: String,
val name: String,
val releaseDate: String,
val genre: String,
val credential: String,
val duration: String,
val director: String,
val synopsis: String,
var userRating: String,
var isWatched: Boolean,
var isRemoved: Boolean,
)
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/models/MovieDetails.kt
|
1344280848
|
package com.busal.finals.moviewatchlist.adapter
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import jp.co.cyberagent.android.gpuimage.filter.GPUImageGaussianBlurFilter
import jp.co.cyberagent.android.gpuimage.GPUImage
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.busal.finals.moviewatchlist.MovieDetailsViewActivity
import com.busal.finals.moviewatchlist.databinding.ActivityWatchedListAdapterBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.squareup.picasso.Picasso
import jp.co.cyberagent.android.gpuimage.filter.GPUImageBrightnessFilter
import java.lang.Exception
class WatchedListAdapter(
private val activity: Activity,
private var movieList:List<MovieDetails>,
): RecyclerView.Adapter<WatchedListAdapter.WatchedListViewHolder>(){
class WatchedListViewHolder(
private val activity: Activity,
private val binding: ActivityWatchedListAdapterBinding
): RecyclerView.ViewHolder(binding.root){
fun bind(movieDetails: MovieDetails){
val posterURL = movieDetails.poster
Picasso.get().load(posterURL).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
if (bitmap != null) {
// Apply blur to the bitmap
val blurredBitmap = applyBlurAndDarken(bitmap)
// Set the blurred bitmap to the ImageView
binding.moviePosterWatched.setImageBitmap(blurredBitmap)
}
}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
})
binding.movieTitleText2.text = movieDetails.name
binding.yearText2.text = movieDetails.releaseDate
binding.genreText2.text = movieDetails.genre
binding.userRatingText.text = movieDetails.userRating
if(movieDetails.isWatched){
binding.statusText2.text = "Watched"
}
if(movieDetails.isRemoved){
binding.statusText2.text = "Removed"
}
binding.item2.setOnClickListener{
val intent = Intent(activity, MovieDetailsViewActivity::class.java)
intent.putExtra("PARAM_ID",movieDetails.id)
activity.startActivity(intent)
}
}
private fun applyBlurAndDarken(originalBitmap: Bitmap): Bitmap {
val gpuImage = GPUImage(activity)
gpuImage.setImage(originalBitmap)
// Apply blur
val blurFilter = GPUImageGaussianBlurFilter(0.8f)
gpuImage.setFilter(blurFilter)
val blurredBitmap = gpuImage.bitmapWithFilterApplied
// Apply darken
val darkenFilter = GPUImageBrightnessFilter(-0.2f) // Adjust the brightness value as needed
gpuImage.setImage(blurredBitmap)
gpuImage.setFilter(darkenFilter)
return gpuImage.bitmapWithFilterApplied
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WatchedListViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ActivityWatchedListAdapterBinding.inflate(
inflater,
parent,
false,
)
return WatchedListViewHolder(activity, binding)
}
override fun getItemCount() = movieList.size
override fun onBindViewHolder(holder: WatchedListViewHolder, position: Int) {
holder.bind(movieList[position])
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/adapter/WatchedListAdapter.kt
|
2275595313
|
package com.busal.finals.moviewatchlist.adapter
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.busal.finals.moviewatchlist.MovieDetailsViewActivity
import com.busal.finals.moviewatchlist.databinding.ActivitySearchListAdapterBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.busal.finals.moviewatchlist.storage.LocalStorage
import com.squareup.picasso.Picasso
import jp.co.cyberagent.android.gpuimage.GPUImage
import jp.co.cyberagent.android.gpuimage.filter.GPUImageBrightnessFilter
import jp.co.cyberagent.android.gpuimage.filter.GPUImageGaussianBlurFilter
import java.lang.Exception
class SearchListAdapter(
private val activity: Activity,
var searchedMovieLists:List<MovieDetails>,
private val listReloadListener: ListReloadListener
): RecyclerView.Adapter<SearchListAdapter.SearchListViewHolder>(){
interface ListReloadListener {
fun onListReloaded(source: String)
}
class SearchListViewHolder(
private val activity: Activity,
private val binding: ActivitySearchListAdapterBinding,
private val adapter: SearchListAdapter,
): RecyclerView.ViewHolder(binding.root){
fun bind(position: Int){
val selectedMovie = adapter.searchedMovieLists[position]
val posterURL = selectedMovie.poster
Picasso.get().load(posterURL).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
if (bitmap != null) {
// Apply blur to the bitmap
val blurredBitmap = applyBlurAndDarken(bitmap)
// Set the blurred bitmap to the ImageView
binding.searchedMoviePoster.setImageBitmap(blurredBitmap)
}
}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
})
binding.searchedMovieTitleText.text = selectedMovie.name
binding.searchedYearText.text = selectedMovie.releaseDate
binding.searchedGenreText.text = selectedMovie.genre
binding.searchedAddToWatchListButton.setOnClickListener {
val movieList = LocalStorage(activity).movieList.toMutableList()
movieList.add(0,selectedMovie)
LocalStorage(activity).movieList = movieList
adapter.reloadList("SearchListAdapter")
}
binding.item.setOnClickListener{
val intent = Intent(activity, MovieDetailsViewActivity::class.java)
intent.putExtra("PARAM_ID",selectedMovie.id)
intent.putExtra("PARAM_ADDORCHECK",true)
activity.startActivity(intent)
}
}
private fun applyBlurAndDarken(originalBitmap: Bitmap): Bitmap {
val gpuImage = GPUImage(activity)
gpuImage.setImage(originalBitmap)
// Apply blur
val blurFilter = GPUImageGaussianBlurFilter(0.8f)
gpuImage.setFilter(blurFilter)
val blurredBitmap = gpuImage.bitmapWithFilterApplied
// Apply darken
val darkenFilter = GPUImageBrightnessFilter(-0.2f) // Adjust the brightness value as needed
gpuImage.setImage(blurredBitmap)
gpuImage.setFilter(darkenFilter)
return gpuImage.bitmapWithFilterApplied
}
}
private fun reloadList(source:String){
listReloadListener.onListReloaded(source)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchListViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ActivitySearchListAdapterBinding.inflate(
inflater,
parent,
false,
)
return SearchListViewHolder(activity, binding, this)
}
override fun getItemCount() = searchedMovieLists.size
override fun onBindViewHolder(holder: SearchListViewHolder, position: Int) {
holder.bind(position)
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/adapter/SearchListAdapter.kt
|
3384838339
|
package com.busal.finals.moviewatchlist.adapter
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.busal.finals.moviewatchlist.MovieDetailsViewActivity
import com.busal.finals.moviewatchlist.databinding.ActivityHomeListAdapterBinding
import com.busal.finals.moviewatchlist.databinding.RatingDialogLayoutBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.busal.finals.moviewatchlist.storage.LocalStorage
import com.squareup.picasso.Picasso
import jp.co.cyberagent.android.gpuimage.GPUImage
import jp.co.cyberagent.android.gpuimage.filter.GPUImageBrightnessFilter
import jp.co.cyberagent.android.gpuimage.filter.GPUImageGaussianBlurFilter
import java.lang.Exception
class HomeListAdapter(
private val activity:Activity,
var movieLists:List<MovieDetails>,
private val listReloadListener: ListReloadListener
): RecyclerView.Adapter<HomeListAdapter.HomeListViewHolder>(){
interface ListReloadListener {
fun onListReloaded(source: String)
}
class HomeListViewHolder(
private val activity: Activity,
private val binding: ActivityHomeListAdapterBinding,
private val adapter: HomeListAdapter,
): RecyclerView.ViewHolder(binding.root){
private lateinit var updateMovieList: MutableList<MovieDetails>
fun bind(position: Int){
val selectedMovie = adapter.movieLists[position]
updateMovieList = LocalStorage(activity).movieList.toMutableList()
val posterURL = selectedMovie.poster
val index = updateMovieList.indexOfFirst { it.id == selectedMovie.id }
if(index != -1){
updateMovieList[index]=selectedMovie
}
Picasso.get().load(posterURL).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
if (bitmap != null) {
// Apply blur to the bitmap
val blurredBitmap = applyBlurAndDarken(bitmap)
// Set the blurred bitmap to the ImageView
binding.moviePoster.setImageBitmap(blurredBitmap)
}
}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
})
binding.movieTitleText.text = selectedMovie.name
binding.yearText.text = selectedMovie.releaseDate
binding.genreText.text = selectedMovie.genre
binding.watchedButton.setOnClickListener {
showRatingDialog(selectedMovie)
}
selectedMovie.userRating
binding.removeButton.setOnClickListener {
showRemoveConfirmationDialog(selectedMovie)
}
binding.item.setOnClickListener{
val intent = Intent(activity,MovieDetailsViewActivity::class.java)
intent.putExtra("PARAM_ID",selectedMovie.id)
activity.startActivity(intent)
}
}
private fun showRatingDialog(selectedMovie: MovieDetails) {
val builder = AlertDialog.Builder(activity)
val dialogBinding = RatingDialogLayoutBinding.inflate(activity.layoutInflater)
builder.setView(dialogBinding.root)
val dialog = builder.create()
// Set click listeners for rating buttons using the binding
val buttons = listOf(
dialogBinding.ratingButton1,
dialogBinding.ratingButton2,
dialogBinding.ratingButton3,
dialogBinding.ratingButton4,
dialogBinding.ratingButton5
)
dialogBinding.rateMovieTitleText.text="Rate: ${selectedMovie.name}"
// Set a click listener for each rating button
for (i in 1..5) {
buttons[i - 1].setOnClickListener {
// Set the user rating for the selected movie
selectedMovie.userRating = "$i/5"
selectedMovie.isWatched = true
// Save the updated movie list to local storage
LocalStorage(activity).movieList = updateMovieList
// Reload the list using the adapter
adapter.reloadList("HomeListAdapter")
// Dismiss the dialog
dialog.dismiss()
}
}
// Set a click listener for the Cancel button
dialogBinding.cancelRateButton.setOnClickListener {
// Dismiss the dialog
dialog.dismiss()
}
// Show the dialog
dialog.show()
}
private fun showRemoveConfirmationDialog(selectedMovie: MovieDetails) {
val builder = AlertDialog.Builder(activity)
builder.setTitle("${selectedMovie.name}")
builder.setMessage("Are you sure you want to remove this on the list?")
builder.setPositiveButton("Yes") { dialog, which ->
// User clicked Yes, proceed with removal
selectedMovie.isRemoved = true
LocalStorage(activity).movieList = updateMovieList
adapter.reloadList("HomeListAdapter")
dialog.dismiss()
}
builder.setNegativeButton("No") { dialog, which ->
// User clicked No, close the dialog
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
private fun applyBlurAndDarken(originalBitmap: Bitmap): Bitmap {
val gpuImage = GPUImage(activity)
gpuImage.setImage(originalBitmap)
// Apply blur
val blurFilter = GPUImageGaussianBlurFilter(0.8f)
gpuImage.setFilter(blurFilter)
val blurredBitmap = gpuImage.bitmapWithFilterApplied
// Apply darken
val darkenFilter = GPUImageBrightnessFilter(-0.2f) // Adjust the brightness value as needed
gpuImage.setImage(blurredBitmap)
gpuImage.setFilter(darkenFilter)
return gpuImage.bitmapWithFilterApplied
}
}
private fun reloadList(source:String){
listReloadListener.onListReloaded(source)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeListViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ActivityHomeListAdapterBinding.inflate(
inflater,
parent,
false,
)
return HomeListViewHolder(activity, binding,this)
}
override fun getItemCount() = movieLists.size
override fun onBindViewHolder(holder: HomeListViewHolder, position: Int) {
holder.bind(position)
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/adapter/HomeListAdapter.kt
|
4011638221
|
package com.busal.finals.moviewatchlist
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.busal.finals.moviewatchlist.databinding.ActivityMovieDetailsViewBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.busal.finals.moviewatchlist.storage.LocalStorage
import com.squareup.picasso.Picasso
class MovieDetailsViewActivity : AppCompatActivity() {
private lateinit var binding:ActivityMovieDetailsViewBinding
private var isAddOrCheck : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMovieDetailsViewBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
val movieId =intent.getIntExtra("PARAM_ID",-1)
isAddOrCheck = intent.getBooleanExtra("PARAM_ADDORCHECK",false)
val movie = getMovieDetails(movieId)
if (movie!=null){
val posterURL = movie.poster
Picasso.get().load(posterURL).into(binding.moviePosterView)
binding.typeText.text = movie.type
binding.titleText.text = "Title: ${movie.name} "
binding.airedText.text = "Release Year: ${movie.releaseDate}"
binding.genresText.text = "Genre: ${movie.genre}"
binding.ratingText.text = "Rating: ${movie.credential}"
binding.durationText.text = "Duration: ${movie.duration}"
binding.directorText.text = movie.director
binding.synopsisText.text = "Synopsis: ${movie.synopsis}"
}
}
private fun getMovieDetails(id:Int): MovieDetails?{
val movieList : List<MovieDetails>
if(isAddOrCheck){
movieList = LocalStorage(this).searchedMovieList
}else{
movieList = LocalStorage(this).movieList
}
return movieList.find{it.id==id}
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/MovieDetailsViewActivity.kt
|
3154923833
|
package com.busal.finals.moviewatchlist.storage
import android.content.Context
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class LocalStorage(context: Context) {
private val sharedPref = context
.getSharedPreferences("GENERAL", Context.MODE_PRIVATE)
var isSaved: Boolean
get() = sharedPref.getBoolean("KEY_ISSAVED",true)
set(value) = sharedPref.edit().putBoolean("KEY_ISSAVED",value).apply()
private inline fun <reified T> Gson.toJson(src: T): String {
return toJson(src, object : TypeToken<T>() {}.type)
}
private inline fun <reified T> Gson.fromJson(json: String): T {
return fromJson(json, object : TypeToken<T>() {}.type)
}
var movieList: List<MovieDetails>
get() {
val json: String? = sharedPref.getString("KEY_MOVIE_LIST", null)
return if (json != null) {
Gson().fromJson(json)
} else {
emptyList()
}
}
set(value) {
val gson = Gson()
val json = gson.toJson(value)
sharedPref.edit().putString("KEY_MOVIE_LIST", json).apply()
}
var searchedMovieList: List<MovieDetails>
get() {
val json: String? = sharedPref.getString("KEY_SEARCHED_MOVIE_LIST", null)
return if (json != null) {
Gson().fromJson(json)
} else {
emptyList()
}
}
set(value) {
val gson = Gson()
val json = gson.toJson(value)
sharedPref.edit().putString("KEY_SEARCHED_MOVIE_LIST", json).apply()
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/storage/LocalStorage.kt
|
2171110301
|
package com.busal.finals.moviewatchlist
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.busal.finals.moviewatchlist.databinding.ActivitySignInMainBinding
class SignInMainActivity : AppCompatActivity() {
private lateinit var binding:ActivitySignInMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivitySignInMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
proceedToMain()
}
private fun proceedToMain(){
val intent = Intent(this, WatchListActivity::class.java)
startActivity(intent)
finish()
}
private fun isSignedIn():Boolean{
return true
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/SignInMainActivity.kt
|
2552337437
|
package com.busal.finals.moviewatchlist
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.busal.finals.moviewatchlist.adapter.WatchedListAdapter
import com.busal.finals.moviewatchlist.databinding.FragmentWatchedBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.busal.finals.moviewatchlist.storage.LocalStorage
class WatchedFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
private lateinit var binding:FragmentWatchedBinding
private lateinit var movieList:List<MovieDetails>
private var onWatched = true
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentWatchedBinding.inflate(inflater,container,false)
getMovieList()
showWatched()
binding.watchedOrRemovedButton.setOnClickListener {
if(onWatched){
binding.watchedOrRemovedButton.text= getString(R.string.removed)
onWatched=false
showRemoved()
}else{
binding.watchedOrRemovedButton.text= getString(R.string.watched)
onWatched=true
showWatched()
}
}
return binding.root
}
private fun getMovieList(){
movieList=LocalStorage(requireContext()).movieList
}
private fun displayMovies(data:List<MovieDetails>){
binding.watchedListRecyclerView.layoutManager = LinearLayoutManager(activity)
binding.watchedListRecyclerView.adapter = WatchedListAdapter(requireActivity(), data)
}
private lateinit var displayedList: List<MovieDetails>
private fun showRemoved() {
displayedList = movieList.filter { it.isRemoved && !it.isWatched }
displayMovies(displayedList)
}
private fun showWatched() {
displayedList = movieList.filter { it.isWatched && !it.isRemoved }
displayMovies(displayedList)
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/WatchedFragment.kt
|
897844244
|
package com.busal.finals.moviewatchlist
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.busal.finals.moviewatchlist.adapter.HomeListAdapter
import com.busal.finals.moviewatchlist.adapter.SearchListAdapter
import com.busal.finals.moviewatchlist.databinding.FragmentHomeBinding
import com.busal.finals.moviewatchlist.models.MovieDetails
import com.busal.finals.moviewatchlist.storage.LocalStorage
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Integer.min
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
class HomeFragment : Fragment(), HomeListAdapter.ListReloadListener, SearchListAdapter.ListReloadListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
private lateinit var mContext: Context
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
private lateinit var binding:FragmentHomeBinding
private lateinit var movieList:List<MovieDetails>
private lateinit var searchedMovieList:List<MovieDetails>
private var isAddMovie = false
private var toggleAnimeOrMovie = true
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(inflater,container,false)
binding.searchButton.setOnClickListener {
binding.searchButton.visibility = View.INVISIBLE
binding.addMovieButton.visibility = View.INVISIBLE
binding.doneButton.visibility = View.VISIBLE
binding.searchWatchListBarText.visibility = View.VISIBLE
}
binding.doneButton.setOnClickListener {
binding.searchButton.visibility = View.VISIBLE
binding.addMovieButton.visibility = View.VISIBLE
binding.doneButton.visibility = View.INVISIBLE
binding.searchWatchListBarText.visibility = View.INVISIBLE
}
binding.addMovieButton.setOnClickListener {
if(isAddMovie){
binding.addMovieButton.text = getString(R.string.add_movie)
binding.searchButton.visibility = View.VISIBLE
binding.animeAddButton.visibility = View.INVISIBLE
binding.movieAddButton.visibility = View.INVISIBLE
loadLocal()
isListEmpty()
binding.movieListRecyclerView.visibility = View.VISIBLE
isAddMovie = false
}else{
binding.addMovieButton.text = getString(R.string.done_)
binding.searchButton.visibility = View.INVISIBLE
binding.animeAddButton.visibility = View.VISIBLE
binding.movieAddButton.visibility = View.VISIBLE
binding.movieListRecyclerView.visibility = View.INVISIBLE
binding.addMoviesMessageText.visibility = View.INVISIBLE
isAddMovie = true
}
}
binding.animeAddButton.setOnClickListener {
toggleAnimeOrMovie=true
searchAnimeOrMovie()
}
binding.movieAddButton.setOnClickListener {
toggleAnimeOrMovie=false
searchAnimeOrMovie()
}
binding.cancelSearchButton.setOnClickListener {
binding.addSearchQueryText.visibility = View.INVISIBLE
binding.cancelSearchButton.visibility = View.INVISIBLE
binding.proceedSearchButton.visibility = View.INVISIBLE
binding.movieListRecyclerView.visibility = View.INVISIBLE
binding.animeAddButton.visibility = View.VISIBLE
binding.movieAddButton.visibility = View.VISIBLE
binding.addMovieButton.visibility = View.VISIBLE
}
binding.proceedSearchButton.setOnClickListener {
lifecycleScope.launch {
queryApiSearch()
}
}
loadLocal()
isListEmpty()
return binding.root
}
private suspend fun queryApiSearch() {
val query = binding.addSearchQueryText.text.toString().trim()
if (query.isNotEmpty()) {
if (toggleAnimeOrMovie) {
lifecycleScope.launch {
val result = animeSearch(query)
handleAnimeSearchResult(result)
getSearchedFromLocal()
filterSearched()
getSearchedFromLocal()
displaySearchResults()
binding.movieListRecyclerView.visibility = View.VISIBLE
}
}else{
val result = movieSearch(query)
handleMovieSearchResult(result)
getSearchedFromLocal()
filterSearched()
getSearchedFromLocal()
displaySearchResults()
binding.movieListRecyclerView.visibility = View.VISIBLE
}
}
}
private fun getSearchedFromLocal(){
searchedMovieList = LocalStorage(requireContext()).searchedMovieList
}
private fun displaySearchResults(){
binding.movieListRecyclerView.adapter = null
binding.movieListRecyclerView.layoutManager = LinearLayoutManager(activity)
binding.movieListRecyclerView.adapter = SearchListAdapter(requireActivity(),searchedMovieList,this)
}
private fun filterSearched() {
val localMovieList = LocalStorage(requireContext()).movieList
val localMovieIds = localMovieList.map { it.id } ?: emptyList()
val filteredMovieList = searchedMovieList.filter { movie ->
movie.id !in localMovieIds
}
LocalStorage(requireContext()).searchedMovieList = filteredMovieList
}
private suspend fun movieSearch(query: String): String {
val apiKey = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI2N2RmYzlhZjJiYWM2MmY5NjA5NjZmNDEyNmFjZGY4ZiIsInN1YiI6IjY1NzFiNDFhYjA0NjA1MDExZDcyN2VlZiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.aG-psNKl0wZcaRGqtHBB41GDkIxgn7EZlhwjeOY18_E"
val apiUrl = "https://api.themoviedb.org/3/search/movie?query=${URLEncoder.encode(query, "UTF-8")}&include_adult=false&language=en-US&page=1"
val authHeader = "Bearer $apiKey"
return withContext(Dispatchers.IO) {
try {
val url = URL(apiUrl)
val connection = url.openConnection() as HttpURLConnection
// Set authorization header
connection.setRequestProperty("Authorization", authHeader)
val inputStream = connection.inputStream
val reader = BufferedReader(InputStreamReader(inputStream))
val response = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
response.append(line)
}
reader.close()
inputStream.close()
return@withContext response.toString()
} catch (e: Exception) {
e.printStackTrace()
}
return@withContext ""
}
}
private fun handleMovieSearchResult(result: String) {
try {
val jsonResponse = JSONObject(result)
// Check if "results" key exists
if (jsonResponse.has("results")) {
val resultsArray = jsonResponse.getJSONArray("results")
// Create a list to store MovieDetails objects
val searchedMovieListPrivate = mutableListOf<MovieDetails>()
for (i in 0 until resultsArray.length()) {
val movieObject = resultsArray.getJSONObject(i)
val movieId = movieObject.getInt("id")
val title = movieObject.getString("title")
val releaseDate = movieObject.getString("release_date").substring(0, 4)
val genresArray = movieObject.getJSONArray("genre_ids")
val genres = mutableListOf<String>()
for (j in 0 until min(2, genresArray.length())) {
val genreId = genresArray.getInt(j)
genres.add(getGenreNameById(genreId))
}
val posterPath = movieObject.getString("poster_path")
val posterLink = "https://image.tmdb.org/t/p/w500$posterPath"
val overview = movieObject.getString("overview")
val popularity = movieObject.getDouble("popularity").toString()
val movieDetails = MovieDetails(
movieId,
posterLink,
"Movie",
title,
releaseDate,
genres.joinToString(),
popularity,
"",
"",
overview,
"",
isWatched = false, isRemoved = false
)
searchedMovieListPrivate.add(movieDetails)
}
LocalStorage(requireContext()).searchedMovieList = searchedMovieListPrivate
} else {
Log.w("MovieSearchTask", "No 'results' key found in the JSON response")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun getGenreNameById(genreId: Int): String {
val genreMap = mapOf(
28 to "Action",
12 to "Adventure",
16 to "Animation",
35 to "Comedy",
80 to "Crime",
99 to "Documentary",
18 to "Drama",
10751 to "Family",
14 to "Fantasy",
36 to "History",
27 to "Horror",
10402 to "Music",
9648 to "Mystery",
10749 to "Romance",
878 to "Science Fiction",
10770 to "TV Movie",
53 to "Thriller",
10752 to "War",
37 to "Western"
)
return genreMap.getOrDefault(genreId, "Unknown Genre")
}
private suspend fun animeSearch(query: String): String {
val apiUrl = "https://api.jikan.moe/v4/anime?q=${query}"
return withContext(Dispatchers.IO) {
try {
val url = URL(apiUrl)
val connection = url.openConnection() as HttpURLConnection
val inputStream = connection.inputStream
val reader = BufferedReader(InputStreamReader(inputStream))
val response = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
response.append(line)
}
reader.close()
inputStream.close()
return@withContext response.toString()
} catch (e: Exception) {
e.printStackTrace()
}
return@withContext ""
}
}
private fun handleAnimeSearchResult(result: String) {
try {
val jsonResponse = JSONObject(result)
// Check if "data" key exists
if (jsonResponse.has("data")) {
val dataArray = jsonResponse.getJSONArray("data")
// Create a list to store MovieDetails objects
val searchedMovieListPrivate = mutableListOf<MovieDetails>()
for (i in 0 until dataArray.length()) {
val animeObject = dataArray.getJSONObject(i)
val malId = animeObject.getInt("mal_id")
val title = animeObject.getString("title")
val airedObject = animeObject.getJSONObject("aired")
val airedPropObject = airedObject.getJSONObject("prop")
val airedFromObject = airedPropObject.getJSONObject("from")
val genresArray = animeObject.getJSONArray("genres")
val genres = mutableListOf<String>()
for (j in 0 until genresArray.length()) {
val genreObject = genresArray.getJSONObject(j)
val genreName = genreObject.getString("name")
genres.add(genreName)
}
val imagesObject = animeObject.getJSONObject("images")
val posterLink = imagesObject.getJSONObject("jpg").getString("large_image_url")
val synopsis = animeObject.getString("synopsis")
val episodes = animeObject.getString("episodes")
val duration = animeObject.getString("duration")
val newDuration = "$episodes episodes, $duration"
val studiosArray = animeObject.getJSONArray("studios")
val studio = mutableListOf<String>()
for (j in 0 until studiosArray.length()) {
val studioObject = studiosArray.getJSONObject(j)
val studioName = studioObject.getString("name")
studio.add(studioName)
}
val releaseYear = airedFromObject.getString("year")
val rating = animeObject.getString("rating")
val movieDetails = MovieDetails(
malId,
posterLink,
"Anime",
title,
releaseYear,
genres.joinToString(),
rating,
newDuration,
"Studio: ${studio.joinToString()}",
synopsis,
"",
isWatched = false, isRemoved = false
)
searchedMovieListPrivate.add(movieDetails)
}
LocalStorage(requireContext()).searchedMovieList = searchedMovieListPrivate
} else {
Log.w("AnimeSearchTask", "No 'data' key found in the JSON response")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun searchAnimeOrMovie(){
binding.addSearchQueryText.visibility = View.VISIBLE
binding.cancelSearchButton.visibility = View.VISIBLE
binding.proceedSearchButton.visibility = View.VISIBLE
binding.animeAddButton.visibility = View.INVISIBLE
binding.movieAddButton.visibility = View.INVISIBLE
binding.addMovieButton.visibility = View.INVISIBLE
if(toggleAnimeOrMovie){
binding.addSearchQueryText.hint = "Search Anime.."
}else{
binding.addSearchQueryText.hint = "Search Movie.."
}
}
override fun onListReloaded(source:String) {
when (source) {
"HomeListAdapter" -> {
displayMovies()
loadLocal()
isListEmpty()
}
"SearchListAdapter" -> {
filterSearched()
getSearchedFromLocal()
displaySearchResults()
}
}
}
private fun isListEmpty(){
if(movieList.isNotEmpty()){
displayMovies()
if(listToDisplay.isEmpty()){
binding.addMoviesMessageText.visibility = View.VISIBLE
}else{
binding.addMoviesMessageText.visibility = View.INVISIBLE
}
}else{
binding.addMoviesMessageText.visibility = View.VISIBLE
}
}
private lateinit var listToDisplay:List<MovieDetails>
private fun filterDisplay(){
binding.movieListRecyclerView.adapter = null
listToDisplay = LocalStorage(requireContext()).movieList
listToDisplay = listToDisplay.filter { !it.isRemoved && !it.isWatched }
}
private fun displayMovies(){
filterDisplay()
binding.movieListRecyclerView.adapter = null
binding.movieListRecyclerView.layoutManager = LinearLayoutManager(activity)
binding.movieListRecyclerView.adapter = HomeListAdapter(requireActivity(), listToDisplay,this)
}
private fun loadLocal(){
movieList=LocalStorage(requireContext()).movieList
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/HomeFragment.kt
|
640882574
|
package com.busal.finals.moviewatchlist
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.busal.finals.moviewatchlist.databinding.ActivityWatchListBinding
class WatchListActivity : AppCompatActivity() {
private lateinit var binding : ActivityWatchListBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityWatchListBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
replaceFragment(HomeFragment())
binding.bottomNavigationView.setOnItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.homeMenu-> {
replaceFragment(HomeFragment())
true
}
R.id.filterSearchMenu -> {
replaceFragment(FilterFragment())
true
}
R.id.watchedMenu -> {
replaceFragment(WatchedFragment())
true
}
else -> false
}
}
}
private fun replaceFragment(fragment: Fragment){
val fragmentManager = this.supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(binding.frameLayout.id,fragment)
fragmentTransaction.commit()
}
}
|
Movie-Watchlist/app/src/main/java/com/busal/finals/moviewatchlist/WatchListActivity.kt
|
2372502064
|
package com.example.simplequotesapp
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.simplequotesapp", appContext.packageName)
}
}
|
compose-cheezy-simple-quote-app/app/src/androidTest/java/com/example/simplequotesapp/ExampleInstrumentedTest.kt
|
3155583824
|
package com.example.simplequotesapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
compose-cheezy-simple-quote-app/app/src/test/java/com/example/simplequotesapp/ExampleUnitTest.kt
|
2617227757
|
package com.example.simplequotesapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/ui/theme/Color.kt
|
3217407680
|
package com.example.simplequotesapp.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 SimpleQuotesAppTheme(
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
)
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/ui/theme/Theme.kt
|
3411627656
|
package com.example.simplequotesapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/ui/theme/Type.kt
|
3350212076
|
package com.example.simplequotesapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.simplequotesapp.screens.QuoteDetail
import com.example.simplequotesapp.screens.QuoteListScreen
import com.example.simplequotesapp.ui.theme.SimpleQuotesAppTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
CoroutineScope(Dispatchers.IO).launch {
DataManager.loadAssetsFromFile(applicationContext)
}
setContent {
App()
}
}
}
@Composable
fun App() {
if (DataManager.isDataLoaded.value) {
if (DataManager.currentPage.value == Pages.LISTING) {
QuoteListScreen(data = DataManager.data) {
DataManager.switchPages(it)
}
}else{
DataManager.currentQuote?.let { QuoteDetail(quote = it) }
}
} else {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize(1f)
) {
Text(
text = "Loading...",
style = MaterialTheme.typography.bodySmall
)
}
}
}
enum class Pages {
LISTING,
DETAIL
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/MainActivity.kt
|
4064631181
|
package com.example.simplequotesapp
import android.content.Context
import androidx.compose.runtime.mutableStateOf
import com.example.simplequotesapp.models.Quote
import com.google.gson.Gson
object DataManager {
var data = emptyArray<Quote>()
var currentQuote: Quote? = null
var currentPage = mutableStateOf(Pages.LISTING)
var isDataLoaded = mutableStateOf(false)
fun loadAssetsFromFile(context: Context){
val inputStream = context.assets.open("quotes.json")
val size: Int = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
val json = String(buffer, Charsets.UTF_8)
val gson = Gson()
data = gson.fromJson(json, Array<Quote>::class.java)
isDataLoaded.value = true
}
fun switchPages(quote: Quote?){
if(currentPage.value == Pages.LISTING){
currentQuote = quote
currentPage.value = Pages.DETAIL
}else{
currentPage.value = Pages.LISTING
}
}
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/DataManager.kt
|
3401809440
|
package com.example.simplequotesapp.models
data class Quote(val text: String, val author: String)
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/models/Quote.kt
|
4273394872
|
package com.example.simplequotesapp.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.FormatQuote
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.simplequotesapp.R
import com.example.simplequotesapp.models.Quote
@Composable
fun QuoteListItem(quote: Quote, onClick: (quote: Quote) -> Unit) {
Card(
elevation = CardDefaults.cardElevation(
defaultElevation = 4.dp
),
modifier = Modifier
.clickable { onClick(quote) }
.padding(8.dp)
) {
Row(
modifier = Modifier.padding(16.dp)
) {
Image(
imageVector = Icons.Filled.FormatQuote,
colorFilter = ColorFilter.tint(Color.White),
alignment = Alignment.TopStart,
contentDescription = "Quote",
modifier = Modifier
.size(40.dp)
.rotate(180F)
.background(Color.Black)
)
Spacer(modifier = Modifier.padding(4.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = quote.text,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, 8.dp)
)
Box(
modifier = Modifier
.background(Color(0xFFEEEEEE))
.fillMaxWidth(.4f)
.height(1.dp)
)
Text(
text = quote.author,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Thin,
modifier = Modifier.padding(top = 4.dp)
)
}
}
}
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/screens/QuoteListItem.kt
|
3425170189
|
package com.example.simplequotesapp.screens
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import com.example.simplequotesapp.models.Quote
@Composable
fun QuoteList(data: Array<Quote>, onClick: (quote: Quote) -> Unit) {
LazyColumn(content = {
items(data){
QuoteListItem(quote = it, onClick)
}
})
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/screens/QuoteList.kt
|
2399543888
|
package com.example.simplequotesapp.screens
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FormatQuote
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import com.example.simplequotesapp.DataManager
import com.example.simplequotesapp.R
import com.example.simplequotesapp.models.Quote
@Composable
fun QuoteDetail(quote: Quote) {
BackHandler {
DataManager.switchPages(null)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize(1f)
.background(
Brush.sweepGradient(
colors = listOf(
Color(0xFFffffff),
Color(0xFFe3e3e3)
)
)
)
){
Card (
elevation = CardDefaults.cardElevation(
defaultElevation = 4.dp
),
modifier = Modifier.padding(32.dp)
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(16.dp, 24.dp)
) {
Image(
imageVector = Icons.Filled.FormatQuote,
contentDescription = "Quote",
modifier = Modifier
.size(80.dp)
.rotate(180F)
)
Text(
text = quote.text,
fontFamily = FontFamily(Font(R.font.montserrat_regular)),
style = MaterialTheme.typography.bodySmall
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = quote.author,
fontFamily = FontFamily(Font(R.font.montserrat_regular)),
style = MaterialTheme.typography.titleLarge
)
}
}
}
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/screens/QuoteDetailScreen.kt
|
3965130786
|
package com.example.simplequotesapp.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.simplequotesapp.R
import com.example.simplequotesapp.models.Quote
@Composable
fun QuoteListScreen(data: Array<Quote>, onClick: (quote: Quote) -> Unit) {
Column {
Text(
text = "Quotes App",
textAlign = TextAlign.Center,
modifier = Modifier
.padding(8.dp, 24.dp)
.fillMaxWidth(1f),
style = MaterialTheme.typography.bodyMedium,
fontFamily = FontFamily(Font(R.font.montserrat_regular))
)
QuoteList(data = data, onClick)
}
}
|
compose-cheezy-simple-quote-app/app/src/main/java/com/example/simplequotesapp/screens/QuoteListScreen.kt
|
1379274629
|
package com.example.calculator
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.calculator", appContext.packageName)
}
}
|
Kotlin.JC_AngleConverter_app/app/src/androidTest/java/com/example/calculator/ExampleInstrumentedTest.kt
|
4259167099
|
package com.example.calculator
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)
}
}
|
Kotlin.JC_AngleConverter_app/app/src/test/java/com/example/calculator/ExampleUnitTest.kt
|
3889441106
|
package com.example.calculator.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/ui/theme/Shape.kt
|
759366598
|
package com.example.calculator.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/ui/theme/Color.kt
|
2516980428
|
package com.example.calculator.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun CalculatorTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/ui/theme/Theme.kt
|
3282411496
|
package com.example.calculator.ui.theme
import androidx.compose.material.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(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/ui/theme/Type.kt
|
1977300223
|
package com.example.calculator
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.calculator.ui.theme.CalculatorTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CalculatorTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Solver().Changer()
}
}
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun DefaultPreview() {
CalculatorTheme {
Solver().Changer()
}
}
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/MainActivity.kt
|
1249001831
|
package com.example.calculator
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.floor
class Solver {
@Composable
fun Changer() {
var inputText by remember { mutableStateOf("") }
val degrees: Double = inputText.toDoubleOrNull() ?: 0.0
val radian: Double = degrees * 0.01745
val radianCalc = String.format("%.2f", radian)
val degreesCalc = floor(degrees)
val minutesCalc = floor((degrees - degreesCalc) * 60)
val secondsCalc = ((degrees - degreesCalc) * 60 - minutesCalc) * 60
val roundSec = secondsCalc.toInt()
val roundMin = minutesCalc.toInt()
val roundDeg = degreesCalc.toInt()
val grad: Double = degrees * 0.9
val roundGrad = String.format("%.2f", grad)
Column(
modifier = Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Degrees calculator",
fontWeight = FontWeight.Bold,
fontSize = 30.sp
)
Spacer(modifier = Modifier.height(30.dp))
EditDegrees(
label = R.string.input_degrees,
value = inputText,
onChange = { inputText = it })
Spacer(modifier = Modifier.height(20.dp))
Text(
text = stringResource(id = R.string.radian, radianCalc),
fontSize = 30.sp,
modifier = Modifier
.align(Alignment.Start)
.padding(start = 20.dp)
)
Text(
text = stringResource(id = R.string.minutes, roundDeg, roundMin, roundSec),
fontSize = 30.sp,
modifier = Modifier
.align(Alignment.Start)
.padding(start = 20.dp)
)
Text(
text = stringResource(id = R.string.grad, roundGrad),
fontSize = 30.sp,
modifier = Modifier
.align(Alignment.Start)
.padding(start = 20.dp)
)
}
}
@Composable
fun EditDegrees(
@StringRes label: Int,
value: String,
onChange: (String) -> Unit
) {
TextField(
label = { Text(text = stringResource(label)) },
value = value,
onValueChange = onChange,
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
)
)
}
}
|
Kotlin.JC_AngleConverter_app/app/src/main/java/com/example/calculator/Solver.kt
|
2288009277
|
package io.github.s_ymb.simplenumbergame
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.s_ymb.simplenumbergame", appContext.packageName)
}
}
|
simpleNumberGame/app/src/androidTest/java/io/github/s_ymb/simplenumbergame/ExampleInstrumentedTest.kt
|
3564213272
|
package com.s_ymb.numbergame
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.s_ymb.numbergame", appContext.packageName)
}
}
|
simpleNumberGame/app/src/androidTest/java/com/s_ymb/numbergame/ExampleInstrumentedTest.kt
|
2159937975
|
package io.github.s_ymb.simplenumbergame
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)
}
}
|
simpleNumberGame/app/src/test/java/io/github/s_ymb/simplenumbergame/ExampleUnitTest.kt
|
2068050776
|
package com.s_ymb.numbergame
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)
}
}
|
simpleNumberGame/app/src/test/java/com/s_ymb/numbergame/ExampleUnitTest.kt
|
3055886782
|
package io.github.s_ymb.simplenumbergame.ui.home
import androidx.lifecycle.ViewModel
import io.github.s_ymb.simplenumbergame.data.DupErr
import io.github.s_ymb.simplenumbergame.data.GridData
import io.github.s_ymb.simplenumbergame.data.NumbergameData
import io.github.s_ymb.simplenumbergame.data.NumbergameData.Companion.IMPOSSIBLE_IDX
import io.github.s_ymb.simplenumbergame.data.NumbergameData.Companion.NUM_NOT_SET
import io.github.s_ymb.simplenumbergame.data.SatisfiedGridArrayInit
import io.github.s_ymb.simplenumbergame.data.SatisfiedGridData
import io.github.s_ymb.simplenumbergame.data.ScreenBtnData
import io.github.s_ymb.simplenumbergame.data.ScreenCellData
import io.github.s_ymb.simplenumbergame.ui.ToastUiState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class NumbergameViewModel : ViewModel() {
// Game UI state
private val _uiState = MutableStateFlow(NumbergameUiState())
val uiState: StateFlow<NumbergameUiState> = _uiState.asStateFlow()
// Toast UI state(toast用)
private val _toastUiState = MutableStateFlow(ToastUiState())
val toastUiState = _toastUiState.asStateFlow()
private val gridData = GridData()
private var blankCellCnt = 30 //空白のセルの個数
private var selectedRow = IMPOSSIBLE_IDX //選択中セルの行番号
private var selectedCol = IMPOSSIBLE_IDX //選択中セルの列番号
/*
メイン画面の初期化処理。保存詳細画面から再開機能で遷移した場合は、保存詳細画面の内容で初期化
*/
init {
// セルを空に設定
clearGame()
}
/*
データクラスの内容でviewModelルの情報を基にUIステートに値を設定する
*/
private fun setGridDataToUiState() {
//ui state にセル情報設定用の変数
//表示するセルの中身をデータより設定
val tmpData: Array<Array<ScreenCellData>> = Array(NumbergameData.NUM_OF_ROW)
{
Array(NumbergameData.NUM_OF_COL)
{
ScreenCellData(
num = NUM_NOT_SET,
init = false,
isSelected = false,
isSameNum = false
)
}
}
//ui stateにボタン情報設定用の変数(番号毎にセルに出現している数)
val tmpBtn: Array<ScreenBtnData> = Array(NumbergameData.KIND_OF_DATA + 1) {ScreenBtnData(0)}
// 9×9の数字の配列をui state に設定する
// 選択中のセルと同じ数字の表示を変える為に選択中のセルの数字を保存
var selectedNum = NUM_NOT_SET //初期値は未設定の数字(0)
if(selectedRow != IMPOSSIBLE_IDX && selectedCol != IMPOSSIBLE_IDX){
// 選択中のセルと同じ数字の表示を変える為に選択中のセルの数字を保存
selectedNum = gridData.data[selectedRow][selectedCol].num
}
//
// ・セルを表示する情報を設定(番号、初期値、選択中、同じ番号が選択中等
// ・ボタンに表示する表示済みの数字毎の数を集計して設定
// ・未設定のセルの数を集計(ゲーム終了判定用)
for(rowIdx in 0 until NumbergameData.NUM_OF_ROW){
for(colIdx in 0 until NumbergameData.NUM_OF_COL){
//セルの設定
tmpData[rowIdx][colIdx].num = gridData.data[rowIdx][colIdx].num
tmpData[rowIdx][colIdx].init = gridData.data[rowIdx][colIdx].init
//数字ボタンの設定
tmpBtn[gridData.data[rowIdx][colIdx].num].cnt++ //ボタンに表示する、数字毎の数をインクリメント
// 選択中のセルの場合、セルに選択中のフラグをONにする
tmpData[rowIdx][colIdx].isSelected = (rowIdx == selectedRow && colIdx == selectedCol)
// 選択中のセルと同じ数字の場合(空白以外)、UIで強調表示するためフラグを設定
tmpData[rowIdx][colIdx].isSameNum = false
if(selectedNum != NUM_NOT_SET) {
if (selectedNum == gridData.data[rowIdx][colIdx].num) {
// 選択中のセルと同じ番号のセルは強調表示する為にフラグを設定
tmpData[rowIdx][colIdx].isSameNum = true
}
}
}
}
//未設定セルの数が0個の場合、ゲーム終了とする
var isGameOver = true
gridData.data.forEach {
it.forEach{cell ->
isGameOver = isGameOver && (cell.num != NUM_NOT_SET)
}
}
// 空白のセルが存在しない場合
_uiState.value = NumbergameUiState(
currentData = tmpData,
currentBtn = tmpBtn,
blankCellCnt = blankCellCnt,
isGameOver = isGameOver,
)
}
/*
画面全消去
*/
private fun clearGame(){
// 全てのセルを消す
gridData.clearAll(true)
//選択中セルの初期化
selectedCol = IMPOSSIBLE_IDX
selectedRow = IMPOSSIBLE_IDX
//描画データ再作成
setGridDataToUiState()
}
/*
新規ゲーム
*/
fun newGame(){
//正解リストより初期値を設定する
// 正解配列をランダムに選択
val satisfiedIdx: Int= (0 until SatisfiedGridArrayInit.data.size).random()
// 正解配列をランダムに並べ変える、9×9のセルに初期値設定する
val satisfiedGridData = SatisfiedGridData(SatisfiedGridArrayInit.data[satisfiedIdx])
gridData.newGame(satisfiedGridData.getRandom(), blankCellCnt)
//選択中セルの初期化
selectedCol = IMPOSSIBLE_IDX
selectedRow = IMPOSSIBLE_IDX
//描画データ再作成
setGridDataToUiState()
}
/*
9×9のセルがクリックされた時、セルを選択状態にする
*/
fun onCellClicked(rowId: Int, colId: Int){
selectedRow = rowId
selectedCol = colId
//描画データ再作成
setGridDataToUiState()
}
/*
番号のボタンが押された場合、選択中のセルに番号を設定する
*/
fun onNumberBtnClicked(number: Int){
var ret = DupErr.NOT_SELECTED //とりあえず未選択エラー状態
if((selectedRow != IMPOSSIBLE_IDX) && (selectedCol != IMPOSSIBLE_IDX)) {
// 画面で数字を入力する場所が選択されていた場合、データを設定
ret = gridData.setData(selectedRow, selectedCol, number, false)
}
// 数値が未選択 or 重複(数独のルールを逸脱)した場合toast で表示
if(DupErr.NO_DUP != ret) {
_toastUiState.value = ToastUiState(
showToast = true,
toastMsgId = ret.ordinal,
)
}
//描画データ再作成
setGridDataToUiState()
}
/*
Toast 表示後に _uiStateToast を初期値に更新
*/
fun toastShown(){
_toastUiState.value = ToastUiState()
}
/*
スライダーで新規作成時の固定セルの個数が変更されたときメンバー変数に反映する
*/
fun setBlankCellCnt(blankCnt: Int){
blankCellCnt = blankCnt
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/home/NumbergameViewModel.kt
|
1841615080
|
package io.github.s_ymb.simplenumbergame.ui.home
import io.github.s_ymb.simplenumbergame.data.NumbergameData
import io.github.s_ymb.simplenumbergame.data.ScreenBtnData
import io.github.s_ymb.simplenumbergame.data.ScreenCellData
data class NumbergameUiState(
val currentData: Array<Array<ScreenCellData>> = Array(NumbergameData.NUM_OF_ROW)
{ Array(NumbergameData.NUM_OF_COL)
{
ScreenCellData(num = NumbergameData.NUM_NOT_SET, init = false, isSelected = false, isSameNum = false)
}
},
val currentBtn: Array<ScreenBtnData> = Array(NumbergameData.KIND_OF_DATA + 1){ScreenBtnData(0)},
val isGameOver: Boolean = false,
val blankCellCnt: Int = 0,
) {
override fun hashCode(): Int {
var result = currentData.contentDeepHashCode()
result = 31 * result + currentBtn.contentHashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as NumbergameUiState
if (!currentData.contentDeepEquals(other.currentData)) return false
return currentBtn.contentEquals(other.currentBtn)
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/home/NumbergameUiState.kt
|
2101071032
|
package io.github.s_ymb.simplenumbergame.ui.home
import android.annotation.SuppressLint
import android.app.Activity
import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
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.graphics.RectangleShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import io.github.s_ymb.simplenumbergame.R
import io.github.s_ymb.simplenumbergame.data.DupErr
import io.github.s_ymb.simplenumbergame.data.NumbergameData
import io.github.s_ymb.simplenumbergame.data.ScreenBtnData
import io.github.s_ymb.simplenumbergame.data.ScreenCellData
/**
* 数独のメイン画面
*/
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun GameScreen(
gameViewModel: NumbergameViewModel = viewModel()
) {
val gameUiState by gameViewModel.uiState.collectAsState()
val toastUiState by gameViewModel.toastUiState.collectAsState()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
) {
Box(
modifier = Modifier
.background(color=Color.Blue)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
) {
// グリッド表示
NumberGridLayout(
onCellClicked = { rowId, colId -> gameViewModel.onCellClicked(rowId, colId) },
currentData = gameUiState.currentData
)
}
}
Spacer(
modifier = Modifier
.size(8.dp)
)
// 数字ボタン表示
NumBtnLayout(
onNumBtnClicked = { num: Int -> gameViewModel.onNumberBtnClicked(num) },
currentBtn = gameUiState.currentBtn,
)
Spacer(
modifier = Modifier
.size(8.dp)
)
// エラーメッセージ用のToast を表示(この画面では重複エラーのIDが設定される)
if(toastUiState.showToast) {
val toastMsg = when (toastUiState.toastMsgId){
DupErr.ROW_DUP.ordinal -> stringResource(R.string.err_btn_row_dup)
DupErr.COL_DUP.ordinal -> stringResource(R.string.err_btn_col_dup)
DupErr.SQ_DUP.ordinal -> stringResource(R.string.err_btn_sq_dup)
DupErr.FIX_DUP.ordinal -> stringResource(R.string.err_btn_fix_cell_selected)
DupErr.NOT_SELECTED.ordinal -> stringResource(R.string.err_btn_cell_not_selected)
else -> "想定外のエラー"
}
val context = LocalContext.current
val toast = Toast.makeText(context, toastMsg, Toast.LENGTH_LONG)
// TODO 設定しても下端に出るので置いておく
// toast.setGravity(Gravity.TOP, 0, 0);
toast.show()
// toast 表示済に更新
gameViewModel.toastShown()
}
// スライダーを表示
SliderLayout(
defaultPos = gameUiState.blankCellCnt.toFloat(),
onValueChangeFinished = { num: Int -> gameViewModel.setBlankCellCnt(num) },
)
// 機能ボタン表示
FunBtnLayout(
onNewGameBtnClicked = { gameViewModel.newGame() },
)
// 終了確認ダイアログを表示
if(gameUiState.isGameOver) {
FinalDialog(
onNewGameBtnClicked = { gameViewModel.newGame() },
)
}
}
}
/*
9×9の2次元グリッドを描画
*/
@Composable
fun NumberGridLayout(
onCellClicked: (Int, Int) -> Unit,
currentData: Array<Array<ScreenCellData>>,
modifier: Modifier = Modifier
) {
for ((rowIdx: Int, rowData: Array<ScreenCellData>) in currentData.withIndex()) {
Row(
verticalAlignment = Alignment.Bottom,
) {
for ((colIdx: Int, cell: ScreenCellData) in rowData.withIndex()) {
var borderWidth: Int
borderWidth = 1
var borderColor: Color = colorResource(R.color.cell_border_color_not_selected)
var textColor: Color= Color.Black
var fWeight: FontWeight = FontWeight.Light
if (cell.isSelected) {
// 選択済みのセルは表示枠を変更
borderWidth = 4
borderColor = colorResource(R.color.cell_border_color_selected)
}
if(cell.isSameNum){
// 選択済みのセルと同じ数字の場合、
// 文字を太字に設定
fWeight = FontWeight.ExtraBold
// テキストの色を設定
textColor = colorResource(R.color.cell_text_color_same_num)
// textColor = Color.Red
}
var bgColor: Color = colorResource(R.color.cell_bg_color_default)
if (cell.init) {
//初期設定されたセルの場合は背景色をグレーに
bgColor = colorResource(R.color.cell_bg_color_init)
}
var numStr: String
numStr = ""
if (cell.num != NumbergameData.NUM_NOT_SET) {
numStr = cell.num.toString()
}
val contentDesc = "${rowIdx}行${colIdx}列"
Text(
text = numStr,
color = textColor,
textAlign = TextAlign.Center,
fontSize = 30.sp,
fontWeight = fWeight,
modifier = modifier
// .padding(0.dp,)
.width(39.dp)
.height(43.dp)
// .wrapContentHeight(Alignment.CenterVertically)//.background(bgColor)
.semantics{contentDescription = contentDesc}
.border(
border = BorderStroke(
width = borderWidth.dp,
color = borderColor
),
shape = RectangleShape,
)
.background(
color = bgColor,
)
.clickable {
// クリックされたテキスト
onCellClicked(rowIdx, colIdx)
},
)
if (colIdx % 3 == 2 && colIdx != 8) {
//平方毎にスペースを開ける
Spacer(
modifier = modifier
.size(3.dp)
)
}
}
}
if (rowIdx % 3 == 2 && rowIdx != 8) {
//平方毎にスペースを開ける
Spacer(
modifier = modifier
.size(3.dp)
)
}
}
}
/*
数字入力ボタンを表示
*/
@Composable
fun NumBtnLayout(
onNumBtnClicked: (Int) -> Unit,
currentBtn: Array<ScreenBtnData>,
modifier: Modifier = Modifier,
) {
val numBtnDescPost = stringResource(R.string.desc_btn_num)
Row(
verticalAlignment = Alignment.Bottom,
modifier = modifier,
) {
//ボタンの編集可否を設定
for (btnNum in 1..5) {
// 選択中のセルの設定可否を初期設定
var btnEnabled = true
var btnTextColor = Color.White
// 数字が9個設定してある数字ボタンは使用不可
if (currentBtn[btnNum].cnt == NumbergameData.MAX_NUM_CNT) {
btnEnabled = false
btnTextColor = Color.Black
}
val numBtnDesc = btnNum.toString() + numBtnDescPost
Button(
onClick = { onNumBtnClicked(btnNum) },
enabled = btnEnabled,
modifier = Modifier.semantics{contentDescription = numBtnDesc},
) {
Text(
text = btnNum.toString(),
fontSize = 20.sp,
color = btnTextColor,
)
Text(
text = currentBtn[btnNum].cnt.toString(),
fontSize = 12.sp,
textAlign = TextAlign.End,
color = btnTextColor,
)
}
}
}
Spacer(
modifier = Modifier
.size(4.dp)
)
Row(
verticalAlignment = Alignment.Bottom,
modifier = modifier,
//.background(color= Color.Yellow)
) {
// 6~9のボタン と 削除ボタン
for (btnNum in 6..9) {
// 数字が9個設定してある数字ボタンは使用不可
var btnEnabled = true
var btnTextColor = Color.White
if (currentBtn[btnNum].cnt == NumbergameData.MAX_NUM_CNT) {
btnEnabled = false
btnTextColor = Color.Black
}
val numBtnDesc = btnNum.toString() + numBtnDescPost
Button(
onClick = { onNumBtnClicked(btnNum) },
enabled = btnEnabled,
modifier = Modifier.semantics{contentDescription = numBtnDesc},
) {
Text(
text = btnNum.toString(),
fontSize = 20.sp,
color = btnTextColor,
)
Text(
text = currentBtn[btnNum].cnt.toString(),
fontSize = 12.sp,
textAlign = TextAlign.End,
color = btnTextColor,
)
}
}
//削除ボタン
val delBtnDesc = stringResource(R.string.desc_btn_del)
Button(
onClick = { onNumBtnClicked(NumbergameData.NUM_NOT_SET) },
modifier = Modifier.semantics{contentDescription = delBtnDesc},
contentPadding = PaddingValues(
start = 6.dp,
top = 4.dp,
end = 6.dp,
bottom = 4.dp,),
) {
Text(
text = stringResource(R.string.btn_num_delete),
fontSize = 24.sp,
)
}
}
}
/*
機能ボタン(新規・終了)を表示
*/
@Composable
fun FunBtnLayout(
onNewGameBtnClicked: () -> Unit,
modifier: Modifier = Modifier,
) {
val newBtnDesc = stringResource(R.string.desc_btn_new)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier,
) {
Row(
verticalAlignment = Alignment.Top,
) {
//新規ボタン
Button(
modifier = Modifier.semantics{contentDescription = newBtnDesc},
onClick = { onNewGameBtnClicked() },
contentPadding = PaddingValues(
start = 24.dp,
top = 8.dp,
end = 24.dp,
bottom = 8.dp,),
) {
Text(
text = stringResource(R.string.btn_new),
fontSize = 24.sp,
)
}
//終了ボタン
val endBtnDesc = stringResource(R.string.desc_btn_end)
val activity = (LocalContext.current as Activity)
Button(
modifier = Modifier.semantics{contentDescription = endBtnDesc},
onClick = { activity.finish() },
contentPadding = PaddingValues(
start = 24.dp,
top = 8.dp,
end = 24.dp,
bottom = 8.dp,),
) {
Text(
text = stringResource(R.string.btn_exit),
fontSize = 24.sp,
)
}
}
}
}
/*
固定セルの個数を選択するスライダー表示
*/
@Composable
private fun SliderLayout(
defaultPos: Float,
onValueChangeFinished: (Int) -> Unit,
modifier: Modifier = Modifier,
){
var sliderPosition by remember { mutableFloatStateOf(defaultPos) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier,
) {
Slider(
value = sliderPosition,
// TODO 固定セルの初期値と設定できる範囲の検討が必要
valueRange = 30f..60f,
onValueChange = { sliderPosition = it },
onValueChangeFinished ={onValueChangeFinished(sliderPosition.toInt())},
//steps = 3,
)
val sliderTxt: String = stringResource(R.string.slider_title1) + sliderPosition.toInt().toString() + stringResource(R.string.slider_title2)
Text(
text = sliderTxt,
fontSize = 16.sp,
)
}
}
/*
* 終了確認ダイアログ(ゲーム完了時)
*/
@Composable
private fun FinalDialog(
onNewGameBtnClicked: () -> Unit,
modifier: Modifier = Modifier,
) {
val activity = (LocalContext.current as Activity)
AlertDialog(
modifier = modifier,
onDismissRequest = {
// Dismiss the dialog when the user clicks outside the dialog or on the back
// button. If you want to disable that functionality, simply use an empty
// onCloseRequest.
},
title = {
Text(
text = stringResource(R.string.congratulations),
fontSize = 24.sp,
)
},
dismissButton = {
TextButton(
onClick = {
activity.finish()
}
) {
Text(
text = stringResource(R.string.btn_exit),
fontSize = 24.sp,
)
}
},
confirmButton = {
TextButton(onClick = onNewGameBtnClicked) {
Text(
text = stringResource(R.string.btn_new),
fontSize = 24.sp,
)
}
}
)
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/home/NumbergameScreen.kt
|
725490406
|
package io.github.s_ymb.simplenumbergame.ui
data class ToastUiState(
val showToast: Boolean = false,
val toastMsgId: Int = 0,
)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/ToastUiState.kt
|
1124117723
|
package io.github.s_ymb.simplenumbergame.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)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/theme/Color.kt
|
1281807597
|
package io.github.s_ymb.simplenumbergame.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 NumbergameTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// MainActivity 本来の Theme へ差し替える
//setTheme(R.style.AppTheme)
// 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
)
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/theme/Theme.kt
|
3143490578
|
package io.github.s_ymb.simplenumbergame.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
)
*/
)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/ui/theme/Type.kt
|
320865790
|
package io.github.s_ymb.simplenumbergame
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import io.github.s_ymb.simplenumbergame.ui.home.GameScreen
import io.github.s_ymb.simplenumbergame.ui.theme.NumbergameTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
super.onCreate(savedInstanceState)
this.installSplashScreen()
setContent {
NumbergameTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GameScreen()
}
}
}
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/MainActivity.kt
|
3824507511
|
package io.github.s_ymb.simplenumbergame.data
data class ScreenBtnData(
var cnt: Int,
)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/ScreenBtnData.kt
|
4294132198
|
package io.github.s_ymb.simplenumbergame.data
/*
9×9の各セルの属性情報
*/
data class CellData (
var num: Int = 0, // 番号
var init: Boolean = false // 新規時に設定されたか
)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/CellData.kt
|
2095469943
|
package io.github.s_ymb.simplenumbergame.data
/*
画面表示用の9×9のセル1つの情報
CellData クラスにuiに表示する、
isSelected(選択中のセルは赤枠)
isSameNum(選択中のセルと同じ数字は強調表示)
の情報を追加
*/
data class ScreenCellData(
var num: Int,
var init: Boolean, //初期データか?
var isSelected : Boolean, //選択中のセルか?
var isSameNum : Boolean, //選択中のセルの数字と同じか?
)
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/ScreenCellData.kt
|
3383070838
|
package io.github.s_ymb.simplenumbergame.data
open class NumbergameData {
companion object {
const val NUM_NOT_SET: Int = 0 //未設定セルは0で表現
const val NUM_OF_COL: Int = 9 // 全体で9行
const val NUM_OF_ROW: Int = 9 // 全体で9列
const val SQR_SIZE: Int = 3 // 平方領域は3×3マス
const val KIND_OF_DATA: Int = 9 // マスに入る数値は1~9(0は未設定扱い)
const val MAX_NUM_CNT: Int = 9 // 各数字は全体で9個まで
const val IMPOSSIBLE_IDX = -1 //ありえないインデックス値 ここで定義すべきではないが…
}
/*
コピーのデータ配列に指定された位置、値が設定できるかチェックする
*/
protected fun checkData(targetData: Array<Array<Int>>, row: Int, col: Int, newNum: Int): DupErr {
val copyData: Array<Array<Int>> = Array(NUM_OF_ROW) { Array(NUM_OF_COL) { 0 } }
for (rowIdx in 0 until NUM_OF_ROW) {
for (colIdx in 0 until NUM_OF_COL) {
copyData[rowIdx][colIdx] = targetData[rowIdx][colIdx]
}
}
// 今回セットする位置に値を設定してみて重複チェックを行う
copyData[row][col] = newNum
// 行重複チェック(変更対象のエリアのみチェック)
if (!rowCheck(copyData, row)) {
return DupErr.ROW_DUP
}
// 列重複チェック(変更対象のエリアのみチェック)
if (!colCheck(copyData, col)) {
return DupErr.COL_DUP
}
// 平方重複チェック(変更対象のエリアのみチェック)
if (!sqrCheck(copyData, row, col)) {
return DupErr.SQ_DUP
}
return DupErr.NO_DUP
}
/*
行重複チェック
*/
private fun rowCheck(checkGrid: Array<Array<Int>>, checkRowIdx: Int): Boolean {
val oneRow = Array(NUM_OF_COL) { NUM_NOT_SET } // 1行分のデータ配列
// チェック対象行の値を取得
for (colIdx in 0 until NUM_OF_COL) {
oneRow[colIdx] = checkGrid[checkRowIdx][colIdx]
}
// 重複チェック
return dupCheck(oneRow)
}
/*
列重複チェック
*/
private fun colCheck(checkGrid: Array<Array<Int>>, checkColIdx: Int): Boolean {
val oneCol = Array(NUM_OF_ROW) { 0 } // 1列分のデータ配列
// チェック対象列の値を取得
for (rowIdx in 0 until NUM_OF_COL) {
oneCol[rowIdx] = checkGrid[rowIdx][checkColIdx]
}
// 重複チェック
return dupCheck(oneCol)
}
/*
平方重複チェック
*/
private fun sqrCheck(
checkGrid: Array<Array<Int>>,
checkRowIdx: Int,
checkColIdx: Int
): Boolean {
val sqrStartRow: Int = (checkRowIdx / SQR_SIZE) * SQR_SIZE //平方の左上のセルの行番号
val sqrStartCol: Int = (checkColIdx / SQR_SIZE) * SQR_SIZE //平方の左上のセルの列番号
val oneSqr = Array(SQR_SIZE * SQR_SIZE) { 0 } //平方内のデータ配列
// チェック対象 平方内の値を取得
for(rowIdx in 0 until SQR_SIZE){
for(colIdx in 0 until SQR_SIZE) {
oneSqr[rowIdx * SQR_SIZE + colIdx] = checkGrid[sqrStartRow + rowIdx][sqrStartCol + colIdx]
}
}
// 重複チェック
return dupCheck(oneSqr)
}
/*
各ブロック要素に0以外で同じ数字が存在するかチェック
*/
private fun dupCheck(checkArray: Array<Int>): Boolean {
//数値は”なし”で初期化
val isExist = BooleanArray(KIND_OF_DATA + 1) { false } //NUM_NOT_SET も種類の1つなので+1
// 各行に0以外で同じ数字が存在するかチェック
for (num in checkArray) {
if (isExist[num]) {
// num番目の要素はすでに存在していて、未設定値との比較以外では重複と判定
if (num != NUM_NOT_SET) {
return false
}
}
// num番目の配列は存在する
isExist[num] = true
}
//重複なし
return true
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/NumbergameData.kt
|
1856940370
|
package io.github.s_ymb.simplenumbergame.data
class SatisfiedGridArrayInit {
companion object{
val data = arrayOf(
arrayOf(
intArrayOf(1,2,4,6,3,7,8,9,5),
intArrayOf(5,7,3,2,8,9,6,4,1),
intArrayOf(9,6,8,4,1,5,3,2,7),
intArrayOf(2,8,5,1,7,6,4,3,9),
intArrayOf(4,9,1,8,5,3,7,6,2),
intArrayOf(7,3,6,9,2,4,1,5,8),
intArrayOf(6,5,2,7,4,8,9,1,3),
intArrayOf(3,4,7,5,9,1,2,8,6),
intArrayOf(8,1,9,3,6,2,5,7,4)
),
arrayOf(
intArrayOf(1,8,3,6,4,5,7,2,9),
intArrayOf(5,6,4,9,2,7,1,8,3),
intArrayOf(9,7,2,3,1,8,4,5,6),
intArrayOf(8,2,7,4,5,9,6,3,1),
intArrayOf(3,9,5,1,7,6,2,4,8),
intArrayOf(4,1,6,2,8,3,9,7,5),
intArrayOf(7,4,9,8,3,1,5,6,2),
intArrayOf(2,3,1,5,6,4,8,9,7),
intArrayOf(6,5,8,7,9,2,3,1,4)
),
arrayOf(
intArrayOf(4,1,9,6,8,3,7,2,5),
intArrayOf(2,7,6,5,9,4,1,8,3),
intArrayOf(8,3,5,2,1,7,6,9,4),
intArrayOf(1,4,3,9,6,2,8,5,7),
intArrayOf(6,9,8,7,5,1,3,4,2),
intArrayOf(5,2,7,4,3,8,9,1,6),
intArrayOf(9,6,2,8,7,5,4,3,1),
intArrayOf(7,5,1,3,4,9,2,6,8),
intArrayOf(3,8,4,1,2,6,5,7,9)
),
arrayOf(
intArrayOf(4,5,1,3,6,8,7,2,9),
intArrayOf(2,9,8,4,1,7,5,6,3),
intArrayOf(3,6,7,5,2,9,1,4,8),
intArrayOf(6,1,2,7,3,5,8,9,4),
intArrayOf(8,3,4,6,9,1,2,7,5),
intArrayOf(9,7,5,8,4,2,3,1,6),
intArrayOf(5,2,9,1,8,4,6,3,7),
intArrayOf(7,4,6,2,5,3,9,8,1),
intArrayOf(1,8,3,9,7,6,4,5,2)
),
arrayOf(
intArrayOf(6,2,1,7,4,3,5,9,8),
intArrayOf(7,3,9,5,8,6,1,4,2),
intArrayOf(4,5,8,9,1,2,3,6,7),
intArrayOf(3,6,5,1,2,7,9,8,4),
intArrayOf(9,8,4,3,6,5,7,2,1),
intArrayOf(1,7,2,8,9,4,6,3,5),
intArrayOf(5,4,7,6,3,8,2,1,9),
intArrayOf(8,9,6,2,7,1,4,5,3),
intArrayOf(2,1,3,4,5,9,8,7,6)
),
arrayOf(
intArrayOf(7,4,2,8,3,9,1,5,6),
intArrayOf(3,8,1,4,5,6,7,9,2),
intArrayOf(5,9,6,1,2,7,8,4,3),
intArrayOf(4,6,8,3,9,1,2,7,5),
intArrayOf(9,7,3,5,8,2,6,1,4),
intArrayOf(1,2,5,7,6,4,3,8,9),
intArrayOf(8,3,9,6,1,5,4,2,7),
intArrayOf(6,5,7,2,4,8,9,3,1),
intArrayOf(2,1,4,9,7,3,5,6,8),
),
arrayOf(
intArrayOf(7,8,2,9,3,4,1,5,6),
intArrayOf(3,4,1,8,5,6,2,7,9),
intArrayOf(5,9,6,1,2,7,8,4,3),
intArrayOf(4,2,8,3,7,1,6,9,5),
intArrayOf(9,6,3,5,8,2,4,1,7),
intArrayOf(1,7,5,4,6,9,3,8,2),
intArrayOf(8,3,9,6,1,5,7,2,4),
intArrayOf(6,5,7,2,4,8,9,3,1),
intArrayOf(2,1,4,7,9,3,5,6,8),
),
arrayOf(
intArrayOf(8,6,5,3,9,4,7,2,1),
intArrayOf(7,1,2,5,8,6,3,4,9),
intArrayOf(3,4,9,7,2,1,5,6,8),
intArrayOf(1,5,6,9,4,7,8,3,2),
intArrayOf(9,8,4,2,3,5,1,7,6),
intArrayOf(2,3,7,6,1,8,9,5,4),
intArrayOf(4,9,3,1,7,2,6,8,5),
intArrayOf(5,2,1,8,6,3,4,9,7),
intArrayOf(6,7,8,4,5,9,2,1,3),
),
arrayOf(
intArrayOf(9,5,7,4,6,3,1,8,2),
intArrayOf(3,6,2,5,1,8,7,4,9),
intArrayOf(1,8,4,2,7,9,6,3,5),
intArrayOf(5,7,8,3,9,4,2,1,6),
intArrayOf(6,2,3,1,8,7,9,5,4),
intArrayOf(4,9,1,6,2,5,3,7,8),
intArrayOf(2,3,6,8,4,1,5,9,7),
intArrayOf(8,1,9,7,5,2,4,6,3),
intArrayOf(7,4,5,9,3,6,8,2,1),
),
arrayOf(
intArrayOf(9,7,8,3,5,1,6,2,4),
intArrayOf(4,1,3,2,7,6,5,8,9),
intArrayOf(2,6,5,9,4,8,7,1,3),
intArrayOf(7,3,4,5,1,9,2,6,8),
intArrayOf(8,9,6,7,3,2,1,4,5),
intArrayOf(5,2,1,6,8,4,9,3,7),
intArrayOf(6,4,2,8,9,7,3,5,1),
intArrayOf(1,5,9,4,2,3,8,7,6),
intArrayOf(3,8,7,1,6,5,4,9,2),
)
)
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/SatisfiedGridArrayInit.kt
|
1848187004
|
package io.github.s_ymb.simplenumbergame.data
/*
コンストラクタで渡された数独の正解配列をランダムに 行・列 入替するクラス
*/
class SatisfiedGridData (satisfiedArray: Array<IntArray> = Array(NUM_OF_ROW){
IntArray(NUM_OF_COL){
NUM_NOT_SET
}
}): NumbergameData(){
private val satisfied = satisfiedArray
/*
データ入替の種類
*/
enum class RotateType{
LINE_ROTATE, //行入替
AREA_ROTATE, //9×9のエリア入替
}
enum class RotateDirection{
ROW, // 行入替
COL // 列入替
}
enum class RotatePattern{
PATTERN_12, // 1行(列)と2行(列)を入替
PATTERN_13, // 1行(列)と3行(列)を入替
PATTERN_23 // 2行(列)と3行(列)を入替
}
enum class RotateArea {
START, // 行入替の場合、最上段のエリア、列入替の場合、左端のエリア
MIDDLE, // 真ん中のエリア
END // 行入替の場合、最下段のエリア、列入替の場合、右端のエリア
}
/*
行・列入替のパターンをランダムに選択し、コンストラクタで受け取った数列を
行 or 列 入替した数列を戻す
*/
fun getRandom() : Array<IntArray> {
// 入れ替えるパターンをランダムに選択
val rotateType = (RotateType.entries.toTypedArray()).random().ordinal
val rotateDirection = (RotateDirection.entries.toTypedArray()).random().ordinal
val rotateArea = (RotateArea.entries.toTypedArray()).random().ordinal
val rotatePattern = (RotatePattern.entries.toTypedArray()).random().ordinal
val offset: Array<IntArray> = getOffset(
type = rotateType,
direction = rotateDirection,
pattern = rotatePattern,
area = rotateArea
)
// 1~9のランダムな順列を生成
val seedArray = (1..KIND_OF_DATA).shuffled()
// 正解リストの値を生成する数字のIndex番号として入替パターンのオフセット分ずらした位置に配置する
val retArray: Array<IntArray> = Array(NUM_OF_ROW) { IntArray(NUM_OF_COL) { NUM_NOT_SET } }
for (rowIdx in 0 until NUM_OF_ROW) {
for (colIdx in 0 until NUM_OF_COL) {
if (rotateDirection == RotateDirection.ROW.ordinal) {
// 行入替パターンの場合、設定元の行番号をオフセット分ずらした値を設定する
retArray[rowIdx][colIdx] =
seedArray[satisfied[rowIdx + offset[rowIdx][colIdx]][colIdx] - 1] // 配列は0オリジンなので1ずらす
} else {
// 列入替パターンの場合、設定元の列番号をオフセット分ずらした値を設定する
retArray[rowIdx][colIdx] =
seedArray[satisfied[rowIdx][colIdx + offset[rowIdx][colIdx]] - 1] // 配列は0オリジンなので1ずらす
}
}
}
return retArray
}
/*
行・列 入替のパターン毎に移動させる距離をオフセット配列に設定していく
例.1 例2.
1行目と2行目を入れ替えたい場合 中央のブロックと右側のブロックを入れ替えたい場合
1 1 1 1 1 1 1 1 1 0 0 0 3 3 3 -3 -3 -3
-1 -1 -1 -1 -1 -1 -1 -1 -1 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 -3 -3 -3
*/
private fun getOffset(type: Int, direction: Int, pattern: Int,area: Int): Array<IntArray> {
val retOffset =
Array(NUM_OF_ROW) { IntArray(NUM_OF_COL) { NUM_NOT_SET } }
if (type == RotateType.LINE_ROTATE.ordinal) {
// 行 or 列 入替の場合
if (direction == RotateDirection.ROW.ordinal) {
//行入替の場合
//マスクのパターンを取得
val maskOffset = getRowMask(pattern = pattern)
//指定エリアにマスクパターンを反映する
val areaStartRow = SQR_SIZE * area
for (maskIdx in 0 until SQR_SIZE) {
for (colIdx in 0 until NUM_OF_COL) {
retOffset[areaStartRow + maskIdx][colIdx] = maskOffset[maskIdx][colIdx]
}
}
} else if (direction == RotateDirection.COL.ordinal) {
//列入替の場合
// マスクのパターンを取得
val maskOffset = getColMask(pattern = pattern)
//指定エリアにマスクパターンを反映する
val areaStartCol = SQR_SIZE * area
for (maskIdx in 0 until SQR_SIZE) {
for (rowIdx in 0 until NUM_OF_ROW) {
retOffset[rowIdx][areaStartCol + maskIdx] = maskOffset[rowIdx][maskIdx]
}
}
}
} else if (type == RotateType.AREA_ROTATE.ordinal) {
var swapFrom = 0
var swapTo = 0
// エリア入替の場合(マスクパターン毎に、ここでセット)
when (pattern) {
RotatePattern.PATTERN_12.ordinal
-> {
// 最初エリアと途中エリアを入れ替える
swapFrom = RotateArea.START.ordinal
swapTo = RotateArea.MIDDLE.ordinal
}
RotatePattern.PATTERN_13.ordinal
-> {
// 最初エリアと最終エリアを入れ替える
swapFrom = RotateArea.START.ordinal
swapTo = RotateArea.END.ordinal
}
RotatePattern.PATTERN_23.ordinal
-> {
// 途中のエリアと最終のエリアを入れ替える
swapFrom = RotateArea.MIDDLE.ordinal
swapTo = RotateArea.END.ordinal
}
}
// 入替元の先頭位置と移動距離を設定
val startIndexFrom = SQR_SIZE * swapFrom
val startIndexTo = SQR_SIZE * swapTo
val distance = SQR_SIZE * (swapTo - swapFrom)
if (direction == RotateDirection.ROW.ordinal) {
// エリアの行入替の場合
//入替元に設定するマスク
for (rowIdx in startIndexFrom until startIndexFrom + SQR_SIZE) {
for (colIdx in 0 until NUM_OF_COL) {
retOffset[rowIdx][colIdx] = distance
}
}
// 入替先に設定するマスク
for (rowIdx in startIndexTo until startIndexTo + SQR_SIZE) {
for (colIdx in 0 until NUM_OF_COL) {
retOffset[rowIdx][colIdx] = -distance
}
}
} else if (direction == RotateDirection.COL.ordinal) {
// エリアの列入替の場合
for (colIdx in startIndexFrom until startIndexFrom + SQR_SIZE) {
for (rowIdx in 0 until NUM_OF_ROW) {
retOffset[rowIdx][colIdx] = distance
}
}
for (colIdx in startIndexTo until startIndexTo + SQR_SIZE) {
for (rowIdx in 0 until NUM_OF_ROW) {
retOffset[rowIdx][colIdx] = -distance
}
}
}
}
return retOffset
}
/*
行入替の場合の移動パターンの配列を作成する
*/
private fun getRowMask(pattern: Int): Array<IntArray>{
// 1エリア分の行数のマスク
val retMask = Array(SQR_SIZE){IntArray(NUM_OF_COL){NUM_NOT_SET}}
when(pattern) {
RotatePattern.PATTERN_12.ordinal -> {
// 1行目と2行目の入替の場合、1行目([0])に+1を2行目([1])にー1を設定
for (colIdx in 0 until NUM_OF_COL) {
retMask[0][colIdx] = 1
retMask[1][colIdx] = -1
}
}
RotatePattern.PATTERN_13.ordinal -> {
// 1行目と3行目の入替の場合、1行目([0])に+2を3行目([2])に-2を設定
for (colIdx in 0 until NUM_OF_COL) {
retMask[0][colIdx] = 2
retMask[2][colIdx] = -2
}
}
RotatePattern.PATTERN_23.ordinal -> {
// 2行目と3行目の入替の場合、2行目([1])に+1を3行目([2])に-1を設定
for (colIdx in 0 until NUM_OF_COL) {
retMask[1][colIdx] = 1
retMask[2][colIdx] = -1
}
}
}
return retMask
}
/*
列入替の場合の移動パターンの配列を作成する
*/
private fun getColMask(pattern: Int): Array<IntArray> {
val retMask = Array(NUM_OF_ROW){IntArray(SQR_SIZE){NUM_NOT_SET}}
when(pattern) {
RotatePattern.PATTERN_12.ordinal -> {
// 1列目と2列目の入替の場合、1列目([0])に+1を2列目([1])にー1を設定
for (rowIdx in 0 until NUM_OF_ROW) {
retMask[rowIdx][0] = 1
retMask[rowIdx][1] = -1
}
}
RotatePattern.PATTERN_13.ordinal -> {
// 1列目と3列目の入替の場合、1列目([0])に+2を3行列([2])に-2を設定
for (rowIdx in 0 until NUM_OF_ROW) {
retMask[rowIdx][0] = 2
retMask[rowIdx][2] = -2
}
}
RotatePattern.PATTERN_23.ordinal -> {
// 2列目と3列目の入替の場合、2列目([1])に+1を3列目([2])に-1を設定
for (rowIdx in 0 until NUM_OF_ROW) {
retMask[rowIdx][1]= 1
retMask[rowIdx][2] = -1
}
}
}
return retMask
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/SatisfiedGridData.kt
|
4180479228
|
package io.github.s_ymb.simplenumbergame.data
import io.github.s_ymb.simplenumbergame.data.DupErr.NO_DUP
import kotlin.random.Random
/*
9×9のセルを表現するクラス(操作も含む)
基底クラス(NumbergameDataは課題で設定された初期データという概念はない)
*/
class GridData(
val data: Array<Array<CellData>> = Array(NUM_OF_ROW) { Array(NUM_OF_COL) { CellData(0, false) } }
) : NumbergameData() {
/*
データの指定位置に指定データが設定可能か判定して可能な場合、値を設定する
同じ数字が範囲内に重複する場合、範囲に応じたエラーを返す。
*/
fun setData(row: Int, col: Int, newNum: Int, isInit: Boolean): DupErr {
if(data[row][col].init){
return DupErr.FIX_DUP //課題として表示された列が指定されたら即エラーリターン
}
// いままでに設定されている値を単なる数値の2次元配列にコピー
val tmp: Array<Array<Int>> = Array(NUM_OF_ROW) { Array(NUM_OF_COL) { 0 } }
for ((rowIdx, colArray) in data.withIndex()) {
for ((colIdx, cell) in colArray.withIndex()) {
tmp[rowIdx][colIdx] = cell.num
}
}
// コピーした配列がNumbergameのルールに沿っているかチェックする
// チェックロジックは継承元のNumbergameDataにて実装
val dataCheckResult: DupErr = checkData(tmp, row, col, newNum)
if (NO_DUP == dataCheckResult) {
//チェックOKの場合、データに反映する。
data[row][col].num = newNum
data[row][col].init = isInit
}
return dataCheckResult
}
/*
新規ゲームデータの作成
入力の課題配列(satisfiedArray)より
指定個数の数字(fixCellSelected)を
メンバ変数のdataに課題として設定する
*/
fun newGame(satisfiedArray: Array<IntArray>, blankCellSelected: Int) {
// データ全消去
clearAll(true)
// ランダムに指定個数データを設定
val fixCellSelected = NUM_OF_COL * NUM_OF_ROW - blankCellSelected
var fixCelCnt = 0
while (fixCelCnt <= fixCellSelected) {
val seedRow = Random.nextInt(NUM_OF_ROW)
val seedCol = Random.nextInt(NUM_OF_COL)
// 初期データが設定されているデータ以外の場合(偶然同じセルがランダムに選択されないように)
if (!data[seedRow][seedCol].init) {
//引数の課題配列をメンバ変数のdataに設定する
data[seedRow][seedCol].num = satisfiedArray[seedRow][seedCol]
data[seedRow][seedCol].init = true
fixCelCnt++
}
}
}
/*
全てのデータを初期化
引数:withFixCell true:全てのデータ、false:新規ゲームで設定されたデータ以外
*/
fun clearAll (withFixCell: Boolean) {
for ((rowIdx, colArray) in data.withIndex()) {
for ((colIdx) in colArray.withIndex()) {
// 全データクリアの場合もしくは初期列以外の場合
if((withFixCell) || !data[rowIdx][colIdx].init) {
// データを初期化
data[rowIdx][colIdx].num = NUM_NOT_SET
data[rowIdx][colIdx].init = false
}
}
}
}
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/GridData.kt
|
1031253527
|
package io.github.s_ymb.simplenumbergame.data
enum class DupErr {
NO_DUP, //重複なし
ROW_DUP, //行で重複
COL_DUP, //列で重複
SQ_DUP, //四角いエリアで重複
FIX_DUP, //初期値なので変更不可
NOT_SELECTED, //そもそも入力場所が選択されていない
}
|
simpleNumberGame/app/src/main/java/io/github/s_ymb/simplenumbergame/data/DupErr.kt
|
155775530
|
package com.justme.snapnews
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.justme.snapnews", appContext.packageName)
}
}
|
SnapNews/app/src/androidTest/java/com/justme/snapnews/ExampleInstrumentedTest.kt
|
4251751293
|
package com.justme.snapnews
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)
}
}
|
SnapNews/app/src/test/java/com/justme/snapnews/ExampleUnitTest.kt
|
4018563764
|
package com.justme.snapnews.ui
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.justme.snapnews.R
import com.justme.snapnews.ui.fragments.BookmarksFragment
import com.justme.snapnews.ui.fragments.DashboardFragment
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class MainActivity : AppCompatActivity() {
private lateinit var imgHistoryIcon: ImageView
private lateinit var txtNameOfApp: TextView
private lateinit var imgBookmarkMainAc: ImageView
private lateinit var flFrame: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPreferences = getSharedPreferences("snapnewsCache", Context.MODE_PRIVATE)
setContentView(R.layout.activity_main)
onBackPressedDispatcher.addCallback(this@MainActivity, onBackPressedCallback)
val sfm = supportFragmentManager
imgHistoryIcon = findViewById(R.id.imgHistoryIcon)
txtNameOfApp = findViewById(R.id.txtNameOfApp)
imgBookmarkMainAc = findViewById(R.id.imgBookmarkMainAc)
flFrame = findViewById(R.id.flFrame)
sharedPreferences.edit().putString("openedAt", getCurrentTime()).apply()
fragmentView(sfm, DashboardFragment())
// imgHistoryIcon.setOnClickListener {
// fragmentView(sfm, HistoryFragment())
// }
txtNameOfApp.setOnClickListener {
fragmentView(sfm, DashboardFragment())
}
imgBookmarkMainAc.setOnClickListener {
fragmentView(sfm, BookmarksFragment())
}
}
override fun onDestroy() {
super.onDestroy()
val sharedPreferences = getSharedPreferences("snapnewsCache", Context.MODE_PRIVATE)
sharedPreferences.edit().putString("lastOpenedAt", getCurrentTime()).apply()
}
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val frag = supportFragmentManager.findFragmentById(R.id.flFrame)
if (frag !is DashboardFragment) fragmentView(
supportFragmentManager,
DashboardFragment()
)
else finish()
}
}
private fun fragmentView(sfm: FragmentManager, fragment: Fragment) {
sfm.beginTransaction().replace(R.id.flFrame, fragment).commit()
}
private fun getCurrentTime(): String {
val currentTime = Date()
val formatter =
SimpleDateFormat("HH:mm", Locale.getDefault()) // Customize the format as needed
return formatter.format(currentTime)
}
}
|
SnapNews/app/src/main/java/com/justme/snapnews/ui/MainActivity.kt
|
1177554678
|
package com.justme.snapnews.ui.fragments
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.justme.snapnews.R
import com.justme.snapnews.data.db.bookmarksdb.BookmarkDAO
import com.justme.snapnews.data.db.bookmarksdb.BookmarkDB
import com.justme.snapnews.data.db.bookmarksdb.BookmarkEntity
import com.justme.snapnews.ui.adapters.BookmarkRecyclerAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class BookmarksFragment : Fragment() {
private lateinit var rlBookmarks : RelativeLayout
private lateinit var txtBookmark : TextView
private lateinit var rvBookmarks : RecyclerView
private lateinit var pbBookmarks : ProgressBar
private lateinit var layoutManager: LinearLayoutManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_bookmarks, container, false)
rlBookmarks = view.findViewById(R.id.rlBookmarks)
txtBookmark = view.findViewById(R.id.txtBookmark)
rvBookmarks = view.findViewById(R.id.rvBookmarks)
pbBookmarks = view.findViewById(R.id.pbBookmarks)
val db = Room.databaseBuilder(activity as Context, BookmarkDB::class.java, "bookmarks").build()
val dao = db.bookmarkDAO()
val articles : MutableList<BookmarkEntity>
runBlocking { articles = retrieveBookmarks(dao) }
if (articles.isNotEmpty()){
pbBookmarks.visibility = View.GONE
rlBookmarks.visibility = View.VISIBLE
layoutManager = LinearLayoutManager(activity as Context)
rvBookmarks.layoutManager = layoutManager
rvBookmarks.adapter = BookmarkRecyclerAdapter(activity as Context, articles)
}
return view
}
private suspend fun retrieveBookmarks(dao : BookmarkDAO) : MutableList<BookmarkEntity>{
return withContext(Dispatchers.IO) {
return@withContext dao.getAllBookmarks()
}
}
}
|
SnapNews/app/src/main/java/com/justme/snapnews/ui/fragments/BookmarksFragment.kt
|
2517597858
|
package com.justme.snapnews.ui.fragments
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.HorizontalScrollView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.justme.snapnews.R
import com.justme.snapnews.data.db.cachedarticlesdb.CachedArticlesDB
import com.justme.snapnews.data.db.cachedarticlesdb.CachedArticlesDao
import com.justme.snapnews.data.models.NewsItem
import com.justme.snapnews.ui.adapters.DashboardRecyclerAdapter
import com.justme.snapnews.util.URL
import com.justme.snapnews.util.isConnectedToInternet
import java.time.LocalTime
import java.time.temporal.ChronoUnit
import java.util.Locale
class DashboardFragment : Fragment() {
private lateinit var rlDashboard: RelativeLayout
private lateinit var rvDashboard: RecyclerView
private lateinit var pbDashboard: ProgressBar
private lateinit var hsvFilterButtons: HorizontalScrollView
private lateinit var btnFilterTechnology: Button
private lateinit var btnFilterBusiness: Button
private lateinit var btnFilterScience: Button
private lateinit var btnFilterCrime: Button
private lateinit var btnFilterDomestic: Button
private lateinit var btnFilterEducation: Button
private lateinit var btnFilterEntertainment: Button
private lateinit var btnFilterEnvironment: Button
private lateinit var btnFilterFood: Button
private lateinit var btnFilterHealth: Button
private lateinit var btnFilterOther: Button
private lateinit var btnFilterPolitics: Button
private lateinit var btnFilterSports: Button
private lateinit var btnFilterTourism: Button
private lateinit var btnFilterWorld: Button
private lateinit var rvTopNews: RecyclerView
private lateinit var pbEntireDashboard: ProgressBar
private lateinit var txtTopTen: TextView
private lateinit var layoutManager: LinearLayoutManager
private val tag = "DashboardFragment"
private var futureArticles = mutableListOf<NewsItem>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_dashboard, container, false)
val sharedPreferences =
requireContext().getSharedPreferences("snapnewsCache", Context.MODE_PRIVATE)
rlDashboard = view.findViewById(R.id.rlDashboard)
rvDashboard = view.findViewById(R.id.rvDashboard)
pbDashboard = view.findViewById(R.id.pbDashboard)
hsvFilterButtons = view.findViewById(R.id.hsvFilterButtons)
btnFilterTechnology = view.findViewById(R.id.btnFilterTechnology)
btnFilterBusiness = view.findViewById(R.id.btnFilterBusiness)
btnFilterScience = view.findViewById(R.id.btnFilterScience)
btnFilterCrime = view.findViewById(R.id.btnFilterCrime)
btnFilterDomestic = view.findViewById(R.id.btnFilterDomestic)
btnFilterEducation = view.findViewById(R.id.btnFilterEducation)
btnFilterEntertainment = view.findViewById(R.id.btnFilterEntertainment)
btnFilterEnvironment = view.findViewById(R.id.btnFilterEnvironment)
btnFilterFood = view.findViewById(R.id.btnFilterFood)
btnFilterHealth = view.findViewById(R.id.btnFilterHealth)
btnFilterOther = view.findViewById(R.id.btnFilterOther)
btnFilterPolitics = view.findViewById(R.id.btnFilterPolitics)
btnFilterSports = view.findViewById(R.id.btnFilterSports)
btnFilterTourism = view.findViewById(R.id.btnFilterTourism)
btnFilterWorld = view.findViewById(R.id.btnFilterWorld)
rvTopNews = view.findViewById(R.id.rvTopNews)
pbEntireDashboard = view.findViewById(R.id.pbEntireDashboard)
txtTopTen = view.findViewById(R.id.txtTopNews)
layoutManager = LinearLayoutManager(activity as Context)
rvDashboard.layoutManager = layoutManager
layoutManager = LinearLayoutManager(activity as Context)
rvTopNews.layoutManager = layoutManager
hsvFilterButtons.isHorizontalScrollBarEnabled = false
val lastOpenedAt = sharedPreferences.getString("lastOpenedAt", "00:00") ?: "00:00"
val curTime = sharedPreferences.getString("openedAt", "00:00") ?: "00:00"
val timeCheck = isTimeDifferenceOneHourOrMore(lastOpenedAt, curTime)
val queue = Volley.newRequestQueue(activity as Context)
var selectedBtn = btnFilterTechnology
val db = Room.databaseBuilder(
activity as Context,
CachedArticlesDB::class.java,
"cached-article"
).build()
val dao = db.cachedArticlesDao()
addToQueue("top", queue, rvTopNews)
// backgroundDBOperations("top", dao)
selectedBtn = btnClick(btnFilterTechnology, selectedBtn, dao, queue, timeCheck)
btnFilterTechnology.setOnClickListener {
selectedBtn = btnClick(btnFilterTechnology, selectedBtn, dao, queue, timeCheck)
}
btnFilterBusiness.setOnClickListener {
selectedBtn = btnClick(btnFilterBusiness, selectedBtn, dao, queue, timeCheck)
}
btnFilterCrime.setOnClickListener {
selectedBtn = btnClick(btnFilterCrime, selectedBtn, dao, queue, timeCheck)
}
btnFilterDomestic.setOnClickListener {
selectedBtn = btnClick(btnFilterDomestic, selectedBtn, dao, queue, timeCheck)
}
btnFilterEntertainment.setOnClickListener {
selectedBtn = btnClick(btnFilterEntertainment, selectedBtn, dao, queue, timeCheck)
}
btnFilterEducation.setOnClickListener {
selectedBtn = btnClick(btnFilterEducation, selectedBtn, dao, queue, timeCheck)
}
btnFilterEnvironment.setOnClickListener {
selectedBtn = btnClick(btnFilterEnvironment, selectedBtn, dao, queue, timeCheck)
}
btnFilterFood.setOnClickListener {
selectedBtn = btnClick(btnFilterFood, selectedBtn, dao, queue, timeCheck)
}
btnFilterHealth.setOnClickListener {
selectedBtn = btnClick(btnFilterHealth, selectedBtn, dao, queue, timeCheck)
}
btnFilterOther.setOnClickListener {
selectedBtn = btnClick(btnFilterOther, selectedBtn, dao, queue, timeCheck)
}
btnFilterPolitics.setOnClickListener {
selectedBtn = btnClick(btnFilterPolitics, selectedBtn, dao, queue, timeCheck)
}
btnFilterSports.setOnClickListener {
selectedBtn = btnClick(btnFilterSports, selectedBtn, dao, queue, timeCheck)
}
btnFilterTourism.setOnClickListener {
selectedBtn = btnClick(btnFilterTourism, selectedBtn, dao, queue, timeCheck)
}
btnFilterWorld.setOnClickListener {
selectedBtn = btnClick(btnFilterWorld, selectedBtn, dao, queue, timeCheck)
}
btnFilterScience.setOnClickListener {
selectedBtn = btnClick(btnFilterScience, selectedBtn, dao, queue, timeCheck)
}
return view
}
private fun isTimeDifferenceOneHourOrMore(time1: String, time2: String): Boolean {
val formatter = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
val parsedTime1 = LocalTime.parse(time1, formatter)
val parsedTime2 = LocalTime.parse(time2, formatter)
val minutesBetween = ChronoUnit.MINUTES.between(parsedTime1, parsedTime2)
return minutesBetween >= 60
}
private fun buttonHandler(
btn: Button,
selectedFilterBtn: Button,
queue: RequestQueue,
category: String
) {
if (selectedFilterBtn != btn) changeColorOfBtn(selectedFilterBtn, true)
changeColorOfBtn(btn, false)
addToQueue(category, queue, rvDashboard)
}
private fun addToQueue(
category: String,
queue: RequestQueue,
recycler: RecyclerView
) { // TODO : rewrite this function so that the adapter initialization can happen in the click listener
var url = URL
url += "&category=$category"
if (category == "domestic") url += "&country=in"
val newsArticles: MutableList<NewsItem> = mutableListOf()
if (isConnectedToInternet(activity as Context)) {
try {
val jsonObjectRequest = object :
JsonObjectRequest(Method.GET, url, null, Response.Listener { jsonObj ->
if (jsonObj.getString("status") == "success") {
if (category == "top") {
pbEntireDashboard.visibility = View.GONE
rvTopNews.visibility = View.VISIBLE
} else {
pbDashboard.visibility = View.GONE
rvDashboard.visibility = View.VISIBLE
hsvFilterButtons.visibility = View.VISIBLE
txtTopTen.visibility = View.VISIBLE
}
val articles = jsonObj.getJSONArray("results")
for (i in 0 until articles.length()) {
val article = articles.getJSONObject(i)
val newsItem = NewsItem(
article_id = article.getString("article_id"),
content = article.getString("content"),
link = article.getString("link"),
title = article.getString("title"),
category = category,
country = article.getJSONArray("country").getString(0),
description = article.getString("description"),
image_url = article.getString("image_url"),
source_id = article.getString("source_id"),
isBookmarked = false
)
newsArticles.add(newsItem)
}
futureArticles = newsArticles
recycler.adapter =
DashboardRecyclerAdapter(activity as Context, newsArticles)
} else {
Toast.makeText(
activity as Context,
"News can't be fetched. Try again later",
Toast.LENGTH_SHORT
).show()
Log.e(tag, "success status code not received.")
}
}, Response.ErrorListener {
Toast.makeText(
activity as Context,
"News can't be fetched. Try again later",
Toast.LENGTH_SHORT
).show()
Log.e(tag, "response error listener", it.cause)
}) {}
println("Here")
queue.add(jsonObjectRequest)
println("Now")
} catch (e: Exception) {
Toast.makeText(
activity as Context,
"Parse Error",
Toast.LENGTH_SHORT
).show()
Log.e(tag, "Json parse error probs", e.cause)
}
} else {
val dialog = AlertDialog.Builder(activity as Context)
dialog.setTitle("Error!")
dialog.setMessage("Internet Connection not Found!")
dialog.setPositiveButton("Open Settings") { _, _ ->
val settingsIntent = Intent(Settings.ACTION_WIRELESS_SETTINGS)
startActivity(settingsIntent)
if (isAdded) {
requireActivity().finish()
}
}
dialog.setNegativeButton("Exit") { _, _ ->
ActivityCompat.finishAffinity(requireActivity())
}
dialog.create()
dialog.show()
}
}
private fun changeColorOfBtn(
btn: Button,
isSelectedBtn: Boolean
) { //TODO: change changeBtnColor so that the selected button check is removed as selected button will always be changed
if (!isSelectedBtn) {
btn.setBackgroundColor(resources.getColor(R.color.white, null))
btn.setTextColor(resources.getColor(R.color.black, null))
} else {
btn.setBackgroundColor(resources.getColor(R.color.gradient_red, null))
btn.setTextColor(resources.getColor(R.color.white, null))
}
}
// private fun backgroundDBOperations(category: String, dao: CachedArticlesDao) {
// CoroutineScope(Dispatchers.IO).launch {
// if (futureArticles.isEmpty()) return@launch
// dao.deleteAll(category)
// val cachedArticles = converterToCachedArticlesEntity(futureArticles)
// for (article in cachedArticles) dao.insertArticle(article)
// }
// }
private fun btnClick(
btn: Button,
selectedFilterBtn: Button,
dao: CachedArticlesDao,
queue: RequestQueue,
timeCheck: Boolean
): Button {
val category = btn.text.toString().lowercase(Locale.getDefault())
rvDashboard.visibility = View.INVISIBLE
pbDashboard.visibility = View.VISIBLE
buttonHandler(btn, selectedFilterBtn, queue, category)
// backgroundDBOperations(category, dao)
// } else {
// var articles = mutableListOf<CachedArticlesEntity>()
// val job1 = CoroutineScope(Dispatchers.IO).launch{
// articles = dao.getAllCachedArticles(category) ?: mutableListOf()
// }
// val job2 = CoroutineScope(Dispatchers.Main).launch {
// if (articles.isNotEmpty()) {
// pbDashboard.visibility = View.GONE
// rvDashboard.visibility = View.VISIBLE
// val newsItems = converterToNewsItem(articles)
// if (selectedFilterBtn == btn) changeColorOfBtn(selectedFilterBtn, true)
// changeColorOfBtn(btn, false)
// dashboardRecyclerAdapter =
// DashboardRecyclerAdapter(activity as Context, newsItems)
// rvDashboard.adapter = dashboardRecyclerAdapter
// } else {
// buttonHandler(btn, selectedFilterBtn, queue, category)
//// backgroundDBOperations(category, dao)
// }
// }
// runBlocking {
// job1.join()
// job2.join()
// }
// }
return btn
}
}
|
SnapNews/app/src/main/java/com/justme/snapnews/ui/fragments/DashboardFragment.kt
|
3124655001
|
package com.justme.snapnews.ui.adapters
import android.content.Context
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.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.justme.snapnews.R
import com.justme.snapnews.data.db.bookmarksdb.BookmarkDB
import com.justme.snapnews.data.models.NewsItem
import com.justme.snapnews.util.converterToBookmarkEntity
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DashboardRecyclerAdapter(
private val context: Context,
private val newsItems: MutableList<NewsItem>
) :
RecyclerView.Adapter<DashboardRecyclerAdapter.DashboardViewHolder>() {
class DashboardViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val imgNewsImage: ImageView = view.findViewById(R.id.imgNewsImage)
val txtHeadline: TextView = view.findViewById(R.id.txtHeadline)
val imgBookmark: ImageView = view.findViewById(R.id.imgBookmark)
val txtDescription: TextView = view.findViewById(R.id.txtDescription)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DashboardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.single_item_dashboard, parent, false)
return DashboardViewHolder(view)
}
override fun getItemCount(): Int = newsItems.size
override fun onBindViewHolder(holder: DashboardViewHolder, position: Int) {
println("In")
val data = newsItems[position]
if (data.title.isNotEmpty())
holder.txtHeadline.text = data.title
else
holder.txtHeadline.text = context.getString(R.string.placeholder_headline)
if (!data.description.isNullOrEmpty())
holder.txtDescription.text = data.content.substringBefore(".") + "."
else
holder.txtDescription.text = data.description
Picasso.get().load(data.image_url).error(R.drawable.garden_test).into(holder.imgNewsImage)
if (data.isBookmarked)
holder.imgBookmark.setImageResource(R.drawable.ic_bookmark_filled)
else
holder.imgBookmark.setImageResource(R.drawable.ic_bookmark_outline)
val db = Room.databaseBuilder(context, BookmarkDB::class.java, "bookmarks").build()
val dao = db.bookmarkDAO()
holder.imgBookmark.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
val bookmark = converterToBookmarkEntity(data)
if (data.isBookmarked) {
data.isBookmarked = false
holder.imgBookmark.setImageResource(R.drawable.ic_bookmark_outline)
dao.deleteFromBookmarks(bookmark)
} else {
data.isBookmarked = true
holder.imgBookmark.setImageResource(R.drawable.ic_bookmark_filled)
dao.insertInBookmarks(bookmark)
}
}
}
}
}
|
SnapNews/app/src/main/java/com/justme/snapnews/ui/adapters/DashboardRecyclerAdapter.kt
|
1975634109
|
package com.justme.snapnews.ui.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.justme.snapnews.R
import com.justme.snapnews.data.db.bookmarksdb.BookmarkDB
import com.justme.snapnews.data.db.bookmarksdb.BookmarkEntity
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class BookmarkRecyclerAdapter(
private val context: Context,
private val bookmarks: MutableList<BookmarkEntity>
) :
RecyclerView.Adapter<BookmarkRecyclerAdapter.BookmarkViewHolder>() {
class BookmarkViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val rlSingleItem: RelativeLayout = view.findViewById(R.id.rlSingleItem)
val imgNewsImage: ImageView = view.findViewById(R.id.imgNewsImage)
val txtHeadline: TextView = view.findViewById(R.id.txtHeadline)
val imgBookmark: ImageView = view.findViewById(R.id.imgBookmark)
val txtDescription: TextView = view.findViewById(R.id.txtDescription)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookmarkViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.single_item_dashboard, parent, false)
return BookmarkViewHolder(view)
}
override fun getItemCount(): Int = bookmarks.size
override fun onBindViewHolder(holder: BookmarkViewHolder, position: Int) {
val data = bookmarks[position]
if (data.title.isNotEmpty())
holder.txtHeadline.text = data.title
else
holder.txtHeadline.text = context.getString(R.string.placeholder_headline)
if (!data.description.isNullOrEmpty())
holder.txtDescription.text = data.content.substringBefore(".") + "."
else
holder.txtDescription.text = data.description
Picasso.get().load(data.image_url).error(R.drawable.garden_test).into(holder.imgNewsImage)
holder.imgBookmark.setImageResource(R.drawable.ic_bookmark_filled)
val db = Room.databaseBuilder(context, BookmarkDB::class.java, "bookmarks").build()
val dao = db.bookmarkDAO()
holder.imgBookmark.setOnClickListener {
holder.rlSingleItem.visibility = View.GONE
CoroutineScope(Dispatchers.IO).launch {
dao.deleteFromBookmarks(data)
}
}
}
}
|
SnapNews/app/src/main/java/com/justme/snapnews/ui/adapters/BookmarkRecyclerAdapter.kt
|
1933744682
|
package com.justme.snapnews.util
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
fun isConnectedToInternet(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network = connectivityManager.activeNetwork
val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
return networkCapabilities != null &&
(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR))
}
|
SnapNews/app/src/main/java/com/justme/snapnews/util/NetworkConnectivity.kt
|
2064319136
|
package com.justme.snapnews.util
import com.justme.snapnews.data.db.bookmarksdb.BookmarkEntity
import com.justme.snapnews.data.db.cachedarticlesdb.CachedArticlesEntity
import com.justme.snapnews.data.models.NewsItem
fun converterToNewsItem(articles : MutableList<CachedArticlesEntity>) : MutableList<NewsItem>{
val newsItems = mutableListOf<NewsItem>()
for (article in articles){
val newsItem = NewsItem(
article.article_id ?: "",
article.content ?: "",
article.link ?: "",
article.title ?: "",
article.category ?: "",
article.country ?: "",
article.description ?: "",
article.image_url ?: "",
article.source_id ?: "",
article.isBookmarked ?: false
)
newsItems.add(newsItem)
}
return newsItems
}
fun converterToCachedArticlesEntity(articles : MutableList<NewsItem>) : MutableList<CachedArticlesEntity>{
val cachedArticles = mutableListOf<CachedArticlesEntity>()
for (article in articles){
val cachedArticle = CachedArticlesEntity(
article.article_id,
article.content,
article.link,
article.title,
article.country,
article.description ?: "",
article.image_url,
article.source_id,
article.isBookmarked,
article.category
)
cachedArticles.add(cachedArticle)
}
return cachedArticles
}
fun converterToBookmarkEntity(newsItem: NewsItem) : BookmarkEntity{
return BookmarkEntity(
newsItem.article_id,
newsItem.content,
newsItem.link,
newsItem.title,
newsItem.category,
newsItem.country,
newsItem.description,
newsItem.image_url,
newsItem.source_id,
newsItem.isBookmarked
)
}
|
SnapNews/app/src/main/java/com/justme/snapnews/util/Converter.kt
|
890685602
|
package com.justme.snapnews.data.models
data class NewsItem(
val article_id: String,
val content: String,
val link: String,
val title: String,
val category: String,
val country: String,
val description: String?,
val image_url: String,
val source_id: String,
var isBookmarked: Boolean
)
|
SnapNews/app/src/main/java/com/justme/snapnews/data/models/NewsItem.kt
|
2474499260
|
package com.justme.snapnews.data.db.bookmarksdb
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "bookmarks")
data class BookmarkEntity(
@PrimaryKey val article_id: String,
@ColumnInfo(name = "content") val content: String,
@ColumnInfo(name = "link") val link: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "category") val category: String,
@ColumnInfo(name = "country") val country: String,
@ColumnInfo(name = "description") val description: String?,
@ColumnInfo(name = "image_url") val image_url: String,
@ColumnInfo(name = "source_id") val source_id: String,
@ColumnInfo(name = "isBookmarked") var isBookmarked: Boolean
)
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/bookmarksdb/BookmarkEntity.kt
|
1265770027
|
package com.justme.snapnews.data.db.bookmarksdb
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
@Dao
interface BookmarkDAO {
@Insert
fun insertInBookmarks(bookmarkEntity: BookmarkEntity)
@Query("SELECT * FROM bookmarks")
fun getAllBookmarks() : MutableList<BookmarkEntity>
@Delete
fun deleteFromBookmarks(bookmarkEntity: BookmarkEntity)
}
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/bookmarksdb/BookmarkDAO.kt
|
4251687531
|
package com.justme.snapnews.data.db.bookmarksdb
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [BookmarkEntity::class], version = 1)
abstract class BookmarkDB : RoomDatabase() {
abstract fun bookmarkDAO(): BookmarkDAO
}
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/bookmarksdb/BookmarkDB.kt
|
4163335867
|
package com.justme.snapnews.data.db.cachedarticlesdb
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "cached-articles")
data class CachedArticlesEntity(
@PrimaryKey val article_id: String,
@ColumnInfo(name = "content") val content: String? = "",
@ColumnInfo(name = "link") val link: String? = "",
@ColumnInfo(name = "title") val title: String? = "",
@ColumnInfo(name = "country") val country: String? = "",
@ColumnInfo(name = "description") val description: String? = "",
@ColumnInfo(name = "image_url") val image_url: String? = "",
@ColumnInfo(name = "source_id") val source_id: String? = "",
@ColumnInfo(name = "isBookmarked") val isBookmarked: Boolean? = false,
@ColumnInfo(name = "category") val category: String? = ""
)
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/cachedarticlesdb/CachedArticlesEntity.kt
|
1462286653
|
package com.justme.snapnews.data.db.cachedarticlesdb
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface CachedArticlesDao {
@Query("SELECT * FROM `cached-articles` WHERE category = :category")
fun getAllCachedArticles(category: String): MutableList<CachedArticlesEntity>?
@Insert
fun insertArticle(article: CachedArticlesEntity)
@Query("DELETE FROM `cached-articles` WHERE category = :category")
fun deleteAll(category: String)
}
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/cachedarticlesdb/CachedArticlesDAO.kt
|
2267415782
|
package com.justme.snapnews.data.db.cachedarticlesdb
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [CachedArticlesEntity::class],
version = 1
)
abstract class CachedArticlesDB : RoomDatabase(){
abstract fun cachedArticlesDao(): CachedArticlesDao
}
|
SnapNews/app/src/main/java/com/justme/snapnews/data/db/cachedarticlesdb/CachedArticlesDB.kt
|
2430869158
|
package com.yunyan.snake
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.yunyan.snake", appContext.packageName)
}
}
|
final-test1/app/src/androidTest/java/com/yunyan/snake/ExampleInstrumentedTest.kt
|
3892693206
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.