content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.puffy.events /** * SAM interface which is called each time the EventStream associated with the listener pushes a new * event */ fun interface EventListener<EventType> { fun onEvent(event: EventType): Unit } interface EventStreamListener<Identifier, EventType> { fun register(identifier: Identifier, listener: EventListener<EventType>) fun unregister(identifier: Identifier, listener: EventListener<EventType>) } interface EventStream<EventType> { fun sendEvent(event: EventType) }
puffy-anti-exploit/src/main/kotlin/com/puffy/events/EventStream.kt
2247590143
package com.puffy.events import net.minecraft.server.network.ServerPlayerEntity data class DetectionInfo(val detectionSourceName: String, val player: ServerPlayerEntity) object DetectionEventEmitter : EventStream<DetectionInfo> { private object DetectionEventListener : EventStreamListener<String, DetectionInfo> { private val listeners: MutableMap<String, MutableSet<EventListener<DetectionInfo>>> = mutableMapOf() override fun register(identifier: String, listener: EventListener<DetectionInfo>) { if (listeners[identifier] == null) { listeners[identifier] = mutableSetOf() } listeners[identifier]?.add(listener) } override fun unregister(identifier: String, listener: EventListener<DetectionInfo>) { listeners[identifier]?.remove(listener) } fun notifyListeners(event: DetectionInfo) { listeners.forEach { entry -> entry.value.forEach { eventListener -> eventListener.onEvent(event) } } } } override fun sendEvent(event: DetectionInfo) { DetectionEventListener.notifyListeners(event) } fun addListener(identifier: String, listener: EventListener<DetectionInfo>) { DetectionEventListener.register(identifier, listener) } }
puffy-anti-exploit/src/main/kotlin/com/puffy/events/DetectionEventEmitter.kt
1423186424
package com.puffy.events import kotlin.reflect.KClass import kotlin.reflect.full.isSubclassOf import net.minecraft.network.packet.Packet import net.minecraft.server.network.ServerPlayerEntity data class PacketEvent<T : Packet<*>>(val player: ServerPlayerEntity, val packet: T) object PacketEventEmitter : EventStream<PacketEvent<*>> { private object PacketEventListener : EventStreamListener<ServerPlayerEntity, PacketEvent<*>> { private val listeners: MutableMap<ServerPlayerEntity, MutableSet<EventListener<PacketEvent<*>>>> = mutableMapOf() override fun register( identifier: ServerPlayerEntity, listener: EventListener<PacketEvent<*>> ) { if (listeners[identifier] == null) { listeners[identifier] = mutableSetOf() } listeners[identifier]?.add(listener) } override fun unregister( identifier: ServerPlayerEntity, listener: EventListener<PacketEvent<*>> ) { listeners[identifier]?.remove(listener) } fun notifyListeners(event: PacketEvent<*>) { listeners .filter { entry -> entry.key == event.player } .forEach { entry -> entry.value.forEach { listener -> listener.onEvent(event) } } } } override fun sendEvent(event: PacketEvent<*>) { PacketEventListener.notifyListeners(event) } fun <T : Packet<*>> addListener( player: ServerPlayerEntity, packetClass: KClass<T>, listener: EventListener<PacketEvent<T>> ) { PacketEventListener.register(player) { event -> val receivedPacketClass = event.packet::class if ( receivedPacketClass == packetClass || receivedPacketClass.isSubclassOf(packetClass) ) { // We perform a reflection check, so this is guaranteed // to be a proper cast--we're just unable to do it at // compile-time because the type info for PacketEvent<T> // is erased once submitted to the listeners. @Suppress("UNCHECKED_CAST") listener.onEvent(event as PacketEvent<T>) } } } }
puffy-anti-exploit/src/main/kotlin/com/puffy/events/PacketEventEmitter.kt
3187645316
package com.ubaya.uts160421066 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.ubaya.uts160421066", appContext.packageName) } }
uts160421066/app/src/androidTest/java/com/ubaya/uts160421066/ExampleInstrumentedTest.kt
1475807930
package com.ubaya.uts160421066 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) } }
uts160421066/app/src/test/java/com/ubaya/uts160421066/ExampleUnitTest.kt
1403255944
package com.ubaya.uts160421066.model.response import com.google.gson.annotations.SerializedName data class ResponseProfile( @field:SerializedName("profile") val profile: List<ProfileItem> ) data class ProfileItem( @field:SerializedName("last_name") val lastName: String, @field:SerializedName("first_name") val firstName: String, @field:SerializedName("username") val username: String ) data class LoginResponse(val message: String)
uts160421066/app/src/main/java/com/ubaya/uts160421066/model/response/ResponseProfile.kt
3593657140
package com.ubaya.uts160421066.model.response import com.google.gson.annotations.SerializedName data class ResponseHobby( @field:SerializedName("hobbies") val hobbies: List<HobbiesItem> ) data class HobbiesItem( @field:SerializedName("image") val image: String, @field:SerializedName("detail_description") val detailDescription: String, @field:SerializedName("date") val date: String, @field:SerializedName("description") val description: String, @field:SerializedName("title") val title: String, @field:SerializedName("username") val username: String )
uts160421066/app/src/main/java/com/ubaya/uts160421066/model/response/ResponseHobby.kt
3658772308
package com.ubaya.uts160421066.model.retrofit import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class ApiConfig { companion object{ fun getApiService(): ApiService { val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() val tes: String = "http://192.168.151.105/uts160421066/index.php/" val retrofit = Retrofit.Builder() .baseUrl(tes) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() return retrofit.create(ApiService::class.java) } } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/model/retrofit/ApiConfig.kt
1845193555
package com.ubaya.uts160421066.model.retrofit import com.ubaya.uts160421066.model.response.LoginResponse import com.ubaya.uts160421066.model.response.ResponseHobby import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.* interface ApiService { @GET("hobby") fun getHobbies(): Call<ResponseHobby> @FormUrlEncoded @POST("login") fun loginUser( @Field("username") username: String, @Field("password") password: String ): Call<LoginResponse> }
uts160421066/app/src/main/java/com/ubaya/uts160421066/model/retrofit/ApiService.kt
3998074090
package com.ubaya.uts160421066.view import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.ubaya.uts160421066.R class DetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_detail) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/DetailActivity.kt
527196978
package com.ubaya.uts160421066.view import android.os.Bundle import android.util.Log import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.recyclerview.widget.LinearLayoutManager import com.ubaya.uts160421066.databinding.ActivityMainBinding import com.ubaya.uts160421066.model.response.HobbiesItem import com.ubaya.uts160421066.model.response.ResponseHobby import com.ubaya.uts160421066.model.retrofit.ApiConfig import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) findHobby() } private fun findHobby() { val client = ApiConfig.getApiService().getHobbies() client.enqueue(object : Callback<ResponseHobby> { override fun onResponse( call: Call<ResponseHobby>, response: Response<ResponseHobby> ) { if (response.isSuccessful) { val responseBody = response.body() if (responseBody != null) { setHobbyData(responseBody.hobbies) } } else { Log.e(TAG, "onFailure: ${response.message()}") } } override fun onFailure(call: Call<ResponseHobby>, t: Throwable) { Log.e(TAG, "onFailure: ${t.message}") } }) } private fun setHobbyData(hobbies: List<HobbiesItem>) { val adapter = HobbyAdapter() adapter.submitList(hobbies) binding.rvHobby.adapter = adapter binding.rvHobby.layoutManager = LinearLayoutManager(this) } companion object { const val TAG = "MainActivity" } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/MainActivity.kt
111348091
package com.ubaya.uts160421066.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.ubaya.uts160421066.databinding.FragmentLoginBinding import com.ubaya.uts160421066.model.response.LoginResponse import com.ubaya.uts160421066.model.retrofit.ApiConfig import com.ubaya.uts160421066.view.SharedPrefManager import retrofit2.Callback import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response class LoginFragment : Fragment() { private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! private lateinit var sharedPrefManager: SharedPrefManager override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) sharedPrefManager = SharedPrefManager(requireContext()) binding.btnLogin.setOnClickListener { val username = binding.etUsername.text.toString().trim() val password = binding.etPassword.text.toString().trim() val call: Call<LoginResponse> = ApiConfig.getApiService().loginUser(username,password) call.enqueue(object : Callback<LoginResponse> { override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) { if (response.isSuccessful) { val loginResponse = response.body() sharedPrefManager.saveLoginStatus(true) val action = LoginFragmentDirections.actionLoginFragmentToMainActivity() findNavController().navigate(action) } else { Toast.makeText(requireContext(), "Login failed", Toast.LENGTH_SHORT).show() } } override fun onFailure(call: Call<LoginResponse>, t: Throwable) { Toast.makeText(requireContext(), "Login failed", Toast.LENGTH_SHORT).show() } }) } binding.btnRegister.setOnClickListener { val action = LoginFragmentDirections.actionLoginFragmentToRegisterFragment() findNavController().navigate(action) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/LoginFragment.kt
700468438
package com.ubaya.uts160421066.view import android.content.Context import android.content.SharedPreferences class SharedPrefManager(context: Context) { private val sharedPref: SharedPreferences = context.getSharedPreferences("MY_APP_PREF", Context.MODE_PRIVATE) fun saveLoginStatus(isLoggedIn: Boolean) { val editor = sharedPref.edit() editor.putBoolean("IS_LOGGED_IN", isLoggedIn) editor.apply() } fun getLoginStatus(): Boolean { return sharedPref.getBoolean("IS_LOGGED_IN", false) } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/SharedPrefManager.kt
3745915189
package com.ubaya.uts160421066.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.ubaya.uts160421066.databinding.FragmentRegisterBinding class RegisterFragment : Fragment() { private var _binding: FragmentRegisterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRegisterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnToSignIn.setOnClickListener { val action = RegisterFragmentDirections.actionRegisterFragmentToLoginFragment() findNavController().navigate(action) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/RegisterFragment.kt
2172017221
package com.ubaya.uts160421066.view import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.ubaya.uts160421066.R import com.ubaya.uts160421066.databinding.HobbyCardBinding import com.ubaya.uts160421066.model.response.HobbiesItem class HobbyAdapter : ListAdapter<HobbiesItem, HobbyAdapter.MyViewHolder>(DIFF_CALLBACK) { companion object { private val DIFF_CALLBACK: DiffUtil.ItemCallback<HobbiesItem> = object : DiffUtil.ItemCallback<HobbiesItem>() { override fun areItemsTheSame(oldItem: HobbiesItem, newItem: HobbiesItem): Boolean { return oldItem.title == newItem.title } override fun areContentsTheSame( oldItem: HobbiesItem, newItem: HobbiesItem ): Boolean { return oldItem == newItem } } } inner class MyViewHolder(private val binding: HobbyCardBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(hobby: HobbiesItem) { val urlBase: String = "http://192.168.151.105/uts160421066/images/" binding.apply { titleTextView.text = hobby.title usernameTextView.text = hobby.username descriptionTextView.text = hobby.description Glide.with(itemView) .load(urlBase + hobby.image) .centerCrop() .into(imageView) // Mengatur action ketika tombol "Read" diklik readButton.setOnClickListener { val detailDescription = hobby.detailDescription descriptionTextView.text = detailDescription readButton.visibility = View.GONE } } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = HobbyCardBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(getItem(position)) } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/HobbyAdapter.kt
1684021550
package com.ubaya.uts160421066.view import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import com.ubaya.uts160421066.databinding.ActivityLoginBinding class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) enableEdgeToEdge() } }
uts160421066/app/src/main/java/com/ubaya/uts160421066/view/LoginActivity.kt
2901772708
package ru.btpit.zadanie2 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("ru.btpit.zadanie2", appContext.packageName) } }
Prac11/app/src/androidTest/java/ru/btpit/zadanie2/ExampleInstrumentedTest.kt
3083740801
package ru.btpit.zadanie2 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) } }
Prac11/app/src/test/java/ru/btpit/zadanie2/ExampleUnitTest.kt
4265266184
package ru.netology.nmedia.dto data class Post( val id: Long, val author: String, val content: String, val published: String, val likecount: Int, val share: Int, val video: String? = null, val isLiked: Boolean )
Prac11/app/src/main/java/ru/btpit/zadanie2/dto/Post.kt
3451135788
package ru.netology.nmedia.viewmodel import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import ru.netology.nmedia.dto.Post import ru.netology.nmedia.repository.PostRepository import ru.netology.nmedia.repository.PostRepositoryFileImpl import ru.netology.nmedia.repository.PostRepositoryInMemoryImpl import ru.netology.nmedia.repository.PostRepositorySharedPrefsImpl private val empty = Post( id = 0, content = "", author = "", isLiked = false, published = "", likecount = 0, share = 0 ) class PostViewModel(application: Application): AndroidViewModel(application) { private val repository: PostRepository = PostRepositoryFileImpl(application) val data = repository.getAll() val edited = MutableLiveData(empty) val selectedPost = MutableLiveData<Post>() fun save() { edited.value?.let { repository.save(it) } edited.value = empty } fun edit(post: Post) { edited.value = post } fun changeContent(content: String) { edited.value?.let { val text = content.trim() if (it.content == text){ return } edited.value = it.copy(content = text) } } fun like(id: Long) = repository.like(id) fun share(id: Long) = repository.share(id) fun removeById(id: Long) = repository.removeById(id) fun getPostById(id: Long){ repository.postID(id).observeForever{ selectedPost.value = it } } }
Prac11/app/src/main/java/ru/btpit/zadanie2/viewmodel/PostViewModel.kt
2720337840
package ru.netology.nmedia.repository import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.gson.Gson import com.google.gson.reflect.TypeToken import ru.netology.nmedia.dto.Post class PostRepositorySharedPrefsImpl( context:Context, ) : PostRepository{ private val gson = Gson() private val prefs = context.getSharedPreferences("repo", Context.MODE_PRIVATE) private val type = TypeToken.getParameterized(List::class.java, Post::class.java).type private val key = "posts" private var nextId = 1L private var post = emptyList<Post>() private val data = MutableLiveData(post) init { prefs.getString(key, null)?.let { post = gson.fromJson(it, type) data.value = post } } override fun getAll(): LiveData<List<Post>> = data override fun like(id:Long) { post = post.map { if (it.id == id && it.isLiked) { it.copy(likecount = it.likecount - 1, isLiked = false) } else if (it.id == id && !it.isLiked) { it.copy(likecount = it.likecount + 1, isLiked = true) } else { it } } data.value = post sync() } override fun postID(id: Long): LiveData<Post> { val postLiveData = MutableLiveData<Post>() postLiveData.value = post.find { it.id == id } return postLiveData } override fun save(posts: Post) { if (posts.id == 0L) { // TODO: remove hardcoded author & published post = listOf( posts.copy( id = nextId++, author = "Me", isLiked = false, published = "now" ) ) + post data.value = post sync() return } post = post.map { if (it.id != posts.id) it else it.copy(content = posts.content) } data.value = post sync() } override fun share(id: Long) { post = post.map { if (it.id != id) { it } else { it.copy(share = it.share + 1) } } data.value = post sync() } override fun removeById(id: Long) { post = post.filter { it.id != id } data.value =post sync() } private fun sync(){ with(prefs.edit()){ putString(key, gson.toJson(post)) apply() } } }
Prac11/app/src/main/java/ru/btpit/zadanie2/repository/PostRepositorySharedPrefsImpl.kt
2153387211
package ru.netology.nmedia.repository import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import ru.netology.nmedia.dto.Post class PostRepositoryInMemoryImpl : PostRepository { private var nextId = 1L private var post = listOf( Post(id = nextId++, author = "Нетология. Университет интернет-профессий будущего", content = "Привет, это новая Нетология! Когда-то Нетология начиналась с интенсивов по онлайн-маркетингу. Затем появились курсы по дизайну, разработке, аналитике и управлению. Мы растём сами и помогаем расти студентам: от новичков до уверенных профессионалов. Но самое важное остаётся с нами: мы верим, что в каждом уже есть сила, которая заставляет хотеть больше, целиться выше, бежать быстрее. Наша миссия — помочь встать на путь роста и начать цепочку перемен → http://netolo.gy/fyb", published = "21 мая в 18:36", likecount = 999, share = 5, isLiked = false ), Post( id = nextId++, author = "Нетология. Университет интернет-профессий будущего", content = "Знаний хватит на всех: на следующей неделе разбираемся Информатикой" , published = "30 сентября в 22:12", isLiked = false, likecount = 999, share = 5 ), Post( id = nextId++, author = "Инфляция", content = "Инфля́ция — устойчивое повышение общего уровня цен на товары и услуги; процесс обесценивания денег, падение их покупательной способности вследствие чрезмерного выпуска" , published = "10 сентября в 12:12", isLiked = false, likecount = 999, share = 5 ), ) private val data = MutableLiveData(post) override fun getAll(): LiveData<List<Post>> = data override fun like(id:Long) { post = post.map { if (it.id == id && it.isLiked) { it.copy(likecount = it.likecount - 1, isLiked = false) } else if (it.id == id && !it.isLiked) { it.copy(likecount = it.likecount + 1, isLiked = true) } else { it } } data.value = post } override fun postID(id: Long): LiveData<Post> { val postLiveData = MutableLiveData<Post>() postLiveData.value = post.find { it.id == id } return postLiveData } override fun save(posts: Post) { if (posts.id == 0L) { // TODO: remove hardcoded author & published post = listOf( posts.copy( id = nextId++, author = "Me", isLiked = false, published = "now" ) ) + post data.value = post return } post = post.map { if (it.id != posts.id) it else it.copy(content = posts.content) } data.value = post } override fun share(id: Long) { post = post.map { if (it.id != id) { it } else { it.copy(share = it.share + 1) } } data.value = post } override fun removeById(id: Long) { post = post.filter { it.id != id } data.value =post } }
Prac11/app/src/main/java/ru/btpit/zadanie2/repository/PostRepositoryInMemoryImpl.kt
85017205
package ru.netology.nmedia.repository import androidx.lifecycle.LiveData import ru.netology.nmedia.dto.Post interface PostRepository { fun getAll(): LiveData<List<Post>> fun like(id:Long) fun share(id:Long) fun save(post: Post) fun postID(id: Long): LiveData<Post> fun removeById(id: Long) }
Prac11/app/src/main/java/ru/btpit/zadanie2/repository/PostRepository.kt
2294695960
package ru.netology.nmedia.repository import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.gson.Gson import com.google.gson.reflect.TypeToken import ru.netology.nmedia.dto.Post class PostRepositoryFileImpl( private val context: Context, ) : PostRepository{ private val gson = Gson() private val type = TypeToken.getParameterized(List::class.java, Post::class.java).type private val filename = "posts.json" private var nextId = 0L private var post = emptyList<Post>() private val data = MutableLiveData(post) init { val file = context.filesDir.resolve(filename) if (file.exists()) { context.openFileInput(filename).bufferedReader().use { post = gson.fromJson(it, type) data.value = post } } else { sync() } } override fun getAll(): LiveData<List<Post>> = data override fun like(id:Long) { post = post.map { if (it.id == id && it.isLiked) { it.copy(likecount = it.likecount - 1, isLiked = false) } else if (it.id == id && !it.isLiked) { it.copy(likecount = it.likecount + 1, isLiked = true) } else { it } } data.value = post sync() } override fun save(post: Post) { var sum = 1L for (p in this.post){ sum += p.id } if (post.id == nextId && post.id != sum) { this.post = listOf( post.copy( id = sum, author = "Me", isLiked = false, published = "now" ) ) + this.post data.value = this.post sync() return } this.post = this.post.map { if (it.id != post.id) it else it.copy(content = post.content) } data.value = this.post sync() } override fun share(id: Long) { post = post.map { if (it.id != id) { it } else { it.copy(share = it.share + 1) } } data.value = post sync() } override fun removeById(id: Long) { post = post.filter { it.id != id } data.value =post sync() } override fun postID(id: Long): LiveData<Post> { val postLiveData = MutableLiveData<Post>() postLiveData.value = post.find { it.id == id } return postLiveData } private fun sync() { context.openFileOutput(filename, Context.MODE_PRIVATE).bufferedWriter().use { it.write(gson.toJson(post)) } } }
Prac11/app/src/main/java/ru/btpit/zadanie2/repository/PostRepositoryFileImpl.kt
2348903068
package ru.netology.nmedia.util import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager object AndroidUtils { fun hideKeyboard(view: View) { val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } }
Prac11/app/src/main/java/ru/btpit/zadanie2/util/AndroidUtils.kt
2311480506
package ru.btpit.zadanie2.util import android.os.Bundle import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty object StringArg: ReadWriteProperty<Bundle, String?> { override fun setValue(thisRef: Bundle, property: KProperty<*>, value: String?) { thisRef.putString(property.name, value) } override fun getValue(thisRef: Bundle, property: KProperty<*>): String? = thisRef.getString(property.name) }
Prac11/app/src/main/java/ru/btpit/zadanie2/util/StringArg.kt
165811611
package ru.btpit.zadanie2.activity import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import ru.btpit.zadanie2.databinding.FragmentNewPostBinding import ru.btpit.zadanie2.util.StringArg import ru.netology.nmedia.util.AndroidUtils import ru.netology.nmedia.viewmodel.PostViewModel class NewPostFragment : Fragment() { companion object { var Bundle.textArg: String? by StringArg } private val viewModel: PostViewModel by viewModels( ownerProducer = ::requireParentFragment ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentNewPostBinding.inflate( inflater, container, false ) if (arguments?.textArg == null ) { binding.Name.text ="Добавить пост" } else { binding.Name.text ="Изменение поста" } arguments?.textArg ?.let(binding.edit::setText) binding.ok.setOnClickListener { viewModel.changeContent(binding.edit.text.toString()) viewModel.save() AndroidUtils.hideKeyboard(requireView()) findNavController().navigateUp() } return binding.root } } //// override fun onCreate(savedInstanceState: Bundle?) { //// super.onCreate(savedInstanceState) //// val binding = ActivityNewPostBinding.inflate(layoutInflater) //// setContentView(binding.root) // // val text = intent.getStringExtra(Intent.EXTRA_TEXT) // binding.edit.text = Editable.Factory.getInstance().newEditable(text) // if (text == "") // { // binding.Name.text = "Создание поста" // } // else binding.Name.text = "Редактирование поста" // binding.edit.requestFocus() // binding.ok.setOnClickListener { // val intent = Intent() // if (binding.edit.text.isNullOrBlank()) { // setResult(Activity.RESULT_CANCELED, intent) // } else { // val content = binding.edit.text.toString() // intent.putExtra(Intent.EXTRA_TEXT, content) // setResult(Activity.RESULT_OK, intent) // } // finish() // } // // } //}
Prac11/app/src/main/java/ru/btpit/zadanie2/activity/NewPostFragment.kt
1247971612
package ru.btpit.zadanie2.activity import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import ru.btpit.zadanie2.R import ru.btpit.zadanie2.activity.NewPostFragment.Companion.textArg import ru.btpit.zadanie2.databinding.ActivityOnePostFragmentBinding import ru.btpit.zadanie2.databinding.FragmentFeedBinding import ru.btpit.zadanie2.databinding.FragmentNewPostBinding import ru.btpit.zadanie2.util.StringArg import ru.netology.nmedia.dto.Post import ru.netology.nmedia.util.AndroidUtils import ru.netology.nmedia.viewmodel.PostViewModel class OnePostFragment : Fragment() { companion object { var Bundle.textArg: String? by StringArg } private val viewModel: PostViewModel by viewModels( ownerProducer = ::requireParentFragment ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = ActivityOnePostFragmentBinding.inflate( inflater, container, false ) val postId = arguments?.getLong("postId") postId?.let { id -> viewModel.getPostById(id) viewModel.selectedPost.observe(viewLifecycleOwner) { post -> binding.textView.text = post.author binding.textView2.text = post.published binding.textView5.text = post.content binding.like.text = post.likecount.toString() binding.share.text = post.share.toString() binding.like.isChecked = post.isLiked binding.like.text = formatNumber(post.likecount) binding.share.text = formatNumber1(post.share) binding.back.setOnClickListener { findNavController().navigateUp() } binding.editorPost.setOnClickListener { viewModel.edit(post) // val text = post.content // newPostActivity.launch(text) val bundle = Bundle() bundle.textArg = post.content findNavController().navigate(R.id.action_onePostFragment_to_newPostFragment3, bundle) } binding.like.setOnClickListener { viewModel.like(postId) } binding.share.setOnClickListener { val intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, post.content) type = "text/plain" } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) viewModel.share(postId) } binding.Video.setOnClickListener{ val url = "https://www.youtube.com/watch?v=qeQnMgega0k" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } viewModel.data.observe(viewLifecycleOwner) { posts -> val updatedPost = posts.find { it.id == postId } updatedPost?.let { binding.like.text = it.likecount.toString() binding.share.text = it.share.toString() } } } binding.del.setOnClickListener{ viewModel.removeById(postId) findNavController().navigateUp() } } return binding.root } // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // setContentView(R.layout.activity_one_post_fragment) // } } private fun formatNumber(number: Int): String { return when { number >= 1000000 -> { val value = number / 1000000 val remainder = number % 1000000 if (remainder > 0) { if (remainder >= 100000) { String.format("%.1f M", value + remainder / 1000000.0) } else { String.format("%d.%d M", value, remainder / 100000) } } else { "$value M" } } number in 1000..9999 -> { String.format("%.1fK", number / 1000.0) } number >= 10000 -> { String.format("%dK", number / 1000) } else -> number.toString() } } private fun formatNumber1(number: Int): String { return when { number >= 1000000 -> { val value = number / 1000000 val remainder = number % 1000000 if (remainder > 0) { if (remainder >= 100000) { String.format("%.1f M", value + remainder / 1000000.0) } else { String.format("%d.%d M", value, remainder / 100000) } } else { "$value M" } } number in 1000..9999 -> { String.format("%.1fK", number / 1000.0) } number >= 10000 -> { String.format("%dK", number / 1000) } else -> number.toString() } }
Prac11/app/src/main/java/ru/btpit/zadanie2/activity/OnePostFragment.kt
1842773262
package ru.btpit.zadanie2.activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.findNavController import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import ru.btpit.zadanie2.R import ru.btpit.zadanie2.activity.NewPostFragment.Companion.textArg import ru.btpit.zadanie2.databinding.ActivityAppBinding class AppActivity : AppCompatActivity(R.layout.activity_app) { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.let { if (it.action != Intent.ACTION_SEND) { return@let } val text = it.getStringExtra(Intent.EXTRA_TEXT) if (text?.isNotBlank() != true) { return@let } intent.removeExtra(Intent.EXTRA_TEXT) findNavController(R.id.nav_host_fragment).navigate( R.id.action_feedFragment_to_newPostFragment, Bundle().apply { textArg = text } ) } } }
Prac11/app/src/main/java/ru/btpit/zadanie2/activity/AppActivity.kt
526621554
package ru.btpit.zadanie2.activity import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import ru.btpit.zadanie2.R import ru.btpit.zadanie2.activity.NewPostFragment.Companion.textArg import ru.btpit.zadanie2.databinding.FragmentFeedBinding import ru.netology.nmedia.dto.Post import ru.netology.nmedia.viewmodel.PostViewModel class FeedFragment : Fragment() { private val viewModel: PostViewModel by viewModels( ownerProducer = ::requireParentFragment ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentFeedBinding.inflate( inflater, container, false ) // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // val binding = ActivityPostsBinding.inflate(layoutInflater) // setContentView(binding.root) // run { // val preferences = getPreferences(Context.MODE_PRIVATE) // preferences.edit().apply { // putString("key", "value") // commit() // } // } // run { // getPreferences(Context.MODE_PRIVATE) // .getString("key", "no value")?.let{ // Snackbar.make(binding.root, it, BaseTransientBottomBar.LENGTH_INDEFINITE) // .show() // } // } // val newPostActivity = registerForActivityResult(NewPostResultContract()) { result -> // result ?: return@registerForActivityResult // viewModel.changeContent(result) // viewModel.save() val adapter = Posts(object : OnInteractionListener { override fun onEdit(post: Post) { viewModel.edit(post) // val text = post.content // newPostActivity.launch(text) val bundle = Bundle() bundle.textArg = post.content findNavController().navigate(R.id.action_feedFragment_to_newPostFragment, bundle) } override fun onLike(post: Post) { viewModel.like(post.id) } override fun onVideo(post: Post) { val url = "https://www.youtube.com/watch?v=qeQnMgega0k" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } override fun onShare(post: Post) { val intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, post.content) type = "text/plain" } val shareIntent = Intent.createChooser(intent, getString(R.string.chooser_share_post)) startActivity(shareIntent) viewModel.share(post.id) } override fun onAuthorClicked(post: Post) { val bundle = Bundle() bundle.putLong("postId", post.id) findNavController().navigate(R.id.action_feedFragment_to_onePostFragment, bundle) } override fun onRemove(post: Post) { viewModel.removeById(post.id) } }) binding.list.adapter = adapter viewModel.data.observe(viewLifecycleOwner) { posts -> adapter.submitList(posts) } binding.add.setOnClickListener { findNavController().navigate(R.id.action_feedFragment_to_newPostFragment) } return binding.root // val newPostLauncher = registerForActivityResult(NewPostResultContract()) { result -> // result ?: return@registerForActivityResult // viewModel.changeContent(result) // viewModel.save() // } // binding.add.setOnClickListener { // val text = "" // newPostLauncher.launch(text) // // } // viewModel.edited.observe(this) { post -> // if (post.id == 0L) { // return@observe // } // with(binding.contentPost) { // requestFocus() // setText(post.content) // } // } // Обработчик нажатия на кнопку share // val adapterr = posts { // viewModel.share(it.id) // } // binding.list.adapter = adapterr // viewModel.data.observe(this) { posts -> // adapter.submitList(posts) // } // val viewModel: PostViewModel by viewModels() // viewModel.data.observe(this) { post -> // post.map {post -> // binding.container.removeAllViews() // ActivityMainBinding.inflate(layoutInflater, binding., true).apply{ // author.text = post.author // published.text = post.published // content.text = post.content // val formattedLike = formatNumber(post.likecount) // textView.text = formattedLike // val formattedShare = formatNumber1(post.share) // textView2.text = formattedShare // // // like.setImageResource( // if (post.isLiked) R.mipmap.like2 else R.mipmap.like // // ) // like.setOnClickListener { // // viewModel.like(post.id) // // // } // share.setOnClickListener { // // // viewModel.share(post.id) // } // }.root // // } // } // binding.save.setOnClickListener { // with(binding.contentPost) { // if (text.isNullOrBlank()) { // Toast.makeText( // this@MainActivity, // context.getString(R.string.errorAdd), // Toast.LENGTH_SHORT // ).show() // return@setOnClickListener // } // // viewModel.changeContent(text.toString()) // viewModel.save() // // setText("") // clearFocus() // AndroidUtils.hideKeyboard(this) // } // } } }
Prac11/app/src/main/java/ru/btpit/zadanie2/activity/FeedFragment.kt
1448235130
package ru.btpit.zadanie2.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.widget.PopupMenu import androidx.activity.viewModels import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import ru.btpit.zadanie2.R import ru.btpit.zadanie2.databinding.ActivityMainBinding import ru.netology.nmedia.dto.Post import ru.netology.nmedia.viewmodel.PostViewModel interface OnInteractionListener { fun onLike(post: Post) {} fun onEdit(post: Post) {} fun onShare(post: Post) {} fun onRemove(post: Post) {} fun onVideo(post: Post) {} fun onAuthorClicked(post: Post) {} } class Posts( private val onInteractionListener: OnInteractionListener, ) : ListAdapter<Post, PostViewHolder>(PostDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder { val binding = ActivityMainBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PostViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: PostViewHolder, position: Int) { val post = getItem(position) holder.bind(post) } } class PostViewHolder( private val binding: ActivityMainBinding, private val onInteractionListener: OnInteractionListener, ) : RecyclerView.ViewHolder(binding.root) { fun bind(post: Post) { binding.apply { author.text = post.author published.text = post.published content.text = post.content // val formattedLike = formatNumber(post.likecount) //// textView.text = formattedLike // val formattedShare = formatNumber1(post.share) // textView2.text = formattedShare like.isChecked = post.isLiked like.text = "${formatNumber(post.likecount)}" share.text = "${formatNumber1(post.share)}" // like.setImageResource( // if (post.isLiked) R.mipmap.like2 else R.mipmap.like // // ) like.setOnClickListener { onInteractionListener.onLike(post) } Video.setOnClickListener { onInteractionListener.onVideo(post) } author.setOnClickListener { onInteractionListener.onAuthorClicked(post) } share.setOnClickListener { onInteractionListener.onShare(post) } menu.setOnClickListener { PopupMenu(it.context, it).apply { inflate(R.menu.options) setOnMenuItemClickListener { item -> when (item.itemId) { R.id.remove -> { onInteractionListener.onRemove(post) true } R.id.edit -> { onInteractionListener.onEdit(post) true } else -> false } } }.show() } } } } class PostDiffCallback : DiffUtil.ItemCallback<Post>() { override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem == newItem } } private fun formatNumber(number: Int): String { return when { number >= 1000000 -> { val value = number / 1000000 val remainder = number % 1000000 if (remainder > 0) { if (remainder >= 100000) { String.format("%.1f M", value + remainder / 1000000.0) } else { String.format("%d.%d M", value, remainder / 100000) } } else { "$value M" } } number in 1000..9999 -> { String.format("%.1fK", number / 1000.0) } number >= 10000 -> { String.format("%dK", number / 1000) } else -> number.toString() } } private fun formatNumber1(number: Int): String { return when { number >= 1000000 -> { val value = number / 1000000 val remainder = number % 1000000 if (remainder > 0) { if (remainder >= 100000) { String.format("%.1f M", value + remainder / 1000000.0) } else { String.format("%d.%d M", value, remainder / 100000) } } else { "$value M" } } number in 1000..9999 -> { String.format("%.1fK", number / 1000.0) } number >= 10000 -> { String.format("%dK", number / 1000) } else -> number.toString() } }
Prac11/app/src/main/java/ru/btpit/zadanie2/activity/Posts.kt
560199867
package com.goalapp.goal 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.goalapp.goal", appContext.packageName) } }
Goal-Multi_Module/app/src/androidTest/java/com/goalapp/goal/ExampleInstrumentedTest.kt
2890118926
package com.goalapp.goal 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) } }
Goal-Multi_Module/app/src/test/java/com/goalapp/goal/ExampleUnitTest.kt
262415417
package com.goalapp.goal import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App: Application()
Goal-Multi_Module/app/src/main/java/com/goalapp/goal/App.kt
1760396448
package com.goalapp.goal.di import com.goalapp.data.GoalRepositoryImpl import com.goalapp.domain.repository.GoalRepository import com.goalapp.domain.repository.ThemePreferencesRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RepositoryModule { @Singleton @Provides fun provideGoalRepository(repository: GoalRepositoryImpl):GoalRepository{ return repository } @Singleton @Provides fun provideThemeRepository(repository: ThemePreferencesRepository):ThemePreferencesRepository{ return repository } }
Goal-Multi_Module/app/src/main/java/com/goalapp/goal/di/RepositoryModule.kt
3063184127
package com.goalapp.goal.di import com.goalapp.domain.repository.GoalRepository import com.goalapp.domain.usecase.CompleteGoalUseCase import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetCompleteGoalListUseCase import com.goalapp.domain.usecase.GetGoalDetailUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.GetRunningGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import com.goalapp.domain.usecase.MinusStageUseCase import com.goalapp.domain.usecase.PlusStageUseCase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.hilt.android.components.ViewModelComponent import javax.inject.Named import javax.inject.Singleton @Module @InstallIn(ViewModelComponent::class) object UseCaseModule { @Provides fun providesGetGoalListUseCase (repository: GoalRepository):GetGoalListUseCase{ return GetGoalListUseCase(repository) } @Provides fun providesRunningGoalListUseCase (repository: GoalRepository):GetRunningGoalListUseCase{ return GetRunningGoalListUseCase(repository) } @Provides fun providesCompleteGoalListUseCase (repository: GoalRepository):GetCompleteGoalListUseCase{ return GetCompleteGoalListUseCase(repository) } @Provides fun providesGetGoalDetailUseCase (repository: GoalRepository):GetGoalDetailUseCase{ return GetGoalDetailUseCase(repository) } @Provides fun providesInsertGoalUseCase(repository: GoalRepository):InsertGoalUseCase{ return InsertGoalUseCase(repository) } @Provides fun providesDeleteGoalUseCase(repository: GoalRepository):DeleteGoalUseCase{ return DeleteGoalUseCase(repository) } @Provides fun providesPlusStageGoalUseCase(repository: GoalRepository):PlusStageUseCase{ return PlusStageUseCase(repository) } @Provides fun providesMinusStageGoalUseCase(repository: GoalRepository):MinusStageUseCase{ return MinusStageUseCase(repository) } @Provides fun providesCompleteGoalUseCase(repository: GoalRepository):CompleteGoalUseCase{ return CompleteGoalUseCase(repository) } } @Module @InstallIn(ActivityRetainedComponent::class) object AssistedInjectViewModelModule{ @Provides fun providesGetGoalDetailUseCase (repository: GoalRepository):GetGoalDetailUseCase{ return GetGoalDetailUseCase(repository) } @Provides fun providesPlusStageGoalUseCase(repository: GoalRepository):PlusStageUseCase{ return PlusStageUseCase(repository) } @Provides fun providesMinusStageGoalUseCase(repository: GoalRepository):MinusStageUseCase{ return MinusStageUseCase(repository) } @Provides fun providesCompleteGoalUseCase(repository: GoalRepository):CompleteGoalUseCase{ return CompleteGoalUseCase(repository) } }
Goal-Multi_Module/app/src/main/java/com/goalapp/goal/di/UseCaseModule.kt
1833660400
package com.goalapp.goal.di import android.app.Application import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler import androidx.datastore.preferences.SharedPreferencesMigration import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.preferencesDataStoreFile import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import javax.inject.Singleton private const val USER_THEME_PREFERENCES = "user_theme_preferences" @InstallIn(SingletonComponent::class) @Module object DataStoreModule { @Singleton @Provides fun provideContext(application: Application): Context { return application.applicationContext } @Singleton @Provides fun providePreferencesDataStore(@ApplicationContext appContext: Context): DataStore<Preferences> { return PreferenceDataStoreFactory.create( corruptionHandler = ReplaceFileCorruptionHandler( produceNewData = { emptyPreferences() } ), migrations = listOf(SharedPreferencesMigration(appContext,USER_THEME_PREFERENCES)), scope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile = { appContext.preferencesDataStoreFile(USER_THEME_PREFERENCES) } ) } }
Goal-Multi_Module/app/src/main/java/com/goalapp/goal/di/DataStoreModule.kt
1481982314
package com.goalapp.goal.di import android.content.Context import androidx.room.Room import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.goalapp.data.db.GoalDao import com.goalapp.data.db.GoalDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { /* val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE `Book` (`id` INTEGER, `name` TEXT, " + "PRIMARY KEY(`id`))") } } */ @Provides @Singleton fun provideGoalDatabase(@ApplicationContext context: Context): GoalDatabase { return Room.databaseBuilder( context, GoalDatabase::class.java, "Goal-db" ) //.addMigrations(MIGRATION_1_2) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideGoalDao(goalDatabase: GoalDatabase):GoalDao = goalDatabase.goalDao() }
Goal-Multi_Module/app/src/main/java/com/goalapp/goal/di/DatabaseModule.kt
1332314580
package com.goalapp.data 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.goalapp.data.test", appContext.packageName) } }
Goal-Multi_Module/data/src/androidTest/java/com/goalapp/data/ExampleInstrumentedTest.kt
3198763450
package com.goalapp.data 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) } }
Goal-Multi_Module/data/src/test/java/com/goalapp/data/ExampleUnitTest.kt
3004463051
package com.goalapp.data import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.goalapp.domain.repository.ThemePreferencesRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import java.io.IOException import javax.inject.Inject private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_theme_preferences") class ThemeRepositoryImpl@Inject constructor( private val context: Context ) : ThemePreferencesRepository { private val themeKey = intPreferencesKey("THEME_KEY") val theme : Flow<Int> = context.dataStore.data .catch { exception -> if (exception is IOException) { emit(emptyPreferences()) } else { throw exception } } .map {preferences -> preferences[themeKey] ?: 0 } override suspend fun setAppTheme(theme: Int) { context.dataStore.edit { preferences -> preferences[themeKey] = theme } } }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/ThemeRepositoryImpl.kt
3225408222
package com.goalapp.data.mapper import com.goalapp.data.db.GoalEntity import com.goalapp.domain.model.GoalRepo object GoalMapper:Mapper<GoalEntity, GoalRepo> { override fun GoalEntity.mapToDomainModel(): GoalRepo = GoalRepo( id=id, bigGoal = bigGoal, smallGoal = smallGoal, stage=stage, makeTime = makeTime, completeTime = completeTime, completion = completion ) override fun GoalRepo.mapFromDomainModel(): GoalEntity = GoalEntity( id=id, bigGoal = bigGoal, smallGoal = smallGoal, stage=stage, makeTime = makeTime, completeTime = completeTime, completion = completion ) }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/mapper/GoalMapper.kt
1646623313
package com.goalapp.data.mapper interface Mapper<From, To> { fun From.mapToDomainModel(): To fun To.mapFromDomainModel(): From }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/mapper/Mapper.kt
26049806
package com.goalapp.data.utils import android.util.Log import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken class Converters { /* @TypeConverter fun fromString(value: String?): ArrayList<String>? { val listType = object : TypeToken<ArrayList<String>>() {}.type Log.e("fromString","fromString") return Gson().fromJson(value, listType) } @TypeConverter fun fromArrayList(list: ArrayList<String>?): String? { val gson = Gson() Log.e("fromArrayList", list.toString()) return gson.toJson(list) } */ @TypeConverter fun listToJson(value: List<String>?) = Gson().toJson(value) @TypeConverter fun jsonToList(value: String) = Gson().fromJson(value, Array<String>::class.java).toList() }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/utils/Converters.kt
3350274166
package com.goalapp.data.db import android.annotation.SuppressLint import android.content.Context import androidx.room.AutoMigration import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverter import androidx.room.TypeConverters import androidx.room.migration.AutoMigrationSpec import androidx.room.migration.Migration import com.goalapp.data.utils.Converters @Database( entities = [GoalEntity::class], version = 1, /* autoMigrations = [ AutoMigration ( from = 1, to = 2, spec = GoalDatabase.MyAutoMigration::class ) ], */ exportSchema = true, ) @TypeConverters(Converters::class) abstract class GoalDatabase: RoomDatabase() { abstract fun goalDao(): GoalDao class MyAutoMigration : AutoMigrationSpec }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/db/GoalDatabase.kt
1289873008
package com.goalapp.data.db 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 GoalDao{ @Query("SELECT * FROM Goal") // ACS DESC fun getAll(): Flow<List<GoalEntity>> @Query("SELECT * FROM GOAL WHERE completion = 0") fun getRunningGoalList():Flow<List<GoalEntity>> @Query("SELECT * FROM GOAL WHERE completion = 1") fun getCompleteGoalList():Flow<List<GoalEntity>> @Query("SELECT * FROM Goal WHERE id = :id") fun getGoalDetail(id: Int): Flow<GoalEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(contact: GoalEntity) @Delete suspend fun delete(contact: GoalEntity) @Query("UPDATE Goal SET stage = stage + 1 WHERE id = :id") suspend fun plusStage(id: Int) @Query("UPDATE Goal SET stage = stage - 1 WHERE id = :id") suspend fun minusStage(id: Int) @Update suspend fun completeGoal(contact: GoalEntity) }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/db/GoalDao.kt
4175250189
package com.goalapp.data.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "Goal") data class GoalEntity( @PrimaryKey(autoGenerate = true) var id: Int = 0, @ColumnInfo(name = "Big_Goal") //칼럼명을 변수명과 같이 쓰려면 생략 var bigGoal: String, @ColumnInfo(name = "Small_Goal") var smallGoal: List<String>, @ColumnInfo(name = "Stage") var stage: Int, @ColumnInfo(name = "Make_time") var makeTime: String, @ColumnInfo(name = "Complete_time") var completeTime: String?, @ColumnInfo(name = "Completion") var completion: Boolean, ) { //constructor() : this(null, "", "",false,-1,"") }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/db/GoalEntity.kt
3018148492
package com.goalapp.data import com.goalapp.data.db.GoalDao import com.goalapp.data.db.GoalEntity import com.goalapp.data.mapper.GoalMapper.mapFromDomainModel import com.goalapp.data.mapper.GoalMapper.mapToDomainModel import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.GoalRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import javax.inject.Inject import javax.inject.Singleton @Singleton class GoalRepositoryImpl @Inject constructor( private val goalDao: GoalDao ):GoalRepository { override fun getGoalList(): Flow<List<GoalRepo>> = flow { //return getRepos() emitAll(goalDao.getAll().map { it.mapToDomainModel() }) } override fun getRunningGoalList(): Flow<List<GoalRepo>> = flow{ emitAll(goalDao.getRunningGoalList().map { it.mapToDomainModel() }) } override fun getCompleteGoalList(): Flow<List<GoalRepo>> = flow { emitAll(goalDao.getCompleteGoalList().map { it.mapToDomainModel() }) } override fun getGoalDetail(id: Int): Flow<GoalRepo> =flow { emitAll(goalDao.getGoalDetail(id).map { it.mapToDomainModel() }) } override suspend fun insertItem(item: GoalRepo) { goalDao.insert(item.mapFromDomainModel()) } override suspend fun deleteItem(item: GoalRepo) { goalDao.delete(item.mapFromDomainModel()) } override suspend fun plusStage(id: Int) { goalDao.plusStage(id) } override suspend fun minusStage(id: Int) { goalDao.minusStage(id) } override suspend fun completeGoal(item: GoalRepo) { goalDao.completeGoal(item.mapFromDomainModel()) } private fun List<GoalEntity>.mapToDomainModel() = map { it.mapToDomainModel() } }
Goal-Multi_Module/data/src/main/java/com/goalapp/data/GoalRepositoryImpl.kt
2388979295
package com.goalapp.domain.repository import com.goalapp.domain.model.GoalRepo import kotlinx.coroutines.flow.Flow interface GoalRepository { fun getGoalList(): Flow<List<GoalRepo>> fun getRunningGoalList(): Flow<List<GoalRepo>> fun getCompleteGoalList(): Flow<List<GoalRepo>> fun getGoalDetail(id: Int): Flow<GoalRepo> suspend fun insertItem(item:GoalRepo) suspend fun deleteItem(item:GoalRepo) suspend fun plusStage(id:Int) suspend fun minusStage(id:Int) suspend fun completeGoal(item:GoalRepo) }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/repository/GoalRepository.kt
1549943591
package com.goalapp.domain.repository interface ThemePreferencesRepository{ suspend fun setAppTheme(theme:Int) }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/repository/ThemePreferencesRepository.kt
520375958
package com.goalapp.domain.model data class GoalRepo ( var id: Int = 0, var bigGoal: String, var smallGoal: List<String>, var stage: Int, var makeTime: String, var completeTime: String?, var completion: Boolean, )
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/model/GoalRepo.kt
3621833842
package com.goalapp.domain.usecase import com.goalapp.domain.repository.ThemePreferencesRepository class ThemeUseCase(private val themePreferencesRepository: ThemePreferencesRepository) { //operator fun invoke() = themePreferencesRepository.setAppTheme() }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/ThemeUseCase.kt
797814112
package com.goalapp.domain.usecase import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.GoalRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class DeleteGoalUseCase( private val goalRepository: GoalRepository) { operator fun invoke( item: GoalRepo, scope: CoroutineScope ) { scope.launch(Dispatchers.Main) { goalRepository.deleteItem(item) } } }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/DeleteGoalUseCase.kt
3226291298
package com.goalapp.domain.usecase import com.goalapp.domain.repository.GoalRepository class GetGoalListUseCase(private val goalRepository: GoalRepository) { operator fun invoke() = goalRepository.getGoalList() /* operator fun invoke( scope: CoroutineScope ) { scope.launch(Dispatchers.IO) { goalRepository.getRepos() } } */ } class GetRunningGoalListUseCase(private val goalRepository: GoalRepository) { operator fun invoke() = goalRepository.getRunningGoalList() } class GetCompleteGoalListUseCase(private val goalRepository: GoalRepository) { operator fun invoke() = goalRepository.getCompleteGoalList() }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/GetGoalListUseCase.kt
4077217980
package com.goalapp.domain.usecase import com.goalapp.domain.repository.GoalRepository class GetGoalDetailUseCase( private val goalRepository: GoalRepository ) { operator fun invoke( id: Int ) = goalRepository.getGoalDetail(id) /* operator fun invoke( scope: CoroutineScope ) { scope.launch(Dispatchers.IO) { goalRepository.getRepos() } } */ }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/GetGoalDetailUseCase.kt
1727634521
package com.goalapp.domain.usecase import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.GoalRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class InsertGoalUseCase( private val goalRepository: GoalRepository) { operator fun invoke( item: GoalRepo, scope: CoroutineScope ) { scope.launch(Dispatchers.Main) { goalRepository.insertItem(item) } } }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/InsertGoalUseCase.kt
264088727
package com.goalapp.domain.usecase import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.GoalRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch class PlusStageUseCase( private val goalRepository: GoalRepository) { operator fun invoke( id: Int, scope: CoroutineScope ) { scope.launch(Dispatchers.Main) { goalRepository.plusStage(id) } } } class MinusStageUseCase( private val goalRepository: GoalRepository) { operator fun invoke( id: Int, scope: CoroutineScope ) { scope.launch(Dispatchers.Main) { goalRepository.minusStage(id) } } } class CompleteGoalUseCase( private val goalRepository: GoalRepository){ operator fun invoke( item: GoalRepo, scope: CoroutineScope ) { scope.launch(Dispatchers.Main) { goalRepository.completeGoal(item) } } }
Goal-Multi_Module/domain/src/main/java/com/goalapp/domain/usecase/UpdateGoalUseCase.kt
2115447679
package com.goalapp.presentation 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.goalapp.presentation.test", appContext.packageName) } }
Goal-Multi_Module/presentation/src/androidTest/java/com/goalapp/presentation/ExampleInstrumentedTest.kt
847950213
package com.goalapp.presentation 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) } }
Goal-Multi_Module/presentation/src/test/java/com/goalapp/presentation/ExampleUnitTest.kt
2027168884
package com.goalapp.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.goalapp.data.ThemeRepositoryImpl import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.ThemePreferencesRepository import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( getGoalReposUseCase: GetGoalListUseCase, private val themeRepositoryImpl: ThemeRepositoryImpl ): ViewModel(){ val items = getGoalReposUseCase().stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) val themeId = themeRepositoryImpl.theme suspend fun setAppTheme(theme:Int){ themeRepositoryImpl.setAppTheme(theme) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/MainViewModel.kt
975175404
package com.goalapp.presentation import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.AttributeSet import android.util.Log import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatDelegate import androidx.datastore.dataStore import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.goalapp.presentation.databinding.ActivityMainBinding import com.goalapp.presentation.view.goallist.RunningGoalListViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlin.properties.Delegates @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val mainViewModel: MainViewModel by viewModels() lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //앱이 실행될 때 MainViewModel에서 DataStore에 담겨있는 themeId를 가져옴. val themePreferences = runBlocking { if(mainViewModel.themeId.first()!=null){ mainViewModel.themeId.first() } else{ R.style.Theme_gray_Goal } } setTheme(themePreferences) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.fragment_container_view) as NavHostFragment navController = navHostFragment.navController binding.navBar.setupWithNavController(navController) } //자식 프래그먼트에서 BottomNavi 가릴 수 있게 지원 함수 fun HideBottomNavi(state: Boolean){ if(state) binding.navBar.visibility = View.GONE else binding.navBar.visibility = View.VISIBLE } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/MainActivity.kt
2929590900
package com.goalapp.presentation.adapter import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.navigation.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.goalapp.domain.model.GoalRepo import com.goalapp.presentation.R import com.goalapp.presentation.databinding.ListItemBinding class RunningGoalAdapter : ListAdapter<GoalRepo, RunningGoalAdapter.MyViewHolder>(diffUtil) { class MyViewHolder(private val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: GoalRepo) { var percent = (item.stage.toDouble() / item.smallGoal.size.toDouble() * 100).toInt() itemView.setOnClickListener{ val id = bundleOf("id" to item.id.toString()) itemView.findNavController().navigate(R.id.action_to_RunningGoalDetail, id) } binding.tvBig.text = item.bigGoal binding.tvSmall.text = "${percent}%" if (percent < 10) { binding.viewPercentLine.setColorFilter(Color.rgb(209, 178, 255)) } else if (percent in 10..19) { binding.viewPercentLine.setColorFilter(Color.rgb(181, 178, 255)) } else if (percent in 20..29) { binding.viewPercentLine.setColorFilter(Color.rgb(178, 204, 255)) } else if (percent in 30..39) { binding.viewPercentLine.setColorFilter(Color.rgb(178, 235, 244)) } else if (percent in 40..49) { binding.viewPercentLine.setColorFilter(Color.rgb(183, 240, 177)) } else if (percent in 50..59) { binding.viewPercentLine.setColorFilter(Color.rgb(206, 242, 121)) } else if (percent in 60..69) { binding.viewPercentLine.setColorFilter(Color.rgb(250, 237, 125)) } else if (percent in 70..79) { binding.viewPercentLine.setColorFilter(Color.rgb(255, 224, 140)) } else if (percent in 80..89) { binding.viewPercentLine.setColorFilter(Color.rgb(255, 193, 158)) } else if (percent in 90..99) { binding.viewPercentLine.setColorFilter(Color.rgb(255, 178, 217)) } else if (percent >= 100) { binding.viewPercentLine.setColorFilter(Color.rgb(255, 167, 167)) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(currentList[position]) } companion object { val diffUtil = object : DiffUtil.ItemCallback<GoalRepo>() { override fun areItemsTheSame(oldItem: GoalRepo, newItem: GoalRepo): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: GoalRepo, newItem: GoalRepo): Boolean { return oldItem == newItem } } } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/adapter/RunningGoalAdapter.kt
2105306878
package com.goalapp.presentation.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.navigation.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.goalapp.domain.model.GoalRepo import com.goalapp.presentation.R import com.goalapp.presentation.databinding.ListItemBinding class CompleteGoalAdapter : ListAdapter<GoalRepo, CompleteGoalAdapter.MyViewHolder>(diffUtil) { class MyViewHolder(private val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: GoalRepo) { itemView.setOnClickListener{ val id = bundleOf("id" to item.id.toString()) itemView.findNavController().navigate(R.id.action_to_RunningGoalDetail, id) } binding.tvBig.text = item.bigGoal binding.tvSmall.text = item.completeTime } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bind(currentList[position]) } companion object { val diffUtil = object : DiffUtil.ItemCallback<GoalRepo>() { override fun areItemsTheSame(oldItem: GoalRepo, newItem: GoalRepo): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: GoalRepo, newItem: GoalRepo): Boolean { return oldItem == newItem } } } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/adapter/CompleteGoalAdapter.kt
3341099604
package com.goalapp.presentation.view import androidx.appcompat.app.AppCompatActivity class EXMakeGoal : AppCompatActivity() { /* private var adView: AdView? = null private val mFormat = SimpleDateFormat("yyyy/M/d") // 날짜 포맷 private var todoViewModel: TodoViewModel? = null var small_goal_data = ArrayList<String>() var view_small_goal_data = ArrayList<String>() var et_small_goal: EditText? = null var et_big_goal: EditText? = null var btn_plus_small_goal: Button? = null var btn_del_small_goal: Button? = null var btn_save_goal: Button? = null protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeUtils.onActivityCreateSetTheme(this) setContentView(R.layout.make_goal) MobileAds.initialize(this, object : OnInitializationCompleteListener() { fun onInitializationComplete(initializationStatus: InitializationStatus?) {} }) adView = findViewById(R.id.adView) val adRequest: AdRequest = Builder().build() adView.loadAd(adRequest) val listView2 = findViewById<View>(R.id.listview2) as ListView et_big_goal = findViewById<EditText>(R.id.et_big_goal) et_small_goal = findViewById<EditText>(R.id.et_small_goal) btn_plus_small_goal = findViewById<Button>(R.id.btn_plus_small_goal) btn_del_small_goal = findViewById<Button>(R.id.btn_del_small_goal) btn_save_goal = findViewById<Button>(R.id.btn_save_goal) val adapter: ArrayAdapter<*> = ArrayAdapter<Any?>(this, R.layout.list_type1, view_small_goal_data) listView2.adapter = adapter todoViewModel = ViewModelProvider(this).get(TodoViewModel::class.java) todoViewModel.getAllTodos().observe(this, object : Observer<List<Todo?>?> { override fun onChanged(todos: List<Todo?>) { btn_plus_small_goal!!.setOnClickListener { //소목표 10개 입력받아서 리스트에 저장하는 소목표 추가 버튼 부분 if (et_small_goal.getText().toString().isEmpty() || et_small_goal.getText() .toString().length == 0 || et_small_goal.getText().toString() .replace(" ", "") == "" ) { Toast.makeText(getApplicationContext(), "소목표를 작성해주세요.", Toast.LENGTH_SHORT) .show() } //소목표 작성 칸에 아무것도 적지 않았을 경우인데 수정 필요! else { if (small_goal_data.size <= 9) //원래 10인줄 알았는데 9를 입력해야 10개까지 입력됨. { val str: String = et_small_goal.getText().toString() small_goal_data.add(str) view_small_goal_data.add(small_goal_data.size.toString() + "단계 : " + str) et_small_goal.setText("") //입력한 값은 지워줘야지 adapter.notifyDataSetChanged() } else if (small_goal_data.size > 9) { Toast.makeText( getApplicationContext(), "소목표는 최대 10개까지 입력 가능합니다.", Toast.LENGTH_SHORT ).show() } // 10개 이상 입력 시 제한문구 나옴. } } //소목표 추가 버튼 btn_del_small_goal!!.setOnClickListener { val count: Int ///,checked ; count = adapter.getCount() Log.e("갯수 : ", count.toString()) if (count > 0) { small_goal_data.removeAt(count - 1) view_small_goal_data.removeAt(count - 1) } else if (count == 0) { Toast.makeText( getApplicationContext(), "작성된 소목표가 존재하지 않습니다!", Toast.LENGTH_SHORT ).show() } adapter.notifyDataSetChanged() } //소목표 삭제 버튼 btn_save_goal!!.setOnClickListener { if (et_big_goal.getText().toString().isEmpty() || et_big_goal.getText() .toString().length == 0 || et_big_goal.getText().toString() .replace(" ", "") == "" ) { Toast.makeText(getApplicationContext(), "대목표를 작성해주세요.", Toast.LENGTH_SHORT) .show() } else if (small_goal_data.isEmpty()) { Toast.makeText(getApplicationContext(), "소목표를 작성해주세요.", Toast.LENGTH_SHORT) .show() } else { val date = Date() val make_time = mFormat.format(date) todoViewModel.insert( Todo( et_big_goal.getText().toString(), small_goal_data, 0, make_time, null ) ) val intent: Intent = Intent(getApplicationContext(), MainActivity::class.java) intent.putExtra("big_goal_name", et_big_goal.getText().toString()) intent.putStringArrayListExtra("small_goal_name", small_goal_data) startActivity(intent) finish() } } } }) } // oncreate() override fun onBackPressed() { val intent: Intent = Intent(this@MakeGoal, MainActivity::class.java) startActivity(intent) finish() } */ } //MakeGoal class
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/EXMakeGoal.kt
2750832883
package com.goalapp.presentation.view.addgoal import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class AddGoalViewModel @Inject constructor( getGoalReposUseCase: GetGoalListUseCase, private val insertGoalUseCase: InsertGoalUseCase, private val deleteGoalUseCase: DeleteGoalUseCase ): ViewModel(){ val items = getGoalReposUseCase().stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) fun insertItem(item:GoalRepo) { insertGoalUseCase(item, scope = viewModelScope) } fun deleteItem(item:GoalRepo){ deleteGoalUseCase(item, scope = viewModelScope) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/addgoal/AddGoalViewModel.kt
3706791511
package com.goalapp.presentation.view.addgoal import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.view.isEmpty import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.findNavController import com.goalapp.domain.model.GoalRepo import com.goalapp.presentation.MainActivity import com.goalapp.presentation.R import com.goalapp.presentation.databinding.FragmentAddGoalBinding import dagger.hilt.android.AndroidEntryPoint import java.text.SimpleDateFormat import java.util.Date @AndroidEntryPoint class AddGoalFragment : Fragment() { private var _binding: FragmentAddGoalBinding? = null private val binding get() = _binding!! private val addGoalViewModel: AddGoalViewModel by viewModels() var smallGoalList:MutableList<String> = ArrayList<String>() private val mFormat = SimpleDateFormat("yyyy/M/d") // 날짜 포맷 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val mainAct = activity as MainActivity mainAct.HideBottomNavi(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentAddGoalBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val date = Date() val makeTime = mFormat.format(date) var bigGoal = binding.etBigGoal var smallGoal = binding.etSmallGoal var smallList = binding.smallList var btnPlusSmallGoal = binding.btnPlusSmallGoal var btnDelSmallGoal = binding.btnDelSmallGoal var btnSaveGoal = binding.btnSaveGoal btnPlusSmallGoal.setOnClickListener { if(checkLogic(binding.etSmallGoal.text.toString())){ smallGoalList.add(smallGoal.text.toString()) Log.e("AddGoalFragment",smallGoalList.toString()) smallGoal.text = null } } btnDelSmallGoal.setOnClickListener { if(!smallList.isEmpty()){ smallGoalList.removeLast() Log.e("AddGoalFragment",smallGoalList.toString()) } } btnSaveGoal.setOnClickListener { if(checkLogic(binding.etBigGoal.text.toString()) && smallGoalList.isNotEmpty()){ val goalRepo = mappingGoalRepo( bigGoal = bigGoal.text.toString(), smallGoalList = smallGoalList, makeTime = makeTime) addGoalViewModel.insertItem(goalRepo) (activity as MainActivity).navController.navigate(R.id.action_to_RunningGoalList) } else Toast.makeText(requireContext(),"목표를 입력해주세요.",Toast.LENGTH_SHORT).show() } } //TEST private fun mappingGoalRepo(bigGoal: String, smallGoalList: MutableList<String>, makeTime:String): GoalRepo { Log.e("mappingGoalRepo","bigGoal:${bigGoal}, smallGoalList:${smallGoalList.toString()}") return GoalRepo( bigGoal = bigGoal, smallGoal = smallGoalList, stage=1, makeTime = makeTime, completeTime = "", completion = false ) } private fun checkLogic(value:String):Boolean{ if(value.replace(" ","").equals("")){ Toast.makeText(requireContext(),"목표를 입력해주세요.",Toast.LENGTH_SHORT).show() return false } else{ return true } } override fun onDestroy() { super.onDestroy() val mainAct = activity as MainActivity mainAct.HideBottomNavi(false) } override fun onDestroyView() { Log.e("AddGoalFragment","onDestoryView()") super.onDestroyView() _binding = null } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/addgoal/AddGoalFragment.kt
2297637821
package com.goalapp.presentation.view.goaldetail import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.usecase.CompleteGoalUseCase import com.goalapp.domain.usecase.GetGoalDetailUseCase import com.goalapp.domain.usecase.MinusStageUseCase import com.goalapp.domain.usecase.PlusStageUseCase import dagger.Module import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject class RunningGoalDetailViewModel @AssistedInject constructor( @Assisted private var id: Int, getGoalDetailUseCase: GetGoalDetailUseCase, private val plusStageUseCase: PlusStageUseCase, private val minusStageUseCase: MinusStageUseCase, private val completeGoalUseCase: CompleteGoalUseCase ): ViewModel() { val item = getGoalDetailUseCase(id).stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) fun plusStage(id: Int) { plusStageUseCase(id, scope = viewModelScope) } fun minusStage(id: Int) { minusStageUseCase(id, scope = viewModelScope) } fun completeGoal(goal:GoalRepo){ completeGoalUseCase(goal, scope = viewModelScope) } @AssistedFactory interface RunningGoalDetailViewModelFactory { fun create(id: Int): RunningGoalDetailViewModel } companion object { fun provideFactory( assistedFactory: RunningGoalDetailViewModelFactory, id: Int ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return assistedFactory.create(id) as T } } } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goaldetail/RunningGoalDetailViewModel.kt
3280392782
package com.goalapp.presentation.view.goaldetail import android.graphics.drawable.AnimationDrawable import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.goalapp.domain.model.GoalRepo import com.goalapp.presentation.MainActivity import com.goalapp.presentation.R import com.goalapp.presentation.databinding.FragmentRunningGoalDetailBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.Date import javax.inject.Inject @AndroidEntryPoint class RunningGoalDetailFragment : Fragment() { private var _binding :FragmentRunningGoalDetailBinding? = null private val binding get() = _binding!! private val mFormat = SimpleDateFormat("yyyy/M/d") // 날짜 포맷 private var date = Date() private lateinit var currentTime:String private lateinit var userAnimation: AnimationDrawable private lateinit var ballAnimation: AnimationDrawable private lateinit var roadAnimation: AnimationDrawable private var id:Int = 0 @Inject lateinit var runnigGoalViewModelFactory: RunningGoalDetailViewModel.RunningGoalDetailViewModelFactory private val runningGoalDetailViewModel by viewModels<RunningGoalDetailViewModel>{ RunningGoalDetailViewModel.provideFactory(runnigGoalViewModelFactory, id) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val mainAct = activity as MainActivity mainAct.HideBottomNavi(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentRunningGoalDetailBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) id = requireArguments().getString("id")!!.toInt() Log.e("RunningGoalDetailFragment","id: ${id.toString()}") currentTime = mFormat.format(date) val userAni = binding.user1.apply { setBackgroundResource(R.drawable.user_run) userAnimation = background as AnimationDrawable setOnClickListener { userAnimation.start() ballAnimation.start() roadAnimation.start() } } val ballAni = binding.ball1.apply { setBackgroundResource(R.drawable.ball_ani) ballAnimation = background as AnimationDrawable } val roadAni = binding.road.apply { setBackgroundResource(R.drawable.road_ani) roadAnimation = background as AnimationDrawable } lifecycleScope.launch { runningGoalDetailViewModel.item.flowWithLifecycle(lifecycle).collect{ if(it != null){ Log.e("RunningGoalDetailFragment","Goal: ${it.toString()}") diffDay(it,currentTime) initUI(it) } } } initButtonLogic(id) } override fun onDestroy() { super.onDestroy() val mainAct = activity as MainActivity mainAct.HideBottomNavi(false) } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun initUI(item: GoalRepo){ binding.tvBigGoal.text = item.bigGoal updateSmallGoal(item) } private fun updateSmallGoal(item: GoalRepo){ val stage = item.stage binding.tvSmallGoal.text = item.smallGoal[stage-1] binding.btnCompleteGoal.isClickable = false if(stage == 1){ if(item.smallGoal.size == 1){ binding.tvNextSmallGoal.visibility = View.INVISIBLE binding.btnPlusStage.isClickable = false binding.btnCompleteGoal.isClickable = true completeGoal(item) } else{ binding.tvNextSmallGoal.visibility = View.VISIBLE binding.tvNextSmallGoal.text = item.smallGoal[stage] } binding.tvCompSmallGoal.visibility = View.INVISIBLE binding.btnMinusStage.isClickable = false } else if(stage > 1 && stage < item.smallGoal.size){ binding.tvCompSmallGoal.visibility = View.VISIBLE binding.tvCompSmallGoal.text = item.smallGoal[stage-2] binding.tvNextSmallGoal.visibility = View.VISIBLE binding.tvNextSmallGoal.text = item.smallGoal[stage] binding.btnPlusStage.isClickable = true binding.btnMinusStage.isClickable = true } else if(stage == item.smallGoal.size){ binding.tvCompSmallGoal.text = item.smallGoal[stage-2] binding.tvNextSmallGoal.visibility = View.INVISIBLE binding.btnPlusStage.isClickable = false binding.btnCompleteGoal.isClickable = true completeGoal(item) } } private fun initButtonLogic(id: Int){ binding.btnPlusStage.setOnClickListener { runningGoalDetailViewModel.plusStage(id) } binding.btnMinusStage.setOnClickListener { runningGoalDetailViewModel.minusStage(id) } } private fun completeGoal(goal:GoalRepo){ binding.btnCompleteGoal.setOnClickListener { binding.btnMinusStage.isClickable = false binding.btnPlusStage.isClickable = false binding.btnCompleteGoal.isClickable = false runningGoalDetailViewModel.completeGoal( GoalRepo( id = goal.id, bigGoal = goal.bigGoal, smallGoal = goal.smallGoal, stage = goal.stage, makeTime = goal.makeTime, completeTime = currentTime, completion = true, ) ) } } private fun diffDay(goal: GoalRepo, currentDate:String){ // 문자열을 LocalDate 객체로 변환 val oldDate = mFormat.parse(goal.makeTime) val currentDate = mFormat.parse(currentDate) val daysDifference = ((currentDate.time - oldDate.time) / (24 * 60 * 60 * 1000)).toInt() if(goal.completion == false){ binding.tvDay.text = "${daysDifference}일째 진행중..!" } else binding.tvDay.text = "${daysDifference}일 동안 고생하셨습니다!" } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goaldetail/RunningGoalDetailFragment.kt
2577783909
package com.goalapp.presentation.view.setting import android.os.Bundle import android.text.Layout import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import com.goalapp.presentation.R import com.goalapp.presentation.databinding.FragmentSettingBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class SettingFragment : Fragment() { private var _binding :FragmentSettingBinding? = null private val binding get() = _binding!! private val settingViewModel:SettingViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSettingBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnBackground.setOnClickListener { binding.fragmentSetting.addView(createLayout()) } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun createLayout() :View{ val inflater = this.layoutInflater val layout = inflater.inflate(R.layout.list_background_theme, null) as LinearLayout val layoutBackground = layout.findViewById<LinearLayout>(R.id.layoutBackground) layout.findViewById<Button>(R.id.btnRed).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_red_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnPink).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_pink_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnYellow).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_yellow_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnGreen).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_green_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnBlue).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_blue_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnPurple).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_purple_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnWhite).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_white_Goal) } requireActivity().recreate() } layout.findViewById<Button>(R.id.btnGray).setOnClickListener { lifecycleScope.launch { settingViewModel.setAppTheme(R.style.Theme_gray_Goal) } requireActivity().recreate() } layoutBackground.setOnClickListener { deleteLayout(layout) } return layout } private fun deleteLayout(layout: View){ binding.fragmentSetting.removeView(layout) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/setting/SettingFragment.kt
3001207544
package com.goalapp.presentation.view.setting import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.goalapp.data.ThemeRepositoryImpl import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.repository.ThemePreferencesRepository import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class SettingViewModel @Inject constructor( private val themeRepositoryImpl: ThemeRepositoryImpl ): ViewModel(){ val theme = themeRepositoryImpl.theme.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) suspend fun setAppTheme(theme:Int){ themeRepositoryImpl.setAppTheme(theme) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/setting/SettingViewModel.kt
57683224
package com.goalapp.presentation.view.goallist import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import com.goalapp.presentation.R import com.goalapp.presentation.adapter.CompleteGoalAdapter import com.goalapp.presentation.adapter.RunningGoalAdapter import com.goalapp.presentation.databinding.FragmentCompleteGoalListBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch @AndroidEntryPoint class CompleteGoalListFragment : Fragment() { private var _binding :FragmentCompleteGoalListBinding? = null private val binding get() = _binding!! private val completeGoalListViewModel:CompleteGoalListViewModel by viewModels() private lateinit var completeGoalAdapter: CompleteGoalAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentCompleteGoalListBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) completeGoalAdapter = CompleteGoalAdapter() binding.listGoal.adapter = completeGoalAdapter binding.listGoal.layoutManager = GridLayoutManager(requireContext(),2, GridLayoutManager.VERTICAL, false) lifecycleScope.launch { completeGoalListViewModel.items.flowWithLifecycle(lifecycle).collect{ if(it != null){ completeGoalAdapter.submitList(it) Log.e("CompleteGoalListFragment",it.toString()) } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goallist/CompleteGoalListFragment.kt
96070163
package com.goalapp.presentation.view.goallist import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.GetRunningGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class RunningGoalListViewModel @Inject constructor( getRunningGoalListUseCase: GetRunningGoalListUseCase, private val insertGoalUseCase: InsertGoalUseCase, private val deleteGoalUseCase: DeleteGoalUseCase ): ViewModel(){ val items = getRunningGoalListUseCase().stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) fun insertItem(item:GoalRepo) { insertGoalUseCase(item, scope = viewModelScope) } fun deleteItem(item:GoalRepo){ deleteGoalUseCase(item, scope = viewModelScope) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goallist/RunningGoalListViewModel.kt
2780424587
package com.goalapp.presentation.view.goallist import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.GridLayoutManager import com.goalapp.presentation.R import com.goalapp.presentation.adapter.RunningGoalAdapter import com.goalapp.presentation.databinding.FragmentRunningGoalListBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class RunningGoalListFragment : Fragment() { private var _binding: FragmentRunningGoalListBinding? = null private val binding get() = _binding!! //private lateinit var runningGoalListViewModel: RunningGoalListViewModel private val runningGoalListViewModel: RunningGoalListViewModel by viewModels() private lateinit var runningGoalAdapter: RunningGoalAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRunningGoalListBinding.inflate(inflater,container,false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) runningGoalAdapter = RunningGoalAdapter() binding.listGoal.adapter = runningGoalAdapter binding.listGoal.layoutManager = GridLayoutManager(requireContext(),2, GridLayoutManager.VERTICAL, false) binding.btnMakeGoal.setOnClickListener { findNavController().navigate(R.id.RunningGoalListFragmentToAddGoalFragment) } //viewModel.insertItem(GoalRepo(bigGoal = "TEST", stage = 0, makeTime = "", completeTime = "", completion = false)) lifecycleScope.launch { runningGoalListViewModel.items.flowWithLifecycle(lifecycle).collect{ if (it != null) { runningGoalAdapter.submitList(it) Log.e("RunningGoalListFragment",it.toString()) } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goallist/RunningGoalListFragment.kt
1366953239
package com.goalapp.presentation.view.goallist import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.goalapp.domain.model.GoalRepo import com.goalapp.domain.usecase.DeleteGoalUseCase import com.goalapp.domain.usecase.GetCompleteGoalListUseCase import com.goalapp.domain.usecase.GetGoalListUseCase import com.goalapp.domain.usecase.InsertGoalUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class CompleteGoalListViewModel @Inject constructor( getCompleteGoalListUseCase: GetCompleteGoalListUseCase, private val insertGoalUseCase: InsertGoalUseCase, private val deleteGoalUseCase: DeleteGoalUseCase ): ViewModel(){ val items = getCompleteGoalListUseCase().stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000), initialValue = null ) fun insertItem(item:GoalRepo) { insertGoalUseCase(item, scope = viewModelScope) } fun deleteItem(item:GoalRepo){ deleteGoalUseCase(item, scope = viewModelScope) } }
Goal-Multi_Module/presentation/src/main/java/com/goalapp/presentation/view/goallist/CompleteGoalListViewModel.kt
611266670
package com.openclassrooms.realestatemanager import com.google.common.truth.Truth.assertThat import com.openclassrooms.realestatemanager.utils.Utils import org.junit.Test import java.util.Calendar class UtilsTest { @Test fun getTodayDate() { // WHEN val date = Utils.getTodayDate() // THEN val newDate = Calendar.getInstance() val stringDate = if (newDate.get(Calendar.DAY_OF_MONTH) < 10) { "0$newDate" } else { newDate.get(Calendar.DAY_OF_MONTH).toString() } assertThat(date.substring(0, 2)).isEqualTo(stringDate) if (newDate.get(Calendar.MONTH) + 1 < 10) { assertThat( date.substring(3, 5)).isEqualTo("0${newDate.get(Calendar.MONTH) + 1}") } else { assertThat(date.substring(3, 5)).isEqualTo(newDate.get(Calendar.MONTH) + 1).toString() } assertThat(date.substring(6, 10)).isEqualTo(newDate.get(Calendar.YEAR).toString()) } @Test fun convertDollarToEuro() { // WHEN val result = Utils.convertDollarToEuro(500.0) // THEN assertThat(475.0).isEqualTo(result) } @Test fun convertEuroToDollars() { // WHEN val result = Utils.convertEuroToDollars(500.0) // THEN assertThat(525.0).isEqualTo(result) } }
RealEstateManager/app/src/test/java/com/openclassrooms/realestatemanager/UtilsTest.kt
2271471141
package com.openclassrooms.realestatemanager.ui import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.openclassrooms.realestatemanager.R import com.openclassrooms.realestatemanager.utils.Utils class MainActivity : AppCompatActivity() { private var textViewMain: TextView? = null private var textViewQuantity: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //test ktilint // this.textViewMain = findViewById(R.id.activity_second_activity_text_view_main); textViewMain = findViewById(R.id.activity_main_activity_text_view_main) textViewQuantity = findViewById(R.id.activity_main_activity_text_view_quantity) configureTextViewMain() configureTextViewQuantity() } private fun configureTextViewMain() { // !! (non nul assert) textViewMain!!.textSize = 15f textViewMain!!.text = "Le premier bien immobilier enregistré vaut " } private fun configureTextViewQuantity() { val quantity = Utils.convertDollarToEuro(100.0) textViewQuantity!!.textSize = 20f textViewQuantity!!.text = quantity.toString() //setText must use a text format, not an int } }
RealEstateManager/app/src/main/java/com/openclassrooms/realestatemanager/ui/MainActivity.kt
727211678
package com.openclassrooms.realestatemanager.models data class PictureOfProperty( val id: String, val url: String, val description: String, val name: String )
RealEstateManager/app/src/main/java/com/openclassrooms/realestatemanager/models/PictureOfProperty.kt
3238650296
package com.openclassrooms.realestatemanager.models import android.graphics.Picture data class Property ( val id: String, val type: String, val price: Int, val area: Int, val numberOfRooms: Int, val description: String, val picturesList: List<PictureOfProperty>, // to create val address: String, val interestPoints: List<InterestPoint>, // to create val state: String, val createDate: String, val soldDate: String, val agentId: String, val lat: Double, val lng: Double )
RealEstateManager/app/src/main/java/com/openclassrooms/realestatemanager/models/Property.kt
1401913103
package com.openclassrooms.realestatemanager.models enum class InterestPoint { SCHOOL, PARK, SHOP, TRANSPORT }
RealEstateManager/app/src/main/java/com/openclassrooms/realestatemanager/models/InterestPoint.kt
3143184665
package br.com.dv.mzcronn import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class MzcronnApplicationTests { @Test fun contextLoads() { } }
nationality/src/test/kotlin/br/com/dv/mzcronn/MzcronnApplicationTests.kt
1849839733
package br.com.dv.mzcronn import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.cloud.openfeign.EnableFeignClients import org.springframework.scheduling.annotation.EnableScheduling @SpringBootApplication @EnableFeignClients @EnableScheduling class MzcronnApplication fun main(args: Array<String>) { runApplication<MzcronnApplication>(*args) }
nationality/src/main/kotlin/br/com/dv/mzcronn/MzcronnApplication.kt
2564298187
package br.com.dv.mzcronn.util import java.util.logging.Logger fun <R : Any> R.logger(): Lazy<Logger> = lazy { Logger.getLogger(unwrapCompanionClass(this.javaClass).name) } fun <T : Any> unwrapCompanionClass(ofClass: Class<T>): Class<*> { return if (ofClass.enclosingClass != null && ofClass.enclosingClass.kotlin.objectInstance?.javaClass == ofClass) { ofClass.enclosingClass } else { ofClass } }
nationality/src/main/kotlin/br/com/dv/mzcronn/util/LoggingUtils.kt
3435871817
package br.com.dv.mzcronn.transfermarket interface TransferMarketService { fun getTransferMarketData(): Map<String, Number> fun updateTransferMarketData() }
nationality/src/main/kotlin/br/com/dv/mzcronn/transfermarket/TransferMarketService.kt
3899908763
package br.com.dv.mzcronn.transfermarket import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.servlet.ModelAndView @Controller class TransferMarketController(private val transferMarketService: TransferMarketService) { @GetMapping("/transfer-market") fun listTransferMarketPlayers(): ModelAndView { val playersPerCountry = transferMarketService.getTransferMarketData() return ModelAndView("transfermarket").apply { addObject("playersPerCountry", playersPerCountry) } } }
nationality/src/main/kotlin/br/com/dv/mzcronn/transfermarket/TransferMarketController.kt
3509965690
package br.com.dv.mzcronn.transfermarket import br.com.dv.mzcronn.common.CountryDataService import br.com.dv.mzcronn.openfeign.MainClient import br.com.dv.mzcronn.util.logger import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service @Service class TransferMarketServiceImpl(private val client: MainClient, private val parser: TransferMarketParser, countryDataService: CountryDataService) : TransferMarketService { private val log by logger() private var transferMarketCache: MutableMap<String, Int> = mutableMapOf() private val countriesMap = countryDataService.getCountryMap().map { it.value to it.key.toInt() }.toMap() override fun getTransferMarketData(): Map<String, Number> { return transferMarketCache } @Scheduled(fixedRate = 3600000) override fun updateTransferMarketData() { countriesMap.forEach { (countryName, countryId) -> val html = client.getTransferMarketHtml(countryId) val totalPlayers = parser.parse(html) transferMarketCache[countryName] = totalPlayers log.info("Transfer market – $countryName total players: $totalPlayers") } } }
nationality/src/main/kotlin/br/com/dv/mzcronn/transfermarket/TransferMarketServiceImpl.kt
2569287090
package br.com.dv.mzcronn.transfermarket import org.springframework.stereotype.Component import java.util.regex.Pattern @Component class TransferMarketParser { fun parse(html: String): Int { val pattern = Pattern.compile("\"totalHits\":\"(\\d+)\"") val matcher = pattern.matcher(html) return if (matcher.find()) matcher.group(1).toInt() else 0 } }
nationality/src/main/kotlin/br/com/dv/mzcronn/transfermarket/TransferMarketParser.kt
2069822576
package br.com.dv.mzcronn.coach import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.servlet.ModelAndView @Controller class CoachController(private val coachService: CoachService) { @GetMapping("/coaches") fun listCoaches(@RequestParam(defaultValue = "1") n: Int): ModelAndView { val coaches = coachService.getCoachesByClass(n) return ModelAndView("coaches").apply { addObject("coaches", coaches) addObject("n", n) } } }
nationality/src/main/kotlin/br/com/dv/mzcronn/coach/CoachController.kt
1361028770
package br.com.dv.mzcronn.coach import br.com.dv.mzcronn.openfeign.MainClient import br.com.dv.mzcronn.util.logger import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service @Service class CoachServiceImpl(private val client: MainClient, private val parser: CoachParser) : CoachService { private val log by logger() private val coachesCache: MutableMap<Int, List<Coach>> = mutableMapOf() override fun getCoachesByClass(n: Int): List<Coach> = coachesCache[n] ?: listOf() @Scheduled(fixedRate = 150000) fun updateCoaches() { (1..13).forEach { n -> try { val html = client.getCoachesHtml(n) coachesCache[n] = parser.parse(html) log.info(""" |Updated cl_$n coaches: |${coachesCache[n]} """.trimMargin()) Thread.sleep(2000) } catch (e: InterruptedException) { log.warning("Thread interrupted while updating cl_$n coaches") } } } }
nationality/src/main/kotlin/br/com/dv/mzcronn/coach/CoachServiceImpl.kt
4237355032
package br.com.dv.mzcronn.coach interface CoachService { fun getCoachesByClass(n: Int): List<Coach> }
nationality/src/main/kotlin/br/com/dv/mzcronn/coach/CoachService.kt
3174483939
package br.com.dv.mzcronn.coach data class Coach(val name: String, val country: String)
nationality/src/main/kotlin/br/com/dv/mzcronn/coach/Coach.kt
427654647
package br.com.dv.mzcronn.coach import org.jsoup.Jsoup import org.springframework.stereotype.Component @Component class CoachParser { fun parse(html: String): List<Coach> { val doc = Jsoup.parse(html) val coaches = mutableListOf<Coach>() doc.select("table#coaches_list tbody tr").forEach { row -> val name = row.select("td").first()?.text() ?: "" val countryImg = row.select("td img").first() val country = countryImg?.attr("title") ?: "" if (name.isNotBlank() && country.isNotBlank()) { coaches.add(Coach(name, country)) } } return coaches } }
nationality/src/main/kotlin/br/com/dv/mzcronn/coach/CoachParser.kt
4056896690
package br.com.dv.mzcronn.common import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import jakarta.annotation.PostConstruct import org.springframework.core.io.ResourceLoader import org.springframework.stereotype.Service @Service class CountryDataService(private val resourceLoader: ResourceLoader) { private lateinit var countryMap: Map<String, String> @PostConstruct fun init() { val mapper = jacksonObjectMapper() val resource = resourceLoader.getResource("classpath:countries.json") countryMap = mapper.readValue(resource.inputStream, object : TypeReference<Map<String, String>>() {}) } fun getCountryMap(): Map<String, String> = countryMap }
nationality/src/main/kotlin/br/com/dv/mzcronn/common/CountryDataService.kt
1859868164
package br.com.dv.mzcronn.openfeign import feign.RequestInterceptor import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class FeignConfig { @Value("\${PHPSESSID}") private lateinit var phpSessId: String @Bean fun requestInterceptor(): RequestInterceptor = RequestInterceptor { template -> template.header("Cookie", "PHPSESSID=$phpSessId") } }
nationality/src/main/kotlin/br/com/dv/mzcronn/openfeign/FeignConfig.kt
2309526928
package br.com.dv.mzcronn.openfeign import org.springframework.cloud.openfeign.FeignClient import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable @FeignClient(name = "mzClient", url = "https://www.managerzone.com", configuration = [FeignConfig::class]) interface MainClient { @GetMapping("/ajax.php?p=coaches&sub=hire-coaches&coachClass=5&country=0&skills_conjunction=and&of=cl_{of}&od=2&sport=soccer&o=0") fun getCoachesHtml(@PathVariable("of") of: Int): String @GetMapping("/ajax.php?p=transfer&sub=transfer-search&sport=soccer&issearch=true&u=&nationality={nationality}&deadline=0&category=&valuea=&valueb=&bida=&bidb=&agea=19&ageb=37&tot_low=0&tot_high=110&s0a=0&s0b=10&s1a=0&s1b=10&s2a=0&s2b=10&s3a=0&s3b=10&s4a=0&s4b=10&s5a=0&s5b=10&s6a=0&s6b=10&s7a=0&s7b=10&s8a=0&s8b=10&s9a=0&s9b=10&s10a=0&s10b=10&s11a=0&s11b=10&s12a=0&s12b=10") fun getTransferMarketHtml(@PathVariable("nationality") nationality: Int): String }
nationality/src/main/kotlin/br/com/dv/mzcronn/openfeign/MainClient.kt
4017241108
package com.example.appquizuskropkacom 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.appquizuskropkacom", appContext.packageName) } }
AppQuizusKropkaCom/app/src/androidTest/java/com/example/appquizuskropkacom/ExampleInstrumentedTest.kt
1660322938
package com.example.appquizuskropkacom 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) } }
AppQuizusKropkaCom/app/src/test/java/com/example/appquizuskropkacom/ExampleUnitTest.kt
4056603410
package com.example.appquizuskropkacom import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.RadioGroup import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btn1 = findViewById<Button>(R.id.btn1) val wynik = findViewById<TextView>(R.id.Wynik) btn1.setOnClickListener { } } }
AppQuizusKropkaCom/app/src/main/java/com/example/appquizuskropkacom/MainActivity.kt
1946887826
package com.workmanager.onetimerequest 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.workmanager.onetimerequest", appContext.packageName) } }
WorkManager-OneTimeWorkRequest/app/src/androidTest/java/com/workmanager/onetimerequest/ExampleInstrumentedTest.kt
4249687896
package com.workmanager.onetimerequest 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) } }
WorkManager-OneTimeWorkRequest/app/src/test/java/com/workmanager/onetimerequest/ExampleUnitTest.kt
239129273
package com.workmanager.onetimerequest.notify import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Color import android.media.AudioAttributes import android.media.RingtoneManager import android.os.Build import androidx.core.app.NotificationCompat import androidx.work.ListenableWorker.Result.success import androidx.work.Worker import androidx.work.WorkerParameters import com.workmanager.onetimerequest.R import com.workmanager.onetimerequest.TimeScheduleActivity import com.workmanager.onetimerequest.util.victorToBitmap class NotifyOneTimeRequest( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams) { override fun doWork(): Result { val id = inputData.getLong(NOTIFICATION_ID, 0).toInt() sendNotification(id) return success() } @SuppressLint("UnspecifiedImmutableFlag") private fun sendNotification(id: Int) { val intent = Intent(applicationContext, TimeScheduleActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK putExtra(NOTIFICATION_ID, id) } val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val bitmap = applicationContext.victorToBitmap(R.drawable.ic_schedule_black_24dp) val titleNotification = applicationContext.getString(R.string.notification_title) val subtitleNotification = applicationContext.getString(R.string.notification_subtitle) val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE) } else { PendingIntent.getActivity( applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } val notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL) .setLargeIcon(bitmap).setSmallIcon(R.drawable.ic_schedule_white) .setContentTitle(titleNotification).setContentText(subtitleNotification) .setDefaults(NotificationCompat.DEFAULT_ALL).setContentIntent(pendingIntent) .setAutoCancel(true) notification.priority = NotificationCompat.PRIORITY_MAX if (Build.VERSION.SDK_INT >= 0) { notification.setChannelId(NOTIFICATION_CHANNEL) val ringtoneManager = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val audioAttributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build() val channel = NotificationChannel( NOTIFICATION_CHANNEL, NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH ) channel.enableLights(true) channel.lightColor = Color.RED channel.enableVibration(true) channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400) channel.setSound(ringtoneManager, audioAttributes) notificationManager.createNotificationChannel(channel) } notificationManager.notify(id, notification.build()) } companion object { const val NOTIFICATION_ID = "appName_notification_id" const val NOTIFICATION_NAME = "appName" const val NOTIFICATION_CHANNEL = "appName_channel_01" const val NOTIFICATION_WORK = "appName_notification_work" } }
WorkManager-OneTimeWorkRequest/app/src/main/java/com/workmanager/onetimerequest/notify/NotifyOneTimeRequest.kt
2516225271