content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.newsadmin.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Image(val url : String , val publicId : String? ): Parcelable
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/Image.kt | 1127650307 |
package com.example.newsadmin.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class News(
val _id:String,
val title: String,
val author: String,
val content: String,
val categoryId: Category,
val image: Image,
val createdAt: String,
val updatedAt: String,
val __v: Int,
var isFavorite:Boolean = false,
): Parcelable
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/News.kt | 4229105753 |
package com.example.newsadmin.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Category(
val _id:String,
val name:String,
val description: String,
val image: Image,
val createdAt: String,
val updatedAt: String,
val __v: Int
):Parcelable
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/Category.kt | 2490024325 |
package com.example.newsadmin.models
data class Favoris(
val _id: String,
val user: String,
val article: News,
val createdAt: String,
val updatedAt: String,
val __v: Int
)
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/Favoris.kt | 1465839143 |
package com.example.newsadmin.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class User(
val _id: String,
val firstName: String ,
val lastName: String,
val email: String,
val isAdmin : Boolean,
val isAccountVerified : Boolean,
val profilePhoto : Image,
val __v: Int,
val createdAt: String,
val updatedAt: String,
var token: String? = null
): Parcelable
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/User.kt | 2618621576 |
package com.example.newsadmin.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class Rate(
val rating:Int,
val user:String,
val article:String,
):Parcelable
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/Rate.kt | 195193084 |
package com.example.newsadmin.models
data class Rating(
val _id: String,
var user: User,
var article:News,
var rating: Int,
val createdAt: String,
val updatedAt: String,
val __v: Int
)
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/models/Rating.kt | 1785583629 |
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.example.newsadmin.R
class CustomSpinnerAdapter(context: Context, private val categories: Array<String>) :
ArrayAdapter<String>(context, R.layout.item_custom_spinner, categories) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return getCustomView(position, convertView, parent)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return getCustomView(position, convertView, parent)
}
private fun getCustomView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = LayoutInflater.from(context)
val view = convertView ?: inflater.inflate(R.layout.item_custom_spinner, parent, false)
val categoryTextView: TextView = view.findViewById(R.id.customCategoryTextView)
categoryTextView.text = categories[position]
return view
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/adapters/CustomSpinnerAdapter.kt | 3715618739 |
package com.example.newsadmin.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.newsadmin.R
import com.example.newsadmin.models.Category
class CategoriesHomeAdapter(
private val categoryList: ArrayList<Category>,
private val onClickCategory: (Category) -> Unit,
private var currentCategory: Category?
): RecyclerView.Adapter<CategoriesHomeAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.custom_category_home,parent,false);
val holder = MyViewHolder(itemView)
return holder;
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem:Category = categoryList[position]
holder.title.text= currentItem.name
holder.itemView.isSelected = (currentItem == currentCategory)
holder.title.setTextColor(
ContextCompat.getColor(
holder.itemView.context,
if (holder.itemView.isSelected) R.color.white else R.color.black
)
)
holder.itemView.setOnClickListener {
if (currentItem != currentCategory) {
currentCategory = currentItem
onClickCategory(currentItem)
notifyDataSetChanged()
}
}
}
override fun getItemCount(): Int {
return categoryList.size;
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val title : TextView = itemView.findViewById(R.id.custom_category_home)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/adapters/CategoriesHomeAdapter.kt | 3166693447 |
package com.example.newsadmin.adapters
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.example.newsadmin.fragments.HomeFragmentDirections
import com.example.newsadmin.R
import com.example.newsadmin.models.News
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class NewsAdapter (
private val newsList: ArrayList<News>,
private val navController: NavController,
): RecyclerView.Adapter<NewsAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.custom_new,parent,false);
val holder = MyViewHolder(itemView)
return holder;
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = newsList[position]
holder.image.visibility = View.GONE
holder.progressBar.visibility = View.VISIBLE
//load the images
val request = coil.request.ImageRequest.Builder(holder.image.context)
.data(currentItem.image.url)
.target(holder.image)
.target(
onStart = {
holder.progressBar.visibility = View.VISIBLE
},
onSuccess = { result ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(result)
},
onError = { _ ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(ContextCompat.getDrawable(holder.image.context,R.drawable.baseline_error_outline_24))
}
).build()
coil.ImageLoader(holder.image.context).enqueue(request)
holder.title.text= currentItem.title
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault())
val outputFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault())
val date:Date = inputFormat.parse(currentItem.createdAt)!!
val formattedDate:String = outputFormat.format(date)
holder.date.text = formattedDate
holder.author.text = currentItem.author
val currentNew = holder.currentNew
currentNew.setOnClickListener {
val action = HomeFragmentDirections.actionHomeFragmentToArticleDetailsFragment(newsList[position])
navController.navigate(action)
}
}
override fun getItemCount(): Int {
return newsList.size;
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val progressBar :ProgressBar = itemView.findViewById(R.id.progressBarNew)
val currentNew : LinearLayout = itemView.findViewById(R.id.newId)
val image : ImageView = currentNew.findViewById(R.id.imageViewNew)
val title : TextView = currentNew.findViewById(R.id.titleTextViewNew)
val date : TextView = currentNew.findViewById(R.id.timeTextViewNew)
val author: TextView = currentNew.findViewById(R.id.authorTextViewNew)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/adapters/NewsAdapter.kt | 2040648007 |
package com.example.newsadmin.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.example.newsadmin.R
import com.example.newsadmin.fragments.CategoriesFragmentDirections
import com.example.newsadmin.models.Category
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class CategoriesAdapter(
private val categoryList: ArrayList<Category>,
private val navController: NavController,
): RecyclerView.Adapter<CategoriesAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.single_category,parent,false);
val holder = MyViewHolder(itemView)
return holder;
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem:Category = categoryList[position]
holder.title.text= currentItem.name
//load the images
val request = coil.request.ImageRequest.Builder(holder.image.context)
.data(currentItem.image.url)
.target(holder.image)
.target(
onStart = {
holder.progressBar.visibility = View.VISIBLE
},
onSuccess = { result ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(result)
},
onError = { _ ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(ContextCompat.getDrawable(holder.image.context,R.drawable.baseline_error_outline_24))
}
).build()
coil.ImageLoader(holder.image.context).enqueue(request)
//date
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault())
val outputFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault())
val date: Date = inputFormat.parse(currentItem.createdAt)!!
val formattedDate:String = outputFormat.format(date)
holder.date.text = formattedDate
holder.itemView.setOnClickListener {
val action = CategoriesFragmentDirections.actionCategoriesFragmentToCategoryDetailsFragment(currentItem)
navController.navigate(action)
}
}
override fun getItemCount(): Int {
return categoryList.size;
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val image:ImageView = itemView.findViewById(R.id.imageViewCategory)
val title : TextView = itemView.findViewById(R.id.titleTextViewCategory)
val date : TextView = itemView.findViewById(R.id.dateTextViewCategory)
val progressBar : ProgressBar = itemView.findViewById(R.id.progressBarImageCategory)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/adapters/CategoriesAdapter.kt | 2108254144 |
package com.example.newsadmin.adapters
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.example.newsadmin.R
import com.example.newsadmin.fragments.UsersFragmentDirections
import com.example.newsadmin.models.User
class UsersAdapter(
private val usersList: ArrayList<User>,
private val navController: NavController,
): RecyclerView.Adapter<UsersAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView =
LayoutInflater.from(parent.context).inflate(R.layout.single_user, parent, false);
return MyViewHolder(itemView);
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem:User = usersList[position]
holder.title.text= currentItem.firstName+" "+currentItem.lastName
holder.email.text= currentItem.email
//load the images
val request = coil.request.ImageRequest.Builder(holder.image.context)
.data(currentItem.profilePhoto.url)
.target(holder.image)
.target(
onStart = {
holder.progressBar.visibility = View.VISIBLE
},
onSuccess = { result ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(result)
},
onError = { _ ->
holder.progressBar.visibility = View.GONE
holder.image.visibility = View.VISIBLE
holder.image.setImageDrawable(ContextCompat.getDrawable(holder.image.context,R.drawable.baseline_error_outline_24))
}
).build()
coil.ImageLoader(holder.image.context).enqueue(request)
holder.itemView.setOnClickListener {
val action = UsersFragmentDirections.actionUsersFragmentToUserDetailsFragment(currentItem)
navController.navigate(action)
}
}
override fun getItemCount(): Int {
return usersList.size;
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val image:ImageView = itemView.findViewById(R.id.imageViewSingleUser)
val title : TextView = itemView.findViewById(R.id.titleTextViewSingleUser)
val email : TextView = itemView.findViewById(R.id.dateTextViewSingleUser)
val progressBar : ProgressBar = itemView.findViewById(R.id.progressBarImageSingleUser)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/adapters/UsersAdapter.kt | 1239706815 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.utils.GetAllUsersResponse
import com.example.newsadmin.utils.UpdateUserResponse
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
import java.io.File
class UsersData(private var userId: String, private var token: String) {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api"
fun getAllUsers(
onSuccess : (GetAllUsersResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/users"
crud.get(
urlApi,
null,
token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val getAllUsersResponse = gson.fromJson(response, GetAllUsersResponse::class.java)
onSuccess(getAllUsersResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateUser(
firstName:String?,
lastName:String?,
email:String?,
password:String?,
onSuccess : (UpdateUserResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/users/$userId"
var json:String = ""
if (password!=null){
json = """
{
"firstName": "$firstName",
"lastName": "$lastName",
"email": "$email",
"password": "$password"
}
""".trimIndent()
}else{
json = """
{
"firstName": "$firstName",
"lastName": "$lastName",
"email": "$email"
}
""".trimIndent()
}
crud.update(
urlApi,
json,
token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val updateUserResponse = gson.fromJson(response, UpdateUserResponse::class.java)
onSuccess(updateUserResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateUserWithImage(
firstName:String?,
lastName:String?,
email:String?,
password:String?,
file:File,
onSuccess : (UpdateUserResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi = "$baseUrl/users/$userId"
crud.putWithImage(
urlApi,
firstName!!,
lastName!!,
email!!,
password!!,
token,
file,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val updateUserResponse = gson.fromJson(response, UpdateUserResponse::class.java)
Log.d("updateUserWithImage",updateUserResponse.toString())
onSuccess(updateUserResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/UsersData.kt | 3335938180 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.models.Category
import com.example.newsadmin.utils.AddCategoryResponse
import com.example.newsadmin.utils.DeleteNewsResponse
import com.example.newsadmin.utils.GetSingleNewsResponse
import com.example.newsadmin.utils.ResponseNewsData
import com.example.newsadmin.utils.UpdateArticleResponse
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
import java.io.File
class NewsData {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api"
private lateinit var userId:String ;
private lateinit var token:String ;
constructor(userId:String,token:String){
this.userId = userId
this.token = token
}
fun getSingleNews(id:String,
onSuccess : (GetSingleNewsResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi = "$baseUrl/articles/$id"
val userId:String = userId
val json = """
{
"userId": "$userId"
}
""".trimIndent()
val token:String = token
crud.post(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val singleNewsResponse = gson.fromJson(response, GetSingleNewsResponse::class.java)
onSuccess(singleNewsResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun getNewsByCategory(category: Category,
onSuccess : (ResponseNewsData) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/articles?categoryId=${category._id}"
val userId:String = userId
val json = """
{
"userId": "$userId"
}
""".trimIndent()
val token:String = token
crud.get(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val newsResponse = gson.fromJson(response, ResponseNewsData::class.java)
onSuccess(newsResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun searchNews(key: String,
onSuccess : (ResponseNewsData) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/articles?title=$key"
val userId:String = userId
val json = """
{
"userId": "$userId"
}
""".trimIndent()
val token:String = token
crud.get(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val newsResponse = gson.fromJson(response, ResponseNewsData::class.java)
onSuccess(newsResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun addArticle(
title:String,
author:String,
description:String,
image:File,
categoryId:String,
onSuccess: (AddCategoryResponse) -> Unit,
onFailure: (String) -> Unit
){
val urlApi : String = "$baseUrl/articles"
val fieldsMap = mapOf<String,String>(
"title" to title,
"author" to author,
"content" to description,
"categoryId" to categoryId
)
crud.postWithImage(
urlApi,
token,
image,
fieldsMap,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val addArticleResponse = gson.fromJson(response, AddCategoryResponse::class.java)
onSuccess(addArticleResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateArticle(
id:String,
title:String,
author: String,
description:String,
categoryId:String,
onSuccess: (UpdateArticleResponse) -> Unit,
onFailure: (String) -> Unit
){
val urlApi : String = "$baseUrl/articles/$id"
val fieldsMap = mapOf<String,String>(
"title" to title,
"author" to author,
"content" to description,
"categoryId" to categoryId
)
crud.putWithoutImage(
urlApi,
token,
fieldsMap,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val updateArticleResponse = gson.fromJson(response, UpdateArticleResponse::class.java)
onSuccess(updateArticleResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateArticleWithImage(
id:String,
title:String,
author: String,
description:String,
categoryId:String,
image:File,
onSuccess: (UpdateArticleResponse) -> Unit,
onFailure: (String) -> Unit
){
val urlApi : String = "$baseUrl/articles/$id"
val fieldsMap = mapOf<String,String>(
"title" to title,
"author" to author,
"content" to description,
"categoryId" to categoryId
)
crud.putWithImageAnas(
urlApi,
token,
image,
fieldsMap,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val updateArticleResponse = gson.fromJson(response, UpdateArticleResponse::class.java)
onSuccess(updateArticleResponse)
Log.d("response",updateArticleResponse.toString())
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun deleteArticle(
id:String,
onSuccess: (DeleteNewsResponse) -> Unit,
onFailure: (String) -> Unit
){
crud.delete(
"$baseUrl/articles/$id",
"",
token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val deleteArticleResponse = gson.fromJson(response, DeleteNewsResponse::class.java)
onSuccess(deleteArticleResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/NewsData.kt | 647799341 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.utils.ResponseNewsData
import com.example.newsadmin.utils.ResponseRateData
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
class RatingData {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api"
private lateinit var userId:String ;
private lateinit var token:String ;
constructor(userId:String,token:String){
this.userId = userId
this.token = token
}
fun handleRating (articleId:String, rating:Int,onSuccess : (ResponseRateData)->Unit,
onFailure : (String) -> Unit){
val urlApi : String = "$baseUrl/ratings"
val userId:String = userId
val json = """
{
"userId": "$userId",
"articleId": "$articleId",
"rating": $rating
}
""".trimIndent()
val token:String = token
crud.post(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val rateResponse = gson.fromJson(response, ResponseRateData::class.java)
onSuccess(rateResponse)
}
override fun onFailure(call: Call, e: IOException) {
Log.d("rating",e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/RatingData.kt | 343363427 |
import android.util.Log
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.io.IOException
class Crud {
private val client = OkHttpClient()
interface ResponseCallback {
fun onResponse(call: Call, response: Response)
fun onFailure(call: Call, e: IOException)
}
fun get(url: String,jsonBody: String?,authToken: String?, callback: ResponseCallback) {
val requestBuilder = Request.Builder()
.url(url)
.get()
if(authToken != null){
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val getRequest = requestBuilder.build()
client.newCall(getRequest).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun post(url: String, jsonBody: String,authToken: String?, callback: ResponseCallback) {
val postBody = jsonBody.toRequestBody("application/json".toMediaTypeOrNull())
val requestBuilder = Request.Builder()
.url(url)
.post(postBody)
if(authToken != null){
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val postRequest = requestBuilder.build()
client.newCall(postRequest).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun update(url: String, jsonBody: String,authToken: String?, callback: ResponseCallback) {
val putBody = jsonBody.toRequestBody("application/json".toMediaTypeOrNull())
val requestBuilder = Request.Builder()
.url(url)
.put(putBody)
if(authToken != null){
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val putRequest = requestBuilder.build()
client.newCall(putRequest).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun delete(url: String,jsonBody: String,authToken: String?, callback: ResponseCallback) {
val deleteBody = jsonBody.toRequestBody("application/json".toMediaTypeOrNull())
val requestBuilder = Request.Builder()
.url(url)
.delete(deleteBody)
if(authToken != null){
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val deleteRequest = requestBuilder.build()
client.newCall(deleteRequest).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun postWithImage(
url:String,
authToken: String?,
file: File,
fields: Map<String, Any>,
callback: ResponseCallback,
){
val requestBody: RequestBody
val builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
fields.forEach { (key, value) ->
builder.addFormDataPart(key, value.toString())
}
builder.addFormDataPart("image", file.name, file.asRequestBody("image/*".toMediaTypeOrNull()))
requestBody = builder.build()
val requestBuilder = Request.Builder()
if (authToken != null) {
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val request = requestBuilder
.url(url)
.post(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun putWithImageAnas(
url:String,
authToken: String?,
file: File,
fields: Map<String, Any>,
callback: ResponseCallback,) {
val requestBody: RequestBody
val builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
fields.forEach { (key, value) ->
builder.addFormDataPart(key, value.toString())
}
builder.addFormDataPart("image", file.name, file.asRequestBody("image/*".toMediaTypeOrNull()))
requestBody = builder.build()
val requestBuilder = Request.Builder()
if (authToken != null) {
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val request = requestBuilder
.url(url)
.put(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun putWithoutImage(
url:String,
authToken: String?,
fields: Map<String, Any>,
callback: ResponseCallback,) {
val requestBody: RequestBody
val builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
fields.forEach { (key, value) ->
builder.addFormDataPart(key, value.toString())
}
requestBody = builder.build()
val requestBuilder = Request.Builder()
if (authToken != null) {
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val request = requestBuilder
.url(url)
.put(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
fun putWithImage(
url: String,
firstName:String,
lastName:String,
email:String,
password:String?,
authToken: String?,
file:File,
callback: ResponseCallback) {
val requestBody: RequestBody
if (password != null) {
requestBody= MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.name, file.asRequestBody("image/*".toMediaTypeOrNull()))
.addFormDataPart("firstName", firstName)
.addFormDataPart("lastName", lastName)
.addFormDataPart("email", email)
.addFormDataPart("password", password)
.build()
} else {
requestBody= MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.name, file.asRequestBody("image/*".toMediaTypeOrNull()))
.addFormDataPart("firstName", firstName)
.addFormDataPart("lastName", lastName)
.addFormDataPart("email", email)
.build()
}
val requestBuilder = Request.Builder()
if (authToken != null) {
val headerValue = "Bearer $authToken"
requestBuilder.addHeader("Authorization", headerValue)
}
val request = requestBuilder
.url(url)
.put(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
callback.onResponse(call, response)
}
override fun onFailure(call: Call, e: IOException) {
callback.onFailure(call,e)
}
})
}
}
| NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/Crud.kt | 2200142616 |
package com.example.newsadmin.data
import Crud
import com.example.newsadmin.utils.AddCategoryResponse
import com.example.newsadmin.utils.DeleteCategoryResponse
import com.example.newsadmin.utils.GetAllCategoriesResponse
import com.example.newsadmin.utils.GetSingleCategoryResponse
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
import java.io.File
class CategoriesData {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api/categories/"
private lateinit var token:String ;
constructor(token:String){
this.token = token
}
fun addCategory(
name:String,
description:String,
image:File,
onSuccess: (AddCategoryResponse) -> Unit,
onFailure: (String) -> Unit
){
val urlApi : String = baseUrl
val fieldsMap = mapOf<String,String>(
"name" to name,
"description" to description
)
crud.postWithImage(
urlApi,
token,
image,
fieldsMap,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val addCategoryResponse = gson.fromJson(response, AddCategoryResponse::class.java)
onSuccess(addCategoryResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun getAllCategories(
onSuccess : (GetAllCategoriesResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = baseUrl
crud.get(
urlApi,
null,
token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val getAllCategoriesResponse = gson.fromJson(response, GetAllCategoriesResponse::class.java)
onSuccess(getAllCategoriesResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun getSingleCategory(
id:String,
onSuccess : (GetSingleCategoryResponse) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl$id"
crud.get(
urlApi,
null,
token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val getAllCategoriesResponse = gson.fromJson(response, GetSingleCategoryResponse::class.java)
onSuccess(getAllCategoriesResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateCategory(
id:String,
name:String,
description:String,
image:File,
onSuccess: (AddCategoryResponse) -> Unit,
onFailure: (String) -> Unit
) {
val urlApi: String = "$baseUrl$id"
val fieldsMap = mapOf<String, String>(
"name" to name,
"description" to description
)
crud.putWithImageAnas(
urlApi,
token,
image,
fieldsMap,
object : Crud.ResponseCallback {
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val addCategoryResponse =
gson.fromJson(response, AddCategoryResponse::class.java)
onSuccess(addCategoryResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updateCategoryWithoutImage(
id:String,
name:String,
description:String,
onSuccess: (AddCategoryResponse) -> Unit,
onFailure: (String) -> Unit
) {
val urlApi: String = "$baseUrl$id"
val fieldsMap = mapOf<String, String>(
"name" to name,
"description" to description
)
crud.putWithoutImage(
urlApi,
token,
fieldsMap,
object : Crud.ResponseCallback {
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val addCategoryResponse =
gson.fromJson(response, AddCategoryResponse::class.java)
onSuccess(addCategoryResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun deleteCategory(
id:String,
onSuccess: (DeleteCategoryResponse) -> Unit,
onFailure: (String) -> Unit
){
val urlApi: String = "$baseUrl$id"
crud.delete(
urlApi,
"",
token,
object : Crud.ResponseCallback {
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val deleteCategoryResponse =
gson.fromJson(response, DeleteCategoryResponse::class.java)
onSuccess(deleteCategoryResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/CategoriesData.kt | 2221578690 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.models.Favoris
import com.example.newsadmin.models.News
import com.example.newsadmin.utils.ResponseAddFavoris
import com.example.newsadmin.utils.ResponseDeleteFavoris
import com.example.newsadmin.utils.ResponseGetFavoris
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
class FavorisData {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api"
private lateinit var userId:String ;
private lateinit var token:String ;
constructor(userId:String,token:String){
this.userId = userId
this.token = token
}
fun addToFavoris(news: News,
onSuccess : (ResponseAddFavoris) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/favoris"
val json = """
{
"userId": "$userId",
"articleId": "${news._id}"
}
""".trimIndent()
crud.post(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val addToFavorisResponse = gson.fromJson(response, ResponseAddFavoris::class.java)
onSuccess(addToFavorisResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun deleteFromFavoris(favoris: Favoris,
onSuccess : (ResponseDeleteFavoris) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/favoris"
val json = """
{
"favorisId": "${favoris._id}"
}
""".trimIndent()
val token:String = token
crud.delete(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val deleteFromFavorisResponse = gson.fromJson(response, ResponseDeleteFavoris::class.java)
onSuccess(deleteFromFavorisResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun getAllFavoris(
onSuccess : (ResponseGetFavoris) -> Unit,
onFailure : (String) -> Unit
){
val urlApi : String = "$baseUrl/favoris/getfavoris"
val userId:String = userId
val json = """
{
"userId": "$userId"
}
""".trimIndent()
val token:String = token
crud.post(urlApi,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val getFavorisResponse = gson.fromJson(response, ResponseGetFavoris::class.java)
onSuccess(getFavorisResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/FavorisData.kt | 380273386 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.utils.ChangePasswordResponse
import com.example.newsadmin.utils.ForgetPasswordResponse
import com.example.newsadmin.utils.LoginResponse
import com.example.newsadmin.utils.SendVerifyCodeResponse
import com.example.newsadmin.utils.SignUpResponse
import com.example.newsadmin.utils.VerifyCodeResponse
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
class AuthData {
private val crud = Crud()
private val gson = Gson()
private val baseAuth = "https://news-api-8kaq.onrender.com/api/auth"
fun login(
email : String,
password : String,
onSuccess: (LoginResponse) -> Unit,
onFailure: (String) -> Unit
){
val loginUrl : String = "$baseAuth/login"
val json = """
{
"email": "$email",
"password": "$password"
}
""".trimIndent()
crud.post(loginUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseLogin = gson.fromJson(responseData, LoginResponse::class.java)
onSuccess(responseLogin)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun signUp(
firstName : String,
lastName : String,
email : String,
password : String,
onSuccess: (SignUpResponse) -> Unit,
onFailure: (String) -> Unit
){
val signUpUrl : String = "$baseAuth/signup"
val json = """
{
"firstName": "$firstName",
"lastName": "$lastName",
"email": "$email",
"password": "$password"
}
""".trimIndent()
crud.post(signUpUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseSignUp = gson.fromJson(responseData, SignUpResponse::class.java)
onSuccess(responseSignUp)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun forgetPassword(
email : String,
onSuccess: (ForgetPasswordResponse) -> Unit,
onFailure: (String) -> Unit
){
val forgetPasswordUrl : String = "$baseAuth/forgetpassword"
val json = """
{
"email": "$email"
}
""".trimIndent()
crud.post(forgetPasswordUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseForgetPassword = gson.fromJson(responseData, ForgetPasswordResponse::class.java)
onSuccess(responseForgetPassword)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun verifyCode(
email : String,
code : Int,
onSuccess: (VerifyCodeResponse) -> Unit,
onFailure: (String) -> Unit
){
val verifyCodeUrl : String = "$baseAuth/verifycode"
val json = """
{
"email": "$email",
"verifyCode": $code
}
""".trimIndent()
crud.post(verifyCodeUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseVerifyCode = gson.fromJson(responseData, VerifyCodeResponse::class.java)
onSuccess(responseVerifyCode)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun sendVerificationCode(
email : String,
onSuccess: (SendVerifyCodeResponse) -> Unit,
onFailure: (String) -> Unit
){
val sendVerificationCodeUrl : String = "$baseAuth/sendverificationcode"
val json = """
{
"email": "$email"
}
""".trimIndent()
crud.post(sendVerificationCodeUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseSendVerificationCode = gson.fromJson(responseData, SendVerifyCodeResponse::class.java)
onSuccess(responseSendVerificationCode)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
fun updatePassword(
email : String,
password : String,
onSuccess: (ChangePasswordResponse) -> Unit,
onFailure: (String) -> Unit
){
val updatePasswordUrl : String = "$baseAuth/updatepassword"
val json = """
{
"email": "$email",
"password": "$password"
}
""".trimIndent()
crud.post(updatePasswordUrl,json,null,object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val responseData = response.body?.string()
val responseUpdatePassword = gson.fromJson(responseData, ChangePasswordResponse::class.java)
onSuccess(responseUpdatePassword)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/AuthData.kt | 3501230454 |
package com.example.newsadmin.data
import Crud
import android.util.Log
import com.example.newsadmin.utils.ResponseHomeData
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
import okio.IOException
class HomeData {
private val crud:Crud = Crud();
private val baseUrl : String = "https://news-api-8kaq.onrender.com/api"
private lateinit var userId:String ;
private lateinit var token:String ;
//constructor(userId:String,token:String)
constructor(userId:String,token:String){
this.userId = userId
this.token = token
}
fun getHomeData(
onSuccess : (ResponseHomeData) -> Unit,
onFailure : (String) -> Unit
) {
val homeUrl : String = "$baseUrl/home"
val userId:String = "$userId"
val json = """
{
"userId": "$userId"
}
""".trimIndent()
val token:String = token
crud.post(homeUrl,json,token,
object: Crud.ResponseCallback{
override fun onResponse(call: Call, response: Response) {
val response = response.body?.string()
val gson = Gson()
val homeResponse = gson.fromJson(response,ResponseHomeData::class.java)
onSuccess(homeResponse)
}
override fun onFailure(call: Call, e: IOException) {
onFailure(e.message!!)
}
}
)
}
} | NewsAdminKotlin/app/src/main/java/com/example/newsadmin/data/HomeData.kt | 3516374411 |
package com.bignerdranch.android.geoquiz
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.bignerdranch.android.geoquiz", appContext.packageName)
}
} | Week8/app/src/androidTest/java/com/bignerdranch/android/geoquiz/ExampleInstrumentedTest.kt | 334131583 |
package com.bignerdranch.android.geoquiz
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)
}
} | Week8/app/src/test/java/com/bignerdranch/android/geoquiz/ExampleUnitTest.kt | 3502407908 |
package com.bignerdranch.android.geoquiz
import Question
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.make
import com.bignerdranch.android.geoquiz.databinding.ActivityMainBinding
private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val quizViewModel: QuizViewModel by viewModels()
private val cheatLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
result ->
if (result.resultCode == Activity.RESULT_OK) {
quizViewModel.isCheater =
result.data?.getBooleanExtra(EXTRA_ANSWER_SHOWN, false) ?: false
}
}
private fun updateQuestion() {
val questionTextResId = quizViewModel.currentQuestionText
binding.questionTextView.setText(questionTextResId)
}
private fun checkAnswer(userAnswer: Boolean) {
val correctAnswer = quizViewModel.currentQuestionAnswer
val messageResId = when {
// EXERCISE 1C
quizViewModel.questionBank[quizViewModel.currentIndex].hasCheated -> R.string.judgement_toast
//quizViewModel.isCheater -> R.string.judgement_toast
//
userAnswer == correctAnswer -> R.string.correct_toast
else -> R.string.incorrect_toast
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate(Bundle?) called")
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
Log.d(TAG, "Got a QuizViewModel: $quizViewModel")
binding.trueButton.setOnClickListener { view: View ->
checkAnswer(true)
}
binding.falseButton.setOnClickListener { view: View ->
checkAnswer(false)
}
binding.cheatButton.setOnClickListener { view: View ->
// EXERCISE 1C
quizViewModel.questionBank[quizViewModel.currentIndex].hasCheated = true
//
val answerIsTrue = quizViewModel.currentQuestionAnswer
val intent = CheatActivity.newIntent(this@MainActivity, answerIsTrue)
cheatLauncher.launch(intent)
}
binding.questionTextView.setOnClickListener { view: View ->
quizViewModel.moveToNext()
updateQuestion()
}
binding.nextButton.setOnClickListener {
quizViewModel.moveToNext()
updateQuestion()
}
binding.previousButton.setOnClickListener {
quizViewModel.moveToPrevious()
updateQuestion()
}
updateQuestion()
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart() called")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume() called")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onStart() called")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStart() called")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onStart() called")
}
} | Week8/app/src/main/java/com/bignerdranch/android/geoquiz/MainActivity.kt | 635053154 |
package com.bignerdranch.android.geoquiz
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.bignerdranch.android.geoquiz.databinding.ActivityCheatBinding
const val EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown"
private const val EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true"
class CheatActivity : AppCompatActivity() {
private lateinit var binding: ActivityCheatBinding
private var answerIsTrue = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCheatBinding.inflate(layoutInflater)
setContentView(binding.root)
answerIsTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false)
binding.showAnswerButton.setOnClickListener { view: View ->
val answerText = when {
answerIsTrue -> R.string.true_button
else -> R.string.false_button
}
binding.answerTextView.setText(answerText)
setAnswerShownResult(true)
}
}
private fun setAnswerShownResult(isAnswerShown: Boolean) {
val data = Intent().apply {
putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown)
}
setResult(Activity.RESULT_OK, data)
}
companion object {
fun newIntent(packageContext: Context, answerIsTrue: Boolean): Intent {
return Intent(packageContext, CheatActivity::class.java).apply {
putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue)
}
}
}
} | Week8/app/src/main/java/com/bignerdranch/android/geoquiz/CheatActivity.kt | 3039649423 |
import androidx.annotation.StringRes
data class Question(@StringRes val textResId: Int, val answer: Boolean, var isAnswered: Boolean, var hasCheated: Boolean) | Week8/app/src/main/java/com/bignerdranch/android/geoquiz/Question.kt | 974329654 |
package com.bignerdranch.android.geoquiz
import Question
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
const val IS_CHEATER_KEY = "IS_CHEATER_KEY"
const val CURRENT_INDEX_KEY = "CURRENT_INDEX_KEY"
class QuizViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
val questionBank = listOf(
// EXERCISE 1C - ADDED hasCheated variable
Question(R.string.question_australia, true, false, false),
Question(R.string.question_oceans, true, false, false),
Question(R.string.question_africa, false, false, false),
Question(R.string.question_americas, false, false, false),
Question(R.string.question_asia, true, false, false)
)
var currentIndex: Int
get() = savedStateHandle.get(CURRENT_INDEX_KEY) ?: 0
set(value) = savedStateHandle.set(CURRENT_INDEX_KEY, value)
val currentQuestionAnswer: Boolean
get() = questionBank[currentIndex].answer
val currentQuestionText: Int
get() = questionBank[currentIndex].textResId
var isCheater: Boolean
get() = savedStateHandle.get(IS_CHEATER_KEY) ?: false
set(value) = savedStateHandle.set(IS_CHEATER_KEY, value)
fun moveToNext() {
currentIndex = (currentIndex + 1) % questionBank.size
}
fun moveToPrevious() {
if (currentIndex == 0) {
currentIndex = questionBank.size - 1
}
else {
currentIndex = (currentIndex - 1) % questionBank.size
}
}
} | Week8/app/src/main/java/com/bignerdranch/android/geoquiz/QuizViewModel.kt | 1891455489 |
package com.cpe42020.Visimp
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.cpe42020.Visimp", appContext.packageName)
}
} | ViSimp-Navigation-System/app/src/androidTest/java/com/cpe42020/Visimp/ExampleInstrumentedTest.kt | 1396486704 |
package com.cpe42020.Visimp
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)
}
} | ViSimp-Navigation-System/app/src/test/java/com/cpe42020/Visimp/ExampleUnitTest.kt | 773073335 |
package com.cpe42020.Visimp
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.cpe42020.Visimp.ml.SsdMobilenetV11Metadata1
import org.tensorflow.lite.support.common.FileUtil
import org.tensorflow.lite.support.image.ImageProcessor
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.image.ops.ResizeOp
import java.util.Locale
import kotlin.math.atan2
import kotlin.math.min
class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener {
private lateinit var labels: List<String>
private var colors = listOf<Int>(
Color.BLUE, Color.GREEN, Color.RED, Color.CYAN, Color.GRAY, Color.BLACK,
Color.DKGRAY, Color.MAGENTA, Color.YELLOW, Color.RED
)
private val paint = Paint()
private lateinit var imageProcessor: ImageProcessor
private lateinit var bitmap: Bitmap
private lateinit var imageView: ImageView
private lateinit var cameraDevice: CameraDevice
private lateinit var handler: Handler
private lateinit var cameraManager: CameraManager
private lateinit var textureView: TextureView
private lateinit var model: SsdMobilenetV11Metadata1
private lateinit var tts: TextToSpeech
private var lastSpokenObject: String? = null
private var cameraCharacteristics: CameraCharacteristics? = null
private var lastSpokenTimestamp: Long = 0
var left: String? = null
var right: String? = null
private lateinit var NavGuidance: NavGuidance
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getPermission()
val displayMetrics = resources.displayMetrics
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
val densityDpi = displayMetrics.densityDpi
val mmwidth = screenWidth/(densityDpi/25.4)
val mmheight = screenHeight/(densityDpi/25.4)
val centerX = (mmwidth / 2)
val centerY = (mmheight / 2)
val radius = min(centerX, centerY) - 30 // Adjust as needed
labels = FileUtil.loadLabels(this, "labels.txt")
imageProcessor =
ImageProcessor.Builder().add(ResizeOp(300, 300, ResizeOp.ResizeMethod.BILINEAR)).build()
model = SsdMobilenetV11Metadata1.newInstance(this)
val handlerThread = HandlerThread("videoThread")
handlerThread.start()
handler = Handler(handlerThread.looper)
imageView = findViewById(R.id.imageView)
textureView = findViewById(R.id.textureView)
textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(p0: SurfaceTexture, p1: Int, p2: Int) {
openCamera()
}
override fun onSurfaceTextureSizeChanged(p0: SurfaceTexture, p1: Int, p2: Int) {}
override fun onSurfaceTextureDestroyed(p0: SurfaceTexture): Boolean {
return false
}
override fun onSurfaceTextureUpdated(p0: SurfaceTexture) {
bitmap = textureView.bitmap!!
var image = TensorImage.fromBitmap(bitmap)
image = imageProcessor.process(image)
val outputs = model.process(image)
val locations = outputs.locationsAsTensorBuffer.floatArray
val classes = outputs.classesAsTensorBuffer.floatArray
val scores = outputs.scoresAsTensorBuffer.floatArray
val mutable = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(mutable)
val h = mutable.height
val w = mutable.width
paint.textSize = h / 15f
paint.strokeWidth = h / 85f
var largestBoxIndex = -1
var largestBoxArea = 0.0
scores.forEachIndexed { index, fl ->
if (fl > 0.63) {
//val label = labels[classes[index].toInt()]
val boxArea =
(locations[index * 4 + 2] - locations[index * 4]) * (locations[index * 4 + 3] - locations[index * 4 + 1])
if (boxArea > largestBoxArea) {
largestBoxArea = boxArea.toDouble()
largestBoxIndex = index
}
}
}
if (largestBoxIndex != -1) {
val index = largestBoxIndex
val label = labels[classes[index].toInt()]
val boxLeft = locations[index * 4 + 1] * w
val boxTop = locations[index * 4] * h
val boxRight = locations[index * 4 + 3] * w
val boxBottom = locations[index * 4 + 2] * h
val boxHeight = (boxBottom - boxTop)
val boxWidth = (boxLeft - boxRight)
val sHeight = resources.displayMetrics.heightPixels
val strokeWidth = 4f
val textSize = 200f // Set your desired text size here
paint.textSize = textSize
paint.strokeWidth = strokeWidth
val distance = calculateDistance(boxHeight, label)
paint.color = colors[index]
paint.style = Paint.Style.STROKE
canvas.drawRect(RectF(boxLeft, boxTop, boxRight, boxBottom), paint)
paint.style = Paint.Style.FILL
canvas.drawText(label, boxLeft, boxTop, paint)
val formattedDistance = String.format("%.2f", distance)
canvas.drawText(formattedDistance, boxLeft, boxBottom, paint)
val obj_center_x = (boxLeft + boxRight) / 2
val obj_center_y = (boxTop + boxBottom) / 2
val camera_middle_x = resources.displayMetrics.widthPixels / 2.15
val camera_middle_y = resources.displayMetrics.heightPixels / 2
val vector_x = obj_center_x - camera_middle_x
val vector_y = obj_center_y - camera_middle_y
var angle_deg =
Math.toDegrees(atan2(vector_y.toDouble(), vector_x.toDouble()))
if (angle_deg < 0) {
angle_deg += 360
}
val direction: String = when {
0.0 <= angle_deg && angle_deg < 30.0 -> "middle right"
30.0 <= angle_deg && angle_deg < 60.0 -> "bottom right"
60.0 <= angle_deg && angle_deg < 89.9 -> "bottom right"
90.0 <= angle_deg && angle_deg < 120.0 -> "bottom middle"
120.0 <= angle_deg && angle_deg < 150.0 -> "bottom left"
150.0 <= angle_deg && angle_deg < 179.9 -> "bottom left"
180.0 <= angle_deg && angle_deg < 210.0 -> "middle left"
210.0 <= angle_deg && angle_deg < 240.0 -> "top left"
240.0 <= angle_deg && angle_deg < 269.9 -> "top left"
270.0 <= angle_deg && angle_deg < 300.0 -> "top middle"
300.0 <= angle_deg && angle_deg < 330.0 -> "top right"
330.0 <= angle_deg && angle_deg < 360.0 -> "top right"
else -> "center"
}
NavGuidance.speakObject("$label", distance, direction)
}
imageView.setImageBitmap(mutable)
}
}
cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
tts = TextToSpeech(this, this)
NavGuidance = NavGuidance(tts)
}
override fun onDestroy() {
super.onDestroy()
model.close()
if (tts.isSpeaking) {
tts.stop()
}
tts.shutdown()
}
@SuppressLint("MissingPermission")
private fun openCamera() {
cameraManager.openCamera(
cameraManager.cameraIdList[0],
object : CameraDevice.StateCallback() {
override fun onOpened(p0: CameraDevice) {
cameraDevice = p0
val surfaceTexture = textureView.surfaceTexture
val surface = Surface(surfaceTexture)
val captureRequest =
cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
captureRequest.addTarget(surface)
cameraDevice.createCaptureSession(listOf(surface),
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(p0: CameraCaptureSession) {
p0.setRepeatingRequest(captureRequest.build(), null, null)
}
override fun onConfigureFailed(p0: CameraCaptureSession) {}
}, handler
)
}
override fun onDisconnected(p0: CameraDevice) {}
override fun onError(p0: CameraDevice, p1: Int) {}
}, handler
)
}
private fun getPermission() {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), 101)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
getPermission()
}
}
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
val result = tts.setLanguage(Locale.US)
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED
) {
Log.e("TTS", "Language not supported")
}
} else {
Log.e("TTS", "Initialization failed")
}
}
private fun calculateDistance(boxHeight: Float, label:String): Double {
val knownObjectHeight = getKnownObjectHeight(label)
val screenHeight = resources.displayMetrics.heightPixels
val focalLength = getFocalLength()
val objectHeightInPixels = boxHeight * screenHeight
// Calculate distance using the formula
val distanceinMeters = (knownObjectHeight * screenHeight) / boxHeight
return distanceinMeters
}
private fun getFocalLength(): Float {
if (cameraCharacteristics == null) {
val cameraId = cameraManager.cameraIdList[0]
cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId)
}
return cameraCharacteristics?.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)?.get(0) ?: 0f
}
private fun getKnownObjectHeight(label: String): Double {
return when (label) {
"person" -> 0.70 // Average height of a person in meters
"bicycle" -> 1.15 // Average height of a bicycle in meters
"car" -> 1.0 // Average height of a car in meters
"motorcycle" -> 0.80 // Average height of a motorcycle in meters
"airplane" -> 4.0 // Average height of an airplane in meters
"bus" -> 2.0 // Average height of a bus in meters
"train" -> 2.0 // Average height of a train in meters
"truck" -> 2.0 // Average height of a truck in meters
"boat" -> 2.0 // Average height of a boat in meters
"traffic light" -> 1.0 // Average height of a traffic light in meters
"fire hydrant" -> 0.5 // Average height of a fire hydrant in meters
"stop sign" -> 0.70 // Average height of a stop sign in meters
"bench" -> 0.5 // Average height of a bench in meters
"bird" -> 0.2 // Average height of a bird in meters
"cat" -> 0.25 // Average height of a cat in meters
"dog" -> 0.3 // Average height of a dog in meters
"horse" -> 1.5 // Average height of a horse in meters
"sheep" -> 0.8 // Average height of a sheep in meters
"cow" -> 1.5 // Average height of a cow in meters
"elephant" -> 3.0 // Average height of an elephant in meters
"bear" -> 1.5 // Average height of a bear in meters
"zebra" -> 1.3 // Average height of a zebra in meters
"giraffe" -> 5.5 // Average height of a giraffe in meters
"backpack" -> 0.5 // Average height of a backpack in meters
"umbrella" -> 1.0 // Average height of an umbrella in meters
"handbag" -> 0.3 // Average height of a handbag in meters
"tie" -> 0.2 // Average height of a tie in meters
"suitcase" -> 0.6 // Average height of a suitcase in meters
"frisbee" -> 0.2 // Average height of a frisbee in meters
"skis" -> 1.8 // Average height of skis in meters
"snowboard" -> 1.5 // Average height of a snowboard in meters
"sports ball" -> 0.3 // Average height of a sports ball in meters
"kite" -> 1.0 // Average height of a kite in meters
"baseball bat" -> 1.0 // Average height of a baseball bat in meters
"baseball glove" -> 0.5 // Average height of a baseball glove in meters
"skateboard" -> 0.2 // Average height of a skateboard in meters
"surfboard" -> 2.0 // Average height of a surfboard in meters
"tennis racket" -> 1.0 // Average height of a tennis racket in meters
"bottle" -> 0.2 // Average height of a bottle in meters
"wine glass" -> 0.2 // Average height of a wine glass in meters
"cup" -> 0.1 // Average height of a cup in meters
"fork" -> 0.2 // Average height of a fork in meters
"knife" -> 0.2 // Average height of a knife in meters
"spoon" -> 0.2 // Average height of a spoon in meters
"bowl" -> 0.1 // Average height of a bowl in meters
"banana" -> 0.2 // Average height of a banana in meters
"apple" -> 0.1 // Average height of an apple in meters
"sandwich" -> 0.1 // Average height of a sandwich in meters
"orange" -> 0.1 // Average height of an orange in meters
"broccoli" -> 0.2 // Average height of broccoli in meters
"carrot" -> 0.2 // Average height of a carrot in meters
"hot dog" -> 0.1 // Average height of a hot dog in meters
"pizza" -> 0.2 // Average height of a pizza in meters
"donut" -> 0.1 // Average height of a donut in meters
"cake" -> 0.2 // Average height of a cake in meters
"chair" -> 0.65 // Average height of a chair in meters
"couch" -> 0.8 // Average height of a couch in meters
"potted plant" -> 0.4 // Average height of a potted plant in meters
"bed" -> 0.5 // Average height of a bed in meters
"dining table" -> 0.65 // Average height of a dining table in meters
"toilet" -> 0.4 // Average height of a toilet in meters
"tv" -> 0.55 // Average height of a TV in meters
"laptop" -> 0.3 // Average height of a laptop in meters
"mouse" -> 0.05 // Average height of a computer mouse in meters
"remote" -> 0.2 // Average height of a remote control in meters
"keyboard" -> 0.05 // Average height of a keyboard in meters
"cell phone" -> 0.15 // Average height of a cell phone in meters
"microwave" -> 0.3 // Average height of a microwave in meters
"oven" -> 0.8 // Average height of an oven in meters
"toaster" -> 0.2 // Average height of a toaster in meters
"sink" -> 0.7 // Average height of a sink in meters
"refrigerator" -> 0.75 // Average height of a refrigerator in meters
"book" -> 0.1 // Average height of a book in meters
"clock" -> 0.3 // Average height of a clock in meters
"vase" -> 0.3 // Average height of a vase in meters
"scissors" -> 0.2 // Average height of scissors in meters
"teddy bear" -> 0.3 // Average height of a teddy bear in meters
"hair drier" -> 0.2 // Average height of a hair drier in meters
"toothbrush" -> 0.2 // Average height of a toothbrush in meters
"door" -> 1.0
else -> 0.2 // Default value for other classes
}
}
}
| ViSimp-Navigation-System/app/src/main/java/com/cpe42020/Visimp/MainActivity.kt | 1082861550 |
package com.cpe42020.Visimp
import android.speech.tts.TextToSpeech
import android.util.Log
import android.os.Build
import java.util.Locale
class NavGuidance(private val tts: TextToSpeech) {
private var lastSpokenObject: String? = null
private var lastSpokenTimestamp: Long = 0
var left: String? = null
var right: String? = null
fun speakObject(objectName: String, distance: Double, direction: String) {
val currentTime = System.currentTimeMillis()
val timeSinceLastSpoken = currentTime - lastSpokenTimestamp
if (objectName != lastSpokenObject || timeSinceLastSpoken > 5000) {
val directionLower = direction.lowercase()
val instruction: String
if (distance <= 1.00) {
instruction = when {
"top right" in directionLower || "middle right" in directionLower || "bottom right" in directionLower -> {
"move left"
}
"top left" in directionLower || "middle left" in directionLower || "bottom left" in directionLower -> {
"move right"
}
else -> {
"check your sides"
}
}
} else {
instruction = "move forward"
}
when (instruction) {
"move left" -> {
left = objectName
speak("$objectName is near, move left")
}
"move right" -> {
right = objectName
speak("$objectName is near, move right")
}
"check your sides" -> {
if (left != null && right != null) {
speak("Objects on both sides, move backward")
left = null
right = null
} else {
speak("$objectName is in the middle, check your sides")
}
}
"move forward" -> {
speak("Object is far. Move forward")
}
}
lastSpokenObject = objectName
lastSpokenTimestamp = currentTime
}
}
private fun speak(text: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
} else {
val params = HashMap<String, String>()
params[TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID] = "stringId"
tts.speak(text, TextToSpeech.QUEUE_FLUSH, params)
}
}
} | ViSimp-Navigation-System/app/src/main/java/com/cpe42020/Visimp/NavGuidance.kt | 3477396724 |
package com.cpe42020.Visimp
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.graphics.Typeface
import android.view.View
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
import android.graphics.RectF
class CircleTextView(context: Context, attrs: AttributeSet?) : View(context, attrs) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val hourAngles = listOf(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 0)
private val labelIndices =
listOf("BR", "BR", "MB", "BL", "BL", "ML", "TL", "TL", "TM", "TR", "TR", "MR")
private val centerX: Float
private val centerY: Float
private val radius: Float
init {
paint.textSize = 50f
paint.typeface =
Typeface.create(Typeface.DEFAULT, Typeface.BOLD)// Adjust text size as needed
val displayMetrics = resources.displayMetrics
val screenWidth = displayMetrics.widthPixels
val screenHeight = displayMetrics.heightPixels
centerX = (screenWidth / 2.15f).toFloat()
centerY = (screenHeight / 2f).toFloat()
radius = min(centerX, centerY) * 0.9f // Adjust as needed
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Draw text around the circle
for ((i, angle) in hourAngles.withIndex()) {
val x = centerX + radius * cos(Math.toRadians(angle.toDouble())).toFloat()
val y = centerY + radius * 1.5f * sin(Math.toRadians(angle.toDouble())).toFloat()
canvas.drawText(labelIndices[i], x, y, paint)
val pointRadius = 15f
canvas.drawCircle(centerX, centerY, pointRadius, paint)
paint.color = Color.GREEN
canvas.drawText(labelIndices[i], x, y, paint)
}
}
}
| ViSimp-Navigation-System/app/src/main/java/com/cpe42020/Visimp/Circles.kt | 2182310827 |
package com.example.testuas
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.testuas", appContext.packageName)
}
} | testuas/app/src/androidTest/java/com/example/testuas/ExampleInstrumentedTest.kt | 3896503896 |
package com.example.testuas
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)
}
} | testuas/app/src/test/java/com/example/testuas/ExampleUnitTest.kt | 2711315231 |
package com.example.testuas.ui.theme
import android.app.Application
import com.example.testuas.data.DatabaseOrder
import com.example.testuas.repository.OfflineRepositoryOrder
class AplikasiOrderRoom : Application() {
lateinit var container: DependencyContainer
private set
override fun onCreate() {
super.onCreate()
container = DependencyContainer(this)
}
}
class DependencyContainer(private val application: Application) {
private val databaseOrder by lazy { DatabaseOrder.getDatabase(application) }
val offlineRepositoryOrder by lazy { OfflineRepositoryOrder(databaseOrder.orderRoomDao()) }
} | testuas/app/src/main/java/com/example/testuas/ui/theme/PenyediaViewModel.kt | 2282145506 |
@file:OptIn(ExperimentalMaterial3Api::class)
package com.example.testuas.ui.theme.halaman
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import com.example.testuas.Navigasi.DestinasiNavigasi
import com.example.testuas.R
import com.example.testuas.model.DetailOrderRoom
import com.example.testuas.model.UIStateOrderRoom
object DestinasiEntry: DestinasiNavigasi {
override val route = "item_entry"
override val titleRes = R.string.ordernow
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EntryOrderRoomBody(
uiStateOrderRoom: UIStateOrderRoom,
onOrderRoomValueChange: (DetailOrderRoom) -> Unit,
onSaveOrderRoomClick: () -> Unit,
onAddLCClick: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_large)),
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_medium))
) {
FormInputOrderRoom(
detailOrderRoom = uiStateOrderRoom.detailOrderRoom,
onValueChange = onOrderRoomValueChange,
modifier = Modifier.fillMaxWidth()
)
Button(
onClick = onSaveOrderRoomClick,
enabled = uiStateOrderRoom.isEntryValid,
shape = MaterialTheme.shapes.small,
modifier = Modifier.fillMaxWidth()
) {
Text(stringResource(id = R.string.btn_submit_order_room))
}
// Tombol untuk menambahkan LC
Button(
onClick = onAddLCClick,
enabled = true, // Sesuaikan dengan kondisi yang sesuai
shape = MaterialTheme.shapes.small,
modifier = Modifier.fillMaxWidth()
) {
Text(stringResource(id = R.string.add_lc))
}
}
}
@Composable
fun FormInputOrderRoom(
detailOrderRoom: DetailOrderRoom,
modifier: Modifier = Modifier,
onValueChange: (DetailOrderRoom) -> Unit = {},
enabled: Boolean = true
) {
Column(
modifier = Modifier,
verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.padding_medium))
) {
// Sesuaikan dengan entitas OrderRoom (nama, tanggal, durasi, harga, dll.)
OutlinedTextField(
value = detailOrderRoom.namaPelanggan,
onValueChange = { onValueChange(detailOrderRoom.copy(namaPelanggan = it)) },
label = { Text(stringResource(id = R.string.namaPelanggan)) },
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true
)
OutlinedTextField(
value = detailOrderRoom.tanggalSewa,
onValueChange = { onValueChange(detailOrderRoom.copy(tanggalSewa = it)) },
label = { Text(stringResource(id = R.string.tanggalSewa)) },
modifier = Modifier.fillMaxWidth(),
enabled = enabled,
singleLine = true
)
// Tambahkan field lainnya sesuai kebutuhan
// ...
val onSaveOrderRoomClick = null
val uiStateOrderRoom = null
fun EntryOrderRoomBody(
uiStateOrderRoom: UIStateOrderRoom,
onOrderRoomValueChange: (DetailOrderRoom) -> Unit,
onSaveOrderRoomClick: () -> Unit,
onAddLCClick: () -> Unit,
modifier: Modifier = Modifier
) {
// ...
Button(
onClick = onSaveOrderRoomClick,
enabled = uiStateOrderRoom.isEntryValid,
shape = MaterialTheme.shapes.small,
modifier = Modifier.fillMaxWidth()
) {
Text(stringResource(id = R.string.btn_submit_order_room))
}
}
}
} | testuas/app/src/main/java/com/example/testuas/ui/theme/halaman/HalamanEntry.kt | 2824956051 |
package com.example.testuas.ui.theme.halaman
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.testuas.Navigasi.DestinasiNavigasi
import com.example.testuas.R
import com.example.testuas.model.HomeViewModel
import com.example.testuas.model.PenyediaViewModel
object DestinasiHome : DestinasiNavigasi {
override val route = "home"
override val titleRes = R.string.app_name
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
navigateToAddLC: () -> Unit,
navigateToOrderRoom: () -> Unit,
modifier: Modifier = Modifier,
viewModel: HomeViewModel = viewModel(factory = PenyediaViewModel.Factory)
) {
val uiStateLC by viewModel.homeUiStateLC.collectAsState()
val uiStateOrderRoom by viewModel.homeUiState.collectAsState()
Scaffold(
modifier = modifier,
topBar = {
// ... sesuai kebutuhan
},
floatingActionButton = {
Row {
FloatingActionButton(
onClick = navigateToAddLC,
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_large))
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = R.string.lc)
)
}
Spacer(modifier = Modifier.width(dimensionResource(id = R.dimen.padding_small)))
FloatingActionButton(
onClick = navigateToOrderRoom,
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_large))
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = R.string.entry_order_room)
)
}
}
}
) { innerPadding ->
// Gunakan uiStateLC dan uiStateOrderRoom sesuai kebutuhan
BodyHome(
itemLC = uiStateLC.listLC,
itemOrderRoom = uiStateOrderRoom.listOrderRoom,
modifier = Modifier.padding(innerPadding).fillMaxSize()
)
}
}
@Composable
fun BodyHome(itemLC: Any, itemOrderRoom: Any, modifier: Modifier) {
}
| testuas/app/src/main/java/com/example/testuas/ui/theme/halaman/HomePage.kt | 3432250273 |
package com.example.testuas.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) | testuas/app/src/main/java/com/example/testuas/ui/theme/Color.kt | 2762690577 |
package com.example.testuas.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 TestuasTheme(
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
)
} | testuas/app/src/main/java/com/example/testuas/ui/theme/Theme.kt | 3041422931 |
package com.example.testuas.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
)
*/
) | testuas/app/src/main/java/com/example/testuas/ui/theme/Type.kt | 2193394570 |
package com.example.testuas.repository
import android.content.Context
import androidx.room.Database
import com.example.testuas.data.DatabaseOrder
interface ContainerApp{
val repositoryOrder : RepositoryOrder
}
class ContainerDataApp(private val context: Context): ContainerApp{
override val repositoryOrder: RepositoryOrder by lazy {
OfflineRepositoryOrder(DatabaseOrder.getDatabase(context).orderRoomDao())
}
} | testuas/app/src/main/java/com/example/testuas/repository/ContainerApp.kt | 3602120511 |
package com.example.testuas.repository
import com.example.testuas.data.OrderRoom
import com.example.testuas.data.OrderRoomDao
import kotlinx.coroutines.flow.Flow
class OfflineRepositoryOrder(private val orderRoomDao: OrderRoomDao) : RepositoryOrder {
override fun getAllOrder(): Flow<List<OrderRoom>> = orderRoomDao.getAllOrder()
override fun getOrder(id: Int): Flow<OrderRoom> = orderRoomDao.getOrder(id)
override suspend fun insertOrder(orderRoom: OrderRoom) = orderRoomDao.tambahPenyewaan(orderRoom)
override suspend fun deleteOrder(orderRoom: OrderRoom) = orderRoomDao.delete(orderRoom)
override suspend fun updateOrder(orderRoom: OrderRoom) = orderRoomDao.update(orderRoom)
override fun getOrderStream(id: Int): Flow<OrderRoom?> = orderRoomDao.getOrder(id)
// Implementasi tambahan untuk memenuhi persyaratan RepositoryOrder
override fun getAllOrderStream(): Flow<List<OrderRoom>> = orderRoomDao.getAllOrder()
} | testuas/app/src/main/java/com/example/testuas/repository/OfflineRepositoryOrder.kt | 4072090229 |
package com.example.testuas.repository
import com.example.testuas.data.OrderRoom
import kotlinx.coroutines.flow.Flow
interface RepositoryOrder {
fun getAllOrder(): Flow<List<OrderRoom>>
fun getOrder(id: Int): Flow<OrderRoom>
suspend fun insertOrder(orderRoom: OrderRoom)
suspend fun deleteOrder(orderRoom: OrderRoom)
suspend fun updateOrder(orderRoom: OrderRoom)
fun getAllOrderStream(): Flow<List<OrderRoom>>
fun getOrderStream(id: Int): Flow<OrderRoom?>
} | testuas/app/src/main/java/com/example/testuas/repository/RepositoryOrder.kt | 843774629 |
package com.example.testuas.repository
import com.example.testuas.data.LC
import com.example.testuas.data.LcDao
import kotlinx.coroutines.flow.Flow
class OfflineRepositoryLc(private val lcDao: LcDao) : RepositoryLc {
override fun getAllLC(): Flow<List<LC>> = lcDao.getAllLC()
override fun getLC(id: Int): Flow<LC> = lcDao.getLC(id)
override suspend fun insertLC(lc: LC) = lcDao.insertLC(lc)
override suspend fun deleteLC(lc: LC) = lcDao.deleteLC(lc)
override suspend fun updateLC(lc: LC) = lcDao.updateLC(lc)
}
| testuas/app/src/main/java/com/example/testuas/repository/OfflineRepositoryLc.kt | 563410916 |
package com.example.testuas.repository
import com.example.testuas.data.LC
import kotlinx.coroutines.flow.Flow
interface RepositoryLc {
fun getAllLC(): Flow<List<LC>>
fun getLC(id: Int): Flow<LC>
suspend fun insertLC(lc: LC)
suspend fun deleteLC(lc: LC)
suspend fun updateLC(lc: LC)
} | testuas/app/src/main/java/com/example/testuas/repository/RepositoryLc.kt | 2556222884 |
package com.example.testuas
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.testuas.ui.theme.TestuasTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TestuasTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
TestuasTheme {
Greeting("Android")
}
} | testuas/app/src/main/java/com/example/testuas/MainActivity.kt | 2177511788 |
package com.example.testuas.model
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testuas.data.OrderRoom
import com.example.testuas.repository.OfflineRepositoryLc
import com.example.testuas.repository.OfflineRepositoryOrder
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class HomeViewModel(private val repositoryOrder: OfflineRepositoryOrder,
private val repositoryLC: OfflineRepositoryLc
) : ViewModel() {
companion object {
private const val TIMEOUT_MILLIS = 5_000L
}
data class HomeUiState(
val listOrder: List<OrderRoom> = listOf()
)
val homeUiStateLC: StateFlow<HomeUiState> = repositoryOrder.getAllOrderStream()
val homeUiState: StateFlow<HomeUiState> = repositoryOrder.getAllOrderStream()
.filterNotNull()
.map { HomeUiState(listOrder = it.toList()) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
initialValue = HomeUiState()
)
} | testuas/app/src/main/java/com/example/testuas/model/HomeViewModel.kt | 3373190061 |
package com.example.testuas.model
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.testuas.ui.theme.AplikasiOrderRoom
object PenyediaViewModel {
val Factory = viewModelFactory {
initializer {
HomeViewModel(aplikasiOrderRoom().container.offlineRepositoryOrder)
}
initializer {
OrderRoomViewModel(aplikasiOrderRoom().container.offlineRepositoryOrder)
}
initializer {
OrderRoomViewModel(aplikasiOrderRoom().container.offlineRepositoryOrder)
}
}
}
fun CreationExtras.aplikasiOrderRoom(): AplikasiOrderRoom =
(this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as AplikasiOrderRoom) | testuas/app/src/main/java/com/example/testuas/model/PenyediaViewModel.kt | 3323696298 |
package com.example.testuas.model
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.testuas.data.LC
import com.example.testuas.data.OrderRoom
import com.example.testuas.data.OrderRoomDao
import com.example.testuas.repository.OfflineRepositoryOrder
import com.example.testuas.repository.RepositoryOrder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class OrderRoomViewModel(private val repositoryOrder: OfflineRepositoryOrder): ViewModel() {
var uiStateOrderRoom by mutableStateOf(UIStateOrderRoom())
private set
private fun validateInput(uiState: DetailOrderRoom = uiStateOrderRoom.detailOrderRoom): Boolean {
return with(uiState) {
namaPelanggan.isNotBlank() && tanggalSewa.isNotBlank() && durasiSewaJam > 0
}
}
fun updateUiState(detailOrderRoom: DetailOrderRoom) {
uiStateOrderRoom =
UIStateOrderRoom(detailOrderRoom = detailOrderRoom, isEntryValid = validateInput(detailOrderRoom))
}
suspend fun saveOrderRoom() {
if (validateInput()) {
repositoryOrder.insertOrder(uiStateOrderRoom.detailOrderRoom.toOrderRoom())
}
}
}
data class UIStateOrderRoom(
val detailOrderRoom: DetailOrderRoom = DetailOrderRoom(),
val isEntryValid: Boolean = false
)
data class DetailOrderRoom(
val id: Long = 0,
val namaPelanggan: String = "",
val tanggalSewa: String = "",
val durasiSewaJam: Int = 0,
val hargaTotal: Double = 0.0
)
fun DetailOrderRoom.toOrderRoom(): OrderRoom = OrderRoom(
id = id,
namaPelanggan = namaPelanggan,
tanggalSewa = tanggalSewa,
durasiSewaJam = durasiSewaJam,
hargaTotal = hargaTotal
)
fun OrderRoom.toDetailOrderRoom(): DetailOrderRoom = DetailOrderRoom(
id = id,
namaPelanggan = namaPelanggan,
tanggalSewa = tanggalSewa,
durasiSewaJam = durasiSewaJam,
hargaTotal = hargaTotal
)
fun OrderRoom.toUiStateOrderRoom(isEntryValid: Boolean = false): UIStateOrderRoom = UIStateOrderRoom(
detailOrderRoom = this.toDetailOrderRoom(),
isEntryValid = isEntryValid
) | testuas/app/src/main/java/com/example/testuas/model/OrderRoomViewModel.kt | 3520539350 |
package com.example.testuas.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "table_lc")
data class LC(
@PrimaryKey(autoGenerate = true)
val lcid: Long = 0,
val lcname: String
) | testuas/app/src/main/java/com/example/testuas/data/LC.kt | 682151125 |
package com.example.testuas.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "penyewaan_karaoke")
data class OrderRoom(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val namaPelanggan: String,
val tanggalSewa: String,
val durasiSewaJam: Int,
val hargaTotal: Double
)
| testuas/app/src/main/java/com/example/testuas/data/OrderRoom.kt | 2518053226 |
package com.example.testuas.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface OrderRoomDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun tambahPenyewaan(orderRoom: OrderRoom)
@Update
suspend fun update(orderRoom: OrderRoom)
@Delete
suspend fun delete(orderRoom: OrderRoom)
@Query("SELECT * from penyewaan_karaoke WHERE id = :id")
fun getOrder(id: Int): Flow<OrderRoom>
@Query("SELECT * from penyewaan_karaoke ORDER BY namaPelanggan ASC")
fun getAllOrder() : Flow<List<OrderRoom>>
}
| testuas/app/src/main/java/com/example/testuas/data/OrderRoomDao.kt | 3434215624 |
package com.example.testuas.data
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface LcDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertLC(lc: LC)
@Query("SELECT * from table_lc ORDER BY lcname ASC") // Ganti someField dengan nama field yang sesuai di LC
fun getAllLC(): Flow<List<LC>>
// Fungsi tambahan untuk mendapatkan LC berdasarkan ID
@Query("SELECT * from table_lc WHERE lcid = :id")
fun getLC(id: Int): Flow<LC>
@Delete
suspend fun deleteLC(lc: LC)
@Update
suspend fun updateLC(lc: LC)
} | testuas/app/src/main/java/com/example/testuas/data/LcDao.kt | 1957757560 |
package com.example.testuas.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlin.reflect.KClass
@Database(entities = [OrderRoom::class], version = 1, exportSchema = false)
abstract class DatabaseOrder : RoomDatabase() {
abstract fun orderRoomDao() : OrderRoomDao
companion object {
@Volatile
private var Instance: DatabaseOrder? = null
fun getDatabase(context: Context): DatabaseOrder {
return (Instance ?: synchronized(this) {
Room.databaseBuilder(context, DatabaseOrder::class.java, "order_database").build()
.also { Instance = it }
})
}
}
} | testuas/app/src/main/java/com/example/testuas/data/Database.kt | 2620823210 |
package com.example.testuas.Navigasi
interface DestinasiNavigasi {
val route: String
val titleRes: Int
} | testuas/app/src/main/java/com/example/testuas/Navigasi/DestinasiNavigasi.kt | 2672055428 |
package com.example.foodapp
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.foodapp", appContext.packageName)
}
} | MDP-FoodiePal/app/src/androidTest/java/com/example/foodapp/ExampleInstrumentedTest.kt | 1358944368 |
package com.example.foodapp
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)
}
} | MDP-FoodiePal/app/src/test/java/com/example/foodapp/ExampleUnitTest.kt | 956361102 |
package com.example.foodapp
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import com.example.foodapp.data.User
import com.example.foodapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private var users = ArrayList<User>()
private lateinit var username: EditText
private lateinit var password: EditText
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initialSetup()
loginListener()
checkCredentials(this)
}
fun checkCredentials(context: Context): Unit {
val sharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
val uname = sharedPreferences.getString("username", null)
val pwd = sharedPreferences.getString("password", null)
if(uname != null && pwd != null) {
users.forEach{
if(it.username == uname && it.password == pwd) {
gotoHome(it)
}
}
}
}
private fun saveCredentials(user: User, context: Context) {
val sharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("username", user.username)
editor.putString("password", user.password)
editor.apply()
}
private fun initialSetup() {
username = binding.username
password = binding.password
val usersArray = resources.obtainTypedArray(R.array.users)
for (i in 0 until usersArray.length()) {
val userArrayResourceId = usersArray.getResourceId(i, 0)
val user = resources.getStringArray(userArrayResourceId)
users.add(User(user[0], user[1], user[2]))
}
}
private fun loginListener() {
binding.signIn.setOnClickListener{
val uname: String = username.text.toString().trim()
val pwd: String = password.text.toString().trim()
users.forEach{
if(it.username == uname && it.password == pwd) {
saveCredentials(it, this)
gotoHome(it)
}
}
}
}
private fun gotoHome(user: User) {
val intent = Intent(this, HomeActivity::class.java)
intent.putExtra("user", user)
startActivity(intent)
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/MainActivity.kt | 815903536 |
package com.example.foodapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.view.forEach
import androidx.core.view.setPadding
import androidx.viewpager2.widget.ViewPager2
import com.example.foodapp.adapter.ViewPagerAdapter
import com.example.foodapp.data.Recipe
import com.example.foodapp.databinding.ActivityHomeBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
class HomeActivity : AppCompatActivity() {
private lateinit var binding: ActivityHomeBinding
lateinit var tablayout: TabLayout
private lateinit var viewPager: ViewPager2
private lateinit var fab: FloatingActionButton
private lateinit var bottomNav: BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
setupTabs()
onFabAction()
}
private fun onFabAction() {
binding.fab.setOnClickListener{
val currentFragment = supportFragmentManager.findFragmentByTag("f${binding.viewPager.currentItem}")
if (currentFragment is RecipesFragment) {
showAddRecipe(currentFragment)
} else if(currentFragment is BlogFragment) {
showAddBlog(currentFragment)
} else if(currentFragment is AboutMeFragment) {
showAddAbout(currentFragment)
}
}
}
private fun showAddAbout(aboutMe: AboutMeFragment) {
val builder = AlertDialog.Builder(this)
var aboutMeLayout: LinearLayout? = aboutMe.getRelativeLayout()
builder.setTitle("Add a new info")
val alertLayout = LinearLayout(this)
alertLayout.orientation = LinearLayout.VERTICAL
val field = EditText(this)
field.hint = "Field"
alertLayout.addView(field)
val value = EditText(this)
value.hint = "Value"
alertLayout.addView(value)
builder.setView(alertLayout)
builder.setPositiveButton("OK") { dialog, _ ->
val ll = LinearLayout(this)
ll.orientation = LinearLayout.HORIZONTAL
val fieldText = TextView(this)
fieldText.text = field.text.toString()
fieldText.layoutParams = aboutMe.getLayoutParams(RelativeLayout.BELOW, aboutMe.getLeftElement())
ll.addView(fieldText)
val valueText = TextView(this)
valueText.setPadding(20, 0, 0, 0)
valueText.text = value.text.toString()
ll.addView(valueText)
aboutMeLayout?.addView(ll)
aboutMe.setLeftRighElement(fieldText, valueText)
dialog.dismiss()
}
builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
private fun showAddRecipe(recipesFragment: RecipesFragment) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Add a new recipe")
val alertLayout = LinearLayout(this)
alertLayout.orientation = LinearLayout.VERTICAL
val recipeTitle = EditText(this)
recipeTitle.hint = "Recipe title"
alertLayout.addView(recipeTitle)
val recipeIngredients = EditText(this)
recipeIngredients.hint = "Ingredients"
recipeIngredients.setLines(5)
alertLayout.addView(recipeIngredients)
val recipeInstruction = EditText(this)
recipeInstruction.hint = "Instructions"
alertLayout.addView(recipeInstruction)
builder.setView(alertLayout)
builder.setPositiveButton("OK") { dialog, _ ->
val newRecipe = Recipe(recipeTitle.text.toString(), recipeIngredients.text.toString(), recipeInstruction.text.toString())
recipesFragment.addRecipe(newRecipe)
dialog.dismiss()
}
builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
private fun showAddBlog(blog: BlogFragment) {
var linearLayout: LinearLayout? = blog.getlinearLayout()
val builder = AlertDialog.Builder(this)
builder.setTitle("Add a new Blog")
val editText = EditText(this)
editText.hint = "Enter message"
builder.setView(editText)
builder.setPositiveButton("OK") { dialog, _ ->
val tv = TextView(this)
tv.text = editText.text.toString()
linearLayout?.addView(tv)
dialog.dismiss()
}
builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
fun setupTabs() {
tablayout = binding.tabLayout
viewPager = binding.viewPager
fab = binding.fab
bottomNav = binding.bottomNav
val adapter = ViewPagerAdapter(this)
adapter.addFragment(RecipesFragment())
adapter.addFragment(MealPlannerFragment())
adapter.addFragment(BlogFragment())
adapter.addFragment(ContactFragment())
adapter.addFragment(AboutMeFragment())
viewPager.adapter = adapter
TabLayoutMediator(tablayout, viewPager) { tab, pos ->
tab.text = getTabName(adapter.createFragment(pos).javaClass.simpleName)
}.attach()
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
if (position in arrayOf(0, 2, 4)) {
fab.visibility = View.VISIBLE
} else {
fab.visibility = View.GONE
}
}
})
bottomNav.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.recipesNav -> viewPager.currentItem = 0
R.id.mealPlannerNav -> viewPager.currentItem = 1
R.id.blogsNav -> viewPager.currentItem = 2
}
true
}
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (position in arrayOf(0, 1, 2)) {
bottomNav.menu.getItem(position).isChecked = true
} else {
bottomNav.menu.forEach {
it.isChecked = false
}
}
}
})
}
private val mOnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
when (position) {
0 -> bottomNav.selectedItemId = R.id.recipesNav
1 -> bottomNav.selectedItemId = R.id.mealPlannerNav
2 -> bottomNav.selectedItemId = R.id.blogsNav
}
}
}
fun getTabName(input: String): String {
return input
.replace("Fragment", "")
.replace(Regex("([a-z])([A-Z])"), "$1 $2")
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/HomeActivity.kt | 1505788089 |
package com.example.foodapp
import android.icu.util.Calendar
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CalendarView
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.example.foodapp.data.Recipe
import java.text.SimpleDateFormat
import java.util.Locale
// 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 [MealPlannerFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class MealPlannerFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var selectedDates = mutableSetOf<Long>()
private lateinit var view: View
private lateinit var mealplanner: LinearLayout
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? {
view = inflater.inflate(R.layout.fragment_meal_planner, container, false)
mealplanner = view.findViewById(R.id.mealplanner)
selectDate()
initialSetup()
return view
}
private fun initialSetup() {
val mealplansArray = resources.obtainTypedArray(R.array.meal_plans)
for (i in 0 until mealplansArray.length()) {
val mealplansArrayResourceId = mealplansArray.getResourceId(i, 0)
val mealplan = resources.getStringArray(mealplansArrayResourceId)
addItem(mealplan[0] + "\t\t\t\t\t" + mealplan[1])
}
}
fun selectDate() {
val calendar = view.findViewById<CalendarView>(R.id.calendarView)
calendar.setOnDateChangeListener { _, year, month, dayOfMonth ->
val selectedDate = Calendar.getInstance()
selectedDate.set(year, month, dayOfMonth)
val dateFormat = SimpleDateFormat("EEEE", Locale.getDefault())
val dayOfWeek = dateFormat.format(selectedDate.time)
addMealPlan("$month-$dayOfMonth-$year $dayOfWeek")
println("$month-$dayOfWeek-$year $dayOfWeek")
}
}
private fun addMealPlan(date: String) {
val builder = AlertDialog.Builder(view.context)
builder.setTitle("Add a Meal Plan")
val editText = EditText(view.context)
editText.hint = "Enter meals"
builder.setView(editText)
builder.setPositiveButton("OK") { dialog, _ ->
addItem(date + "\t\t\t\t\t" + editText.text.toString())
dialog.dismiss()
}
builder.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
}
private fun addItem(text: String) {
val tv = TextView(view.context)
tv.text = text
mealplanner.addView(tv)
}
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 MealPlannerFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
MealPlannerFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
| MDP-FoodiePal/app/src/main/java/com/example/foodapp/MealPlannerFragment.kt | 1135041394 |
package com.example.foodapp.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
class ViewPagerAdapter(fa: FragmentActivity): FragmentStateAdapter(fa) {
private var fragments = ArrayList<Fragment>()
override fun getItemCount(): Int {
return fragments.size
}
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
fun addFragment(f: Fragment): Unit {
fragments.add(f)
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/adapter/ViewPagerAdapter.kt | 3688821320 |
package com.example.foodapp
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.foodapp.data.Recipe
import com.google.android.material.floatingactionbutton.FloatingActionButton
// 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 [RecipesFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class RecipesFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var recipes = ArrayList<Recipe>()
private lateinit var recyclerView: RecyclerView
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? {
initialSetup()
val view = inflater.inflate(R.layout.fragment_recipes, container, false)
recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
val adapter = RecipeAdapter(recipes)
recyclerView.adapter = adapter
return view
}
private fun initialSetup() {
val recipesArray = resources.obtainTypedArray(R.array.recipes)
for (i in 0 until recipesArray.length()) {
val recipesArrayResourceId = recipesArray.getResourceId(i, 0)
val recipe = resources.getStringArray(recipesArrayResourceId)
recipes.add(Recipe(recipe[0], recipe[1], recipe[2]))
}
}
fun addRecipe(recipe: Recipe) {
recipes.add(recipe)
val adapter = RecipeAdapter(recipes)
recyclerView.adapter = adapter
}
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 RecipesFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
RecipesFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
fun getRelativeLayout(): LinearLayout? {
return view?.findViewById(com.google.android.material.R.id.layout)
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/RecipesFragment.kt | 422896077 |
package com.example.foodapp
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.foodapp.data.Recipe
class RecipeAdapter(private val recipes: List<Recipe>) : RecyclerView.Adapter<RecipeAdapter.RecipeViewHolder>() {
override fun onBindViewHolder(holder: RecipeViewHolder, position: Int) {
val recipe = recipes[position]
holder.recipeTitle.text = recipe.name
holder.instruction.text = recipe.instruction
holder.ingredients.text = recipe.ingredients
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipeViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recipe_layout, parent, false)
return RecipeViewHolder(view)
}
override fun getItemCount(): Int = recipes.size
class RecipeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var recipeTitle = itemView.findViewById<TextView>(R.id.recipeTitle)
var ingredients = itemView.findViewById<TextView>(R.id.ingredients)
var instruction = itemView.findViewById<TextView>(R.id.instruction)
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/RecipeAdapter.kt | 1389124630 |
package com.example.foodapp
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
// 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 [ContactFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ContactFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var view: View
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? {
view = inflater.inflate(R.layout.fragment_contact, container, false)
setupCall()
setupEmail()
return view
}
private fun setupEmail() {
view.findViewById<Button>(R.id.send).setOnClickListener{
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]"))
intent.putExtra(Intent.EXTRA_SUBJECT, "Contact message")
val name = view.findViewById<EditText>(R.id.nameText)
val emailId = view.findViewById<EditText>(R.id.emailText)
val messageText = view.findViewById<EditText>(R.id.messageText)
intent.putExtra(Intent.EXTRA_TEXT, "$name \n $emailId \n $messageText")
startActivity(Intent.createChooser(intent, "Sending email..."))
}
}
private fun setupCall() {
view.findViewById<Button>(R.id.call).setOnClickListener{
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567890"))
startActivity(intent)
}
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
ContactFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/ContactFragment.kt | 385910439 |
package com.example.foodapp.data
import java.io.Serializable
data class Recipe(var name: String, var instruction: String, var ingredients: String) {
constructor(name: String, instruction: String): this(name, instruction, ""){
this.name = name;
this.instruction = instruction
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/data/Recipe.kt | 1227760151 |
package com.example.foodapp.data
import java.io.Serializable
data class User(val username: String,
val password: String,
val name: String,
): Serializable {
override fun toString(): String = "$username $password"
}
| MDP-FoodiePal/app/src/main/java/com/example/foodapp/data/User.kt | 4139135988 |
package com.example.foodapp
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.example.foodapp.data.User
import java.io.Serializable
// 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 [AboutMeFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class AboutMeFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var view: View
private lateinit var layout: LinearLayout
private lateinit var leftElement: TextView
private lateinit var rightElement: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_about_me, container, false)
setupInitial()
return view
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun setupInitial() {
val receivedIntent = activity?.intent
val user: User? = receivedIntent?.getSerializableExtra("user", User::class.java)
layout = view.findViewById(R.id.aboutMeLayout)
var ll = LinearLayout(view.context)
ll.orientation = LinearLayout.HORIZONTAL
val nameLabel = TextView(view.context)
nameLabel.text = "Name"
nameLabel.id = R.id.name_label_id
ll.addView(nameLabel)
val name = TextView(view.context)
name.setPadding(20, 0, 0, 0)
name.text = user?.name
name.id = R.id.name_text_id
ll.addView(name)
layout.addView(ll)
leftElement = nameLabel
rightElement =name
}
fun getLayoutParams(pos: Int, id: Int): RelativeLayout.LayoutParams {
val layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
layoutParams.addRule(pos, id)
return layoutParams
}
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 AboutMeFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
AboutMeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
fun getRelativeLayout(): LinearLayout? {
return view?.findViewById(R.id.aboutMeLayout)
}
fun getLeftElement(): Int {
return leftElement.id
}
fun getRightElement(): Int {
return rightElement.id
}
fun setLeftRighElement(left: TextView, right: TextView): Unit {
leftElement = left
rightElement = right
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/AboutMeFragment.kt | 2909375798 |
package com.example.foodapp
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
// 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 [BlogFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class BlogFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private var blogs = ArrayList<String>()
private lateinit var linearLayout: LinearLayout
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
val view = inflater.inflate(R.layout.fragment_blog, container, false)
initialSetup(view)
return view
}
private fun initialSetup(view: View) {
val blogsArray = resources.getStringArray(R.array.blogs)
linearLayout = view.findViewById(R.id.blogLayout)
blogsArray.forEach {
val tv = TextView(view.context)
tv.text = it.toString()
linearLayout.addView(tv)
}
}
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 BlogFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
BlogFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
fun getlinearLayout(): LinearLayout? {
return view?.findViewById(R.id.blogLayout)
}
} | MDP-FoodiePal/app/src/main/java/com/example/foodapp/BlogFragment.kt | 2327651823 |
package com.example.tddmasterclass.playlist
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.example.tddmasterclass.BaseUITest
import com.example.tddmasterclass.R
import com.schibsted.spain.barista.assertion.BaristaRecyclerViewAssertions.assertRecyclerViewItemCount
import com.schibsted.spain.barista.assertion.BaristaVisibilityAssertions.assertDisplayed
import com.schibsted.spain.barista.assertion.BaristaVisibilityAssertions.assertNotDisplayed
import com.schibsted.spain.barista.internal.matcher.DrawableMatcher.Companion.withDrawable
import org.hamcrest.Matchers.allOf
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class PlayListFeature : BaseUITest() {
@Test
fun displayScreenTitle() {
assertDisplayed("Playlists")
}
@Test
fun displayListOfPlaylists() {
assertRecyclerViewItemCount(R.id.playlists_list, 10)
onView(allOf(withId(R.id.playlist_name), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 0))))
.check(matches(withText("Hard Rock Cafe")))
.check(matches(isDisplayed()))
onView(allOf(withId(R.id.playlist_category), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 0))))
.check(matches(withText("rock")))
.check(matches(isDisplayed()))
onView(allOf(withId(R.id.playlist_image), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 1))))
.check(matches(withDrawable(R.mipmap.playlist)))
.check(matches(isDisplayed()))
}
@Test
fun hideLoader() {
assertNotDisplayed(R.id.loader)
}
@Test
fun displayRockImageFroRockListItems() {
onView(allOf(withId(R.id.playlist_image), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 0))))
.check(matches(withDrawable(R.mipmap.rock)))
.check(matches(isDisplayed()))
onView(allOf(withId(R.id.playlist_image), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 3))))
.check(matches(withDrawable(R.mipmap.rock)))
.check(matches(isDisplayed()))
}
@Test
fun navigateToDetailScreen() {
onView(allOf(withId(R.id.playlist_image), isDescendantOfA(nthChildOf(withId(R.id.playlists_list), 0))))
.perform(click())
assertDisplayed(R.id.playlist_details_root)
}
} | tddmasterclass/app/src/androidTest/java/com/example/tddmasterclass/playlist/PlayListFeature.kt | 3939651649 |
package com.example.tddmasterclass
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.IdlingResource
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule
import com.example.tddmasterclass.utils.TestIdlingResource
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
abstract class BaseUITest {
@get:Rule
val mActivityRule = ActivityTestRule(MainActivity::class.java)
private lateinit var idlingResource: IdlingResource
@Before
open fun registerIdlingResource() {
idlingResource = TestIdlingResource.countingIdlingResource
IdlingRegistry.getInstance().register(idlingResource)
}
@After
fun tearDown() {
IdlingRegistry.getInstance().unregister(idlingResource)
}
fun nthChildOf(parentMatcher: Matcher<View>, childPosition: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("position $childPosition of parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
if (view.parent !is ViewGroup) return false
val parent = view.parent as ViewGroup
return (parentMatcher.matches(parent)
&& parent.childCount > childPosition
&& parent.getChildAt(childPosition) == view)
}
}
}
} | tddmasterclass/app/src/androidTest/java/com/example/tddmasterclass/BaseUITest.kt | 2414736134 |
package com.example.tddmasterclass.details
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.example.tddmasterclass.BaseUITest
import com.example.tddmasterclass.R
import com.schibsted.spain.barista.assertion.BaristaVisibilityAssertions.assertDisplayed
import org.hamcrest.CoreMatchers
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class PlaylistDetailsFeature : BaseUITest() {
@Test
fun displayPlaylistNameAndDetails() {
navigateToPlaylistDetails(0)
assertDisplayed("Hard Rock Cafe")
assertDisplayed("Rock your senses with this timeless signature vibe list. \n\n • Poison \n • You shook me all night \n • Zombie \n • Rock'n Me \n • Thunderstruck \n • I Hate Myself for Loving you \n • Crazy \n • Knockin' on Heavens Door")
}
@Test
fun displaysErrorMessageWhenNetworkFails() {
navigateToPlaylistDetails(1)
assertDisplayed(R.string.generic_error)
}
private fun navigateToPlaylistDetails(position: Int) {
onView(
CoreMatchers.allOf(
withId(R.id.playlist_image),
isDescendantOfA(
nthChildOf(
withId(R.id.playlists_list),
position
)
)
)
).perform(ViewActions.click())
}
} | tddmasterclass/app/src/androidTest/java/com/example/tddmasterclass/details/PlaylistDetailsFeature.kt | 3906195771 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.utils.BaseUnitTest
import com.example.tddmasterclass.utils.captureValues
import com.example.tddmasterclass.utils.getValueForTest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
class PlaylistViewModelShould : BaseUnitTest() {
private val repository: PlaylistRepository = mock(PlaylistRepository::class.java)
private val playlists = mock<List<Playlist>>()
private val expected = Result.success(playlists)
private val exception = RuntimeException("Something went wrong")
@Test
fun getPlaylistsFromRepository() = runBlockingTest {
val viewModel = mockSuccessfulCase()
viewModel.playlists.getValueForTest()
verify(repository, times(1)).getPlaylists()
}
@Test
fun emitsPlaylistsFromRepository() = runBlockingTest {
val viewModel = mockSuccessfulCase()
assertEquals(expected, viewModel.playlists.getValueForTest())
}
@Test
fun emitErrorWhenReceiveError() {
val viewModel = mockErrorCase()
assertEquals(exception, viewModel.playlists.getValueForTest()!!.exceptionOrNull()!!)
}
@Test
fun showSpinnerWhileLoading() = runBlockingTest {
val viewModel = mockSuccessfulCase()
viewModel.loader.captureValues {
viewModel.playlists.getValueForTest()
assertEquals(true, values[0])
}
}
@Test
fun closeLoaderAfterPlaylistsLoad() = runBlockingTest{
val viewModel = mockSuccessfulCase()
viewModel.loader.captureValues {
viewModel.playlists.getValueForTest()
assertEquals(false, values.last())
}
}
private fun mockErrorCase(): PlaylistViewModel {
runBlocking {
Mockito.`when`(repository.getPlaylists()).thenReturn(
flow {
emit(Result.failure(exception))
}
)
}
return PlaylistViewModel(repository)
}
private fun mockSuccessfulCase(): PlaylistViewModel {
runBlocking {
Mockito.`when`(repository.getPlaylists()).thenReturn(
flow {
emit(expected)
}
)
}
return PlaylistViewModel(repository)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/playlist/PlaylistViewModelShould.kt | 4159520928 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.playlist.PlaylistAPI
import com.example.tddmasterclass.playlist.PlaylistRaw
import com.example.tddmasterclass.playlist.PlaylistService
import com.example.tddmasterclass.utils.BaseUnitTest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
class PlaylistServiceShould : BaseUnitTest() {
private lateinit var service: PlaylistService
private val api: PlaylistAPI = mock()
private val playlists: List<PlaylistRaw> = mock()
private val exception = RuntimeException("Something went wrong")
@Test
fun convertValuesToFlowResultAndEmitsThem() = runBlockingTest {
mockSuccessfulCase()
assertEquals(Result.success(playlists), service.fetchPlaylists().first())
}
@Test
fun emitsErrorResultWhenNetworkFails() = runBlockingTest {
mockErrorCase()
assertEquals("Something went wrong",
service.fetchPlaylists().first().exceptionOrNull()?.message)
}
private suspend fun mockErrorCase() {
`when`(api.fetchAllPlaylists()).thenThrow(exception)
service = PlaylistService(api)
}
private suspend fun mockSuccessfulCase() {
`when`(api.fetchAllPlaylists()).thenReturn(playlists)
service = PlaylistService(api)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/playlist/PlaylistServiceShould.kt | 3112812437 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.playlist.Playlist
import com.example.tddmasterclass.playlist.PlaylistMapper
import com.example.tddmasterclass.playlist.PlaylistRaw
import com.example.tddmasterclass.playlist.PlaylistRepository
import com.example.tddmasterclass.playlist.PlaylistService
import com.example.tddmasterclass.utils.BaseUnitTest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.`when`
import org.mockito.Mockito.verify
class PlaylistRepositoryShould : BaseUnitTest() {
private val service: PlaylistService = mock()
private val mapper: PlaylistMapper = mock()
private val playlists = mock<List<Playlist>>()
private val playlistsRaw = mock<List<PlaylistRaw>>()
private val exception = RuntimeException("Something went wrong")
@Test
fun getPlaylistsFromService() = runBlockingTest {
val repository = mockSuccessfulCase()
repository.getPlaylists()
verify(service, times(1)).fetchPlaylists()
}
@Test
fun emitMappedPlaylistsFromService() = runBlockingTest {
val repository = mockSuccessfulCase()
assertEquals(playlists, repository.getPlaylists().first().getOrNull())
}
@Test
fun propagateErrors() = runBlockingTest {
val repository = mockFailureCase()
assertEquals(exception, repository.getPlaylists().first().exceptionOrNull())
}
private suspend fun mockSuccessfulCase(): PlaylistRepository {
`when`(service.fetchPlaylists()).thenReturn(
flow {
emit(Result.success(playlistsRaw))
}
)
`when`(mapper.invoke(playlistsRaw)).thenReturn(playlists)
return PlaylistRepository(service, mapper)
}
private suspend fun mockFailureCase(): PlaylistRepository {
`when`(service.fetchPlaylists()).thenReturn(
flow {
emit(Result.failure(exception))
}
)
return PlaylistRepository(service, mapper)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/playlist/PlaylistRepositoryShould.kt | 3823784505 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.R
import com.example.tddmasterclass.utils.BaseUnitTest
import org.junit.Assert.assertEquals
import org.junit.Test
class PlaylistMapperShould : BaseUnitTest() {
private val playlistRaw = PlaylistRaw("1", "da name", "da category")
private val playlistRawRock = PlaylistRaw("1", "da name", "rock")
private val mapper = PlaylistMapper()
private val playlists = mapper(listOf(playlistRaw))
private val playlist = playlists[0]
private val playlistRock = mapper(listOf(playlistRawRock))[0]
@Test
fun keepSameId() {
assertEquals(playlistRaw.id, playlist.id)
}
@Test
fun keepSameName() {
assertEquals(playlistRaw.name, playlist.name)
}
@Test
fun keepSameCategory() {
assertEquals(playlistRaw.category, playlist.category)
}
@Test
fun mapDefaultImageWhenNotRock() {
assertEquals(R.mipmap.playlist, playlist.image)
}
@Test
fun mapRockImageWhenRockCategory() {
assertEquals(R.mipmap.rock, playlistRock.image)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/playlist/PlaylistMapperShould.kt | 3895900818 |
package com.example.tddmasterclass.details
import com.example.tddmasterclass.utils.BaseUnitTest
import com.example.tddmasterclass.utils.captureValues
import com.example.tddmasterclass.utils.getValueForTest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
class PlaylistDetailsViewModelShould : BaseUnitTest() {
private lateinit var viewModel: PlaylistDetailsViewModel
private val service: PlaylistDetailsService = mock()
private val id = "1"
private val playlistDetails: PlaylistDetails = mock()
private val expected = Result.success(playlistDetails)
private val exception = RuntimeException("Something went wrong!")
private val error = Result.failure<PlaylistDetails>(exception)
@Test
fun getPlaylistDetailsFromService() = runBlockingTest {
viewModel = mockSuccessfulCase()
viewModel.getPlaylistDetails(id)
verify(service, times(1)).fetchPlaylistDetails(id)
}
@Test
fun emitsPlaylistDetailsFromService() = runBlockingTest {
viewModel = mockSuccessfulCase()
viewModel.getPlaylistDetails(id)
assertEquals(expected, viewModel.playlistDetails.getValueForTest())
}
@Test
fun emitErrorWhenServiceFails() = runBlockingTest {
viewModel = mockErrorCase()
viewModel.getPlaylistDetails(id)
assertEquals(error, viewModel.playlistDetails.getValueForTest())
}
@Test
fun showSpinnerWhileLoading() = runBlockingTest {
viewModel = mockSuccessfulCase()
viewModel.loader.captureValues {
viewModel.getPlaylistDetails(id)
viewModel.playlistDetails.getValueForTest()
assertEquals(true, values[0])
}
}
@Test
fun closeLoaderAfterPlaylistDetailsLoad() = runBlockingTest {
viewModel = mockSuccessfulCase()
viewModel.loader.captureValues {
viewModel.getPlaylistDetails(id)
viewModel.playlistDetails.getValueForTest()
assertEquals(false, values.last())
}
}
private suspend fun mockSuccessfulCase(): PlaylistDetailsViewModel {
`when`(service.fetchPlaylistDetails(id)).thenReturn(
flow {
emit(Result.success(playlistDetails))
}
)
return PlaylistDetailsViewModel(service)
}
private suspend fun mockErrorCase(): PlaylistDetailsViewModel {
`when`(service.fetchPlaylistDetails(id)).thenReturn(
flow {
emit(error)
}
)
return PlaylistDetailsViewModel(service)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/details/PlaylistDetailsViewModelShould.kt | 3930328218 |
package com.example.tddmasterclass.details
import com.example.tddmasterclass.utils.BaseUnitTest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
class PlaylistDetailsServiceShould : BaseUnitTest() {
private lateinit var service: PlaylistDetailsService
private val id = "100"
private val api: PlaylistDetailsAPI = mock()
private val playlistDetails: PlaylistDetails = mock()
private val expected = Result.success(playlistDetails)
private val exception = RuntimeException("Something went wrong")
@Test
fun fetchPlaylistDetailsFromAPI() = runBlockingTest {
service = PlaylistDetailsService(api)
service.fetchPlaylistDetails(id).single()
verify(api, times(1)).fetchPlaylistDetails(id)
}
@Test
fun convertValuesToFlowResultAndEmitThem() = runBlockingTest {
mockSuccessfulCase()
assertEquals(expected, service.fetchPlaylistDetails(id).single())
}
@Test
fun emitsErrorResultWhenNetworkFails() = runBlockingTest {
mockErrorCase()
assertEquals(
"Something went wrong",
service.fetchPlaylistDetails(id).first().exceptionOrNull()?.message
)
}
private suspend fun mockErrorCase() {
`when`(api.fetchPlaylistDetails(id)).thenThrow(exception)
service = PlaylistDetailsService(api)
service.fetchPlaylistDetails(id)
}
private suspend fun mockSuccessfulCase() {
`when`(api.fetchPlaylistDetails(id)).thenReturn(playlistDetails)
service = PlaylistDetailsService(api)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/details/PlaylistDetailsServiceShould.kt | 710270135 |
package com.example.tddmasterclass.utils
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import org.junit.Before
import org.junit.Rule
import org.mockito.MockitoAnnotations
open class BaseUnitTest {
@get: Rule
var coroutinesTestRule = MainCoroutineScopeRule()
@get: Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
}
} | tddmasterclass/app/src/test/java/com/example/tddmasterclass/utils/BaseUnitTest.kt | 551385220 |
/*
* Copyright (C) 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.tddmasterclass.utils
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
/**
* Represents a list of capture values from a LiveData.
*/
class LiveDataValueCapture<T> {
val lock = Any()
private val _values = mutableListOf<T?>()
val values: List<T?>
get() = synchronized(lock) {
_values.toList() // copy to avoid returning reference to mutable list
}
fun addValue(value: T?) = synchronized(lock) {
_values += value
}
}
/**
* Extension function to capture all values that are emitted to a LiveData<T> during the execution of
* `captureBlock`.
*
* @param captureBlock a lambda that will
*/
inline fun <T> LiveData<T>.captureValues(block: LiveDataValueCapture<T>.() -> Unit) {
val capture = LiveDataValueCapture<T>()
val observer = Observer<T> {
capture.addValue(it)
}
observeForever(observer)
try {
capture.block()
} finally {
removeObserver(observer)
}
}
/**
* Get the current value from a LiveData without needing to register an observer.
*/
fun <T> LiveData<T>.getValueForTest(): T? {
var value: T? = null
var observer = Observer<T> {
value = it
}
observeForever(observer)
removeObserver(observer)
return value
}
| tddmasterclass/app/src/test/java/com/example/tddmasterclass/utils/LiveDataTestExtensions.kt | 990018515 |
/*
* Copyright (C) 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.tddmasterclass.utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* MainCoroutineRule installs a TestCoroutineDispatcher for Disptachers.Main.
*
* Since it extends TestCoroutineScope, you can directly launch coroutines on the MainCoroutineRule
* as a [CoroutineScope]:
*
* ```
* mainCoroutineRule.launch { aTestCoroutine() }
* ```
*
* All coroutines started on [MainCoroutineScopeRule] must complete (including timeouts) before the test
* finishes, or it will throw an exception.
*
* When using MainCoroutineRule you should always invoke runBlockingTest on it to avoid creating two
* instances of [TestCoroutineDispatcher] or [TestCoroutineScope] in your test:
*
* ```
* @Test
* fun usingRunBlockingTest() = mainCoroutineRule.runBlockingTest {
* aTestCoroutine()
* }
* ```
*
* You may call [DelayController] methods on [MainCoroutineScopeRule] and they will control the
* virtual-clock.
*
* ```
* mainCoroutineRule.pauseDispatcher()
* // do some coroutines
* mainCoroutineRule.advanceUntilIdle() // run all pending coroutines until the dispatcher is idle
* ```
*
* By default, [MainCoroutineScopeRule] will be in a *resumed* state.
*
* @param dispatcher if provided, this [TestCoroutineDispatcher] will be used.
*/
@ExperimentalCoroutinesApi
class MainCoroutineScopeRule(private val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) :
TestWatcher(),
TestCoroutineScope by TestCoroutineScope(dispatcher) {
override fun starting(description: Description) {
super.starting(description)
// If your codebase allows the injection of other dispatchers like
// Dispatchers.Default and Dispatchers.IO, consider injecting all of them here
// and renaming this class to `CoroutineScopeRule`
//
// All injected dispatchers in a test should point to a single instance of
// TestCoroutineDispatcher.
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description) {
super.finished(description)
advanceUntilIdle()
cleanupTestCoroutines()
Dispatchers.resetMain()
}
}
| tddmasterclass/app/src/test/java/com/example/tddmasterclass/utils/MainCoroutineScopeRule.kt | 4209778403 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.R
data class Playlist(
val id: String,
val name: String,
val category: String,
val image: Int
)
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/Playlist.kt | 4139360474 |
package com.example.tddmasterclass.playlist
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.liveData
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.onEach
class PlaylistViewModel(
private val repository: PlaylistRepository
) : ViewModel() {
val loader = MutableLiveData<Boolean>()
val playlists = liveData {
loader.postValue(true)
emitSource(
repository.getPlaylists().onEach {
loader.postValue(false)
}
.asLiveData()
)
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistViewModel.kt | 2770059136 |
package com.example.tddmasterclass.playlist
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
class PlaylistViewModelFactory @Inject constructor(
private val repository: PlaylistRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PlaylistViewModel(repository) as T
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistViewModelFactory.kt | 3342546562 |
package com.example.tddmasterclass.playlist
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class PlaylistRepository @Inject constructor(
private val service: PlaylistService,
private val mapper: PlaylistMapper
) {
suspend fun getPlaylists(): Flow<Result<List<Playlist>>> =
service.fetchPlaylists().map {
if (it.isSuccess) {
Result.success(mapper.invoke(it.getOrNull()!!))
} else {
Result.failure(it.exceptionOrNull()!!)
}
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistRepository.kt | 1865125471 |
package com.example.tddmasterclass.playlist
import com.example.tddmasterclass.R
import javax.inject.Inject
class PlaylistMapper@Inject constructor() : Function1<List<PlaylistRaw>, List<Playlist>> {
override fun invoke(playlistsRaw: List<PlaylistRaw>): List<Playlist> {
return playlistsRaw.map {
Playlist(
id = it.id,
name = it.name,
category = it.category,
image = getImage(it.category)
)
}
}
private fun getImage(category: String): Int {
return if (category == "rock") {
R.mipmap.rock
} else {
R.mipmap.playlist
}
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistMapper.kt | 3604635482 |
package com.example.tddmasterclass.playlist
data class PlaylistRaw(
val id: String,
val name: String,
val category: String
)
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistRaw.kt | 4074475937 |
package com.example.tddmasterclass.playlist
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.example.tddmasterclass.R
import com.example.tddmasterclass.databinding.FragmentPlaylistBinding
class MyPlaylistRecyclerViewAdapter(
private val values: List<Playlist>,
private val listener: (String) -> Unit
) : RecyclerView.Adapter<MyPlaylistRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
FragmentPlaylistBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = values[position]
holder.playlistName.text = item.name
holder.playlistCategory.text = item.category
holder.playlistImage.setImageResource(item.image)
holder.playlistItemRoot.setOnClickListener {
listener.invoke(item.id)
}
}
override fun getItemCount(): Int = values.size
inner class ViewHolder(binding: FragmentPlaylistBinding) :
RecyclerView.ViewHolder(binding.root) {
val playlistName: TextView = binding.playlistName
val playlistCategory: TextView = binding.playlistCategory
val playlistImage: ImageView = binding.playlistImage
val playlistItemRoot: LinearLayout = binding.playlistItemRoot
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/MyPlaylistRecyclerViewAdapter.kt | 1497531260 |
package com.example.tddmasterclass.playlist
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import java.lang.RuntimeException
import javax.inject.Inject
class PlaylistService @Inject constructor(
private val api: PlaylistAPI
) {
suspend fun fetchPlaylists(): Flow<Result<List<PlaylistRaw>>> {
return flow {
emit(Result.success(api.fetchAllPlaylists()))
}.catch {
emit(Result.failure(RuntimeException("Something went wrong")))
}
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistService.kt | 2409958976 |
package com.example.tddmasterclass.playlist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tddmasterclass.R
import com.example.tddmasterclass.utils.TestIdlingResource
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class PlaylistFragment : Fragment() {
private lateinit var viewModel: PlaylistViewModel
@Inject
lateinit var viewModelFactory: PlaylistViewModelFactory
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_playlist_list, container, false)
setupViewModel()
setupObservers(view)
TestIdlingResource.increment()
return view
}
private fun setupObservers(view: View) {
viewModel.loader.observe(this as LifecycleOwner) { loading ->
view.findViewById<ProgressBar>(R.id.loader).visibility = when (loading) {
true -> View.VISIBLE
else -> View.GONE
}
}
viewModel.playlists.observe(this as LifecycleOwner) { playlists ->
if (playlists.getOrNull() != null) {
setupList(view.findViewById(R.id.playlists_list), playlists.getOrNull()!!)
}
}
}
private fun setupList(
view: RecyclerView,
playlists: List<Playlist>
) {
with(view) {
layoutManager = LinearLayoutManager(context)
adapter = MyPlaylistRecyclerViewAdapter(playlists) { id ->
val action =
PlaylistFragmentDirections.actionPlaylistFragmentToPlaylistDetailFragment(id)
findNavController().navigate(action)
}
}
TestIdlingResource.decrement()
}
private fun setupViewModel() {
viewModel = ViewModelProvider(this, viewModelFactory)[PlaylistViewModel::class.java]
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistFragment.kt | 2571857492 |
package com.example.tddmasterclass.playlist
import retrofit2.http.GET
interface PlaylistAPI {
@GET("playlists")
suspend fun fetchAllPlaylists(): List<PlaylistRaw>
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistAPI.kt | 2241090123 |
package com.example.tddmasterclass.playlist
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.FragmentComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Module
@InstallIn(FragmentComponent::class)
class PlaylistModule {
@Provides
fun playListAPI(retrofit: Retrofit): PlaylistAPI = retrofit.create(PlaylistAPI::class.java)
@Provides
fun retrofit() = Retrofit.Builder()
.baseUrl("http://192.168.15.82:3001/")
.client(OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/playlist/PlaylistModule.kt | 4184606961 |
package com.example.tddmasterclass
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity(R.layout.activity_main) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val finalHost = NavHostFragment.create(R.navigation.nav_graph)
supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, finalHost)
.setPrimaryNavigationFragment(finalHost)
.commit()
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/MainActivity.kt | 809723001 |
package com.example.tddmasterclass
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class GroovyApplication : Application() {
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/GroovyApplication.kt | 456887375 |
package com.example.tddmasterclass.details
import com.example.tddmasterclass.details.PlaylistDetails
import com.example.tddmasterclass.details.PlaylistDetailsAPI
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class PlaylistDetailsService @Inject constructor(
private val api: PlaylistDetailsAPI
) {
suspend fun fetchPlaylistDetails(id: String): Flow<Result<PlaylistDetails>> =
flow {
emit(Result.success(api.fetchPlaylistDetails(id)))
}.catch {
emit(Result.failure(RuntimeException("Something went wrong")))
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsService.kt | 1959442527 |
package com.example.tddmasterclass.details
import com.example.tddmasterclass.details.PlaylistDetails
import retrofit2.http.GET
import retrofit2.http.Path
interface PlaylistDetailsAPI {
@GET("playlist-details/{id}")
suspend fun fetchPlaylistDetails(@Path("id") id: String): PlaylistDetails
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsAPI.kt | 3617780130 |
package com.example.tddmasterclass.details
data class PlaylistDetails (
val id: String,
val name: String,
val details: String
) | tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetails.kt | 3356254327 |
package com.example.tddmasterclass.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import com.example.tddmasterclass.R
import com.example.tddmasterclass.utils.TestIdlingResource
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class PlaylistDetailFragment : Fragment() {
private lateinit var viewModel: PlaylistDetailsViewModel
@Inject
lateinit var viewModelFactory: PlaylistDetailsViewModelFactory
private val args: PlaylistDetailFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_playlist_detail, container, false)
val id = args.playlistid
viewModel = ViewModelProvider(this, viewModelFactory)[PlaylistDetailsViewModel::class.java]
observePlaylistDetails(view)
observeLoader(view)
TestIdlingResource.increment()
viewModel.getPlaylistDetails(id)
return view
}
private fun observePlaylistDetails(view: View) {
viewModel.playlistDetails.observe(this as LifecycleOwner) { playlistDetails ->
if (playlistDetails.getOrNull() != null) {
view.findViewById<TextView>(R.id.playlist_name).text =
playlistDetails.getOrNull()!!.name
view.findViewById<TextView>(R.id.playlist_details).text =
playlistDetails.getOrNull()!!.details
} else {
Snackbar.make(
view.findViewById(R.id.playlist_details_root),
R.string.generic_error,
Snackbar.LENGTH_LONG
).show()
}
TestIdlingResource.decrement()
}
}
private fun observeLoader(view: View) {
viewModel.loader.observe(this as LifecycleOwner) { load ->
view.findViewById<ProgressBar>(R.id.details_loader).visibility = if (load) {
View.VISIBLE
} else {
View.GONE
}
}
}
companion object {
@JvmStatic
fun newInstance() = PlaylistDetailFragment()
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsFragment.kt | 3094991338 |
package com.example.tddmasterclass.details
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.FragmentComponent
import retrofit2.Retrofit
@Module
@InstallIn(FragmentComponent::class)
class PlaylistDetailsModule {
@Provides
fun playlistDetailsAPI(retrofit: Retrofit) = retrofit.create(PlaylistDetailsAPI::class.java)
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsModule.kt | 3304381916 |
package com.example.tddmasterclass.details
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
class PlaylistDetailsViewModelFactory @Inject constructor(
private val repository: PlaylistDetailsService
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return PlaylistDetailsViewModel(repository) as T
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsViewModelFactory.kt | 3129329772 |
package com.example.tddmasterclass.details
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class PlaylistDetailsViewModel(
private val service: PlaylistDetailsService
) : ViewModel() {
val loader = MutableLiveData<Boolean>()
val playlistDetails: MutableLiveData<Result<PlaylistDetails>> = MutableLiveData()
fun getPlaylistDetails(id: String) {
viewModelScope.launch {
loader.postValue(true)
service.fetchPlaylistDetails(id)
.collect {
playlistDetails.postValue(it)
loader.postValue(false)
}
}
}
}
| tddmasterclass/app/src/main/java/com/example/tddmasterclass/details/PlaylistDetailsViewModel.kt | 1377813577 |
package com.example.tddmasterclass.utils
import androidx.test.espresso.IdlingResource
import java.util.concurrent.atomic.AtomicInteger
class SimpleCountingIdlingResource(
private val resourceName: String
) : IdlingResource {
private val counter = AtomicInteger(0)
@Volatile
private var resourceCallback:
IdlingResource.ResourceCallback? = null
override fun getName() = resourceName
override fun isIdleNow() = counter.get() == 0
override fun registerIdleTransitionCallback(
resourceCallback: IdlingResource.ResourceCallback
) {
this.resourceCallback = resourceCallback
}
fun increment() {
counter.getAndIncrement()
}
fun decrement() {
val counterVal = counter.decrementAndGet()
if (counterVal == 0) {
resourceCallback?.onTransitionToIdle()
} else if (counterVal < 0) {
throw IllegalStateException(
"Counter has been corrupted!"
)
}
}
} | tddmasterclass/app/src/main/java/com/example/tddmasterclass/utils/SimpleCountingIdlingResource.kt | 2714722061 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.