content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.projectapplication import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.provider.Settings import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContentProviderCompat.requireContext import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import com.example.projectapplication.databinding.ActivityBoardBinding import com.example.projectapplication.databinding.ActivityMainBinding import com.google.firebase.firestore.Query class BoardActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { val binding = ActivityBoardBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(R.layout.activity_board) fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding = ActivityBoardBinding.inflate(inflater, container, false) //myCheckPermission(this as AppCompatActivity) binding.mainFab.setOnClickListener { Log.d("mobileApp", "binding"); if (MyApplication.checkAuth()) { // ๋กœ๊ทธ์ธํ•œ ์œ ์ €๋งŒ ์‹คํ–‰ ๊ฐ€๋Šฅ. val intent = Intent(this, AddActivity::class.java) // val intent = Intent(requireContext(), AddActivity::class.java) startActivity(intent) } else { Toast.makeText(this, "์ธ์ฆ์„ ์ง„ํ–‰ํ•ด ์ฃผ์„ธ์š”.", Toast.LENGTH_SHORT).show() } } return binding.root } fun makeRecyclerView(){ MyApplication.db.collection("news") .get() .addOnSuccessListener { result -> val itemList = mutableListOf<ItemBoardModel>() for(document in result){ val item = document.toObject(ItemBoardModel::class.java) item.docId=document.id itemList.add(item) } binding.boardRecyclerView.layoutManager = LinearLayoutManager(this) binding.boardRecyclerView.adapter = MyBoardAdapter(this, itemList) } .addOnFailureListener{exception -> Log.d("mobileapp", "error", exception) Toast.makeText(this, "์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ ํš๋“์— ์‹คํŒจํ•˜์˜€์Šต๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show() } } fun myCheckPermission(activity: AppCompatActivity) { val requestPermissionLauncher = activity.registerForActivityResult( ActivityResultContracts.RequestPermission() ) { if (it) { Toast.makeText(activity, "๊ถŒํ•œ ์Šน์ธ", Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, "๊ถŒํ•œ ๊ฑฐ๋ถ€", Toast.LENGTH_SHORT).show() } } if (ContextCompat.checkSelfPermission( activity, Manifest.permission.READ_EXTERNAL_STORAGE ) !== PackageManager.PERMISSION_GRANTED ) { requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } if (ContextCompat.checkSelfPermission( activity, Manifest.permission.WRITE_EXTERNAL_STORAGE ) !== PackageManager.PERMISSION_GRANTED ) { requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (!Environment.isExternalStorageManager()) { val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) activity.startActivity(intent) } } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/BoardActivity.kt
2505381548
package com.example.projectapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SettingActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_setting) } }
Helper_Subway/app/src/main/java/com/example/projectapplication/SettingActivity.kt
3969256130
package com.example.projectapplication 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 android.view.inputmethod.InputMethodManager import androidx.recyclerview.widget.LinearLayoutManager import com.example.projectapplication.databinding.FragmentSubwayBinding import com.google.android.material.internal.ViewUtils.hideKeyboard import retrofit2.Call import retrofit2.Callback import retrofit2.Response // btnSearch // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [SubwayFragment.newInstance] factory method to * create an instance of this fragment. */ class SubwayFragment : Fragment() { // // TODO: Rename and change types of parameters // private var param1: String? = null // private var param2: String? = null // // override fun onCreate(savedInstanceState: Bundle?) { // super.onCreate(savedInstanceState) // arguments?.let { // param1 = it.getString(ARG_PARAM1) // param2 = it.getString(ARG_PARAM2) // } // }ARG_PARAM2 private val modelItemSubway = ItemSubwayModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding = FragmentSubwayBinding.inflate(inflater, container, false) var mutableList: MutableList<ItemSubwayModel> binding.btnSearch.setOnClickListener { // ๊ฒ€์ƒ‰๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ, var keyword = binding.edtProduct.text.toString() // ๊ฒ€์ƒ‰ํ•œ ํ‚ค์›Œ๋“œ ๊ฐ€์ ธ์˜จ๋‹ค. val call: Call<MyModel> = MyApplication.networkService.getList( "6f6669585870686f3831586c724e6b", "json", 1000, ) Log.d("mobileApp", "${call.request()}") // ์˜ค๋ฅ˜ ์ ๊ฒ€ call?.enqueue(object : Callback<MyModel> { override fun onResponse(call: Call<MyModel>, response: Response<MyModel>) { if (keyword.isNotEmpty()) {// if (response.isSuccessful) { // ์ถ”๊ฐ€ val originalList = response.body()?.SeoulMetroFaciInfo?.row if (originalList != null) { // ํ•„ํ„ฐ๋ง๋œ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ val filteredList = originalList.filter { it.containsKeyword(keyword) } // RecyclerView ์–ด๋Œ‘ํ„ฐ ์„ค์ • binding.retrofitRecyclerView.layoutManager = LinearLayoutManager(context) binding.retrofitRecyclerView.adapter = MySubwayAdapter( requireContext(), if (filteredList.isNotEmpty()) filteredList else originalList ) } } } else{ // mutableList = mutableListOf<ItemSubwayModel>() // ์ดˆ๊ธฐํ™” binding.retrofitRecyclerView.layoutManager = LinearLayoutManager(context) binding.retrofitRecyclerView.adapter = MySubwayAdapter(requireContext(), response.body()!!.SeoulMetroFaciInfo.row) } } override fun onFailure(call: Call<MyModel>, t: Throwable) { Log.d("mobileApp", "${t.toString()}") } }) hideKeyboard() } return binding.root } private fun hideKeyboard() { val view = activity?.currentFocus if (view != null) { val imm = activity?.getSystemService(InputMethodManager::class.java) imm?.hideSoftInputFromWindow(view.windowToken, 0) } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SubwayFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = SubwayFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/SubwayFragment.kt
4262498079
package com.example.projectapplication import android.app.AlertDialog import android.content.Intent import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.* import androidx.fragment.app.Fragment import androidx.activity.result.contract.ActivityResultContracts import com.example.projectapplication.databinding.FragmentUserBinding // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [UserFragment.newInstance] factory method to * create an instance of this fragment. */ class UserFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding = FragmentUserBinding.inflate(inflater, container, false) // ์ „ํ™” ๊ฑธ๊ธฐ binding.btnCall.setOnClickListener { var intent = Intent(Intent.ACTION_VIEW, Uri.parse("tel:/1588-4388")) // ์„ค๋ช… : (this, Activity::class.java) startActivity(intent) // ACTION_CALL : ๋ฐ”๋กœ ์ „ํ™”๊ฑฐ๋Š” ์„ค์ • - ์ด ์„ค์ •์„ ํ•ด์ฃผ๋ ค๋ฉด AndroidManifest์— ์ถ”๊ฐ€ํ•ด์ค˜์•ผํ•จ. } // ์›น์‚ฌ์ดํŠธ ์—ฐ๊ฒฐ // ํ•ด๋‹น ์‚ฌ์ดํŠธ์— ์ ‘์†ํ•˜๊ธฐ binding.btnWeb.setOnClickListener { var intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.sisul.or.kr/open_content/calltaxi/")) startActivity(intent) } // ์งˆ๋ฌธํ•˜๊ธฐ ๋ˆ„๋ฅด๋ฉด binding.btnQst.setOnClickListener{ val intent = Intent(requireContext(), BoardActivity::class.java) startActivity(intent) } // ์ˆ˜์ •ํ•˜๊ธฐ val requestGalleryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ try{ val calRatio = calculateInSampleSize(it.data!!.data!!, 150, 150) val option = BitmapFactory.Options() option.inSampleSize = calRatio var inputStream = getActivity()?.getContentResolver()?.openInputStream(it.data!!.data!!) val bitmap = BitmapFactory.decodeStream(inputStream, null, option) inputStream!!.close() inputStream = null bitmap?.let { binding.userImageView.setImageBitmap(bitmap) } ?: let{ Log.d("mobileApp", "bitmap NULL")} } catch(e:Exception){ e.printStackTrace() } // ์›ํ•˜๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์œผ๋ฉด exception ๋ฐœ์ƒ } binding.galleryButton.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) intent.type = "image/*" //startActivity(intent) // ์ด๊ฑฐ ๋˜๊ธดํ•˜์ง€๋งŒ ๊ธฐ์กด์— ์‚ฌ์šฉํ•œ ์ง€๋„, ์ „ํ™”...์€ ๊ทธ๋ƒฅ ํ™”๋ฉด์—์„œ ๋ดค์„ ๋ฟ์ž„. but, ๊ฐค๋Ÿฌ๋ฆฌ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๊ฒƒ์ž„ - startActivity์“ฐ๋ฉด ์•ˆ๋จ. requestGalleryLauncher.launch(intent) } return binding.root } private fun calculateInSampleSize(fileUri: Uri, reqWidth: Int, reqHeight: Int): Int { val options = BitmapFactory.Options() options.inJustDecodeBounds = true try { var inputStream = getActivity()?.getContentResolver()?.openInputStream(fileUri) BitmapFactory.decodeStream(inputStream, null, options) inputStream!!.close() inputStream = null } catch (e: Exception) { e.printStackTrace() } //๋น„์œจ ๊ณ„์‚ฐ........................ val (height: Int, width: Int) = options.run { outHeight to outWidth } var inSampleSize = 1 //inSampleSize ๋น„์œจ ๊ณ„์‚ฐ if (height > reqHeight || width > reqWidth) { val halfHeight: Int = height / 2 val halfWidth: Int = width / 2 while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) { inSampleSize *= 2 } } return inSampleSize } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment UserFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = UserFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/UserFragment.kt
3032433901
package com.example.projectapplication import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule import com.example.projectapplication.databinding.ItemBoardBinding // item_board.xml๊ณผ ItemBoardModel.kt์—ฐ๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ adapter // iter_board.xml์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด binding class MyBoardViewHolder(val binding: ItemBoardBinding) : RecyclerView.ViewHolder(binding.root) // ItemBoardModel๋ฅผ mutablelist๋กœ ์‚ฌ์šฉํ•˜๊ฒ ๋‹ค? class MyBoardAdapter(val context: Context, val itemList: MutableList<ItemBoardModel>): RecyclerView.Adapter<MyBoardViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyBoardViewHolder { val layoutInflater = LayoutInflater.from(parent.context) return MyBoardViewHolder(ItemBoardBinding.inflate(layoutInflater)) } override fun getItemCount(): Int { return itemList.size } override fun onBindViewHolder(holder: MyBoardViewHolder, position: Int) { val data = itemList.get(position) holder.binding.run { itemEmailView.text=data.email // text๋ถ€๋ถ„์— data.email๋ถ€๋ถ„์„ ๋„ฃ๊ฒ ๋‹ค. itemDateView.text=data.date itemContentView.text=data.content } //์Šคํ† ๋ฆฌ์ง€ ์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ........................ // ์ด๋ฏธ์ง€ ๋ถˆ๋Ÿฌ์™€์•ผํ•จ. // val imageRef = MyApplication.storage.reference.child("images/{${data.docId}}.jpg") // imageRef.downloadUrl.addOnCompleteListener{task -> // if(task.isSuccessful){ // // ๋‹ค์šด๋กœ๋“œ ์ด๋ฏธ์ง€๋ฅผ ImageView์— ๋ณด์—ฌ์ค€๋‹ค. // GlideApp.with(context) // ๋ญ๊ฐ€ ๋ฌธ์ œ์ง€? 1์‹œ๊ฐ„ 10๋ถ„์ •๋„ // .load(task.result) // .into(holder.binding.itemImageView) // ์—ฌ๊ธฐ๋ถ€ํ„ฐ ์œ„๋กœ 3์ค„ : ์ด๋ฏธ์ง€ ๊ฐ€์ ธ์˜ค๊ธฐ...? // } // } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/MyBoardAdapter.kt
2845817215
package com.example.projectapplication import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.projectapplication.databinding.ItemSubwayBinding class MySubwayViewHolder(val binding: ItemSubwayBinding): RecyclerView.ViewHolder(binding.root) class MySubwayAdapter(val context: Context, var originaldatas: List<ItemSubwayModel>): RecyclerView.Adapter<RecyclerView.ViewHolder>() { var datas: MutableList<ItemSubwayModel>? = originaldatas?.toMutableList() override fun getItemCount(): Int { return datas?.size ?: 0 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = MySubwayViewHolder(ItemSubwayBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val binding = (holder as MySubwayViewHolder).binding //add...................................... val model = datas!![position] // item_subway์™€ bindingํ•ด์คŒ. binding.itemTitle.text = model.STATION_NM binding.itemName.text = model.FACI_NM binding.itemArea.text = "At" + model.LOCATION binding.itemPos.text = model.USE_YN } }
Helper_Subway/app/src/main/java/com/example/projectapplication/MySubwayAdapter.kt
3819751450
package com.example.projectapplication import android.os.Bundle import android.text.TextUtils import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.preference.EditTextPreference import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat class MySettingFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings, rootKey) val idPreference: EditTextPreference? = findPreference("id") idPreference?.summaryProvider = Preference.SummaryProvider<EditTextPreference> { preference -> val text: String? = preference.text if (TextUtils.isEmpty(text)) { // null์ธ ๊ฒฝ์šฐ "ID ์„ค์ •์ด ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค." } else { "์„ค์ •๋œ ID๋Š” $text ์ž…๋‹ˆ๋‹ค." } } val bgColorPreference: ListPreference? = findPreference("bg_color") bgColorPreference?.summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() // ๊ธ€์ž์ƒ‰ ๋ฐ”๊พธ๊ธฐ val txColorPreference: ListPreference? = findPreference("tx_color") txColorPreference?.summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() } }
Helper_Subway/app/src/main/java/com/example/projectapplication/MySettingFragment.kt
283202881
package com.example.projectapplication data class ItemSubwayModel( var STATION_NM: String? = null, //์—ญ๋ช… var FACI_NM: String? = null, // ์Šน๊ฐ•๊ธฐ๋ช… var LOCATION: String? = null, // ์„ค์น˜์œ„์น˜ var USE_YN: String? = null, // ์šดํ–‰ ์ƒํƒœ (๊ฐ€๋Šฅ or ๋ถˆ๊ฐ€๋Šฅ) var STATION_ID: String? = null, // ์—ญ์ฝ”๋“œ ){ // STATION_NM์ด ํŠน์ • ํ‚ค์›Œ๋“œ๋ฅผ ํฌํ•จํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜ ์ถ”๊ฐ€ fun containsKeyword(keyword: String): Boolean { return STATION_NM?.contains(keyword, ignoreCase = true) == true } } data class MyItems(val row:MutableList<ItemSubwayModel>) data class MyModel(val SeoulMetroFaciInfo: MyItems) //data class MyItem(val item:ItemRetrofitModel) //data class MyItems(val items:MutableList<MyItem>)
Helper_Subway/app/src/main/java/com/example/projectapplication/ItemSubwayModel.kt
3544559938
package com.example.projectapplication import android.content.Intent import android.Manifest import android.provider.Settings import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Environment import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import com.example.projectapplication.AddActivity import com.example.projectapplication.ItemBoardModel import com.example.projectapplication.MyApplication import com.example.projectapplication.MyBoardAdapter import com.example.projectapplication.databinding.FragmentBoardBinding import com.google.firebase.firestore.ktx.toObject import com.google.firebase.firestore.Query // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [BoardFragment.newInstance] factory method to * create an instance of this fragment. */ class BoardFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null lateinit var binding : FragmentBoardBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentBoardBinding.inflate(inflater, container, false) myCheckPermission(requireActivity() as AppCompatActivity) binding.mainFab.setOnClickListener { if(MyApplication.checkAuth()){ // ๋กœ๊ทธ์ธํ•œ ์œ ์ €๋งŒ ์‹คํ–‰ ๊ฐ€๋Šฅ. val intent = Intent(requireContext(), AddActivity::class.java) startActivity(intent) } else{ Toast.makeText(requireContext(), "์ธ์ฆ์„ ์ง„ํ–‰ํ•ด ์ฃผ์„ธ์š”.", Toast.LENGTH_SHORT).show() } } return binding.root } override fun onStart() { super.onStart() if(MyApplication.checkAuth()){ MyApplication.db.collection("news") .orderBy("date", Query.Direction.DESCENDING) .get() .addOnSuccessListener {result -> val itemList = mutableListOf<ItemBoardModel>() // ์•„๋ฌด๋Ÿฐ ๊ฐ’์ด ์—†๋Š” ์ƒํƒœ for(document in result){ val item = document.toObject(ItemBoardModel::class.java) item.docId = document.id itemList.add(item) } binding.boardRecyclerView.layoutManager = LinearLayoutManager(requireContext()) binding.boardRecyclerView.adapter = MyBoardAdapter(requireContext(), itemList) } .addOnFailureListener { Toast.makeText(requireContext(), "๋ฐ์ดํ„ฐ ํš๋“ ์‹คํŒจ", Toast.LENGTH_SHORT).show() } } } fun myCheckPermission(activity: AppCompatActivity) { val requestPermissionLauncher = activity.registerForActivityResult( ActivityResultContracts.RequestPermission() ) { if (it) { Toast.makeText(activity, "๊ถŒํ•œ ์Šน์ธ", Toast.LENGTH_SHORT).show() } else { Toast.makeText(activity, "๊ถŒํ•œ ๊ฑฐ๋ถ€", Toast.LENGTH_SHORT).show() } } if (ContextCompat.checkSelfPermission( activity, Manifest.permission.READ_EXTERNAL_STORAGE ) !== PackageManager.PERMISSION_GRANTED ) { requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) } if (ContextCompat.checkSelfPermission( activity, Manifest.permission.WRITE_EXTERNAL_STORAGE ) !== PackageManager.PERMISSION_GRANTED ) { requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (!Environment.isExternalStorageManager()) { val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) activity.startActivity(intent) } } } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment BoardFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = BoardFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/BoardFragment.kt
3354765151
package com.example.projectapplication import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.projectapplication.databinding.ActivityAddBinding import com.example.projectapplication.databinding.FragmentHomeBinding import com.example.projectapplication.databinding.FragmentUserBinding import kotlinx.coroutines.NonDisposableHandle.parent // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [HomeFragment.newInstance] factory method to * create an instance of this fragment. */ class HomeFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentHomeBinding.inflate(inflater, container, false) // ์ง€๋„์•ฑ ๋“ค์–ด๊ฐ€๊ธฐ binding.btnMap.setOnClickListener { // ์ง€๋„์•ฑ ๋“ค์–ด๊ฐ€๊ธฐ var intent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:37.5662952, 126.9779451")) startActivity(intent) } // Inflate the layout for this fragment //return inflater.inflate(R.layout.fragment_home, container, false) return binding.root } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment HomeFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = HomeFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/HomeFragment.kt
2966297496
package com.example.projectapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import com.example.projectapplication.databinding.ActivityAuthBinding import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.firebase.auth.GoogleAuthProvider class AuthActivity : AppCompatActivity() { lateinit var binding: ActivityAuthBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAuthBinding.inflate(layoutInflater) setContentView(binding.root) changeVisibility(intent.getStringExtra("data").toString()) // ์ฒ˜์Œ์€ ๋กœ๊ทธ์•„์›ƒ ์ƒํƒœ๊ฐ€ ๋ณด์ž„ binding.goSignInBtn.setOnClickListener { // ํšŒ์›๊ฐ€์ž… changeVisibility("signin") } binding.signBtn.setOnClickListener { //์ด๋ฉ”์ผ,๋น„๋ฐ€๋ฒˆํ˜ธ ํšŒ์›๊ฐ€์ž…........................ val email: String = binding.authEmailEditView.text.toString() val password: String = binding.authPasswordEditView.text.toString() MyApplication.auth.createUserWithEmailAndPassword(email, password) // email๊ณผ password๋ฅผ ์ „๋‹ฌํ•˜๊ฒ ๋‹ค. .addOnCompleteListener(this) { task -> if (task.isSuccessful) { MyApplication.auth.currentUser?.sendEmailVerification()?.addOnCompleteListener{ sendTask -> if(sendTask.isSuccessful){ Toast.makeText(baseContext, "ํšŒ์›๊ฐ€์ž… ์„ฑ๊ณต, ์ด๋ฉ”์ผ ํ™•์ธ", Toast.LENGTH_LONG).show() changeVisibility("Logout") } } } else{ Toast.makeText(baseContext, "ํšŒ์›๊ฐ€์ž… ์‹คํŒจ", Toast.LENGTH_LONG).show() changeVisibility("logout") } binding.authEmailEditView.text.clear() // email๊ณผ password๊ฒ€์ƒ‰์ฐฝ์„ ๊นจ๋—ํ•˜๊ฒŒ binding.authPasswordEditView.text.clear() } } binding.loginBtn.setOnClickListener { //์ด๋ฉ”์ผ, ๋น„๋ฐ€๋ฒˆํ˜ธ ๋กœ๊ทธ์ธ....................... val email: String = binding.authEmailEditView.text.toString() val password: String = binding.authPasswordEditView.text.toString() MyApplication.auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { //MyApplication์— ํ•จ์ˆ˜ ์ถ”๊ฐ€ํ•ด์คŒ. if (MyApplication.checkAuth()) { // ํ•จ์ˆ˜ checkAuth๊ฐ€ true๋ฉด MyApplication.email = email //changeVisibility("login") finish() // login๋Œ€์‹  ์›๋ž˜์˜ ํ”„๋กœ๊ทธ๋žจ์œผ๋กœ ๋Œ์•„์™€์•ผํ•œ๋‹ค. --> ๋ฐ”๋กœ mainactivity ํ™”๋ฉด์œผ๋กœ } else { Toast.makeText(baseContext, "์ด๋ฉ”์ผ ์ธ์ฆ ์‹คํŒจ", Toast.LENGTH_LONG).show() } } else { Toast.makeText(baseContext, "๋กœ๊ทธ์ธ ์‹คํŒจ", Toast.LENGTH_LONG).show() changeVisibility("logout") // logout ์ƒํƒœ ์œ ์ง€ } binding.authEmailEditView.text.clear() binding.authPasswordEditView.text.clear() } } binding.logoutBtn.setOnClickListener { //๋กœ๊ทธ์•„์›ƒ........... MyApplication.auth.signOut() MyApplication.email = null //changeVisibility("logout") finish() // ์›๋ž˜์˜ ํ”„๋กœ๊ทธ๋žจ์œผ๋กœ ๋Œ์•„์™€์•ผํ•œ๋‹ค. } val requestLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ val task = GoogleSignIn.getSignedInAccountFromIntent(it.data) // ๊ฒฐ๊ณผ ์ „๋‹ฌ ๋ฐ›์Œ // ์ด๋•Œ ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฅ˜๋Š” ApiException ์˜ค๋ฅ˜ : Google Play ์„œ๋น„์Šค ํ˜ธ์ถœ์ด ์‹คํŒจํ•˜์˜€์„ ๋•Œ ํ…Œ์Šคํฌ์—์„œ ๋ฐ˜ํ™˜ํ•  ์˜ˆ์™ธ try{ val account = task.getResult(ApiException::class.java) val credential = GoogleAuthProvider.getCredential(account.idToken, null) // ๊ตฌ๊ธ€์— ์ธ์ฆ๋˜์–ด์กŒ๋Š”๊ฐ€. MyApplication.auth.signInWithCredential(credential) // credential ์ธ์ฆ์„ ์ด์šฉํ•  ๊ฒƒ์ž„. .addOnCompleteListener(this){ // ์ธ์ฆ์ด ์™„๋ฃŒ๋˜์—ˆ์„ ๋•Œ ์ฒ˜๋ฆฌ task -> if(task.isSuccessful){ // ์ธ์ฆ์ด ์„ฑ๊ณต์ ์ธ ๊ฒฝ์šฐ MyApplication.email = account.email //changeVisibility("login") Log.d("mobileApp", "GoogleSignIn - Successful") finish() // ์›๋ž˜์˜ ํ”„๋กœ๊ทธ๋žจ์œผ๋กœ ๋Œ์•„์™€์•ผํ•œ๋‹ค. } else{ changeVisibility("logout") // logout์ƒํƒœ ์œ ์ง€ Log.d("mobileApp", "GoogleSignIn - NOT Successful") } } }catch (e: ApiException){ changeVisibility("logout") // logout์ƒํƒœ ์œ ์ง€ Log.d("mobileApp", "GoogleSignIn - ${e.message}") // ์–ด๋–ค ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์•Œ๋ ค์คŒ. } } binding.googleLoginBtn.setOnClickListener { //๊ตฌ๊ธ€ ๋กœ๊ทธ์ธ.................... val gso : GoogleSignInOptions = GoogleSignInOptions .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() val signInIntent : Intent = GoogleSignIn.getClient(this, gso).signInIntent requestLauncher.launch(signInIntent) // ํ›„์†์ฒ˜๋ฆฌ } } fun changeVisibility(mode: String) { if (mode.equals("signin")) { // ํšŒ์›๊ฐ€์ž…ํ•ด์•ผํ•  ๋•Œ // ===๋ณด๋‹ค .equals()๊ฐ€ ๋” ์•ˆ์ •์ ์ž„. binding.run { logoutBtn.visibility = View.GONE // ํšŒ์›๊ฐ€์ž…ํ•  ๋•Œ ํ•„์š”ํ•œ ๊ธฐ๋Šฅ๋“ค๋งŒ ๋ณด์ด๋„๋ก ํ•จ. goSignInBtn.visibility = View.GONE googleLoginBtn.visibility = View.GONE authEmailEditView.visibility = View.VISIBLE authPasswordEditView.visibility = View.VISIBLE signBtn.visibility = View.VISIBLE loginBtn.visibility = View.GONE } } else if (mode.equals("login")) { binding.run { authMainTextView.text = "${MyApplication.email} ๋‹˜ ๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค." logoutBtn.visibility = View.VISIBLE goSignInBtn.visibility = View.GONE googleLoginBtn.visibility = View.GONE authEmailEditView.visibility = View.GONE authPasswordEditView.visibility = View.GONE signBtn.visibility = View.GONE loginBtn.visibility = View.GONE } } else if (mode.equals("logout")) { binding.run { authMainTextView.text = "๋กœ๊ทธ์ธ ํ•˜๊ฑฐ๋‚˜ ํšŒ์›๊ฐ€์ž… ํ•ด์ฃผ์„ธ์š”." logoutBtn.visibility = View.GONE goSignInBtn.visibility = View.VISIBLE googleLoginBtn.visibility = View.VISIBLE authEmailEditView.visibility = View.VISIBLE authPasswordEditView.visibility = View.VISIBLE signBtn.visibility = View.GONE loginBtn.visibility = View.VISIBLE } } } }
Helper_Subway/app/src/main/java/com/example/projectapplication/AuthActivity.kt
373404213
package com.example.projectapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.content.ContextCompat import java.util.concurrent.Executor import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //setContentView(R.layout.activity_splash) //activity_splash์•ˆ์“ฐ๊ฒ ๋‹ค. val backExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor() val mainExecutor: Executor = ContextCompat.getMainExecutor(this) backExecutor.schedule({ mainExecutor.execute{ startActivity(Intent(applicationContext, MainActivity::class.java)) // mainactivity๋ถˆ๋Ÿฌ์˜ค๊ณ  finish() // ์ž๊ธด ๋๋ƒ„. } }, 1, TimeUnit.SECONDS) } }
Helper_Subway/app/src/main/java/com/example/projectapplication/SplashActivity.kt
1222666720
package com.example.projectapplication data class ItemBoardModel( var docId: String? = null, var email: String? = null, var content: String? = null, var date: String? = null, )
Helper_Subway/app/src/main/java/com/example/projectapplication/ItemBoardModel.kt
974025322
package com.example.projectapplication import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface NetworkService { //"http://openapi.seoul.go.kr:8088/6f6669585870686f3831586c724e6b/json/SeoulMetroFaciInfo/1/1000/?" @GET("{api_key}/{type}/SeoulMetroFaciInfo/1/{end_num}") fun getList( @Path("api_key") apikey:String, @Path("type") type:String, @Path("end_num") endn:Int, ) : Call<MyModel> }
Helper_Subway/app/src/main/java/com/example/projectapplication/NetworkService.kt
2889093462
package ru.bilchuk.kinobi 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.bilchuk.kinobi", appContext.packageName) } }
Kinobi/app/src/androidTest/java/ru/bilchuk/kinobi/ExampleInstrumentedTest.kt
2680883837
package ru.bilchuk.kinobi 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) } }
Kinobi/app/src/test/java/ru/bilchuk/kinobi/ExampleUnitTest.kt
1748845014
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.di import dagger.Component import ru.bilchuk.kinobi.presentation.movies.details.MovieDetailsFragment import ru.bilchuk.kinobi.presentation.movies.list.MovieListFragment import ru.bilchuk.kinobi.presentation.movies.reviews.ReviewListFragment import javax.inject.Singleton @Singleton @Component(modules = [MovieModule::class, AppModule::class]) interface ApplicationComponent { fun inject(activity: MovieListFragment) fun inject(activity: MovieDetailsFragment) fun inject(activity: ReviewListFragment) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/di/ApplicationComponent.kt
883591099
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.di import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import kotlinx.coroutines.Dispatchers import javax.inject.Singleton @Module class AppModule { @Provides @Singleton fun provideIODispatcher() = Dispatchers.IO @Provides @Singleton fun provideGson(): Gson = GsonBuilder() .setLenient() .create() }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/di/AppModule.kt
177301106
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.di import com.google.gson.Gson import dagger.Binds import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import ru.bilchuk.kinobi.data.datasources.network.NetworkKinoDataSource import ru.bilchuk.kinobi.data.datasources.network.NetworkKinoDataSourceImpl import ru.bilchuk.kinobi.data.mappers.MovieMapper import ru.bilchuk.kinobi.data.mappers.MovieMapperImpl import ru.bilchuk.kinobi.data.mappers.PosterMapper import ru.bilchuk.kinobi.data.mappers.PosterMapperImpl import ru.bilchuk.kinobi.data.mappers.ReviewMapper import ru.bilchuk.kinobi.data.mappers.ReviewMapperImpl import ru.bilchuk.kinobi.data.network.KinoRetrofitConstants import ru.bilchuk.kinobi.data.network.KinoService import ru.bilchuk.kinobi.data.repositories.KinoRepositoryImpl import ru.bilchuk.kinobi.domain.interactors.KinoInteractor import ru.bilchuk.kinobi.domain.interactors.KinoInteractorImpl import ru.bilchuk.kinobi.domain.repositories.KinoRepository @Module abstract class MovieModule { companion object { @Provides fun provideRetrofitMovieService(gson: Gson): KinoService = Retrofit.Builder() .baseUrl(KinoRetrofitConstants.BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(OkHttpClient.Builder().apply { addInterceptor { val request = it.request().newBuilder() .addHeader("X-API-KEY", KinoRetrofitConstants.API_KEY) .build() it.proceed(request) } val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY) addInterceptor(loggingInterceptor) }.build()) .build() .create(KinoService::class.java) } @Binds abstract fun bindNetworkMovieDataSource(impl: NetworkKinoDataSourceImpl): NetworkKinoDataSource @Binds abstract fun bindMovieMapper(impl: MovieMapperImpl): MovieMapper @Binds abstract fun bindPosterMapper(impl: PosterMapperImpl): PosterMapper @Binds abstract fun bindReviewMapper(impl: ReviewMapperImpl): ReviewMapper @Binds abstract fun bindMovieRepository(impl: KinoRepositoryImpl): KinoRepository @Binds abstract fun bindMovieInteractor(impl: KinoInteractorImpl): KinoInteractor }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/di/MovieModule.kt
1984515455
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.datasources.network import ru.bilchuk.kinobi.data.models.network.MoviesDto import ru.bilchuk.kinobi.data.models.network.PostersDto import ru.bilchuk.kinobi.data.models.network.ReviewsDto import ru.bilchuk.kinobi.data.network.KinoService import javax.inject.Inject class NetworkKinoDataSourceImpl @Inject constructor( private val kinoService: KinoService, ): NetworkKinoDataSource { override suspend fun getMovieList(page: Int): MoviesDto = kinoService.getMovieList( page = page, limit = DEFAULT_LIMIT ) override suspend fun getPosterList(movieId: Int): PostersDto = kinoService.getPosterList( movieId = movieId, limit = DEFAULT_LIMIT ) override suspend fun getReviewList(movieId: Int): ReviewsDto = kinoService.getReviewList( movieId = movieId, limit = DEFAULT_LIMIT ) companion object { const val DEFAULT_LIMIT = 20 } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/datasources/network/NetworkKinoDataSourceImpl.kt
4049285118
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.datasources.network import ru.bilchuk.kinobi.data.models.network.MoviesDto import ru.bilchuk.kinobi.data.models.network.PostersDto import ru.bilchuk.kinobi.data.models.network.ReviewsDto interface NetworkKinoDataSource { suspend fun getMovieList(page: Int): MoviesDto suspend fun getPosterList(movieId: Int): PostersDto suspend fun getReviewList(movieId: Int): ReviewsDto }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/datasources/network/NetworkKinoDataSource.kt
423287030
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.network object KinoRetrofitConstants { const val BASE_URL = "https://api.kinopoisk.dev" const val API_KEY = "" }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/network/KinoRetrofitConstants.kt
359132274
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.network import retrofit2.http.GET import retrofit2.http.Query import ru.bilchuk.kinobi.data.models.network.MoviesDto import ru.bilchuk.kinobi.data.models.network.PostersDto import ru.bilchuk.kinobi.data.models.network.ReviewsDto interface KinoService { @GET("/v1.4/movie") suspend fun getMovieList(@Query("page") page: Int, @Query("limit") limit: Int): MoviesDto @GET("/v1.4/image") suspend fun getPosterList(@Query("movieId") movieId: Int, @Query("limit") limit: Int): PostersDto @GET("/v1.4/review") suspend fun getReviewList(@Query("movieId") movieId: Int, @Query("limit") limit: Int): ReviewsDto }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/network/KinoService.kt
2355137013
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.repositories import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import ru.bilchuk.kinobi.data.datasources.network.NetworkKinoDataSource import ru.bilchuk.kinobi.data.mappers.MovieMapper import ru.bilchuk.kinobi.data.mappers.PosterMapper import ru.bilchuk.kinobi.data.mappers.ReviewMapper import ru.bilchuk.kinobi.domain.models.Movie import ru.bilchuk.kinobi.domain.models.Poster import ru.bilchuk.kinobi.domain.models.Review import ru.bilchuk.kinobi.domain.repositories.KinoRepository import javax.inject.Inject class KinoRepositoryImpl @Inject constructor( private val dataSource: NetworkKinoDataSource, private val movieMapper: MovieMapper, private val posterMapper: PosterMapper, private val reviewMapper: ReviewMapper, private val dispatcher: CoroutineDispatcher ): KinoRepository { override suspend fun getMovieList(page: Int): List<Movie> = withContext(dispatcher) { dataSource.getMovieList(page).docs?.map { movieMapper.convert(it) } ?: emptyList() } override suspend fun getPosterList(movieId: Int): List<Poster> = withContext(dispatcher) { dataSource.getPosterList(movieId).docs?.map { posterMapper.convert(it) } ?: emptyList() } override suspend fun getReviewList(movieId: Int): List<Review> = withContext(dispatcher) { dataSource.getReviewList(movieId).docs?.map { reviewMapper.convert(it) } ?: emptyList() } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/repositories/KinoRepositoryImpl.kt
2144747580
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network abstract class GeneralDto { val total: Int = 0 val limit: Int = 0 val page: Int = 0 val pages: Int = 0 }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/GeneralDto.kt
104498420
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network import java.util.Date data class ReviewDto( val title: String?, val review: String?, val date: String?, val author: String, )
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/ReviewDto.kt
2225514214
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network data class MovieDto( val id: Int, val name: String?, val poster: Poster?, val description: String?, val backdrop: Backdrop?, val rating: Rating?, val genres: List<Genre>? ) data class Poster( val url: String?, val previewUrl: String? ) data class Backdrop( val url: String?, val previewUrl: String? ) data class Rating( val kp: Double?, ) data class Genre( val name: String? )
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/MovieDto.kt
171349145
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network data class ReviewsDto( val docs: List<ReviewDto>?, ) : GeneralDto()
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/ReviewsDto.kt
1578884015
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network data class PostersDto( val docs: List<PosterDto>? ) : GeneralDto()
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/PostersDto.kt
284035150
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network data class PosterDto( val url: String?, val previewUrl: String?, )
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/PosterDto.kt
832876141
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.models.network data class MoviesDto( val docs: List<MovieDto>? ) : GeneralDto()
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/models/network/MoviesDto.kt
1474665771
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.PosterDto import ru.bilchuk.kinobi.domain.models.Poster interface PosterMapper { fun convert(dto: PosterDto): Poster }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/PosterMapper.kt
4243227279
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.ReviewDto import ru.bilchuk.kinobi.domain.models.Review import java.text.SimpleDateFormat import java.util.Locale import javax.inject.Inject class ReviewMapperImpl @Inject constructor(): ReviewMapper { override fun convert(dto: ReviewDto): Review = Review( title = dto.title, review = dto.review, date = if (dto.date.isNullOrEmpty()) { null } else { SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault() ).parse(dto.date) }, author = dto.author ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/ReviewMapperImpl.kt
1339303557
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.MovieDto import ru.bilchuk.kinobi.domain.models.Movie interface MovieMapper { fun convert(dto: MovieDto): Movie }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/MovieMapper.kt
4268278273
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.MovieDto import ru.bilchuk.kinobi.domain.models.Backdrop import ru.bilchuk.kinobi.domain.models.Movie import ru.bilchuk.kinobi.domain.models.Poster import ru.bilchuk.kinobi.domain.models.Rating import javax.inject.Inject class MovieMapperImpl @Inject constructor(): MovieMapper { override fun convert(dto: MovieDto): Movie = Movie( id = dto.id, name = dto.name.orEmpty(), poster = Poster( url = dto.poster?.url, previewUrl = dto.poster?.previewUrl, ), description = dto.description.orEmpty(), backdrop = Backdrop( url = dto.backdrop?.url, previewUrl = dto.backdrop?.previewUrl, ), rating = Rating( kp = dto.rating?.kp ), genre = dto.genres?.get(0)?.name ?: "", ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/MovieMapperImpl.kt
3020529278
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.PosterDto import ru.bilchuk.kinobi.domain.models.Poster import javax.inject.Inject class PosterMapperImpl @Inject constructor(): PosterMapper { override fun convert(dto: PosterDto): Poster = Poster( url = dto.url, previewUrl = dto.previewUrl, ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/PosterMapperImpl.kt
91470273
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.data.mappers import ru.bilchuk.kinobi.data.models.network.ReviewDto import ru.bilchuk.kinobi.domain.models.Review interface ReviewMapper { fun convert(dto: ReviewDto): Review }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/data/mappers/ReviewMapper.kt
2925141966
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.domain.repositories import ru.bilchuk.kinobi.domain.models.Movie import ru.bilchuk.kinobi.domain.models.Poster import ru.bilchuk.kinobi.domain.models.Review interface KinoRepository { suspend fun getMovieList(page: Int): List<Movie> suspend fun getPosterList(movieId: Int): List<Poster> suspend fun getReviewList(movieId: Int): List<Review> }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/domain/repositories/KinoRepository.kt
269348622
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.domain.models import android.os.Parcelable import kotlinx.parcelize.Parcelize import java.util.Date @Parcelize data class Movie( val id: Int, val name: String = "", val poster: Poster?, val description: String = "", val backdrop: Backdrop?, val rating: Rating?, val genre: String = "", ) : Parcelable @Parcelize data class Poster( val url: String?, val previewUrl: String?, ) : Parcelable @Parcelize data class Backdrop( val url: String?, val previewUrl: String?, ) : Parcelable @Parcelize data class Rating( val kp: Double?, ) : Parcelable @Parcelize data class Review( val title: String?, val review: String?, val date: Date?, val author: String?, ) : Parcelable
Kinobi/app/src/main/java/ru/bilchuk/kinobi/domain/models/Movie.kt
505464870
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.domain.interactors import ru.bilchuk.kinobi.domain.models.Movie import ru.bilchuk.kinobi.domain.models.Poster import ru.bilchuk.kinobi.domain.models.Review interface KinoInteractor { suspend fun getMovieList(page: Int = FIRST_PAGE): List<Movie> suspend fun getPosterList(movieId: Int): List<Poster> suspend fun getReviewList(movieId: Int): List<Review> companion object { const val FIRST_PAGE = 1 } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/domain/interactors/KinoInteractor.kt
422030317
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.domain.interactors import ru.bilchuk.kinobi.domain.models.Movie import ru.bilchuk.kinobi.domain.models.Poster import ru.bilchuk.kinobi.domain.models.Review import ru.bilchuk.kinobi.domain.repositories.KinoRepository import javax.inject.Inject class KinoInteractorImpl @Inject constructor( private val repository: KinoRepository ): KinoInteractor { override suspend fun getMovieList(page: Int): List<Movie> = repository.getMovieList(page) override suspend fun getPosterList(movieId: Int): List<Poster> = repository.getPosterList(movieId) override suspend fun getReviewList(movieId: Int): List<Review> = repository.getReviewList(movieId) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/domain/interactors/KinoInteractorImpl.kt
3322754165
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import androidx.core.view.updatePadding import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import ru.bilchuk.kinobi.presentation.utils.doOnApplyWindowInsets import com.google.android.material.bottomnavigation.BottomNavigationView import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private var navView: BottomNavigationView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupInsets() navView = binding.navView val navController = findNavController(R.id.nav_host_fragment_activity_main) navView?.setupWithNavController(navController) } fun showBottomNav() { navView?.visibility = View.VISIBLE } fun hideBottomNav() { navView?.visibility = View.GONE } private fun setupInsets() { WindowCompat.setDecorFitsSystemWindows(window, false) binding.navView.doOnApplyWindowInsets { view, insets, padding -> view.updatePadding( bottom = padding.bottom + insets.systemWindowInsetBottom ) } } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/MainActivity.kt
3714669601
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation import android.app.Application import ru.bilchuk.kinobi.di.DaggerApplicationComponent class KinobiApp : Application() { val appComponent = DaggerApplicationComponent.create() }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/KinobiApp.kt
470557200
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.utils import android.content.Context import android.util.TypedValue import android.view.View import android.view.WindowInsets import androidx.fragment.app.Fragment import ru.bilchuk.kinobi.presentation.MainActivity fun View.doOnApplyWindowInsets(block: (View, WindowInsets, InitialPadding) -> Unit) { val initialPadding = recordInitialPaddingForView(this) setOnApplyWindowInsetsListener { v, insets -> block(v, insets, initialPadding) insets } requestApplyInsetsWhenAttached() } fun View.requestApplyInsetsWhenAttached() { if (isAttachedToWindow) { requestApplyInsets() } else { addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { v.removeOnAttachStateChangeListener(this) v.requestApplyInsets() } override fun onViewDetachedFromWindow(v: View) = Unit }) } } fun Fragment.showBottomNav() { val activity = requireActivity() if (activity is MainActivity) { activity.showBottomNav() } } fun Fragment.hideBottomNav() { val activity = requireActivity() if (activity is MainActivity) { activity.hideBottomNav() } } data class InitialPadding(val left: Int, val top: Int, val right: Int, val bottom: Int) private fun recordInitialPaddingForView(view: View) = InitialPadding( view.paddingLeft, view.paddingTop, view.paddingRight, view.paddingBottom) fun Double.format(digits: Int) = "%.${digits}f".format(this)
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/utils/views_ext.kt
4104670291
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.utils import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView class MarginItemDecoration( private val spaceSize: Int, private val spanCount: Int = 1, private val orientation: Int = GridLayoutManager.VERTICAL, private val startMargin: Int = 0, ) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) = with(outRect) { if (orientation == GridLayoutManager.VERTICAL) { if (parent.getChildAdapterPosition(view) < spanCount) { top = spaceSize } if (parent.getChildAdapterPosition(view) % spanCount == 0) { left = spaceSize } } else { if (parent.getChildAdapterPosition(view) < spanCount) { left = spaceSize + startMargin } if (parent.getChildAdapterPosition(view) % spanCount == 0) { top = spaceSize } } right = spaceSize bottom = spaceSize } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/utils/MarginItemDecoration.kt
4217520976
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.more import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import ru.bilchuk.kinobi.presentation.utils.showBottomNav import com.google.android.material.dialog.MaterialAlertDialogBuilder import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.FragmentMoreBinding class MoreFragment : Fragment() { private var _binding: FragmentMoreBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMoreBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) showBottomNav() with(binding) { toolbar.title = getString(R.string.title_more) itemViewCode.setOnClickListener { showSourceCode() } itemAbout.setOnClickListener { showAboutDialog() } } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun showSourceCode() = startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(getString(R.string.url_project_github)) }) private fun showAboutDialog() = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.about_kinobi) .setMessage(R.string.about_kinobi_message) .setPositiveButton(android.R.string.ok) { dialog, _ -> dialog.dismiss() } .show() }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/more/MoreFragment.kt
3122067792
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.details import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import ru.bilchuk.kinobi.domain.interactors.KinoInteractor import ru.bilchuk.kinobi.domain.models.Poster import javax.inject.Inject class MovieDetailsViewModel @Inject constructor( private val interactor: KinoInteractor ) : ViewModel() { private val _uiState = MutableStateFlow(PosterListUiState()) val uiState: StateFlow<PosterListUiState> = _uiState.asStateFlow() fun getPosterList(movieId: Int) { viewModelScope.launch { try { val poster = interactor.getPosterList(movieId) _uiState.update { it.copy( poster = poster ) } } catch (e: Exception) { Log.d("MovieDetailsViewModel", e.message.toString()) _uiState.update { it.copy( isError = true ) } } } } fun userMessageShown() { _uiState.update { it.copy( isError = false ) } } data class PosterListUiState( val isError: Boolean = false, val poster: List<Poster> = emptyList() ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/details/MovieDetailsViewModel.kt
4281826342
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.details import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.Navigation import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.GridLayoutManager import com.bumptech.glide.Glide import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.FragmentMovieDetailsBinding import ru.bilchuk.kinobi.presentation.KinobiApp import ru.bilchuk.kinobi.presentation.movies.description.Description import ru.bilchuk.kinobi.presentation.utils.MarginItemDecoration import ru.bilchuk.kinobi.presentation.utils.format import ru.bilchuk.kinobi.presentation.utils.hideBottomNav import javax.inject.Inject class MovieDetailsFragment : Fragment() { @Inject lateinit var viewModel: MovieDetailsViewModel private val args: MovieDetailsFragmentArgs by navArgs() private var _binding: FragmentMovieDetailsBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.applicationContext as KinobiApp) .appComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMovieDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val movie = args.movie with(binding) { toolbar.apply { setNavigationIcon(R.drawable.ic_baseline_arrow_back_24) setNavigationOnClickListener { findNavController().navigateUp() } title = movie?.name.orEmpty() } Glide .with(root.context) .load(movie?.backdrop?.url ?: movie?.poster?.url) .into(image) val ratingStr = "${movie?.rating?.kp?.format(1).orEmpty()}โ˜…" cardDescription.setOnClickListener { val direction = MovieDetailsFragmentDirections.actionOpenDescription( Description( toolbarTitle = movie?.name.orEmpty(), title = getString(R.string.title_about_movie), extra = ratingStr, subtitle = movie?.genre.orEmpty(), description = movie?.description.orEmpty(), ) ) Navigation.findNavController(it).navigate(direction) } tvDescription.text = movie?.description.orEmpty() tvRating.text = ratingStr tvGenre.text = movie?.genre?.replaceFirstChar{ it.uppercase() }.orEmpty() btnOpenReviews.setOnClickListener { val direction = MovieDetailsFragmentDirections.actionOpenReviews(args.movie) Navigation.findNavController(it).navigate(direction) } bannerList.addItemDecoration( MarginItemDecoration( spaceSize = resources.getDimensionPixelSize(R.dimen.default_margin_small), orientation = GridLayoutManager.HORIZONTAL, startMargin = resources.getDimensionPixelSize(R.dimen.default_margin_small), ) ) } getPosterListAsync() } override fun onStart() { super.onStart() hideBottomNav() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun getPosterListAsync() { args.movie?.let { viewModel.getPosterList(it.id) } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collectLatest { Log.d("MovieDetailsFragment", "UI update: $it") binding.bannerList.adapter = PostersApadter( poster = it.poster ) when { it.isError -> showSnackBar(R.string.general_error) } } } } } private fun showSnackBar(@StringRes message: Int) { Snackbar.make(binding.root, message, Snackbar.LENGTH_SHORT).show() viewModel.userMessageShown() } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/details/MovieDetailsFragment.kt
397955408
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.details import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ru.bilchuk.kinobi.databinding.ListItemPosterBinding import ru.bilchuk.kinobi.domain.models.Poster internal class PostersApadter(private val poster: List<Poster>) : RecyclerView.Adapter<PostersApadter.PosterViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PosterViewHolder = PosterViewHolder( ListItemPosterBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: PosterViewHolder, position: Int) = holder.bindView(poster[position]) override fun getItemCount(): Int = poster.size internal class PosterViewHolder(private val binding: ListItemPosterBinding) : RecyclerView.ViewHolder(binding.root) { fun bindView(poster: Poster) { with(binding) { Glide .with(root.context) .load(poster.url) .into(imgPreview) } } } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/details/PostersApadter.kt
13533386
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.description 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 androidx.navigation.fragment.navArgs import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.FragmentDescriptionBinding import ru.bilchuk.kinobi.presentation.utils.format import ru.bilchuk.kinobi.presentation.utils.hideBottomNav class DescriptionFragment : Fragment() { private val args: DescriptionFragmentArgs by navArgs() private var _binding: FragmentDescriptionBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDescriptionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val description = args.description with(binding) { toolbar.apply { setNavigationIcon(R.drawable.ic_baseline_arrow_back_24) setNavigationOnClickListener { findNavController().navigateUp() } title = description?.toolbarTitle.orEmpty() } tvTitle.text = description?.title tvExtra.text = description?.extra tvSubtitle.text = description?.subtitle?.replaceFirstChar{ it.uppercase() }.orEmpty() tvDescription.text = description?.description } } override fun onStart() { super.onStart() hideBottomNav() } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/description/DescriptionFragment.kt
2371091145
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.description import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Description( val toolbarTitle: String, val title: String, val subtitle: String, val extra: String = "", val description: String, ) : Parcelable
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/description/Description.kt
3253370843
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.list import android.view.LayoutInflater import android.view.ViewGroup import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ru.bilchuk.kinobi.databinding.ListItemMovieBinding import ru.bilchuk.kinobi.domain.models.Movie internal class MoviesAdapter(private val movies: MutableList<Movie> = mutableListOf()) : RecyclerView.Adapter<MoviesAdapter.MovieViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder = MovieViewHolder( ListItemMovieBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: MovieViewHolder, position: Int) = holder.bindView(movies[position]) override fun getItemCount(): Int = movies.size fun addItems(items: List<Movie>) { val startPosition = movies.size movies.addAll(items) notifyItemRangeInserted(startPosition, items.size) } internal class MovieViewHolder(private val binding: ListItemMovieBinding) : RecyclerView.ViewHolder(binding.root) { fun bindView(movie: Movie) { with(binding) { tvTitle.text = movie.name tvGenre.text = movie.genre.replaceFirstChar { it.uppercase() } Glide .with(root.context) .load(movie.poster?.previewUrl) .into(imgPreview) itemCard.setOnClickListener { val direction = MovieListFragmentDirections.actionOpenMovie(movie) Navigation.findNavController(it).navigate(direction) } } } } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/list/MoviesAdapter.kt
3557191896
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.list import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import ru.bilchuk.kinobi.domain.interactors.KinoInteractor import ru.bilchuk.kinobi.domain.models.Movie import javax.inject.Inject class MovieListViewModel @Inject constructor( private val interactor: KinoInteractor ) : ViewModel() { private val _uiState = MutableStateFlow(MovieListUiState()) val uiState: StateFlow<MovieListUiState> = _uiState.asStateFlow() fun getMovieListFirstPage() { _uiState.update { it.copy( isLoading = true ) } viewModelScope.launch { try { val movies = interactor.getMovieList() _uiState.update { it.copy( movies = movies, moviesNextChunk = null, isLoading = false, pagesLoaded = 1, ) } } catch (e: Exception) { Log.d("MovieListViewModel", e.message.toString()) _uiState.update { it.copy( isError = true, isLoading = false, ) } } } } fun getMovieListNextPage() { viewModelScope.launch { try { val movies = interactor.getMovieList(_uiState.value.pagesLoaded + 1) _uiState.update { it.copy( movies = it.movies.toMutableList().apply{ addAll(movies) }, moviesNextChunk = movies, pagesLoaded = it.pagesLoaded + 1, isLoading = false, ) } } catch (e: Exception) { Log.d("MovieListViewModel", e.message.toString()) _uiState.update { it.copy( isError = true, isLoading = false, moviesNextChunk = null, ) } } } } fun userMessageShown() { _uiState.update { it.copy( isError = false ) } } data class MovieListUiState( val isError: Boolean = false, val isLoading: Boolean = false, val movies: List<Movie> = emptyList(), val moviesNextChunk: List<Movie>? = null, val pagesLoaded: Int = 0, ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/list/MovieListViewModel.kt
1332767005
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.list import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.FragmentMovieListBinding import ru.bilchuk.kinobi.presentation.KinobiApp import ru.bilchuk.kinobi.presentation.utils.MarginItemDecoration import ru.bilchuk.kinobi.presentation.utils.showBottomNav import javax.inject.Inject class MovieListFragment : Fragment() { @Inject lateinit var viewModel: MovieListViewModel private var _binding: FragmentMovieListBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.applicationContext as KinobiApp) .appComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMovieListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) showBottomNav() binding.rvMovieList.apply { addItemDecoration( MarginItemDecoration( spaceSize = resources.getDimensionPixelSize(R.dimen.default_margin), spanCount = resources.getInteger(R.integer.movies_list_span_count) ) ) addOnScrollListener(createOnScrollListener()) adapter = MoviesAdapter() } subscribe() viewModel.getMovieListFirstPage() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun subscribe() { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collectLatest { Log.d("MovieListFragment", "UI update: $it") when { it.isError -> showSnackBar(R.string.general_error) } if (it.pagesLoaded == 1) { binding.rvMovieList.adapter = MoviesAdapter(it.movies.toMutableList()) } else if (it.pagesLoaded > 1 && !it.moviesNextChunk.isNullOrEmpty()) { (binding.rvMovieList.adapter as MoviesAdapter).addItems(it.moviesNextChunk) } binding.progress.visibility = if (it.isLoading) View.VISIBLE else View.GONE } } } } private fun showSnackBar(@StringRes message: Int) { Snackbar.make(binding.root, message, Snackbar.LENGTH_SHORT).show() viewModel.userMessageShown() } private fun createOnScrollListener(): RecyclerView.OnScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0) { val visibleThreshold = 2 val layoutManager = (recyclerView.layoutManager as GridLayoutManager) val lastItem = layoutManager.findLastCompletelyVisibleItemPosition() val currentTotalCount = layoutManager.itemCount if (currentTotalCount <= lastItem + visibleThreshold) { viewModel.getMovieListNextPage() } } } } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/list/MovieListFragment.kt
4076898625
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.reviews import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import ru.bilchuk.kinobi.R import ru.bilchuk.kinobi.databinding.FragmentReviewListBinding import ru.bilchuk.kinobi.presentation.KinobiApp import ru.bilchuk.kinobi.presentation.movies.details.MovieDetailsFragmentArgs import ru.bilchuk.kinobi.presentation.utils.MarginItemDecoration import ru.bilchuk.kinobi.presentation.utils.hideBottomNav import javax.inject.Inject class ReviewListFragment : Fragment() { @Inject lateinit var viewModel: ReviewListViewModel private val args: MovieDetailsFragmentArgs by navArgs() private var _binding: FragmentReviewListBinding? = null private val binding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity?.applicationContext as KinobiApp) .appComponent.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentReviewListBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { toolbar.apply { setNavigationIcon(R.drawable.ic_baseline_arrow_back_24) setNavigationOnClickListener { findNavController().navigateUp() } } rvReviews.addItemDecoration( MarginItemDecoration( spaceSize = resources.getDimensionPixelSize(R.dimen.default_margin) ) ) } subscribe() args.movie?.let { viewModel.getReviewList(it.id) } } override fun onStart() { super.onStart() hideBottomNav() } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun subscribe() { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collectLatest { Log.d("ReviewListFragment", "UI update: $it") binding.rvReviews.adapter = ReviewsApadter(it.review) when { it.isError -> showSnackBar(R.string.general_error) } binding.progress.visibility = if (it.isLoading) View.VISIBLE else View.GONE } } } } private fun showSnackBar(@StringRes message: Int) { Snackbar.make(binding.root, message, Snackbar.LENGTH_SHORT).show() viewModel.userMessageShown() } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/reviews/ReviewListFragment.kt
4289814878
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.reviews import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import ru.bilchuk.kinobi.domain.interactors.KinoInteractor import ru.bilchuk.kinobi.domain.models.Review import javax.inject.Inject class ReviewListViewModel @Inject constructor( private val interactor: KinoInteractor ) : ViewModel() { private val _uiState = MutableStateFlow(ReviewListUiState()) val uiState: StateFlow<ReviewListUiState> = _uiState.asStateFlow() fun getReviewList(movieId: Int) { _uiState.update { it.copy( isLoading = true ) } viewModelScope.launch { try { val review = interactor.getReviewList(movieId) _uiState.update { it.copy( review = review, isLoading = false, ) } } catch (e: Exception) { Log.d("ReviewListViewModel", e.message.toString()) _uiState.update { it.copy( isError = true, isLoading = false, ) } } } } fun userMessageShown() { _uiState.update { it.copy( isError = false ) } } data class ReviewListUiState( val isError: Boolean = false, val isLoading: Boolean = false, val review: List<Review> = emptyList() ) }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/reviews/ReviewListViewModel.kt
3752382355
/* * Copyright (C) 2024. Jane Bilchuk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.bilchuk.kinobi.presentation.movies.reviews import android.text.format.DateFormat import android.view.LayoutInflater import android.view.ViewGroup import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import ru.bilchuk.kinobi.databinding.ListItemReviewBinding import ru.bilchuk.kinobi.domain.models.Review import ru.bilchuk.kinobi.presentation.movies.description.Description internal class ReviewsApadter(private val reviews: List<Review>) : RecyclerView.Adapter<ReviewsApadter.ReviewViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReviewViewHolder = ReviewViewHolder( ListItemReviewBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: ReviewViewHolder, position: Int) = holder.bindView(reviews[position]) override fun getItemCount(): Int = reviews.size internal class ReviewViewHolder(private val binding: ListItemReviewBinding) : RecyclerView.ViewHolder(binding.root) { fun bindView(review: Review) { with(binding) { tvTitle.text = review.title.orEmpty() val dateStr = if (review.date != null) { DateFormat.format("dd.MM.yyyy", review.date) } else { "" } tvDate.text = dateStr tvReview.text = review.review.orEmpty() tvAuthor.text = review.author.orEmpty() cardDescription.setOnClickListener { val direction = ReviewListFragmentDirections.actionOpenDescription( Description( toolbarTitle = "", title = review.title.orEmpty(), extra = dateStr.toString(), subtitle = review.author.orEmpty(), description = review.review.orEmpty(), ) ) Navigation.findNavController(it).navigate(direction) } } } } }
Kinobi/app/src/main/java/ru/bilchuk/kinobi/presentation/movies/reviews/ReviewsApadter.kt
3935158805
package com.example.carpicker 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.carpicker", appContext.packageName) } }
Car_Picker/app/src/androidTest/java/com/example/carpicker/ExampleInstrumentedTest.kt
3753385532
package com.example.carpicker 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) } }
Car_Picker/app/src/test/java/com/example/carpicker/ExampleUnitTest.kt
2006501168
package com.example.carpicker.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Car_Picker/app/src/main/java/com/example/carpicker/ui/theme/Color.kt
4083918554
package com.example.carpicker.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun CarPickerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Car_Picker/app/src/main/java/com/example/carpicker/ui/theme/Theme.kt
1103124126
package com.example.carpicker.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Car_Picker/app/src/main/java/com/example/carpicker/ui/theme/Type.kt
2013015702
package com.example.carpicker import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import com.example.carpicker.ui.theme.CarPickerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CarPickerTheme { CarPicker() } } } } @Preview(showSystemUi = true) @Composable fun CarPicker() { CarImageAndButton( Modifier .fillMaxSize() .wrapContentSize(align = Alignment.Center) ) } @Composable fun CarImageAndButton(modifier: Modifier = Modifier) { var result by remember { mutableStateOf(1) } val carImage = when (result) { 1 -> R.drawable.image1 2 -> R.drawable.image2 3 -> R.drawable.image3 4 -> R.drawable.image4 5 -> R.drawable.image5 6 -> R.drawable.image6 7 -> R.drawable.image7 8 -> R.drawable.image8 9 -> R.drawable.image9 10 -> R.drawable.image10 11 -> R.drawable.image11 12 -> R.drawable.image12 13 -> R.drawable.image13 else -> R.drawable.image1 } Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = carImage), contentDescription = null ) Button(onClick = { //mashina rasmi almashsin result++ if (result >13) { result = 1 } }) { Text(text = "Keyingi mashina") } } }
Car_Picker/app/src/main/java/com/example/carpicker/MainActivity.kt
817372234
class Student( val name: String, val id: Int, val grades: List<Int>) { fun avgGrade(): Double { if (grades.isEmpty()) { return 0.0 } return grades.sum() / grades.size.toDouble() } fun hasPassed(passingGrade: Int = 60): Boolean { return grades.all { it >= passingGrade } } } fun main(){ while (true){ print("Enter your name: ") val name = readln().capitalize() print("Enter your id: ") val userid = readln().toInt() print("How many subjects do you study? ") val n = readln().toInt() val grades = mutableListOf<Int>() for (i in 1..n) { print("Enter grade for subject $i: ") val grade = readln().toInt() grades.add(grade) } val student = Student(name, userid, grades) println("Average grade: ${student.avgGrade()}") println("Has passed all subjects: ${student.hasPassed()}") } }
StudentGradesSystemOOP/src/Main.kt
2909465985
package com.example.login 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.login", appContext.packageName) } }
AndroidStudioFTAM/app/src/androidTest/java/com/example/login/ExampleInstrumentedTest.kt
4292129466
package com.example.login 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) } }
AndroidStudioFTAM/app/src/test/java/com/example/login/ExampleUnitTest.kt
595896254
package com.example.login import android.content.Intent import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class ExerciseListActivity : AppCompatActivity() { private lateinit var exerciseAdapter: ExerciseAdapter private lateinit var recyclerView: RecyclerView private lateinit var dbHelper: DatabaseHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_exercise_list) dbHelper = DatabaseHelper(this) val exercisesList = dbHelper.getAllExercises() val btnDone = findViewById<TextView>(R.id.btnDone) recyclerView = findViewById(R.id.recyclerViewExerciseList) exerciseAdapter = ExerciseAdapter(exercisesList) recyclerView.apply { layoutManager = LinearLayoutManager(this@ExerciseListActivity) adapter = exerciseAdapter } btnDone.setOnClickListener { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() } } }
AndroidStudioFTAM/app/src/main/java/com/example/login/ExerciseListActivity.kt
1422458387
package com.example.login import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class ExerciseAdapter(private val exercises: List<Exercise>) : RecyclerView.Adapter<ExerciseAdapter.ExerciseDetailViewHolder>() { var expandedPosition = -1 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseDetailViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.activity_exercise_detail, parent, false) return ExerciseDetailViewHolder(view) } override fun onBindViewHolder(holder: ExerciseDetailViewHolder, position: Int) { val exercise = exercises[position] holder.textViewExerciseName.text = exercise.name holder.textViewMuscleGroup.text = exercise.targetMuscle if (exercise.isExpanded) { holder.textViewSets.setText(exercise.sets.toString()) holder.textViewReps.setText(exercise.reps.toString()) holder.expandDetails() } else { holder.collapseDetails() } if (position == expandedPosition) { holder.itemView.setBackgroundColor(Color.parseColor("#00FF00")) // Light green color } else { holder.itemView.setBackgroundColor(Color.WHITE) } holder.itemView.setOnClickListener { if (expandedPosition >= 0) { val prevExpandedPosition = expandedPosition exercises[prevExpandedPosition].isExpanded = false notifyItemChanged(prevExpandedPosition) } exercise.isExpanded = !exercise.isExpanded expandedPosition = if (exercise.isExpanded) position else -1 notifyItemChanged(position) } } override fun getItemCount(): Int = exercises.size inner class ExerciseDetailViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textViewExerciseName: TextView = itemView.findViewById(R.id.textViewExerciseName) val textViewMuscleGroup: TextView = itemView.findViewById(R.id.textViewTargetMuscle) val textViewSets: EditText = itemView.findViewById(R.id.editTextSets) val textViewReps: EditText = itemView.findViewById(R.id.editTextReps) private val btnAdd: Button = itemView.findViewById(R.id.btnAdd) fun expandDetails() { textViewSets.visibility = View.VISIBLE textViewReps.visibility = View.VISIBLE btnAdd.visibility = View.VISIBLE } fun collapseDetails() { textViewSets.visibility = View.GONE textViewReps.visibility = View.GONE btnAdd.visibility = View.GONE } } }
AndroidStudioFTAM/app/src/main/java/com/example/login/ExerciseAdapter.kt
3257979632
package com.example.login import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import androidx.appcompat.app.AppCompatActivity class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) } /* findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) } findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) } findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) } findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) } findViewById<Button>(R.id.btnMondayPlus).setOnClickListener { val intent = Intent(this, ExerciseListActivity::class.java) startActivity(intent) }*/ } }
AndroidStudioFTAM/app/src/main/java/com/example/login/HomeActivity.kt
865938411
package com.example.login data class Exercise(val id: Int, val name: String, val targetMuscle: String, var sets: Int = 0, var reps: Int = 0, var isExpanded: Boolean = false)
AndroidStudioFTAM/app/src/main/java/com/example/login/Exercise.kt
1315783157
package com.example.login import android.app.Activity import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.login.databinding.ActivityExerciseDetailBinding class ExerciseDetailActivity : AppCompatActivity() { private lateinit var binding: ActivityExerciseDetailBinding private lateinit var dbHelper: DatabaseHelper private lateinit var exerciseAdapter: ExerciseAdapter private var exerciseId: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityExerciseDetailBinding.inflate(layoutInflater) setContentView(binding.root) dbHelper = DatabaseHelper(this) // Fetching the list of exercises from the database val exercisesList: List<Exercise> = dbHelper.getAllExercises() exerciseAdapter = ExerciseAdapter(exercisesList) exerciseId = intent.getIntExtra("EXERCISE_ID", 0) val exercise = dbHelper.getExerciseById(exerciseId) if (exercise != null) { binding.textViewExerciseName.text = exercise.name binding.textViewTargetMuscle.text = exercise.targetMuscle } binding.btnAdd.setOnClickListener { val sets = binding.editTextSets.text.toString().toIntOrNull() ?: 0 val reps = binding.editTextReps.text.toString().toIntOrNull() ?: 0 if (dbHelper.addExerciseDetail(exerciseId, sets, reps)) { val updatedExercise = dbHelper.getExerciseById(exerciseId) updatedExercise?.let { val position = exercisesList.indexOf(it) if (position != -1) { exerciseAdapter.expandedPosition = position exerciseAdapter.notifyDataSetChanged() } } Toast.makeText(this, "Exercise added successfully!", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Failed to add exercise.", Toast.LENGTH_SHORT).show() } setResult(Activity.RESULT_OK) finish() } } }
AndroidStudioFTAM/app/src/main/java/com/example/login/ExerciseDetailActivity.kt
3046651505
package com.example.login data class PastExercises(val name: String, val muscleGroup: String, val date: String, val day: String, val weekNumber: Int)
AndroidStudioFTAM/app/src/main/java/com/example/login/PastExercises.kt
69397841
package com.example.login import android.annotation.SuppressLint import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { private const val DATABASE_VERSION = 4 private const val DATABASE_NAME = "fitnessTracker.db" private const val TABLE_USERS = "userLoginInfo" private const val TABLE_PROFILE = "userProfile" private const val TABLE_EXERCISE = "pastExercises" private const val TABLE_EXERCISE_DETAILS = "exerciseDetails" private const val TABLE_ALL_EXERCISES = "allExercises" private const val COLUMN_ID = "id" private const val COLUMN_USERNAME = "username" private const val COLUMN_PASSWORD = "password" private const val COLUMN_WEIGHT = "weight" private const val COLUMN_HEIGHT = "height" private const val COLUMN_AGE = "age" private const val COLUMN_NAME = "name" private const val COLUMN_CATEGORY = "category" private const val COLUMN_DATE = "date" private const val COLUMN_DAY_OF_WEEK = "day" private const val COLUMN_WEEK_NUMBER = "week" private const val COLUMN_EXERCISE_NAME = "exerciseName" private const val COLUMN_TARGET_MUSCLE = "targetMuscle" private const val COLUMN_EXERCISE_ID = "exerciseID" private const val COLUMN_SETS = "sets" private const val COLUMN_REPS = "reps" } override fun onCreate(db: SQLiteDatabase?) { val createUserTableQuery = ("CREATE TABLE $TABLE_USERS " + "($COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "$COLUMN_USERNAME TEXT, $COLUMN_PASSWORD TEXT)") db?.execSQL(createUserTableQuery) val createUserInfoTableQuery = ("CREATE TABLE $TABLE_PROFILE " + "($COLUMN_USERNAME TEXT PRIMARY KEY, " + "$COLUMN_WEIGHT REAL, $COLUMN_HEIGHT REAL, $COLUMN_AGE INTEGER)") db?.execSQL(createUserInfoTableQuery) val createExerciseTableQuery = ("CREATE TABLE $TABLE_EXERCISE " + "($COLUMN_ID INTEGER PRIMARY KEY, " + "$COLUMN_NAME TEXT, " + "$COLUMN_CATEGORY TEXT, " + "$COLUMN_DATE TEXT) ") db?.execSQL(createExerciseTableQuery) val createWorkoutTableQuery = ("CREATE TABLE $TABLE_EXERCISE_DETAILS " + "($COLUMN_EXERCISE_ID INTEGER PRIMARY KEY, " + "$COLUMN_SETS INTEGER, " + "$COLUMN_REPS INTEGER)") val createAllExercisesTableQuery = ("CREATE TABLE $TABLE_ALL_EXERCISES " + "($COLUMN_EXERCISE_ID INTEGER PRIMARY KEY, " + "$COLUMN_EXERCISE_NAME TEXT, " + "$COLUMN_TARGET_MUSCLE TEXT)") try { db?.execSQL(createWorkoutTableQuery) db?.execSQL(createAllExercisesTableQuery) } catch (e: Exception) { Log.e("DatabaseHelper", "Error creating tables: ${e.message}") } db?.let { populateExercises(it) } } private fun populateExercises(db: SQLiteDatabase) { val exercises = listOf( Exercise(1, "Push-up", "Chest"), Exercise(2, "Squats", "Legs"), Exercise(3, "Bench Press", "Chest"), Exercise(4, "Incline Dumbbell Press", "Chest"), Exercise(5, "Lat Pull Downs", "Back") ) for (exercise in exercises) { val contentValues = ContentValues().apply { put("exerciseID", exercise.id) put("exerciseName", exercise.name) put("targetMuscle", exercise.targetMuscle) } db.insert(TABLE_ALL_EXERCISES, null, contentValues) } } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { db?.execSQL("DROP TABLE IF EXISTS $TABLE_USERS") db?.execSQL("DROP TABLE IF EXISTS $TABLE_PROFILE") db?.execSQL("DROP TABLE IF EXISTS $TABLE_EXERCISE") db?.execSQL("DROP TABLE IF EXISTS $TABLE_EXERCISE_DETAILS") db?.execSQL("DROP TABLE IF EXISTS $TABLE_ALL_EXERCISES") onCreate(db) } fun addUser(username: String, password: String): Boolean { val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(COLUMN_USERNAME, username) contentValues.put(COLUMN_PASSWORD, password) return try { val result = db.insertWithOnConflict(TABLE_USERS, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE) return result != -1L } catch (e: Exception) { Log.e("DatabaseHelper", "Error adding user: ${e.message}") false } /*finally { db.close() }*/ } fun addProfile(username: String, weight: Double, height: Double, age: Int): Boolean { val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(COLUMN_USERNAME, username) contentValues.put(COLUMN_WEIGHT, weight) contentValues.put(COLUMN_HEIGHT, height) contentValues.put(COLUMN_AGE, age) return try { val result = db.insertWithOnConflict(TABLE_PROFILE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE) return result != -1L } catch (e: Exception) { Log.e("DatabaseHelper", "Error adding profile: ${e.message}") false } /*finally { db.close() }*/ } fun addExercise(username: String, exercise: PastExercises) { val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(COLUMN_USERNAME, username) contentValues.put(COLUMN_EXERCISE_NAME, exercise.name) contentValues.put(COLUMN_DATE, exercise.date) contentValues.put(COLUMN_WEEK_NUMBER, exercise.weekNumber) contentValues.put(COLUMN_DAY_OF_WEEK, exercise.day) db.insert(TABLE_EXERCISE, null, contentValues) /*db.close()*/ } @SuppressLint("Range") fun getExerciseById(exerciseId: Int): Exercise? { val db = this.readableDatabase var exercise: Exercise? = null val query = "SELECT * FROM $TABLE_EXERCISE WHERE $COLUMN_ID = ?" val cursor = db.rawQuery(query, arrayOf(exerciseId.toString())) if (cursor.moveToFirst()) { val id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)) val name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)) val targetMuscle = cursor.getString(cursor.getColumnIndex(COLUMN_TARGET_MUSCLE)) exercise = Exercise(id, name, targetMuscle) } cursor.close() return exercise } fun addExerciseDetail(exerciseId: Int, sets: Int, reps: Int): Boolean { val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(COLUMN_EXERCISE_ID, exerciseId) contentValues.put(COLUMN_SETS, sets) contentValues.put(COLUMN_REPS, reps) val result = db.insert(TABLE_EXERCISE_DETAILS, null, contentValues) return result != -1L } @SuppressLint("Range") fun getAllExercises(): List<Exercise> { val exercises = mutableListOf<Exercise>() val db = this.readableDatabase val cursor = db.rawQuery("SELECT * FROM $TABLE_ALL_EXERCISES", null) while (cursor.moveToNext()) { val exercise = Exercise( cursor.getInt(cursor.getColumnIndex("exerciseID")), cursor.getString(cursor.getColumnIndex("exerciseName")), cursor.getString(cursor.getColumnIndex("targetMuscle")), ) exercises.add(exercise) } cursor.close() return exercises } }
AndroidStudioFTAM/app/src/main/java/com/example/login/DatabaseHelper.kt
3817952970
package com.example.login import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.ImageButton import android.widget.Toast class WeightActivity : AppCompatActivity() { private lateinit var dbHelper: DatabaseHelper private lateinit var username: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_weight) dbHelper = DatabaseHelper(this) username = intent.getStringExtra("USERNAME") ?: "" val btnSubmit = findViewById<Button>(R.id.btnSubmit) val editTextWeight = findViewById<EditText>(R.id.editTextWeight) val editTextHeight = findViewById<EditText>(R.id.editTextHeight) val editTextAge = findViewById<EditText>(R.id.editTextAge) btnSubmit.setOnClickListener { val weight = editTextWeight.text.toString().toDoubleOrNull() ?: 0.0 val height = editTextHeight.text.toString().toDoubleOrNull() ?: 0.0 val age = editTextAge.text.toString().toIntOrNull() ?: 0 if (dbHelper.addProfile(username, weight, height, age)) { Toast.makeText(this, "Information saved successfully!", Toast.LENGTH_SHORT).show() val intent = Intent(this, HomeActivity::class.java) startActivity(intent) finish() } else { Toast.makeText(this, "Failed to save information. Please try again.", Toast.LENGTH_SHORT).show() } } } }
AndroidStudioFTAM/app/src/main/java/com/example/login/WeightActivity.kt
1973033055
package com.example.login import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast class LoginActivity : AppCompatActivity() { private lateinit var dbHelper: DatabaseHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) dbHelper = DatabaseHelper(this) val editTextUsername = findViewById<EditText>(R.id.editTextUsername) val editTextPassword = findViewById<EditText>(R.id.editTextPassword) val btnLogin = findViewById<Button>(R.id.btnLogin) val textViewCreateAccount = findViewById<TextView>(R.id.textViewCreateAccount) btnLogin.setOnClickListener { val username = editTextUsername.text.toString() val password = editTextPassword.text.toString() if (isValidCredentials(username, password)) { Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show() val intent = Intent(this, HomeActivity::class.java) startActivity(intent) } else { Toast.makeText(this, "Invalid credentials. Please try again.", Toast.LENGTH_SHORT).show() } } textViewCreateAccount.setOnClickListener { val intent = Intent(this, RegistrationActivity::class.java) startActivity(intent) } } private fun isValidCredentials(username: String, password: String): Boolean { val db = dbHelper.readableDatabase val cursor = db.rawQuery("SELECT * FROM userLoginInfo WHERE username = ? AND password = ?", arrayOf(username, password)) val result = cursor.count > 0 cursor.close() return result } }
AndroidStudioFTAM/app/src/main/java/com/example/login/LoginActivity.kt
3986299002
package com.example.login import android.content.Intent import android.os.Bundle import android.provider.ContactsContract.Data import androidx.appcompat.app.AppCompatActivity import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast class RegistrationActivity : AppCompatActivity() { private lateinit var dbHelper: DatabaseHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registration) dbHelper = DatabaseHelper(this) val editTextNewUsername = findViewById<EditText>(R.id.editTextNewUsername) val editTextNewPassword = findViewById<EditText>(R.id.editTextNewPassword) val btnRegister = findViewById<Button>(R.id.btnRegister) val textViewSignIn = findViewById<TextView>(R.id.textViewSignIn) btnRegister.setOnClickListener { val newUsername = editTextNewUsername.text.toString() val newPassword = editTextNewPassword.text.toString() if (isValidRegistration(newUsername, newPassword)) { if (dbHelper.addUser(newUsername, newPassword)){ // Registration successful Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show() val intent = Intent(this, WeightActivity::class.java) intent.putExtra("USERNAME", newUsername) startActivity(intent) finish() } else { Toast.makeText(this, "Failed to register. Please try again.", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Invalid registration. Please try again.", Toast.LENGTH_SHORT).show() } } textViewSignIn.setOnClickListener { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } } private fun isValidRegistration(newUsername: String, newPassword: String): Boolean { return newUsername.isNotEmpty() && newPassword.isNotEmpty() } }
AndroidStudioFTAM/app/src/main/java/com/example/login/RegistrationActivity.kt
2450083286
import formatter.FormatFromSeparatedFiles object Menu { operator fun invoke() { greeting() val option = readlnOrNull() when (option) { "1" -> FormatFromSeparatedFiles.format() "2" -> Unit //todo: make format xml later "q", "Q" -> println("Bye~") } } private fun greeting(){ println("String resources formatter!") println("1. Format from separate file string and key") println("2. Format from xml file") println("Q. Exit") } }
auto-gen-string-resources-android/src/main/kotlin/Menu.kt
1094860298
package utils object FormatTextUtils { fun formatTextStringResourcesAndroid( key: String, text: String, translatable: Boolean = true ) = "<string name=\"$key\"${if (translatable) "" else " translatable=\"false\""}>$text</string>" }
auto-gen-string-resources-android/src/main/kotlin/utils/FormatTextUtils.kt
2886397796
package utils import java.io.File object FileUtils { fun createFile(filePath: String, content: String) { val file = File(filePath) if (!file.parentFile.exists()) { file.parentFile.mkdirs() } if (file.exists()) { file.delete() } file.writeText(content) } }
auto-gen-string-resources-android/src/main/kotlin/utils/FileUtils.kt
2083250507
fun main() { Menu() }
auto-gen-string-resources-android/src/main/kotlin/Main.kt
3330594429
package formatter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.launch import utils.FileUtils import utils.FormatTextUtils import java.io.File object FormatFromSeparatedFiles { fun format() = runBlocking { val keysFile = File("./separatedFilesOption/keys.txt") val stringsViFile = File("./separatedFilesOption/languages/vi.txt") val stringsEnFile = File("./separatedFilesOption/languages/en.txt") launch { format("./separatedFilesOption/output/value-vi/string.xml", keysFile, stringsViFile) } launch { format("./separatedFilesOption/output/value/string.xml", keysFile, stringsEnFile) } } private suspend fun format( fileName: String, keysFile: File, stringsFile: File ) = withContext(Dispatchers.IO) { val keysRunner = async { keysFile.readLines() } val textsRunner = async { stringsFile.readLines() } val keys = keysRunner.await() val texts = textsRunner.await() if (keys.size == texts.size) { val listStringResources = List(keys.size) { index -> FormatTextUtils.formatTextStringResourcesAndroid( key = keys[index], text = texts[index], translatable = true ) } val stringResources = listStringResources.joinToString( prefix = "<resources>\n\t", separator = "\n\t", postfix = "\n</resources>" ) FileUtils.createFile(fileName, stringResources) } else { error("key and texts are not have the same size") } } }
auto-gen-string-resources-android/src/main/kotlin/formatter/FormatFromSeparatedFiles.kt
1553280953
package com.learn.kotlin_fundamental 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.learn.kotlin_fundamental", appContext.packageName) } }
Kotlin-fundamental/app/src/androidTest/java/com/learn/kotlin_fundamental/ExampleInstrumentedTest.kt
4140746611
package com.learn.kotlin_fundamental import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Kotlin-fundamental/app/src/test/java/com/learn/kotlin_fundamental/ExampleUnitTest.kt
2837587935
package com.learn.kotlin_fundamental.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Kotlin-fundamental/app/src/main/java/com/learn/kotlin_fundamental/ui/theme/Color.kt
2620867607
package com.learn.kotlin_fundamental.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun Kotlin_fundamentalTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Kotlin-fundamental/app/src/main/java/com/learn/kotlin_fundamental/ui/theme/Theme.kt
1043050550
package com.learn.kotlin_fundamental.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Kotlin-fundamental/app/src/main/java/com/learn/kotlin_fundamental/ui/theme/Type.kt
268420509
package com.learn.kotlin_fundamental fun main(){ println("I am ashish , what about you?") // Immutable-List example val colleagueNames = listOf("Ashish","Sanjay","Amrita") println("Immutable list example : $colleagueNames") // Mutable-List example val mutableList = mutableListOf("Ashish","Sanjay","Amrita") mutableList.add("Sameer") mutableList.removeAt(0) println("Mutable list example : $mutableList") }
Kotlin-fundamental/app/src/main/java/com/learn/kotlin_fundamental/MainActivity.kt
4227279060
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(50.dp), )
animationSimple/app/src/main/java/com/example/woof/ui/theme/Shape.kt
1993904518
package com.example.compose import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF6750A4) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFE9DDFF) val md_theme_light_onPrimaryContainer = Color(0xFF22005D) val md_theme_light_secondary = Color(0xFF625B71) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFE8DEF8) val md_theme_light_onSecondaryContainer = Color(0xFF1E192B) val md_theme_light_tertiary = Color(0xFF7E5260) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD9E3) val md_theme_light_onTertiaryContainer = Color(0xFF31101D) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF1C1B1E) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF1C1B1E) val md_theme_light_surfaceVariant = Color(0xFFE7E0EB) val md_theme_light_onSurfaceVariant = Color(0xFF49454E) val md_theme_light_outline = Color(0xFF7A757F) val md_theme_light_inverseOnSurface = Color(0xFFF4EFF4) val md_theme_light_inverseSurface = Color(0xFF313033) val md_theme_light_inversePrimary = Color(0xFFCFBCFF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF6750A4) val md_theme_light_outlineVariant = Color(0xFFCAC4CF) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFCFBCFF) val md_theme_dark_onPrimary = Color(0xFF381E72) val md_theme_dark_primaryContainer = Color(0xFF4F378A) val md_theme_dark_onPrimaryContainer = Color(0xFFE9DDFF) val md_theme_dark_secondary = Color(0xFFCBC2DB) val md_theme_dark_onSecondary = Color(0xFF332D41) val md_theme_dark_secondaryContainer = Color(0xFF4A4458) val md_theme_dark_onSecondaryContainer = Color(0xFFE8DEF8) val md_theme_dark_tertiary = Color(0xFFEFB8C8) val md_theme_dark_onTertiary = Color(0xFF4A2532) val md_theme_dark_tertiaryContainer = Color(0xFF633B48) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD9E3) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1C1B1E) val md_theme_dark_onBackground = Color(0xFFE6E1E6) val md_theme_dark_surface = Color(0xFF1C1B1E) val md_theme_dark_onSurface = Color(0xFFE6E1E6) val md_theme_dark_surfaceVariant = Color(0xFF49454E) val md_theme_dark_onSurfaceVariant = Color(0xFFCAC4CF) val md_theme_dark_outline = Color(0xFF948F99) val md_theme_dark_inverseOnSurface = Color(0xFF1C1B1E) val md_theme_dark_inverseSurface = Color(0xFFE6E1E6) val md_theme_dark_inversePrimary = Color(0xFF6750A4) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFCFBCFF) val md_theme_dark_outlineVariant = Color(0xFF49454E) val md_theme_dark_scrim = Color(0xFF000000) val seed = Color(0xFF6750A4) val CustomColor1 = Color(0xFFDFE1FF) val light_CustomColor1 = Color(0xFF4A58A9) val light_onCustomColor1 = Color(0xFFFFFFFF) val light_CustomColor1Container = Color(0xFFDEE0FF) val light_onCustomColor1Container = Color(0xFF000F5C) val dark_CustomColor1 = Color(0xFFBBC3FF) val dark_onCustomColor1 = Color(0xFF172778) val dark_CustomColor1Container = Color(0xFF313F90) val dark_onCustomColor1Container = Color(0xFFDEE0FF)
animationSimple/app/src/main/java/com/example/woof/ui/theme/Color.kt
3736594220
package com.example.compose import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Shapes import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat import com.example.woof.ui.theme.Shapes import com.example.woof.ui.theme.Typography private val LightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) private val DarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun WoofTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = false, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColors else -> LightColors } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, shapes = Shapes, typography = Typography, content = content ) }
animationSimple/app/src/main/java/com/example/woof/ui/theme/Theme.kt
1038307159
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof.ui.theme import androidx.compose.material3.Typography // Set of Material typography styles to start with val Typography = Typography( )
animationSimple/app/src/main/java/com/example/woof/ui/theme/Type.kt
1486627747
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.animateColorAsState import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.compose.WoofTheme import com.example.woof.data.Dog import com.example.woof.data.dogs class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WoofTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize() ) { WoofApp() } } } } } /** * Composable that displays an app bar and a list of dogs. */ @Composable fun WoofApp() { LazyColumn { items(dogs) { DogItem(dog = it) } } } /** * Composable that displays a list item containing a dog icon and their information. * * @param dog contains the data that populates the list item * @param modifier modifiers to set to this composable */ @Composable fun DogItem( dog: Dog, modifier: Modifier = Modifier ) { var expanded by remember { mutableStateOf(false) } val color by animateColorAsState(targetValue = if (expanded) MaterialTheme.colorScheme.tertiaryContainer else MaterialTheme.colorScheme.primaryContainer,) Card( modifier = modifier .clickable { expanded = !expanded } .padding(8.dp) .background(color = color) ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { DogInformation(dogName = dog.name, dogAge = dog.age ) DogIcon(dogIcon = dog.imageResourceId) // Show details only when expanded is true if (expanded) { Spacer(modifier = Modifier.height(8.dp)) DogHobby(dogHobby = dog.hobbies) } } } } @Composable private fun DogItemButton( expanded: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton( onClick = onClick, modifier = modifier ) { Icon( imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = stringResource(R.string.expand_button_content_description), tint = MaterialTheme.colorScheme.secondary ) } } /** * Composable that displays a photo of a dog. * * @param dogIcon is the resource ID for the image of the dog * @param modifier modifiers to set to this composable */ @Composable fun DogIcon( @DrawableRes dogIcon: Int, modifier: Modifier = Modifier ) { Image( modifier = modifier .fillMaxWidth() .fillMaxHeight() .padding(dimensionResource(R.dimen.padding_small)), painter = painterResource(dogIcon), // Content Description is not needed here - image is decorative, and setting a null content // description allows accessibility services to skip this element during navigation. contentDescription = null ) } @Composable fun DogHobby( @StringRes dogHobby: Int, modifier: Modifier = Modifier ) { Column( modifier = modifier ) { Text( text = stringResource(dogHobby), style = MaterialTheme.typography.bodyLarge ) } } /** * Composable that displays a dog's name and age. * * @param dogName is the resource ID for the string of the dog's name * @param dogAge is the Int that represents the dog's age * @param modifier modifiers to set to this composable */ @Composable fun DogInformation( @StringRes dogName: Int, dogAge: Int, modifier: Modifier = Modifier ) { Column(modifier = modifier) { Text( text = stringResource(dogName), modifier = Modifier.padding(top = dimensionResource(R.dimen.padding_small)) ) Text( text = stringResource(R.string.years_old, dogAge), ) } } /** * Composable that displays what the UI of the app looks like in light theme in the design tab. */ @Preview @Composable fun WoofPreview() { WoofTheme() { WoofApp() } }
animationSimple/app/src/main/java/com/example/woof/MainActivity.kt
1773350782
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.woof.data import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.example.woof.R /** * A data class to represent the information presented in the dog card */ data class Dog( @DrawableRes val imageResourceId: Int, @StringRes val name: Int, val age: Int, @StringRes val hobbies: Int ) val dogs = listOf( Dog(R.drawable.koda, R.string.dog_name_1, 2, R.string.dog_description_1), Dog(R.drawable.lola, R.string.dog_name_2, 16, R.string.dog_description_2), Dog(R.drawable.frankie, R.string.dog_name_3, 2, R.string.dog_description_3), Dog(R.drawable.nox, R.string.dog_name_4, 8, R.string.dog_description_4), Dog(R.drawable.faye, R.string.dog_name_5, 8, R.string.dog_description_5), Dog(R.drawable.bella, R.string.dog_name_6, 14, R.string.dog_description_6), Dog(R.drawable.moana, R.string.dog_name_7, 2, R.string.dog_description_7), Dog(R.drawable.tzeitel, R.string.dog_name_8, 7, R.string.dog_description_8), Dog(R.drawable.leroy, R.string.dog_name_9, 4, R.string.dog_description_9) )
animationSimple/app/src/main/java/com/example/woof/data/Dog.kt
762462049
package com.valbac.calendarinertia 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.valbac.calendarinertia", appContext.packageName) } }
CalendarInertia/app/src/androidTest/java/com/valbac/calendarinertia/ExampleInstrumentedTest.kt
2884920150
package com.valbac.calendarinertia 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) } }
CalendarInertia/app/src/test/java/com/valbac/calendarinertia/ExampleUnitTest.kt
3903375950
package com.valbac.calendarinertia.feature_calendar.data.repository import com.valbac.calendarinertia.feature_calendar.data.remote.PublicHolidayApi import com.valbac.calendarinertia.feature_calendar.data.remote.dto.NextPublicHolidaysDto import com.valbac.calendarinertia.feature_calendar.domain.repository.PublicHolidaysRepository import javax.inject.Inject class PublicHolidaysRepositoryImpl @Inject constructor( private val api: PublicHolidayApi ): PublicHolidaysRepository{ override suspend fun getPublicHolidaysInfo(countryCode: String): List<NextPublicHolidaysDto> { return api.getPublicHolidaysInfo(countryCode) } }
CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/repository/PublicHolidaysRepositoryImpl.kt
1744853491
package com.valbac.calendarinertia.feature_calendar.data.repository import com.valbac.calendarinertia.feature_calendar.data.local.TaskDao import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity import com.valbac.calendarinertia.feature_calendar.domain.repository.TaskRepository import kotlinx.coroutines.flow.Flow class TaskRepositoryImpl( private val dao: TaskDao ): TaskRepository { override suspend fun upsertTask(taskEntity: TaskEntity) { return dao.upsertTask(taskEntity) } override suspend fun deleteTask(taskEntity: TaskEntity) { return dao.deleteTask(taskEntity) } override fun getTasks(): Flow<List<TaskEntity>> { return dao.getTasks() } override suspend fun getTaskById(id: Int): TaskEntity? { return dao.getTaskById(id) } }
CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/repository/TaskRepositoryImpl.kt
183704373
package com.valbac.calendarinertia.feature_calendar.data import android.annotation.SuppressLint import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import com.valbac.calendarinertia.core.AlarmItem import com.valbac.calendarinertia.core.AlarmReceiver import com.valbac.calendarinertia.core.AlarmScheduler import java.time.ZoneId class AlarmSchedulerImpl( private val context: Context ): AlarmScheduler { private val alarmManager = context.getSystemService(AlarmManager::class.java) @SuppressLint("MissingPermission") override fun schedule(item: AlarmItem) { val intent = Intent(context, AlarmReceiver::class.java).apply { putExtra("EXTRA_MESSAGE", item.message) } alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, item.time.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000, PendingIntent.getBroadcast( context, item.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) } override fun cancel(item: AlarmItem) { alarmManager.cancel( PendingIntent.getBroadcast( context, item.hashCode(), Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) } }
CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/AlarmSchedulerImpl.kt
1580356883
package com.valbac.calendarinertia.feature_calendar.data.local import androidx.room.Database import androidx.room.RoomDatabase import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity @Database( entities = [TaskEntity::class], version = 1, exportSchema = false ) abstract class TheDatabase : RoomDatabase() { abstract val taskDao: TaskDao companion object{ const val DATABASE_NAME = "calendar_db" } }
CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/local/TheDatabase.kt
1256445562
package com.valbac.calendarinertia.feature_calendar.data.local import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert import com.valbac.calendarinertia.feature_calendar.domain.model.TaskEntity import kotlinx.coroutines.flow.Flow @Dao interface TaskDao { @Upsert suspend fun upsertTask(taskEntity: TaskEntity) @Delete suspend fun deleteTask(taskEntity: TaskEntity) @Query("SELECT * FROM TaskEntity") fun getTasks(): Flow<List<TaskEntity>> @Query("SELECT * FROM TaskEntity WHERE id = :id") suspend fun getTaskById(id: Int): TaskEntity? }
CalendarInertia/app/src/main/java/com/valbac/calendarinertia/feature_calendar/data/local/TaskDao.kt
3230329521