content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.catans.viewmodel import com.example.catans.base.BaseViewModel class CurrencyViewModel: BaseViewModel() {}
CatAns/app/src/main/java/com/example/catans/viewmodel/CurrencyViewModel.kt
764886594
package com.example.catans import android.os.Bundle import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.res.ResourcesCompat import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.example.catans.databinding.ActivityMainBinding import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.bottomnavigation.BottomNavigationView class MainActivity : AppCompatActivity() { private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration private var mExitTime: Long = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) navController = findNavController(R.id.nav_host_fragment_content_main) val appBarConfiguration = AppBarConfiguration( setOf( R.id.contentFragment, R.id.currencyFragment) ) setupActionBarWithNavController(navController, appBarConfiguration) binding.contentMain.bottomNavigationView.setupWithNavController(navController) } // override fun onCreateOptionsMenu(menu: Menu): Boolean { // menuInflater.inflate(R.menu.menu_main, menu) // return true // } // // override fun onOptionsItemSelected(item: MenuItem): Boolean { // navController.navigate(R.id.action_ContentFragment_to_SecondFragment) // return when (item.itemId) { // R.id.action_settings -> true // else -> super.onOptionsItemSelected(item) // } // } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { if ((System.currentTimeMillis() - mExitTime) > 2000) { Toast.makeText(this, "再按一次退出App", Toast.LENGTH_SHORT).show() mExitTime = System.currentTimeMillis() } else { finish() } } return true } }
CatAns/app/src/main/java/com/example/catans/MainActivity.kt
1356578705
package com.example.catans.util enum class EnumUtils { Departure, Inbound, Currency, } enum class EnumCurrencyUtils { AUD, CNY, EUR, HKD, JPY, USD, }
CatAns/app/src/main/java/com/example/catans/util/EnumUtils.kt
3477158075
package com.example.catans.util import android.app.Activity import android.content.Context import android.util.DisplayMetrics import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import org.mariuszgromada.math.mxparser.Expression import kotlin.math.roundToInt class Utils { companion object { const val URI_BASE_CURRENCY = "&base_currency=" const val URI_API_KEY = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB" const val URL_CURRENCY = "https://api.freecurrencyapi.com/v1/" const val URI_CURRENCY_AUD = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=AUD" const val URI_CURRENCY_CNY = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=CNY" const val URI_CURRENCY_EUR = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=EUR" const val URI_CURRENCY_HKD = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=HKD" const val URI_CURRENCY_JPY = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=JPY" const val URI_CURRENCY_USD = "latest?apikey=fca_live_u8YybRyp0D3N7bhJg9oynaaTJitTuzMlW9qhaphB&base_currency=USD" const val data = "data" const val AUD = "AUD" const val BGN = "BGN" const val BRL = "BRL" const val CAD = "CAD" const val CHF = "CHF" const val CNY = "CNY" const val DKK = "DKK" const val CZK = "CZK" const val EUR = "EUR" const val GBP = "GBP" const val HKD = "HKD" const val HRK = "HRK" const val HUF = "HUF" const val IDR = "IDR" const val ILS = "ILS" const val INR = "INR" const val ISK = "ISK" const val JPY = "JPY" const val KRW = "KRW" const val MXN = "MXN" const val MYR = "MYR" const val NOK = "NOK" const val NZD = "NZD" const val PHP = "PHP" const val PLN = "PLN" const val RON = "RON" const val RUB = "RUB" const val SEK = "SEK" const val SGD = "SGD" const val THB = "THB" const val TRY = "TRY" const val USD = "USD" const val ZAR = "ZAR" const val code = "code" const val money = "money" const val URI_AIRPORT_DEPARTURE = "AirPortFlyAPI/D/TPE" const val URI_AIRPORT_INBOUND = "AirPortFlyAPI/A/TPE" const val URL_AIRPORT = "https://e-traffic.taichung.gov.tw/DataAPI/api/" const val FlyType = "FlyType" const val AirlineID = "AirlineID" const val Airline = "Airline" const val FlightNumber = "FlightNumber" const val DepartureAirportID = "DepartureAirportID" const val DepartureAirport = "DepartureAirport" const val ArrivalAirportID = "ArrivalAirportID" const val ArrivalAirport = "ArrivalAirport" const val ScheduleTime = "ScheduleTime" const val ActualTime = "ActualTime" const val EstimatedTime = "EstimatedTime" const val Remark = "Remark" const val Terminal = "Terminal" const val Gate = "Gate" const val UpdateTime = "UpdateTime" const val TIME_REPEAT: Long = 10000 fun dpToPixel(context: Context, dp: Int): Int { val displayMetrics: DisplayMetrics = context.resources.displayMetrics return if (dp < 0) dp else (dp * displayMetrics.density).roundToInt() } fun pixelToDp(context: Context, pixel: Int): Int { val displayMetrics: DisplayMetrics = context.resources.displayMetrics return if (pixel < 0) pixel else (pixel * displayMetrics.density).roundToInt() } // fun closeKeyboard(activity: Activity) { // val view = activity.window?.peekDecorView(); // if (view != null) { // closeKeyboard(activity, view) // } // } // // fun closeKeyboard(view: View?) { // if (view != null) { // closeKeyboard(view.activity, view) // } // } fun closeKeyboard(activity: Activity?, view: View) { if (activity != null) { val inputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? if (inputMethodManager != null && view.windowToken != null) { inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } } } fun regSymbol(text: String, symbol: String): Boolean { val match1 = text.indexOf(symbol) == text.length - 1 val regex = Regex("[%x/)(+.-]") val match2 = regex.containsMatchIn(text) return match1 || match2 } private fun regOperator(text: String): Boolean = Regex("[+x/-]").containsMatchIn(text) fun regCalculatorPrevious(text: String): Boolean = Regex("[+x/-]").containsMatchIn(text[text.length - 1].toString()) fun regCalculatorNext(text: String, index: Int): Boolean = Regex("[+x/-]").containsMatchIn(text[index].toString()) fun regNumberPreviousZero(text: String): Boolean { if (text.isNotEmpty()) { return Regex("0").containsMatchIn(text[text.length - 1].toString()) } return false } fun regNumberPreviousBackBracket(text: String): Boolean { if (text.isNotEmpty()) { return Regex("[0-9)]").containsMatchIn(text[text.length - 1].toString()) } return false } fun regNumberPrevious(text: String): Boolean = Regex("[0-9]").containsMatchIn(text[text.length - 1].toString()) fun regBracketPrevious(text: String): Boolean = Regex("[)(]").containsMatchIn(text[text.length - 1].toString()) fun regNumberNext(text: String, index: Int): Boolean = Regex("[0-9]").containsMatchIn(text[index].toString()) fun regBracketOpenNext(text: String, index: Int): Boolean = Regex("[(]").containsMatchIn(text[index].toString()) fun regBracketBackNext(text: String, index: Int): Boolean = Regex("[)]").containsMatchIn(text[index].toString()) private fun regOperatorBetweenBracket(text: String): List<Int> { val list = arrayListOf<Int>() for (i in text.indices) { if (text.length >= 5 && regOperator(text[i].toString()) && text[i - 1].toString() == ")") { list.add(i) } } Log.d("regOperatorBetween", list.toString()) return list } fun regOperatorBracket(text: String): Any { var listBracket = arrayListOf<String>() val listOperator = regOperatorBetweenBracket(text) for(i in listOperator.indices) { var subText = if (i == 0) text.substring(0, listOperator[i]) else text.substring(listOperator[i - 1] + 1, listOperator[i]) listBracket = subText(subText, listBracket) if (i == listOperator.size - 1) { subText = text.substring(listOperator[i] + 1, text.length).replace("x", "*") listBracket = subText(subText, listBracket) } } Log.d("listBracket", listBracket.toString()) var getText = "" for (j in listBracket.indices) { getText += listBracket[j] Log.d("getText bracket", getText) if (j <= listOperator.size - 1) { getText += text[listOperator[j]] getText = getText.replace("x", "*") Log.d("getText operator", getText) } } val number = Expression(getText).calculate() Log.d("regOperatorBracket", number.toString()) return if (number % 1 == 0.0) number.toInt() else number } private fun subText(subText: String, listBracket: ArrayList<String>): ArrayList<String> { val sub = if (subText.contains("(") || subText.contains(")")) { subText.replace("(", "").replace(")", "") } else { subText }.replace("x", "*") listBracket.add(expressText(sub)) return listBracket } fun expressText(text: String): String { val number = Expression(text).calculate() return if (number % 1.0 == 0.0) number.toInt().toString() else number.toString() } } }
CatAns/app/src/main/java/com/example/catans/util/Utils.kt
2367694240
package com.example.catans.util fun <T> List<T>.listEquals(other: List<T>) = size == other.size && asSequence() .mapIndexed { index, element -> element == other[index] } .all { it } fun <T> ArrayList<T>.arrayListEquals(other: ArrayList<T>) = size == other.size && asSequence() .mapIndexed { index, element -> element == other[index] } .all { it }
CatAns/app/src/main/java/com/example/catans/util/ExtensionUtils.kt
96487735
package com.example.catans.network import com.example.catans.model.Airport import com.example.catans.model.Currency import com.example.catans.util.EnumUtils import com.example.catans.util.Utils import com.example.catans.util.Utils.Companion.URI_AIRPORT_DEPARTURE import com.example.catans.util.Utils.Companion.URI_AIRPORT_INBOUND import com.example.catans.util.Utils.Companion.URI_CURRENCY_AUD import com.example.catans.util.Utils.Companion.URI_CURRENCY_CNY import com.example.catans.util.Utils.Companion.URI_CURRENCY_EUR import com.example.catans.util.Utils.Companion.URI_CURRENCY_HKD import com.example.catans.util.Utils.Companion.URI_CURRENCY_JPY import com.example.catans.util.Utils.Companion.URI_CURRENCY_USD import com.example.catans.util.Utils.Companion.URL_AIRPORT import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query import java.util.concurrent.TimeUnit interface ApiService { @GET(URI_CURRENCY_AUD) fun getCurrencyAUD(): Call<Currency?> @GET(URI_CURRENCY_CNY) fun getCurrencyCNY(): Call<Currency?> @GET(URI_CURRENCY_EUR) fun getCurrencyEUR(): Call<Currency?> @GET(URI_CURRENCY_HKD) fun getCurrencyHKD(): Call<Currency?> @GET(URI_CURRENCY_JPY) fun getCurrencyJPY(): Call<Currency?> @GET(URI_CURRENCY_USD) fun getCurrencyUSD(): Call<Currency?> @GET(URI_AIRPORT_DEPARTURE) suspend fun getAirportDeparture(@Query("page") page: Int, @Query("per_page") perPage: Int): List<Airport>? @GET(URI_AIRPORT_INBOUND) suspend fun getAirportInbound(@Query("page") page: Int, @Query("per_page") perPage: Int): List<Airport>? companion object { private fun getUrl(enumUtils: EnumUtils): String { return when(enumUtils) { EnumUtils.Inbound, EnumUtils.Departure-> URL_AIRPORT EnumUtils.Currency -> Utils.URL_CURRENCY } } fun create(enumUtils: EnumUtils): ApiService { val okHttpClient = OkHttpClient.Builder() .retryOnConnectionFailure(true) .connectTimeout( 10, TimeUnit.SECONDS) .readTimeout(10,TimeUnit.SECONDS) .writeTimeout(10,TimeUnit.SECONDS) // .addInterceptor() // .authenticator() // .proxy() .build() return Retrofit.Builder() .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(getUrl(enumUtils)) .build() .create(ApiService::class.java) } } }
CatAns/app/src/main/java/com/example/catans/network/ApiService.kt
2228388175
package com.example.catans.component import android.content.Context import android.util.AttributeSet import android.view.View import androidx.constraintlayout.widget.ConstraintLayout import com.example.catans.R import com.google.android.material.snackbar.ContentViewCallback class CustomSnackBarView @JvmOverloads constructor( context: Context, attributeSet: AttributeSet? = null, defaultStyle: Int = 0 ) : ConstraintLayout(context, attributeSet, defaultStyle), ContentViewCallback { init { View.inflate(context, R.layout.navigation_main, this) } override fun animateContentIn(delay: Int, duration: Int) { // TODO("Use some animation") } override fun animateContentOut(delay: Int, duration: Int) { // TODO("Use some animation") } }
CatAns/app/src/main/java/com/example/catans/component/CustomSnackBarView.kt
3487417203
package com.example.catans.component import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.content.ContextCompat import com.example.catans.R import com.google.android.material.snackbar.BaseTransientBottomBar class CustomSnackBar( parent: ViewGroup, content: CustomSnackBarView ) : BaseTransientBottomBar<CustomSnackBar>(parent, content, content) { init { getView().setBackgroundColor( ContextCompat.getColor( view.context, android.R.color.transparent ) ) getView().setPadding(0, 0, 0, 0) } companion object { fun make(viewGroup: ViewGroup): CustomSnackBar { val customView = LayoutInflater.from(viewGroup.context).inflate( R.layout.custom_snack_bar, viewGroup, false ) as CustomSnackBarView // customView.tvMessage.text = "Some Custom Message" return CustomSnackBar(viewGroup, customView) } } }
CatAns/app/src/main/java/com/example/catans/component/CustomSnackBar.kt
774319741
package com.example.catans.adapter import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter class ViewPagerAdapter(fa: Fragment, mList: List<Fragment>) : FragmentStateAdapter(fa) { private var mList: List<Fragment> init { this.mList = mList } override fun getItemCount(): Int = mList.size override fun createFragment(position: Int): Fragment = mList[position] }
CatAns/app/src/main/java/com/example/catans/adapter/ViewPagerAdapter.kt
2677465746
package com.example.catans.adapter import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.res.ResourcesCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.MutableLiveData import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import com.example.catans.BR import com.example.catans.R import com.example.catans.databinding.ItemDataBinding import com.example.catans.model.DataChild import com.example.catans.util.Utils class RepoAdapterData(private val fragment: Fragment, private val bottomSheetClick: () -> Unit) : PagingDataAdapter<DataChild, ItemViewHolder>( COMPARATOR ) { private lateinit var itemViewBinding: ItemDataBinding private var index = MutableLiveData<Int>() companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<DataChild>() { override fun areItemsTheSame(oldItem: DataChild, newItem: DataChild): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: DataChild, newItem: DataChild): Boolean = oldItem == newItem } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { itemViewBinding = DataBindingUtil.inflate(LayoutInflater.from(fragment.context), R.layout.item_data, parent, false) return ItemViewHolder(itemViewBinding, fragment) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val item: DataChild? = getItem(position) itemViewBinding.setVariable(BR.item, item) itemViewBinding.executePendingBindings() val llRoot = holder.itemView.rootView.findViewById<LinearLayout>(R.id.ll_root) val tvCurrencyCode = holder.itemView.rootView.findViewById<TextView>(R.id.tvCurrencyCode) val tvCurrencyMoney= holder.itemView.rootView.findViewById<TextView>(R.id.tvCurrencyMoney) llRoot.setOnClickListener { fragment.activity?.let { activity -> Utils.closeKeyboard(activity, activity.window.decorView) } bottomSheetClick() val new = holder.absoluteAdapterPosition Log.d("RepoAdapterData old", index.value.toString()) Log.d("RepoAdapterData new", new.toString()) index.observe(fragment) { old -> if (old != null && old != new) { itemClick(llRoot, tvCurrencyCode, tvCurrencyMoney, listOf(R.color.purple_100, R.color.grey_500, R.color.grey_500)) } } itemClick(llRoot, tvCurrencyCode, tvCurrencyMoney, listOf(R.color.grey_500, R.color.purple_200,R.color.purple_200)) index.value = new } } private fun itemClick(llRoot: LinearLayout, tvCurrencyCode: TextView, tvCurrencyMoney: TextView, listColor: List<Int>) { llRoot.background = ResourcesCompat.getDrawable(fragment.resources, listColor[0], fragment.activity?.theme) tvCurrencyCode.setTextColor(ResourcesCompat.getColor(fragment.resources, listColor[1], fragment.activity?.theme)) tvCurrencyMoney.setTextColor(ResourcesCompat.getColor(fragment.resources, listColor[2], fragment.activity?.theme)) } }
CatAns/app/src/main/java/com/example/catans/adapter/RepoAdapterData.kt
2723050844
package com.example.catans.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import com.example.catans.R import com.example.catans.databinding.ItemAirportBinding import com.example.catans.model.Airport class RepoAdapterAirport(val fragment: Fragment) : PagingDataAdapter<Airport, ItemViewHolder>( COMPARATOR ) { private lateinit var itemViewBinding: ItemAirportBinding companion object { private val COMPARATOR = object : DiffUtil.ItemCallback<Airport>() { override fun areItemsTheSame(oldItem: Airport, newItem: Airport): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: Airport, newItem: Airport): Boolean { return oldItem == newItem } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { itemViewBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_airport, parent, false) return ItemViewHolder(itemViewBinding, fragment) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val item: Airport? = getItem(position) holder.bindItemAirport(item) } }
CatAns/app/src/main/java/com/example/catans/adapter/RepoAdapterAirport.kt
3404898053
package com.example.catans.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import androidx.cardview.widget.CardView import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import com.example.catans.R class RepoAdapterCalculator(private val fragment: Fragment, private val list: Array<String>, private val itemClick: (index: Int) -> Unit ): BaseAdapter() { private var view: View? = null private var viewHolder: ViewHolder? = null override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { if (convertView == null) { view = LayoutInflater.from(fragment.context).inflate(R.layout.item_grid, null) viewHolder = ViewHolder() viewHolder?.card = view?.findViewById(R.id.cardGrid) viewHolder?.text = view?.findViewById(R.id.tvGrid) view?.tag = viewHolder } else { viewHolder = view?.tag as ViewHolder } val bgColor: Int val tvColor: Int when(position) { 0 -> { bgColor = R.color.grey_200 tvColor = R.color.red_200 } 1, 2, 3, 7, 11, 15 -> { bgColor = R.color.grey_200 tvColor = R.color.deep_green } 19 -> { bgColor = R.color.deep_green tvColor = R.color.white } else -> { bgColor = R.color.white tvColor = R.color.black } } viewHolder?.text?.text = list[position] viewHolder?.text?.setTextColor(ResourcesCompat.getColorStateList(fragment.resources, tvColor, fragment.activity?.theme)) viewHolder?.text?.background = ResourcesCompat.getDrawable(fragment.resources, bgColor, fragment.activity?.theme) viewHolder?.card?.setOnClickListener {view -> itemClick(position) } return view!! } override fun getCount(): Int = list.size override fun getItem(position: Int): Any = list[position] override fun getItemId(position: Int): Long = position.toLong() internal inner class ViewHolder { var card: CardView? = null var text: TextView? = null } }
CatAns/app/src/main/java/com/example/catans/adapter/RepoAdapterCalculator.kt
2631112127
package com.example.catans.adapter import androidx.core.content.res.ResourcesCompat import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import com.example.catans.BR import com.example.catans.R import com.example.catans.databinding.ItemAirportBinding import com.example.catans.model.Airport class ItemViewHolder(private val viewDataBinding: ViewDataBinding, private val fragment: Fragment) : RecyclerView.ViewHolder(viewDataBinding.root) { fun bindItemAirport(airport: Airport?) { val itemViewBinding: ItemAirportBinding = viewDataBinding as ItemAirportBinding airport?.terminal = when { airport?.terminal?.isEmpty() == true -> fragment.getString(R.string.none) else -> if (airport?.terminal?.length == 1) "0${airport.terminal}" else airport?.terminal } airport?.gate = airport?.gate ?: fragment.getString(R.string.none) itemViewBinding.tvEstimated.text = fragment.getString(R.string.estimated_time) itemViewBinding.tvActual.text = fragment.getString(R.string.actual_time) itemViewBinding.tvFlightNumber.text = fragment.getString(R.string.flight_number) itemViewBinding.tvTerminalGate.text = fragment.getString(R.string.terminal_gate) itemViewBinding.tvSlash.text = fragment.getString(R.string.slash) itemViewBinding.tvVerticalLine.text = fragment.getString(R.string.vertical_line) if (airport != null) { val color: Int = when (airport.remark) { fragment.getString(R.string.arrived)-> R.color.green fragment.getString(R.string.departed) -> R.color.green fragment.getString(R.string.cancelled) -> R.color.red fragment.getString(R.string.on_time) -> R.color.blue fragment.getString(R.string.schedule_change) -> R.color.orange else -> R.color.green } itemViewBinding.tvRemark.setTextColor(ResourcesCompat.getColor(fragment.resources, color, fragment.activity?.theme)) itemViewBinding.setVariable(BR.item, airport) itemViewBinding.executePendingBindings() } } }
CatAns/app/src/main/java/com/example/catans/adapter/ItemViewHolder.kt
412792985
package com.example.catans.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ProgressBar import androidx.core.view.isVisible import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import androidx.recyclerview.widget.RecyclerView import com.example.catans.R class FooterAdapter(val retry: () -> Unit) : LoadStateAdapter<FooterAdapter.ViewHolder>() { class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val progressBar: ProgressBar = itemView.findViewById(R.id.progress_bar) val retryButton: Button = itemView.findViewById(R.id.retry_button) } override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_footer, parent, false) val holder = ViewHolder(view) holder.retryButton.setOnClickListener { retry() } return holder } override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) { holder.progressBar.isVisible = loadState is LoadState.Loading holder.retryButton.isVisible = loadState is LoadState.Error } override fun displayLoadStateAsItem(loadState: LoadState): Boolean { // Logger.d("displayLoadStateAsItem: $loadState") return loadState is LoadState.Loading || loadState is LoadState.Error || (loadState is LoadState.NotLoading && loadState.endOfPaginationReached) } }
CatAns/app/src/main/java/com/example/catans/adapter/FooterAdapter.kt
820506464
package com.example.catans.fragment import com.example.catans.base.BaseFragment import com.example.catans.util.EnumUtils class AirportDepartureFragment : BaseFragment() { override fun initView() { enumUtils = EnumUtils.Departure } }
CatAns/app/src/main/java/com/example/catans/fragment/AirportDepartureFragment.kt
2289260109
package com.example.catans.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import com.example.catans.R import com.example.catans.databinding.FragmentSecondBinding class SecondFragment : Fragment() { private var _binding: FragmentSecondBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSecondBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.buttonSecond.setOnClickListener { findNavController().navigate(R.id.action_SecondFragment_to_ContentFragment) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
CatAns/app/src/main/java/com/example/catans/fragment/SecondFragment.kt
3613168959
package com.example.catans.fragment import com.example.catans.base.BaseFragment import com.example.catans.util.EnumUtils class AirportInboundFragment : BaseFragment() { override fun initView() { enumUtils = EnumUtils.Inbound } }
CatAns/app/src/main/java/com/example/catans/fragment/AirportInboundFragment.kt
1307860298
package com.example.catans.fragment import com.example.catans.base.BaseFragment import com.example.catans.util.EnumUtils class CurrencyFragment : BaseFragment() { override fun initView() { enumUtils = EnumUtils.Currency } }
CatAns/app/src/main/java/com/example/catans/fragment/CurrencyFragment.kt
1851832030
package com.example.catans.fragment import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.catans.databinding.FragmentContentBinding import com.example.catans.model.ContentModel class ContentFragment : Fragment() { private var _binding: FragmentContentBinding? = null private val binding get() = _binding!! private val viewModel: ContentModel by lazy { ContentModel() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentContentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.init(binding, this) binding.model = viewModel } override fun onDestroyView() { super.onDestroyView() _binding = null } }
CatAns/app/src/main/java/com/example/catans/fragment/ContentFragment.kt
110358979
package com.example.catans.model import com.example.catans.util.Utils import com.google.gson.annotations.SerializedName /** { "FlyType": "A", "AirlineID": "JX", "Airline": "星宇航空", "FlightNumber": "786", "DepartureAirportID": "MNL", "DepartureAirport": "馬尼拉機場", "ArrivalAirportID": "TPE", "ArrivalAirport": "臺北桃園國際機場", "ScheduleTime": "00:10", "ActualTime": "00:02", "EstimatedTime": "00:02", "Remark": "已到ARRIVED", "Terminal": "1", "Gate": "A9", "UpdateTime": "2023-05-23 11:00:28" }, **/ data class Airport( @SerializedName(Utils.FlyType) val flyType: String?, @SerializedName(Utils.AirlineID) val airlineID: String?, @SerializedName(Utils.Airline) val airline: String?, @SerializedName(Utils.FlightNumber) val flightNumber: String?, @SerializedName(Utils.DepartureAirportID) val departureAirportID: String?, @SerializedName(Utils.DepartureAirport) val departureAirport: String?, @SerializedName(Utils.ArrivalAirportID) val arrivalAirportID: String?, @SerializedName(Utils.ArrivalAirport) val arrivalAirport: String?, @SerializedName(Utils.ScheduleTime) val scheduleTime: String?, @SerializedName(Utils.ActualTime) val actualTime: String?, @SerializedName(Utils.EstimatedTime) val estimatedTime: String?, @SerializedName(Utils.Remark) val remark: String?, @SerializedName(Utils.Terminal) var terminal: String?, @SerializedName(Utils.Gate) var gate: String?, @SerializedName(Utils.UpdateTime) val updateTime: String?, ) { fun toMap(): Map<String, String?> { return mapOf( Utils.FlyType to flyType, Utils.AirlineID to airlineID, Utils.Airline to airline, Utils.FlightNumber to flightNumber, Utils.DepartureAirportID to departureAirportID, Utils.DepartureAirport to departureAirport, Utils.ArrivalAirportID to arrivalAirportID, Utils.ArrivalAirport to arrivalAirport, Utils.ScheduleTime to scheduleTime, Utils.ActualTime to actualTime, Utils.EstimatedTime to estimatedTime, Utils.Remark to remark, Utils.Terminal to terminal, Utils.Gate to gate, Utils.UpdateTime to updateTime, ) } }
CatAns/app/src/main/java/com/example/catans/model/AirportModel.kt
2402007784
package com.example.catans.model import android.view.LayoutInflater import android.view.View import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import com.example.catans.R import com.example.catans.adapter.ViewPagerAdapter import com.example.catans.databinding.FragmentContentBinding import com.example.catans.fragment.AirportDepartureFragment import com.example.catans.fragment.AirportInboundFragment import com.google.android.material.tabs.TabLayoutMediator class ContentModel { fun init(binding: FragmentContentBinding, fragment: Fragment) { val mFragmentList: MutableList<Fragment> = arrayListOf(AirportInboundFragment(), AirportDepartureFragment()) val mFragmentViewList: ArrayList<View> = arrayListOf( LayoutInflater.from(fragment.context).inflate(R.layout.item_tab_entry, null), LayoutInflater.from(fragment.context).inflate(R.layout.item_tab_departure, null), ) binding.viewPager.adapter = ViewPagerAdapter(fragment, mFragmentList) binding.viewPager.currentItem = 0 binding.viewPager.offscreenPageLimit = mFragmentList.size binding.tabLayout.setSelectedTabIndicatorColor(ResourcesCompat.getColor(fragment.resources, R.color.grey_500, fragment.activity?.theme)) TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.customView = mFragmentViewList[position] }.attach() } }
CatAns/app/src/main/java/com/example/catans/model/ContentModel.kt
3301821619
package com.example.catans.model import android.util.Log import android.view.View import androidx.lifecycle.MutableLiveData import androidx.paging.cachedIn import com.example.catans.adapter.RepoAdapterAirport import com.example.catans.databinding.FragmentBaseBinding import com.example.catans.repo.Repository import com.example.catans.util.EnumCurrencyUtils import com.example.catans.util.EnumUtils import kotlinx.coroutines.* class DataModel { interface ChildCallBack { fun getData(callBackList: ArrayList<DataChild>) } interface AirportCallBack { fun getData(getList: List<Airport>?) } fun getDataAirport(scope: CoroutineScope, repoAdapter: RepoAdapterAirport, enumUtils: EnumUtils, airportCallBack: AirportCallBack): RepoAdapterAirport { scope.launch(Dispatchers.IO) { Repository.getPagingAirport(enumUtils, airportCallBack).cachedIn(scope).collect { pagingData -> repoAdapter.submitData(pagingData) } } return repoAdapter } fun getDataCurrency(scope: CoroutineScope, binding: FragmentBaseBinding, getList: MutableLiveData<ArrayList<DataChild>>, enumCurrencyUtils: EnumCurrencyUtils): Deferred<MutableLiveData<ArrayList<DataChild>>> { val list = arrayListOf<DataChild>() Repository.getCurrency(enumCurrencyUtils).enqueue(object : retrofit2.Callback<Currency?> { override fun onResponse(call: retrofit2.Call<Currency?>, response: retrofit2.Response<Currency?>) { val currency = response.body() if (response.isSuccessful && currency != null && currency.data != null) { currency.data.toMap().entries.map { list.add(DataChild(it.key, (it.value ?: 0.0).toString())) } } getList.postValue(list) binding.progressCircular.visibility = View.INVISIBLE binding.noData.root.visibility = if (list.isEmpty()) View.VISIBLE else View.INVISIBLE Log.d("getDataCurrency:", list.size.toString()) } override fun onFailure(call: retrofit2.Call<Currency?>, throwable: Throwable) { binding.progressCircular.visibility = View.INVISIBLE binding.error.root.visibility = View.VISIBLE Log.d("getDataCurrency" , throwable.toString().trim { it <= ' ' }) } }) return scope.async { getList } } }
CatAns/app/src/main/java/com/example/catans/model/DataModel.kt
1017998832
package com.example.catans.model import com.example.catans.util.Utils import com.google.gson.annotations.SerializedName /** "data": { "AUD": 1.5243102464, "BGN": 1.7939302129, "BRL": 4.9594407933, "CAD": 1.3478802387, "CHF": 0.8798901447, "CNY": 7.1904612191, "CZK": 23.3991937698, "DKK": 6.884461162, "EUR": 0.9236101573, "GBP": 0.7896601047, "HKD": 7.8192709186, "HRK": 6.6849007558, "HUF": 357.5926902283, "IDR": 15564.455286269, "ILS": 3.6353606821, "INR": 82.8461200369, "ISK": 137.3424790427, "JPY": 150.4540874655, "KRW": 1325.3184043505, "MXN": 17.0998825547, "MYR": 4.7726805729, "NOK": 10.494731872, "NZD": 1.6142302547, "PHP": 55.7048609626, "PLN": 3.990600602, "RON": 4.5954208695, "RUB": 93.3431399151, "SEK": 10.3146015449, "SGD": 1.3426202517, "THB": 35.9104058652, "TRY": 31.0651853959, "USD": 1, "ZAR": 19.1568024469 } **/ data class Currency( @SerializedName(Utils.data) val data: Data?, ) data class Data( @SerializedName(Utils.AUD) val aud: Double = 0.0, // @SerializedName(Utils.BGN) val bgn: Double = 0.0, // @SerializedName(Utils.BRL) val brl: Double = 0.0, // @SerializedName(Utils.CAD) val cad: Double = 0.0, // @SerializedName(Utils.CHF) val chf: Double = 0.0, @SerializedName(Utils.CNY) val cny: Double = 0.0, // @SerializedName(Utils.CZK) val czk: Double = 0.0, // @SerializedName(Utils.DKK) val dkk: Double = 0.0, @SerializedName(Utils.EUR) val eur: Double = 0.0, // @SerializedName(Utils.GBP) val gbp: Double = 0.0, // @SerializedName(Utils.HRK) val hrk: Double = 0.0, // @SerializedName(Utils.HUF) val huf: Double = 0.0, @SerializedName(Utils.HKD) val hkd: Double = 0.0, // @SerializedName(Utils.IDR) val idr: Double = 0.0, // @SerializedName(Utils.ILS) val ils: Double = 0.0, // @SerializedName(Utils.INR) val inr: Double = 0.0, // @SerializedName(Utils.ISK) val isk: Double = 0.0, @SerializedName(Utils.JPY) val jpy: Double = 0.0, // @SerializedName(Utils.KRW) val krw: Double = 0.0, // @SerializedName(Utils.MXN) val mxn: Double = 0.0, // @SerializedName(Utils.MYR) val myr: Double = 0.0, // @SerializedName(Utils.NOK) val nok: Double = 0.0, // @SerializedName(Utils.NZD) val nzd: Double = 0.0, // @SerializedName(Utils.PHP) val php: Double = 0.0, // @SerializedName(Utils.PLN) val pln: Double = 0.0, // @SerializedName(Utils.RON) val ron: Double = 0.0, // @SerializedName(Utils.RUB) val rub: Double = 0.0, // @SerializedName(Utils.SEK) val sek: Double = 0.0, // @SerializedName(Utils.SGD) val sgd: Double = 0.0, // @SerializedName(Utils.THB) val thb: Double = 0.0, // @SerializedName(Utils.TRY) val trY: Double = 0.0, @SerializedName(Utils.USD) val usd: Double = 0.0, // @SerializedName(Utils.ZAR) val zar: Double = 0.0, ) { fun toMap(): Map<String, Double?> { return mapOf( Utils.AUD to aud, // Utils.BGN to bgn, // Utils.BRL to brl, // Utils.CAD to cad, // Utils.CHF to chf, Utils.CNY to cny, // Utils.CZK to czk, // Utils.DKK to dkk, Utils.EUR to eur, // Utils.GBP to gbp, Utils.HKD to hkd, // Utils.HRK to hrk, // Utils.HUF to huf, // Utils.IDR to idr, // Utils.ILS to ils, // Utils.INR to inr, // Utils.ISK to isk, Utils.JPY to jpy, // Utils.KRW to krw, // Utils.MXN to mxn, // Utils.MYR to myr, // Utils.NOK to nok, // Utils.NZD to nzd, // Utils.PHP to php, // Utils.PLN to pln, // Utils.RON to ron, // Utils.RUB to rub, // Utils.SEK to sek, // Utils.SGD to sgd, // Utils.THB to thb, // Utils.TRY to trY, Utils.USD to usd, // Utils.ZAR to zar, ) } } data class DataChild( @SerializedName(Utils.code) val code: String = "", @SerializedName(Utils.money) val money: String = "0.0", )
CatAns/app/src/main/java/com/example/catans/model/CurrencyModel.kt
188641926
package com.example.catans.repo import androidx.paging.PagingSource import androidx.paging.PagingState import com.example.catans.model.Airport import com.example.catans.model.DataModel import com.example.catans.network.ApiService import com.example.catans.util.EnumUtils import java.lang.Exception class RepoPagingAirport(private val apiService: ApiService, private val enumUtils: EnumUtils, private val airportCallBack: DataModel.AirportCallBack) : PagingSource<Int, Airport>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Airport> { return try { val page = params.key ?: 1 val pageSize = params.loadSize val repoResponse = when(enumUtils) { EnumUtils.Departure -> apiService.getAirportDeparture(page, pageSize) EnumUtils.Inbound -> apiService.getAirportInbound(page, pageSize) else -> apiService.getAirportDeparture(page, pageSize) } airportCallBack.getData(repoResponse) val prevKey = if (page > 1) page - 1 else null val nextKey = if (repoResponse?.isNotEmpty() == true) page + 1 else null LoadResult.Page(repoResponse!!, prevKey, nextKey) } catch (e: Exception) { e.printStackTrace() LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, Airport>): Int? = null }
CatAns/app/src/main/java/com/example/catans/repo/RepoPagingAirport.kt
1052776079
package com.example.catans.repo import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.example.catans.model.Airport import com.example.catans.model.Currency import com.example.catans.model.DataChild import com.example.catans.model.DataModel import com.example.catans.network.ApiService import com.example.catans.util.EnumCurrencyUtils import com.example.catans.util.EnumUtils import kotlinx.coroutines.flow.Flow import retrofit2.Call object Repository { private const val PAGE_SIZE = 1 fun getPagingAirport(enumUtils: EnumUtils, airportCallBack: DataModel.AirportCallBack): Flow<PagingData<Airport>> { return Pager( config = PagingConfig(PAGE_SIZE), pagingSourceFactory = { RepoPagingAirport(ApiService.create(enumUtils), enumUtils, airportCallBack) } ).flow } fun getPagingCurrency(list: ArrayList<DataChild>): Flow<PagingData<DataChild>> { return Pager( config = PagingConfig(PAGE_SIZE), pagingSourceFactory = { RepoPagingData(list) } ).flow } fun getCurrency(enumCurrencyUtils: EnumCurrencyUtils): Call<Currency?> { val service = ApiService.create(EnumUtils.Currency) return when(enumCurrencyUtils) { EnumCurrencyUtils.AUD -> service.getCurrencyAUD() EnumCurrencyUtils.CNY -> service.getCurrencyCNY() EnumCurrencyUtils.EUR -> service.getCurrencyEUR() EnumCurrencyUtils.HKD -> service.getCurrencyHKD() EnumCurrencyUtils.JPY -> service.getCurrencyJPY() EnumCurrencyUtils.USD -> service.getCurrencyUSD() } } }
CatAns/app/src/main/java/com/example/catans/repo/Repository.kt
3751197051
package com.example.catans.repo import androidx.paging.PagingSource import androidx.paging.PagingState import com.example.catans.model.DataChild import java.lang.Exception class RepoPagingData(private val listData: ArrayList<DataChild>) : PagingSource<Int, DataChild>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, DataChild> { return try { LoadResult.Page(listData, null, null) } catch (e: Exception) { e.printStackTrace() LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<Int, DataChild>): Int? = null }
CatAns/app/src/main/java/com/example/catans/repo/RepoPagingData.kt
4008947834
package com.example.catans.base import android.content.Context import android.os.Handler import android.os.Looper import android.util.Log import android.view.View import android.widget.GridView import android.widget.ImageView import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.CombinedLoadStates import androidx.paging.LoadState import androidx.paging.cachedIn import androidx.recyclerview.widget.LinearLayoutManager import com.example.catans.R import com.example.catans.adapter.FooterAdapter import com.example.catans.adapter.RepoAdapterAirport import com.example.catans.adapter.RepoAdapterCalculator import com.example.catans.adapter.RepoAdapterData import com.example.catans.databinding.FragmentBaseBinding import com.example.catans.model.Airport import com.example.catans.model.DataChild import com.example.catans.model.DataModel import com.example.catans.repo.Repository import com.example.catans.util.EnumCurrencyUtils import com.example.catans.util.EnumUtils import com.example.catans.util.Utils import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.textfield.TextInputEditText import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch open class BaseViewModel: ViewModel() { private val listAirport: MutableLiveData<List<Airport>?> = MutableLiveData<List<Airport>?>() private var listData: MutableLiveData<ArrayList<DataChild>> = MutableLiveData<ArrayList<DataChild>>() private val listGrid: MutableLiveData<Array<String>> = MutableLiveData<Array<String>>() private lateinit var repoAdapterAirport: RepoAdapterAirport private lateinit var repoAdapterData: RepoAdapterData private var dialog: BottomSheetDialog? = null private lateinit var behavior: BottomSheetBehavior<View> private var handler: Handler = Handler(Looper.getMainLooper()) private var runnableTime: Runnable? = null private lateinit var text: String fun initCurrency(fragment: Fragment, binding: FragmentBaseBinding) { val tvEditCurrency = binding.itemCurrency.tvEditCurrency tvEditCurrency.requestFocus() tvEditCurrency.addTextChangedListener { tvEditCurrency.setSelection(tvEditCurrency.length()) } binding.itemCurrency.currencyButton.setOnClickListener { val text = tvEditCurrency.text.toString() when { tvEditCurrency.text == null -> tvEditCurrency.setText(fragment.getString(R.string.currency_code_empty)) tvEditCurrency.text?.isEmpty() == true -> tvEditCurrency.setText(fragment.getString(R.string.currency_code_empty)) else -> if (text != Utils.AUD && text != Utils.CNY && text != Utils.EUR && text != Utils.HKD && text != Utils.JPY && text != Utils.USD) { tvEditCurrency.setText(fragment.getString(R.string.currency_code_capital)) } else { val enum = when(text) { Utils.AUD -> EnumCurrencyUtils.AUD Utils.CNY -> EnumCurrencyUtils.CNY Utils.EUR -> EnumCurrencyUtils.EUR Utils.HKD -> EnumCurrencyUtils.HKD Utils.JPY -> EnumCurrencyUtils.JPY Utils.USD -> EnumCurrencyUtils.USD else -> EnumCurrencyUtils.USD } tvEditCurrency.hint = "Code: $text" dataCurrency(fragment, binding, enum) adapterData(fragment, binding, enum) recyclerCurrency(fragment, binding) } } } } private suspend fun dataUpdate(getData: () -> Unit) { delay(Utils.TIME_REPEAT) getData() } fun dataAirport(fragment: Fragment, enumUtils: EnumUtils) { repoAdapterAirport = RepoAdapterAirport(fragment) repoAdapterAirport = DataModel().getDataAirport(viewModelScope, repoAdapterAirport, enumUtils, object : DataModel.AirportCallBack { override fun getData(getList: List<Airport>?) { Log.d("BaseViewModel airport","${getList?.size}") listAirport.value = getList listAirport.observe(fragment) { airports -> viewModelScope.launch { dataUpdate { repoAdapterAirport.refresh() } } Log.d("observe airports","${airports?.size}") } } }) } fun dataCurrency(fragment: Fragment, binding: FragmentBaseBinding, enumCurrencyUtils: EnumCurrencyUtils) { viewModelScope.launch { listData = DataModel().getDataCurrency(viewModelScope, binding, listData, enumCurrencyUtils).await() Log.d("BaseViewModel currency","${listData.value?.size}") listData.observe(fragment) { currency -> viewModelScope.launch(Dispatchers.Main) { Repository.getPagingCurrency(currency).cachedIn(viewModelScope).collect { pagingData -> repoAdapterData.submitData(pagingData) } Log.d("Observe currency","${currency.size}") } } } } fun recyclerCurrency(fragment: Fragment, binding: FragmentBaseBinding) { fragment.context?.let { binding.recyclerView.setPadding(Utils.dpToPixel(it,12), Utils.dpToPixel(it,12), Utils.dpToPixel(it,12), Utils.dpToPixel(it,12)) } binding.recyclerView.layoutManager = LinearLayoutManager(fragment.context) binding.recyclerView.adapter = repoAdapterData } fun recyclerAirport(context: Context, binding: FragmentBaseBinding) { binding.recyclerView.layoutManager = LinearLayoutManager(context) binding.recyclerView.adapter = repoAdapterAirport.withLoadStateFooter(FooterAdapter { repoAdapterAirport.retry() }) } fun adapterAirport(fragment: Fragment, binding: FragmentBaseBinding, enumUtils: EnumUtils) { repoAdapterAirport.addLoadStateListener { loadState(it, binding) { dataAirport(fragment, enumUtils) } } } fun adapterData(fragment: Fragment, binding: FragmentBaseBinding, enumCurrencyUtils: EnumCurrencyUtils) { repoAdapterData = RepoAdapterData(fragment) { bottomSheet(fragment) dialog?.let { bottomSheetClick(fragment, it, behavior) } } repoAdapterData.withLoadStateFooter(FooterAdapter { repoAdapterData.retry() }) repoAdapterData.addLoadStateListener { loadState(it, binding) { dataCurrency(fragment, binding, enumCurrencyUtils) } } } private fun loadState(state : CombinedLoadStates, binding: FragmentBaseBinding, getData: () -> Unit) { when (state.refresh) { is LoadState.NotLoading -> { binding.progressCircular.visibility = View.INVISIBLE binding.recyclerView.visibility = View.VISIBLE } is LoadState.Loading -> { binding.progressCircular.visibility = View.VISIBLE binding.recyclerView.visibility = View.INVISIBLE } is LoadState.Error -> { binding.progressCircular.visibility = View.INVISIBLE error(binding, getData) } } } private fun error(binding: FragmentBaseBinding, getData: () -> Unit) { binding.error.retryButton.setOnClickListener { getData() } } private fun bottomSheet(fragment: Fragment) { val view = View.inflate(fragment.context, R.layout.dialog_bottom_sheet, null) dialog = fragment.context?.let { BottomSheetDialog(it) } dialog?.setContentView(view) behavior = BottomSheetBehavior.from(view.parent as View) val list = fragment.resources.getStringArray(R.array.calculator) val gridView = view.findViewById<GridView>(R.id.gridView) val editText = view.findViewById<TextInputEditText>(R.id.tvEditCalculator) val ivRemove = view.findViewById<ImageView>(R.id.ivRemove) text = editText.text.toString() editText.requestFocus() editText.addTextChangedListener { edit -> if (!edit.isNullOrEmpty()) { editText.setSelection(edit.length) } } ivRemove.setOnClickListener { val index = editText.selectionEnd if (index >= 1) { text = editText.text?.delete(index - 1, index).toString() } } listGrid.value = list listGrid.observe(fragment) {array -> if (array.isNotEmpty()) { val repoAdapterCalculator = RepoAdapterCalculator(fragment, array) { index -> if (index == 0 ) { text = "" } val listOpenBracket = text.split("(") val listBackBracket = text.split(")") if (index == 19) { Log.d("ListBracket Open:", listOpenBracket.toString()) Log.d("ListBracket Back:", listBackBracket.toString()) text = if (text.isEmpty()) { fragment.getString(R.string.reg_empty) } else { when { listOpenBracket.isNotEmpty() && listOpenBracket.size == 1 -> Utils.expressText(text.replace("x", "*")) listOpenBracket.size != listBackBracket.size -> fragment.getString(R.string.reg_bracket) listOpenBracket.size > 1 && listOpenBracket.size == listBackBracket.size -> Utils.regOperatorBracket(text).toString() else -> fragment.getString(R.string.reg_type) } } Log.d("result ", text) } text += when(index) { 1 -> when { text.isEmpty() || Utils.regCalculatorPrevious(text) || text.indexOf("(") == text.length - 1-> "(" text.indexOf(")") == text.length - 1 -> ")" listOpenBracket.size > listBackBracket.size && (Utils.regNumberNext(text,text.indexOf("(") + 1) || Utils.regBracketOpenNext(text,text.indexOf("(") + 1)) && (Utils.regBracketPrevious(text) || Utils.regNumberPrevious(text)) -> ")" listOpenBracket.size == listBackBracket.size && (Utils.regCalculatorNext(text,text.indexOf(")") + 1) || Utils.regBracketBackNext(text,text.indexOf(")") + 1)) && Utils.regCalculatorPrevious(text) -> "(" else -> "" } 2 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "%" 3 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "/" 4 -> "7" 5 -> "8" 6 -> "9" 7 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "x" 8 -> "4" 9 -> "5" 10 -> "6" 11 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "-" 12 -> "1" 13 -> "2" 14 -> "3" 15 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "+" 16 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "-" 17 -> if (!Utils.regNumberPreviousZero(text)) "" else "0" 18 -> if (!Utils.regNumberPreviousBackBracket(text)) "" else "." else -> "" } editText.setText(text) } repoAdapterCalculator.notifyDataSetChanged() gridView.adapter = repoAdapterCalculator } } } private fun bottomSheetClick(fragment: Fragment, dialog: BottomSheetDialog, behavior: BottomSheetBehavior<View>) { // behavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED fragment.context?.let { behavior.peekHeight = Utils.dpToPixel(it, 1600) } dialog.show() // behavior.state = when(behavior.state) { // BottomSheetBehavior.STATE_HIDDEN -> BottomSheetBehavior.STATE_COLLAPSED // else -> BottomSheetBehavior.STATE_HIDDEN // } } fun destroy() { if (runnableTime != null) { handler.removeCallbacks(runnableTime!!) } } // fun fab(binding: FragmentBaseBinding, fragment: Fragment) { // binding.fab.visibility = View.VISIBLE // binding.fab.backgroundTintList = ResourcesCompat.getColorStateList(fragment.resources, R.color.purple_200, fragment.activity?.theme) // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // binding.recyclerView.setOnScrollChangeListener { view, scrollX, scrollY, oldScrollX, oldScrollY -> // // } // } // } }
CatAns/app/src/main/java/com/example/catans/base/BaseViewModel.kt
3761490540
package com.example.catans.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.catans.databinding.FragmentBaseBinding import com.example.catans.util.EnumCurrencyUtils import com.example.catans.util.EnumUtils abstract class BaseFragment : Fragment() { abstract fun initView() lateinit var enumUtils: EnumUtils private var _binding: FragmentBaseBinding? = null val binding get() = _binding!! private val viewModel by lazy { BaseViewModel() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { initView() _binding = FragmentBaseBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) when (enumUtils) { EnumUtils.Departure, EnumUtils.Inbound -> { binding.itemCurrency.root.visibility = View.GONE viewModel.dataAirport(this, enumUtils) viewModel.adapterAirport(this, binding, enumUtils) context?.let { viewModel.recyclerAirport(it, binding) } } EnumUtils.Currency -> { binding.itemCurrency.root.visibility = View.VISIBLE viewModel.initCurrency(this, binding) viewModel.dataCurrency(this, binding, EnumCurrencyUtils.USD) viewModel.adapterData(this, binding, EnumCurrencyUtils.USD) viewModel.recyclerCurrency(this, binding) } } binding.model = viewModel } override fun onDestroyView() { super.onDestroyView() viewModel.destroy() _binding = null } }
CatAns/app/src/main/java/com/example/catans/base/BaseFragment.kt
696376981
package com.ifs21001.pampraktikum8 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.ifs21001.pampraktikum8", appContext.packageName) } }
fragment-dan-navigation-WhatsApp-/app/src/androidTest/java/com/ifs21001/pampraktikum8/ExampleInstrumentedTest.kt
53747941
package com.ifs21001.pampraktikum8 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) } }
fragment-dan-navigation-WhatsApp-/app/src/test/java/com/ifs21001/pampraktikum8/ExampleUnitTest.kt
465203209
package com.ifs21001.pampraktikum8 import android.content.Intent import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.ifs21001.pampraktikum8.databinding.ActivityDetailBinding class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding private var fruit: Fruit? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) fruit = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra(EXTRA_FRUIT, Fruit::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(EXTRA_FRUIT) } supportActionBar?.setDisplayHomeAsUpEnabled(true) if (fruit != null) { supportActionBar?.title = "${fruit!!.name}" loadData(fruit!!) } else { finish() } } private fun loadData(fruit: Fruit) { binding.ivDetailIcon.setImageResource(fruit.icon) binding.tvDetailName.text = fruit.name binding.tvDetailDescription.text = fruit.description binding.tvDetailCharacteristic.text = fruit.characteristic binding.tvDetailKelompok.text = fruit.kelompok binding.tvDetailHabitat.text = fruit.habitat binding.tvDetailMakanan.text = fruit.makanan binding.tvDetailPanjang.text = fruit.panjang binding.tvDetailTinggi.text = fruit.tinggi binding.tvDetailBobot.text = fruit.bobot binding.tvDetailKelemahan.text = fruit.kelemahan } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() } } return super.onOptionsItemSelected(item) } companion object { const val EXTRA_FRUIT = "extra_fruit" } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/DetailActivity.kt
404323537
package com.ifs21001.pampraktikum8 import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.GravityCompat import com.ifs21001.pampraktikum8.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupView() setupAction() } private fun setupView() { binding.navView.setCheckedItem(R.id.nav_home) binding.inAppBar.toolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_more_vert) loadFragment(FLAG_FRAGMENT_HOME) } private fun setupAction() { binding.inAppBar.toolbar.setNavigationOnClickListener { binding.drawerLayout.openDrawer(GravityCompat.START) } binding.inAppBar.toolbar.setOnMenuItemClickListener { menuItem -> when (menuItem.itemId) { R.id.action_settings -> { loadFragment(FLAG_FRAGMENT_HOME, "Memilih menu Settings!") true } R.id.action_logout -> { loadFragment(FLAG_FRAGMENT_HOME, "Memilih menu Logout!") true } else -> true } } binding.navView.setNavigationItemSelectedListener { when (it.itemId) { R.id.nav_home -> { loadFragment(FLAG_FRAGMENT_HOME) binding.drawerLayout.closeDrawer(GravityCompat.START) true } R.id.nav_profile -> { loadFragment(FLAG_FRAGMENT_HOME, "Memilih menu Profile!") binding.drawerLayout.closeDrawer(GravityCompat.START) true } R.id.nav_notes -> { loadFragment(FLAG_FRAGMENT_HOME, "Memilih menu Notes!") binding.drawerLayout.closeDrawer(GravityCompat.START) true } else -> true } } binding.inAppBar.bottomNavView.setOnItemSelectedListener { when (it.itemId) { R.id.navigation_home -> { loadFragment(FLAG_FRAGMENT_HOME) true } R.id.navigation_dashboard -> { loadFragment(FLAG_FRAGMENT_DASHBOARD) true } R.id.navigation_status -> { loadFragment(FLAG_FRAGMENT_STORY) true } R.id.navigation_notifications -> { loadFragment(FLAG_FRAGMENT_NOTIFICATION) true } else -> true } } } private fun loadFragment(flag: String, message: String? = null) { val fragmentManager = supportFragmentManager val fragmentContainerId = binding.inAppBar.inContentMain.frameContainer.id when (flag) { FLAG_FRAGMENT_HOME -> { binding.inAppBar.bottomNavView .menu .findItem(R.id.navigation_home) .setChecked(true) val homeFragment = HomeFragment() val bundle = Bundle().apply { this.putString( HomeFragment.EXTRA_MESSAGE, message ?: "Belum ada menu yang dipilih!" ) } homeFragment.arguments = bundle fragmentManager .beginTransaction() .replace( fragmentContainerId, homeFragment, HomeFragment::class.java.simpleName ) .commit() } FLAG_FRAGMENT_DASHBOARD -> { val dashboardFragment = DashboardFragment() val fragment = fragmentManager .findFragmentByTag(DashboardFragment::class.java.simpleName) if (fragment !is DashboardFragment) { fragmentManager .beginTransaction() .replace( fragmentContainerId, dashboardFragment, DashboardFragment::class.java.simpleName ) .commit() } } FLAG_FRAGMENT_STORY -> { val storyFragment = StoryFragment() val fragment = fragmentManager .findFragmentByTag(StoryFragment::class.java.simpleName) if (fragment !is DashboardFragment) { fragmentManager .beginTransaction() .replace( fragmentContainerId, storyFragment, StoryFragment::class.java.simpleName ) .commit() } } FLAG_FRAGMENT_NOTIFICATION -> { val notificationFragment = NotificationFragment() val fragment = fragmentManager .findFragmentByTag(NotificationFragment::class.java.simpleName) if (fragment !is NotificationFragment) { fragmentManager .beginTransaction() .replace( fragmentContainerId, notificationFragment, NotificationFragment::class.java.simpleName ) .commit() } } } } companion object { const val FLAG_FRAGMENT_HOME = "fragment_home" const val FLAG_FRAGMENT_DASHBOARD = "fragment_dashboard" const val FLAG_FRAGMENT_NOTIFICATION = "fragment_notification" const val FLAG_FRAGMENT_STORY = "fragment_story" } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/MainActivity.kt
3677773829
package com.ifs21001.pampraktikum8 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import com.ifs21001.pampraktikum8.databinding.FragmentDashboardBinding class DashboardFragment : Fragment() { private lateinit var binding: FragmentDashboardBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentDashboardBinding .inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { svFragmentDashboard.setupWithSearchBar(sbFragmentDashboard) svFragmentDashboard .editText .setOnEditorActionListener { textView, actionId, event -> sbFragmentDashboard.setText(svFragmentDashboard.text) svFragmentDashboard.hide() val message = "Kamu mencari dengan keywords:\n${svFragmentDashboard.text}" Toast.makeText( requireContext(), message, Toast.LENGTH_LONG ).show() false } } } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/DashboardFragment.kt
1271834821
package com.ifs21001.pampraktikum8 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.ifs21001.pampraktikum8.databinding.FragmentStoryBinding class StoryFragment : Fragment(), ListFruitAdapter.OnItemClickCallback { private lateinit var binding: FragmentStoryBinding private lateinit var fruitAdapter: ListFruitAdapter private lateinit var fruitsList: ArrayList<Fruit> // Tidak perlu inisialisasi di sini override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentStoryBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fruitsList = getListFruits() setupRecyclerView() } private fun setupRecyclerView() { fruitAdapter = ListFruitAdapter(fruitsList) fruitAdapter.setOnItemClickCallback(this) // Set callback untuk item klik binding.rvFruits.apply { layoutManager = LinearLayoutManager(context) adapter = fruitAdapter } } override fun onItemClicked(data: Fruit) { // Implementasi aksi saat item diklik di sini // Contoh: Menampilkan informasi detail buah } companion object { const val EXTRA_MESSAGE = "extra_message" } private fun getListFruits(): ArrayList<Fruit> { val dataName = resources.getStringArray(R.array.fruit_name) val dataIcon = resources.obtainTypedArray(R.array.fruit_icon) val dataDescription = resources.getStringArray(R.array.fruit_description) val dataCharacteristic = resources.getStringArray(R.array.fruit_characteristic) val dataKelompok = resources.getStringArray(R.array.fruit_kelompok) val dataHabitat = resources.getStringArray(R.array.fruit_habitat) val dataMakanan = resources.getStringArray(R.array.fruit_makanan) val dataPanjang = resources.getStringArray(R.array.fruit_panjang) val dataTinggi = resources.getStringArray(R.array.fruit_tinggi) val dataBobot = resources.getStringArray(R.array.fruit_bobot) val dataKelemahan= resources.getStringArray(R.array.fruit_kelemahan) val listFruit = ArrayList<Fruit>() for (i in dataName.indices) { val fruit = Fruit(dataName[i], dataIcon.getResourceId(i, -1), dataDescription[i], dataCharacteristic[i], dataKelompok[i], dataHabitat[i], dataMakanan[i],dataPanjang[i], dataTinggi[i], dataBobot[i], dataKelemahan[i]) listFruit.add(fruit) } // Penting untuk melepaskan sumber daya yang digunakan oleh dataIcon dataIcon.recycle() return listFruit } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/StoryFragment.kt
684041594
package com.ifs21001.pampraktikum8 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.ifs21001.pampraktikum8.databinding.FragmentNotificationBinding class NotificationFragment : Fragment(), ListDinoAdapter.OnItemClickCallback { private var _binding: FragmentNotificationBinding? = null private val binding get() = _binding!! private lateinit var dinoAdapter: ListDinoAdapter private lateinit var dinosList: ArrayList<Dino> override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentNotificationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dinosList = getListDinos() setupRecyclerView() } private fun setupRecyclerView() { dinoAdapter = ListDinoAdapter(dinosList) dinoAdapter.setOnItemClickCallback(this) binding.rvDinos.apply { layoutManager = LinearLayoutManager(context) adapter = dinoAdapter } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onItemClicked(data: Dino) { // Implementasi aksi saat item diklik di sini // Contoh: Menampilkan informasi detail buah } private fun getListDinos(): ArrayList<Dino> { val dataNama = resources.getStringArray(R.array.dino_nama) val dataPhoto = resources.obtainTypedArray(R.array.dino_photo) val dataDescription = resources.getStringArray(R.array.dino_deskripsi) val dataCharacteristic = resources.getStringArray(R.array.dino_karaktersitik) val dataKelompok = resources.getStringArray(R.array.dino_kelompok) val dataHabitat = resources.getStringArray(R.array.dino_habitat) val dataMakanan = resources.getStringArray(R.array.dino_makanan) val dataPanjang = resources.getStringArray(R.array.dino_panjang) val dataTinggi = resources.getStringArray(R.array.dino_tinggi) val dataBobot = resources.getStringArray(R.array.dino_bobot) val dataKelemahan = resources.getStringArray(R.array.dino_kelemahan) val listDino = ArrayList<Dino>() for (i in dataNama.indices) { val dino = Dino( dataNama[i], dataPhoto.getResourceId(i, -1), dataDescription[i], dataCharacteristic[i], dataKelompok[i], dataHabitat[i], dataMakanan[i], dataPanjang[i], dataTinggi[i], dataBobot[i], dataKelemahan[i] ) listDino.add(dino) } dataPhoto.recycle() return listDino } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/NotificationFragment.kt
1566420160
package com.ifs21001.pampraktikum8 import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Dino( var nama:String, var photo:Int, var deskripsi:String, var karakteristik:String, var kelompok:String, var habitat:String, var makanan:String, var panjang:String, var tinggi:String, var bobot:String, var kelemahan:String, ) : Parcelable
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/Dino.kt
902799144
package com.ifs21001.pampraktikum8 import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class Fruit( var name: String, var icon: Int, var description: String, var characteristic: String, var kelompok: String, var habitat: String, var makanan: String, var panjang: String, var tinggi: String, var bobot: String, var kelemahan: String, ) : Parcelable
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/Fruit.kt
2206614059
package com.ifs21001.pampraktikum8 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.ifs21001.pampraktikum8.databinding.FragmentHomeBinding class HomeFragment : Fragment(), ListFruitAdapter.OnItemClickCallback { private lateinit var binding: FragmentHomeBinding private lateinit var fruitAdapter: ListFruitAdapter private lateinit var fruitsList: ArrayList<Fruit> // Tidak perlu inisialisasi di sini override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fruitsList = getListFruits() setupRecyclerView() } private fun setupRecyclerView() { fruitAdapter = ListFruitAdapter(fruitsList) fruitAdapter.setOnItemClickCallback(this) // Set callback untuk item klik binding.rvFruits.apply { layoutManager = LinearLayoutManager(context) adapter = fruitAdapter } } override fun onItemClicked(data: Fruit) { // Implementasi aksi saat item diklik di sini // Contoh: Menampilkan informasi detail buah } companion object { const val EXTRA_MESSAGE = "extra_message" } private fun getListFruits(): ArrayList<Fruit> { val dataName = resources.getStringArray(R.array.fruit_name) val dataIcon = resources.obtainTypedArray(R.array.fruit_icon) val dataDescription = resources.getStringArray(R.array.fruit_description) val dataCharacteristic = resources.getStringArray(R.array.fruit_characteristic) val dataKelompok = resources.getStringArray(R.array.fruit_kelompok) val dataHabitat = resources.getStringArray(R.array.fruit_habitat) val dataMakanan = resources.getStringArray(R.array.fruit_makanan) val dataPanjang = resources.getStringArray(R.array.fruit_panjang) val dataTinggi = resources.getStringArray(R.array.fruit_tinggi) val dataBobot = resources.getStringArray(R.array.fruit_bobot) val dataKelemahan= resources.getStringArray(R.array.fruit_kelemahan) val listFruit = ArrayList<Fruit>() for (i in dataName.indices) { val fruit = Fruit(dataName[i], dataIcon.getResourceId(i, -1), dataDescription[i], dataCharacteristic[i], dataKelompok[i], dataHabitat[i], dataMakanan[i],dataPanjang[i], dataTinggi[i], dataBobot[i], dataKelemahan[i]) listFruit.add(fruit) } // Penting untuk melepaskan sumber daya yang digunakan oleh dataIcon dataIcon.recycle() return listFruit } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/HomeFragment.kt
3844559105
package com.ifs21001.pampraktikum8 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.ifs21001.pampraktikum8.databinding.FragmentDetailBinding class DetailFragment : Fragment() { private lateinit var binding: FragmentDetailBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentDetailBinding .inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { val info = it.getString(EXTRA_INFO) binding.tvFragmentDetail.text = info } } companion object { const val EXTRA_INFO = "extra_info" } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/DetailFragment.kt
2838853416
package com.ifs21001.pampraktikum8 import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.ifs21001.pampraktikum8.databinding.ItemRowFruitBinding class ListFruitAdapter(private val listFruit: ArrayList<Fruit>) : RecyclerView.Adapter<ListFruitAdapter.ListViewHolder>() { private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ListViewHolder { val binding = ItemRowFruitBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false) return ListViewHolder(binding) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ListViewHolder, position: Int) { val fruit = listFruit[position] holder.binding.ivItemFruit.setImageResource(fruit.icon) holder.binding.tvItemFruit.text = fruit.name holder.binding.cvItemFruit.text = fruit.kelompok holder.itemView.setOnClickListener { onItemClickCallback .onItemClicked(listFruit[holder.adapterPosition]) } } override fun getItemCount(): Int = listFruit.size class ListViewHolder(var binding: ItemRowFruitBinding) : RecyclerView.ViewHolder(binding.root) interface OnItemClickCallback { fun onItemClicked(data: Fruit) } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/ListFruitAdapter.kt
1086799079
package com.ifs21001.pampraktikum8 import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.ifs21001.pampraktikum8.databinding.ItemRowDinoBinding class ListDinoAdapter(private val listDino: ArrayList<Dino>) : RecyclerView.Adapter<ListDinoAdapter.ListViewHolder>() { private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ListViewHolder { val binding = ItemRowDinoBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false) return ListViewHolder(binding) } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: ListViewHolder, position: Int) { val dino = listDino[position] holder.binding.ivItemDino.setImageResource(dino.photo) holder.binding.tvItemDino.text = dino.nama holder.binding.cvItemDino.text = dino.tinggi holder.itemView.setOnClickListener { onItemClickCallback .onItemClicked(listDino[holder.adapterPosition]) } } override fun getItemCount(): Int = listDino.size class ListViewHolder(var binding: ItemRowDinoBinding) : RecyclerView.ViewHolder(binding.root) interface OnItemClickCallback { fun onItemClicked(data: Dino) } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/ListDinoAdapter.kt
1072511542
package com.ifs21001.pampraktikum8 import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter class NotificationPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) { var info1 = "" var info2 = "" override fun createFragment(position: Int): Fragment { val fragment = DetailFragment() fragment.arguments = Bundle().apply { when (position) { 0 -> putString(DetailFragment.EXTRA_INFO, info1) 1 -> putString(DetailFragment.EXTRA_INFO, info2) } } return fragment } override fun getItemCount(): Int { return 2 } }
fragment-dan-navigation-WhatsApp-/app/src/main/java/com/ifs21001/pampraktikum8/NotificationPagerAdapter.kt
1612201551
package com.ispc.tallerandroid 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.ispc.tallerandroid", appContext.packageName) } }
TallerKotlin/app/src/androidTest/java/com/ispc/tallerandroid/ExampleInstrumentedTest.kt
3202640021
package com.ispc.tallerandroid 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) } }
TallerKotlin/app/src/test/java/com/ispc/tallerandroid/ExampleUnitTest.kt
372780154
package com.ispc.tallerandroid import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText class MainActivity : AppCompatActivity() { private lateinit var etUser: EditText private lateinit var etPassword: EditText private lateinit var btnLogin: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) etUser = findViewById(R.id.et_user) etPassword = findViewById(R.id.et_password) btnLogin = findViewById(R.id.btn_login) btnLogin.setOnClickListener { val intent = Intent(this, MainActivity2::class.java) intent.putExtra("user", etUser.text.toString()) intent.putExtra("password", etPassword.text.toString()) startActivity(intent) } } }
TallerKotlin/app/src/main/java/com/ispc/tallerandroid/MainActivity.kt
4325331
package com.ispc.tallerandroid import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView class MainActivity2 : AppCompatActivity() { private lateinit var tvUser: TextView private lateinit var tvPassword: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main2) tvUser = findViewById(R.id.tv_user) tvPassword = findViewById(R.id.tv_password) val data = intent.extras tvUser.text = data?.getString("user") tvPassword.text = data?.getString("password") } }
TallerKotlin/app/src/main/java/com/ispc/tallerandroid/MainActivity2.kt
1230459021
package io.seerviashish.android.leasemint 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("io.seerviashish.android.leasemint", appContext.packageName) } }
LeaseMint/app/src/androidTest/java/io/seerviashish/android/leasemint/ExampleInstrumentedTest.kt
1514127525
package io.seerviashish.android.leasemint 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) } }
LeaseMint/app/src/test/java/io/seerviashish/android/leasemint/ExampleUnitTest.kt
3785514799
package io.seerviashish.android.leasemint.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)
LeaseMint/app/src/main/java/io/seerviashish/android/leasemint/ui/theme/Color.kt
1521438773
package io.seerviashish.android.leasemint.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 LeaseMintTheme( 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 ) }
LeaseMint/app/src/main/java/io/seerviashish/android/leasemint/ui/theme/Theme.kt
2103964839
package io.seerviashish.android.leasemint.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 ) */ )
LeaseMint/app/src/main/java/io/seerviashish/android/leasemint/ui/theme/Type.kt
340509449
package io.seerviashish.android.leasemint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import io.seerviashish.android.leasemint.ui.theme.LeaseMintTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LeaseMintTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { LeaseMintTheme { Greeting("Android") } }
LeaseMint/app/src/main/java/io/seerviashish/android/leasemint/MainActivity.kt
3784782139
package com.vitacc.vit 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.vitacc.vit", appContext.packageName) } }
Basic_Calculator-Kotlin_App/app/src/androidTest/java/com/vitacc/vit/ExampleInstrumentedTest.kt
2229771519
package com.vitacc.vit 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) } }
Basic_Calculator-Kotlin_App/app/src/test/java/com/vitacc/vit/ExampleUnitTest.kt
2857756789
package com.vitacc.vit import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import android.view.View import android.widget.Button import android.widget.TextView import kotlin.time.times class MainActivity : AppCompatActivity() { private var type: Int = 5 private var num2:Int = 0 private var ans: Int = 1 private var canaddition = false private var decimal = true private lateinit var tv: TextView private lateinit var wv: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) tv= findViewById(R.id.result) wv= findViewById(R.id.working) // ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> // val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) // v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) // insets // } } fun erase(view:View){ wv.append("Erasing..") Thread.sleep(200) tv.text = "" wv.text="" } fun addition(view:View){ if(view is Button){ if(view.text == "."){ if(decimal){ wv.append(view.text) decimal = false } } else{ wv.append(view.text) } canaddition = true } } fun operation(view:View){ if(view is Button && canaddition){ canaddition = false decimal = true wv.append(view.text) } } fun backspace(view:View){ val length = wv.length() if(length>0){ // wv.text = "" wv.text = wv.text.subSequence(0,length-1) } } fun multiply(view: View){ try { ans = wv.text.toString().toIntOrNull() ?: 0 // tv.append(ans.toString()) wv.append("x") type = 3 } catch (nfe: NumberFormatException) { // not a valid int } wv.text = "" } fun add(view: View){ try { ans = wv.text.toString().toIntOrNull() ?: 0 type = 1 wv.append("+") } catch (nfe: NumberFormatException) { // not a valid int } wv.text = "" } fun subtract(view: View){ try { ans = wv.text.toString().toIntOrNull() ?: 0 type = 2 wv.append("-") } catch (nfe: NumberFormatException) { // not a valid int } wv.text = "" } fun divide(view: View){ try { ans = wv.text.toString().toIntOrNull() ?: 0 type = 4 wv.append("/") } catch (nfe: NumberFormatException) { // not a valid int } wv.text = "" } fun percentage(view: View){ ans = wv.text.toString().toIntOrNull() ?: 0 wv.text ="" tv.text="" tv.append((ans.toFloat()/100).toString()) type = 5 } fun equalsAction(view: View) { num2 = wv.text.toString().toIntOrNull() ?: 0 wv.text = "" tv.text="" if(type == 1){ tv.append((ans + num2).toString()) } else if(type == 2){ tv.append((ans - num2).toString()) } else if(type == 3){ tv.append((ans * num2).toString()) } else if(type == 4){ if(num2==0){ tv.append("Invalid") } else tv.append((ans / num2).toString()) } } }
Basic_Calculator-Kotlin_App/app/src/main/java/com/vitacc/vit/MainActivity.kt
2944816933
package ru.alexadler9.weatherfetcher.di import okhttp3.OkHttpClient import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepositoryImpl import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.WeatherApi import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.WeatherRemoteSource val networkModule = module { single<OkHttpClient> { OkHttpClient.Builder() .build() } single<Retrofit> { Retrofit.Builder() .baseUrl(BuildConfig.WEATHER_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(get<OkHttpClient>()) .build() } single<WeatherApi> { get<Retrofit>().create(WeatherApi::class.java) } single<WeatherRemoteSource> { WeatherRemoteSource(get<WeatherApi>()) } single<WeatherRepository> { WeatherRepositoryImpl(get<WeatherRemoteSource>()) } }
weather-fetcher/app/src/prod/java/ru/alexadler9/weatherfetcher/di/NetworkModule.kt
3810385195
package ru.alexadler9.weatherfetcher import android.text.InputType import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import org.hamcrest.Matchers.allOf import org.junit.Assert.* import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.MainActivity /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class InstrumentedTest { @get:Rule val rule = ActivityScenarioRule(MainActivity::class.java) @Test fun testInitialStateOfCitySearchViews() { onView(withId(R.id.etCitySearch)).check( matches( allOf( withEffectiveVisibility(Visibility.VISIBLE), isFocusable(), isClickable(), withInputType(InputType.TYPE_CLASS_TEXT), withText("") ) ) ) onView(withId(R.id.ivCitySearch)).check( matches( allOf( withEffectiveVisibility(Visibility.VISIBLE), isClickable() ) ) ) } @Test fun testSearchFieldFixesText() { onView(withId(R.id.etCitySearch)).perform(replaceText("Москва")) onView(withId(R.id.fragmentContainerView)).perform(click()) onView(withId(R.id.etCitySearch)).check(matches(withText("Москва"))) } @Test fun testSearchButtonAccessibility() { onView(withId(R.id.etCitySearch)).perform(replaceText("")) onView(withId(R.id.ivCitySearch)).check(matches(isNotEnabled())) onView(withId(R.id.etCitySearch)).perform(replaceText("Москва")) onView(withId(R.id.ivCitySearch)).check(matches(isEnabled())) } @Test fun testWeatherLoadedSuccessfully() { // For testing, use the "mock" version of the application onView( allOf( withId(R.id.weatherFragment), isDescendantOfA(withId(R.id.fragmentContainerView)) ) ).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) onView(withId(R.id.etCitySearch)).perform(replaceText("Москва")) onView(withId(R.id.ivCitySearch)).perform(click()) onView(withId(R.id.layoutWeather)).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) } @Test fun testForecastLoadedSuccessfully() { // For testing, use the "mock" version of the application onView( allOf( withId(R.id.forecastFragment), isDescendantOfA(withId(R.id.bottomNav)) ) ).perform(click()) onView( allOf( withId(R.id.forecastFragment), isDescendantOfA(withId(R.id.fragmentContainerView)) ) ).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) onView(withId(R.id.etCitySearch)).perform(replaceText("Москва")) onView(withId(R.id.ivCitySearch)).perform(click()) onView(withId(R.id.rvForecasts)).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) } @Test fun testCityNotFound() { // For testing, use the "mock" version of the application onView( allOf( withId(R.id.weatherFragment), isDescendantOfA(withId(R.id.fragmentContainerView)) ) ).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) onView(withId(R.id.etCitySearch)).perform(replaceText("undefined")) onView(withId(R.id.ivCitySearch)).perform(click()) onView(withId(R.id.layoutNotFound)).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) } @Test fun testDataLoadError() { // For testing, use the "mock" version of the application onView( allOf( withId(R.id.weatherFragment), isDescendantOfA(withId(R.id.fragmentContainerView)) ) ).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) onView(withId(R.id.etCitySearch)).perform(replaceText("error")) onView(withId(R.id.ivCitySearch)).perform(click()) onView(withId(R.id.layoutError)).check(matches(withEffectiveVisibility(Visibility.VISIBLE))) } }
weather-fetcher/app/src/androidTest/java/ru/alexadler9/weatherfetcher/InstrumentedTest.kt
3748940366
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito.* import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.WeatherInteractor import ru.alexadler9.weatherfetcher.utility.* import ru.alexadler9.weatherfetcher.utility.ext.CoroutinesTestExtension import ru.alexadler9.weatherfetcher.utility.ext.InstantExecutorExtension @ExtendWith(InstantExecutorExtension::class, CoroutinesTestExtension::class) class WeatherFragmentViewModelTest { private lateinit var weatherRepository: WeatherRepository private lateinit var preferencesRepository: PreferencesRepository private lateinit var weatherInteractor: WeatherInteractor private lateinit var subject: WeatherViewModel @BeforeEach fun setUp() { weatherRepository = mock(WeatherRepository::class.java) preferencesRepository = mock(PreferencesRepository::class.java) weatherInteractor = WeatherInteractor(weatherRepository, preferencesRepository) // subject = WeatherViewModel(weatherInteractor) } /* runTest is a coroutine builder designed for testing. Use this to wrap any tests that include coroutines */ @Test fun `successful loading of weather data`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_1)) `when`(weatherRepository.getWeather(anyString(), anyString())).thenReturn(WEATHER_MODEL) subject = WeatherViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_1) verify(weatherRepository, times(1)).getWeather( GEO_MODEL_1.latitude.toString(), GEO_MODEL_1.longitude.toString() ) assertEquals(subject.viewState.value.city, CITY_NAME_1) assertEquals(subject.viewState.value.state is State.Content, true) assertEquals(subject.viewState.value.state as State.Content, State.Content(WEATHER_MODEL)) } @Test fun `successfully updates the city field`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_1)) `when`(weatherRepository.getWeather(anyString(), anyString())).thenReturn(WEATHER_MODEL) subject = WeatherViewModel(weatherInteractor) assertEquals(subject.viewState.value.cityEditable, "") subject.processUiAction(UiAction.OnCitySearchEdited(CITY_NAME_2)) assertEquals(subject.viewState.value.cityEditable, CITY_NAME_2) } @Test fun `successful city update with weather data loading`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_2)) `when`(weatherRepository.getWeather(anyString(), anyString())).thenReturn(WEATHER_MODEL) subject = WeatherViewModel(weatherInteractor) assertEquals(subject.viewState.value.city, CITY_NAME_1) subject.processUiAction(UiAction.OnCitySearchEdited(CITY_NAME_2)) subject.processUiAction(UiAction.OnCitySearchButtonClicked) // Loads 2 times: first load is for CITY_NAME_1 in the init block, the second is for CITY_NAME_2 verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_2) verify(weatherRepository, times(1)).getWeather( GEO_MODEL_2.latitude.toString(), GEO_MODEL_2.longitude.toString() ) assertEquals(subject.viewState.value.city, CITY_NAME_2) assertEquals(subject.viewState.value.cityEditable, "") assertEquals(subject.viewState.value.state is State.Content, true) assertEquals(subject.viewState.value.state as State.Content, State.Content(WEATHER_MODEL)) } @Test fun `specified city was not found`() = runTest { val exception = RuntimeException("Failed to connect") `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_INCORRECT) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(emptyList()) `when`(weatherRepository.getWeather(anyString(), anyString())).thenThrow(exception) subject = WeatherViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_INCORRECT) verify(weatherRepository, times(0)).getWeather(anyString(), anyString()) assertEquals(subject.viewState.value.city, CITY_NAME_INCORRECT) assertEquals(subject.viewState.value.state is State.NotFound, true) } @Test fun `weather data load failed`() = runTest { val exception = RuntimeException("Failed to connect") `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenThrow(exception) `when`(weatherRepository.getWeather(anyString(), anyString())).thenThrow(exception) subject = WeatherViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_1) verify(weatherRepository, times(0)).getWeather(anyString(), anyString()) assertEquals(subject.viewState.value.city, CITY_NAME_1) assertEquals(subject.viewState.value.state is State.Error, true) assertEquals(subject.viewState.value.state as State.Error, State.Error(exception)) } }
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/weatherfragment/WeatherFragmentViewModelTest.kt
2601993321
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.* import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.WeatherInteractor import ru.alexadler9.weatherfetcher.utility.* import ru.alexadler9.weatherfetcher.utility.ext.CoroutinesTestExtension import ru.alexadler9.weatherfetcher.utility.ext.InstantExecutorExtension @ExtendWith(InstantExecutorExtension::class, CoroutinesTestExtension::class) class ForecastFragmentViewModelTest { private lateinit var weatherRepository: WeatherRepository private lateinit var preferencesRepository: PreferencesRepository private lateinit var weatherInteractor: WeatherInteractor private lateinit var subject: ForecastViewModel @BeforeEach fun setUp() { weatherRepository = mock(WeatherRepository::class.java) preferencesRepository = mock(PreferencesRepository::class.java) weatherInteractor = WeatherInteractor(weatherRepository, preferencesRepository) // subject = ForecastViewModel(weatherInteractor) } /* runTest is a coroutine builder designed for testing. Use this to wrap any tests that include coroutines */ @Test fun `successful loading of forecast data`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_1)) `when`(weatherRepository.getForecast(anyString(), anyString())).thenReturn(FORECAST_MODEL) subject = ForecastViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_1) verify(weatherRepository, times(1)).getForecast( GEO_MODEL_1.latitude.toString(), GEO_MODEL_1.longitude.toString() ) assertEquals(subject.viewState.value.city, CITY_NAME_1) assertEquals(subject.viewState.value.state is State.Content, true) assertEquals(subject.viewState.value.state as State.Content, State.Content(FORECAST_MODEL)) } @Test fun `successfully updates the city field`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_1)) `when`(weatherRepository.getForecast(anyString(), anyString())).thenReturn(FORECAST_MODEL) subject = ForecastViewModel(weatherInteractor) assertEquals(subject.viewState.value.cityEditable, "") subject.processUiAction(UiAction.OnCitySearchEdited(CITY_NAME_2)) assertEquals(subject.viewState.value.cityEditable, CITY_NAME_2) } @Test fun `successful city update with weather data loading`() = runTest { `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(listOf(GEO_MODEL_2)) `when`(weatherRepository.getForecast(anyString(), anyString())).thenReturn(FORECAST_MODEL) subject = ForecastViewModel(weatherInteractor) assertEquals(subject.viewState.value.city, CITY_NAME_1) subject.processUiAction(UiAction.OnCitySearchEdited(CITY_NAME_2)) subject.processUiAction(UiAction.OnCitySearchButtonClicked) // Loads 2 times: first load is for CITY_NAME_1 in the init block, the second is for CITY_NAME_2 verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_2) verify(weatherRepository, times(1)).getForecast( GEO_MODEL_2.latitude.toString(), GEO_MODEL_2.longitude.toString() ) assertEquals(subject.viewState.value.city, CITY_NAME_2) assertEquals(subject.viewState.value.cityEditable, "") assertEquals(subject.viewState.value.state is State.Content, true) assertEquals(subject.viewState.value.state as State.Content, State.Content(FORECAST_MODEL)) } @Test fun `specified city was not found`() = runTest { val exception = RuntimeException("Failed to connect") `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_INCORRECT) `when`(weatherRepository.getCoordinates(anyString())).thenReturn(emptyList()) `when`(weatherRepository.getForecast(anyString(), anyString())).thenThrow(exception) subject = ForecastViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_INCORRECT) verify(weatherRepository, times(0)).getWeather(anyString(), anyString()) assertEquals(subject.viewState.value.city, CITY_NAME_INCORRECT) assertEquals(subject.viewState.value.state is State.NotFound, true) } @Test fun `weather data load failed`() = runTest { val exception = RuntimeException("Failed to connect") `when`(preferencesRepository.getCity()).thenReturn(CITY_NAME_1) `when`(weatherRepository.getCoordinates(anyString())).thenThrow(exception) `when`(weatherRepository.getForecast(anyString(), anyString())).thenThrow(exception) subject = ForecastViewModel(weatherInteractor) verify(weatherRepository, times(1)).getCoordinates(CITY_NAME_1) verify(weatherRepository, times(0)).getForecast(anyString(), anyString()) assertEquals(subject.viewState.value.city, CITY_NAME_1) assertEquals(subject.viewState.value.state is State.Error, true) assertEquals(subject.viewState.value.state as State.Error, State.Error(exception)) } }
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/forecastfragment/ForecastFragmentViewModelTest.kt
39548823
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.greaterThanOrEqualTo import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastCityRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastWeatherRemoteModel import ru.alexadler9.weatherfetcher.utility.FORECAST_WEATHER_REMOTE_MODEL import ru.alexadler9.weatherfetcher.utility.GEO_REMOTE_MODEL import ru.alexadler9.weatherfetcher.utility.WEATHER_REMOTE_MODEL class MapperKtTest { @Test fun `converts remote weather model into a local`() { val weatherModel = WEATHER_REMOTE_MODEL.toDomain() assertEquals(weatherModel.datetime, "01.01.2024 12:00") assertEquals(weatherModel.temp, WEATHER_REMOTE_MODEL.main.temp) assertEquals(weatherModel.tempFeelsLike, WEATHER_REMOTE_MODEL.main.tempFeelsLike) assertEquals(weatherModel.humidity, WEATHER_REMOTE_MODEL.main.humidity) assertEquals(weatherModel.windSpeed, WEATHER_REMOTE_MODEL.wind.speed) assertThat(weatherModel.details.size, greaterThanOrEqualTo(1)) assertEquals(weatherModel.details.size, WEATHER_REMOTE_MODEL.details.size) assertEquals( weatherModel.details.first().description, WEATHER_REMOTE_MODEL.details.first().description ) assertEquals( weatherModel.details.first().icon, BuildConfig.WEATHER_ICON_URL.format(WEATHER_REMOTE_MODEL.details.first().icon) ) } @Test fun `converts forecast-every-three-hours into a forecast-daily for the next three days`() { val listForecastWeatherRemoteModel = mutableListOf<ForecastWeatherRemoteModel>() for (i in 0..40) { // Change dt parameter with 3-hour step // As a result, we get a 5-day forecast including weather data with 3-hour step listForecastWeatherRemoteModel.add( FORECAST_WEATHER_REMOTE_MODEL.copy(dt = FORECAST_WEATHER_REMOTE_MODEL.dt + i * 10800) ) } val forecastRemoteModel = ForecastRemoteModel( cnt = 40, city = ForecastCityRemoteModel(timezone = 0), weather = listForecastWeatherRemoteModel ) val forecastModel = forecastRemoteModel.toDomain() assertEquals(forecastModel.weather.size, 3) assertEquals(forecastModel.weather[0].date, "2 янв.") assertEquals(forecastModel.weather[1].date, "3 янв.") assertEquals(forecastModel.weather[2].date, "4 янв.") } @Test fun `converts remote geo model into a local`() { val geoModel = GEO_REMOTE_MODEL.toDomain() assertEquals(geoModel.latitude, GEO_REMOTE_MODEL.lat) assertEquals(geoModel.longitude, GEO_REMOTE_MODEL.lon) assertEquals(geoModel.country, GEO_REMOTE_MODEL.country) assertEquals(geoModel.localNames, GEO_REMOTE_MODEL.localNames) } }
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/MapperKtTest.kt
2833417907
package ru.alexadler9.weatherfetcher.utility.ext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext /** * Implements TestDispatchers when using coroutines. TestDispatchers are CoroutineDispatcher implementations for testing purposes. * It is necessary to use TestDispatchers if new coroutines are created during the test (or coroutines are used inside test objects) * being tested to make the execution of the new coroutines predictable. */ @OptIn(ExperimentalCoroutinesApi::class) class CoroutinesTestExtension( private val dispatcher: TestDispatcher = UnconfinedTestDispatcher() ) : BeforeEachCallback, AfterEachCallback { override fun beforeEach(context: ExtensionContext?) { Dispatchers.setMain(dispatcher) } override fun afterEach(context: ExtensionContext?) { Dispatchers.resetMain() } }
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/utility/ext/CoroutinesTestExtension.kt
2918916436
package ru.alexadler9.weatherfetcher.utility.ext import androidx.arch.core.executor.ArchTaskExecutor import androidx.arch.core.executor.TaskExecutor import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext /** * Executes each task synchronously. For tests and required for LiveData to function deterministically. * - set a delegate before each test that updates live data values immediately on the calling thread. * - remove the delegate after each tests to avoid influencing other tests. */ class InstantExecutorExtension : BeforeEachCallback, AfterEachCallback { override fun beforeEach(context: ExtensionContext?) { ArchTaskExecutor.getInstance() .setDelegate(object : TaskExecutor() { override fun executeOnDiskIO(runnable: Runnable) = runnable.run() override fun postToMainThread(runnable: Runnable) = runnable.run() override fun isMainThread(): Boolean = true }) } override fun afterEach(context: ExtensionContext?) { ArchTaskExecutor.getInstance().setDelegate(null) } }
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/utility/ext/InstantExecutorExtension.kt
508562697
package ru.alexadler9.weatherfetcher.utility import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.* import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.* const val CITY_NAME_INCORRECT = "123456" const val CITY_NAME_1 = "Москва" const val CITY_NAME_2 = "Челябинск" val GEO_MODEL_1 = GeoModel( latitude = 55.761665, longitude = 37.606667, country = "RU", localNames = mapOf("ru" to CITY_NAME_1) ) val GEO_MODEL_2 = GeoModel( latitude = 61.429722, longitude = 55.154442, country = "RU", localNames = mapOf("ru" to CITY_NAME_2) ) val WEATHER_MODEL = WeatherModel( datetime = "01.01.2024 12:00", temp = "0.00", tempFeelsLike = "-2.00", humidity = "23", windSpeed = "2", details = listOf( WeatherDetailsModel( description = "ясно", icon = BuildConfig.WEATHER_ICON_URL.format("01") ) ) ) val FORECAST_MODEL = ForecastModel( listOf( ForecastWeatherModel( date = "1 янв.", dayOfWeek = "ПН", tempDay = "0.00", tempNight = "0.00", humidity = "23", windSpeed = "2", details = listOf( WeatherDetailsModel( description = "ясно", icon = BuildConfig.WEATHER_ICON_URL.format("01") ) ) ) ) ) val WEATHER_REMOTE_MODEL = WeatherRemoteModel( dt = 1704110400, timezone = 0, main = WeatherMainRemoteModel( temp = "20.00", tempFeelsLike = "18.75", humidity = "23" ), wind = WeatherWindRemoteModel( speed = "2" ), details = listOf( WeatherDetailsRemoteModel( id = 0, main = "Ясно", description = "Ясно", icon = "01" ) ) ) val FORECAST_WEATHER_REMOTE_MODEL = ForecastWeatherRemoteModel( dt = 1704110400, main = WeatherMainRemoteModel( temp = "20.00", tempFeelsLike = "18.75", humidity = "23" ), wind = WeatherWindRemoteModel( speed = "2" ), details = listOf( WeatherDetailsRemoteModel( id = 0, main = "Ясно", description = "Ясно", icon = "01" ) ) ) val GEO_REMOTE_MODEL = GeoRemoteModel( name = "Москва", localNames = mapOf("ru" to "Москва"), lat = 55.761665, lon = 37.606667, country = "RU" )
weather-fetcher/app/src/test/java/ru/alexadler9/weatherfetcher/utility/Constants.kt
2259843156
package ru.alexadler9.weatherfetcher.di import okhttp3.OkHttpClient import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepositoryImpl import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.WeatherApi import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.WeatherRemoteSource import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.mock.MockingInterceptor import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.mock.RequestsHandler val networkModule = module { single<OkHttpClient> { OkHttpClient.Builder() .addInterceptor(MockingInterceptor(get<RequestsHandler>())) .build() } single<Retrofit> { Retrofit.Builder() .baseUrl(BuildConfig.WEATHER_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(get<OkHttpClient>()) .build() } single<RequestsHandler> { RequestsHandler(androidContext(), get<PreferencesRepository>()) } single<WeatherApi> { get<Retrofit>().create(WeatherApi::class.java) } single<WeatherRemoteSource> { WeatherRemoteSource(get<WeatherApi>()) } single<WeatherRepository> { WeatherRepositoryImpl(get<WeatherRemoteSource>()) } }
weather-fetcher/app/src/mock/java/ru/alexadler9/weatherfetcher/di/NetworkModule.kt
382648654
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.mock import okhttp3.* import okio.Buffer import java.io.InputStream private val EMPTY_BODY = ByteArray(0) private val APPLICATION_JSON: MediaType = MediaType.parse("application/json")!! fun successResponse(request: Request, stream: InputStream): Response { val buffer: Buffer = Buffer().readFrom(stream) return Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(200) .message("OK") .body(ResponseBody.create(APPLICATION_JSON, buffer.size(), buffer)) .build() } fun errorResponse(request: Request, code: Int, message: String): Response { return Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(code) .message(message) .body(ResponseBody.create(APPLICATION_JSON, EMPTY_BODY)) .build() }
weather-fetcher/app/src/mock/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/mock/OkHttpResponse.kt
261305705
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.mock import android.os.SystemClock import okhttp3.Interceptor import okhttp3.Response /** * Intercepts and processes requests. */ class MockingInterceptor(private val requestHandler: RequestsHandler) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val path = request.url().encodedPath() if (requestHandler.shouldIntercept(path)) { // Get a mock response val response = requestHandler.proceed(request, path) SystemClock.sleep(200) return response } return chain.proceed(request) } }
weather-fetcher/app/src/mock/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/mock/MockingInterceptor.kt
3899617985
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.mock import android.content.Context import okhttp3.Request import okhttp3.Response import ru.alexadler9.weatherfetcher.data.PreferencesRepository import java.io.IOException import java.io.InputStream /** * Determines which requests should be mocked using test responses. */ class RequestsHandler( private val context: Context, private val preferencesRepository: PreferencesRepository ) { // List of requests that will be mocked // Key is the intercepted request path, and value is the path to JSON file with the response private val responsesMap = mutableMapOf( "data/2.5/weather" to "weather.json", "data/2.5/forecast" to "forecast.json", "geo/1.0/direct" to "geo.json" ) /** * Determines whether the request should be intercepted. */ fun shouldIntercept(path: String): Boolean { for (interceptUrl in responsesMap.keys) { if (path.contains(interceptUrl)) { return true } } return false } fun proceed(request: Request, path: String): Response { when (preferencesRepository.getCity().lowercase()) { "error" -> { return errorResponse(request, 400, "Error for path " + path) } else -> { responsesMap.keys.forEach { if (path.contains(it)) { val mockResponsePath: String = responsesMap[it]!! return createResponseFromAssets(request, mockResponsePath) } } } } return errorResponse(request, 500, "Incorrectly intercepted request") } /** * Creates a Response using a JSON file. */ private fun createResponseFromAssets( request: Request, assetPath: String ): Response { return try { val stream: InputStream = context.assets.open(assetPath) stream.use { successResponse(request, stream) } } catch (e: IOException) { errorResponse(request, 500, e.message ?: "IOException") } } }
weather-fetcher/app/src/mock/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/mock/RequestsHandler.kt
713673092
package ru.alexadler9.weatherfetcher import android.app.Application import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import ru.alexadler9.weatherfetcher.di.networkModule import ru.alexadler9.weatherfetcher.di.prefsModule import ru.alexadler9.weatherfetcher.feature.weatherscreen.di.weatherModule class App : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@App) modules(prefsModule, networkModule, weatherModule) } } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/App.kt
2690854379
package ru.alexadler9.weatherfetcher.di import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.data.PreferencesRepositoryImpl import ru.alexadler9.weatherfetcher.data.local.AppPreferencesSource val prefsModule = module { single<AppPreferencesSource> { AppPreferencesSource(androidApplication()) } single<PreferencesRepository> { PreferencesRepositoryImpl(get<AppPreferencesSource>()) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/di/PrefsModule.kt
2948879351
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui /** * Contract coordinating UI control between MainActivity and Fragments. */ interface WeatherScreenContract { interface ActivityCallbacks { fun onCitySearchUpdated(text: String) } interface FragmentCallbacks { fun onCitySearchEdited(text: String) fun onCitySearchButtonClicked() } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/WeatherScreenContract.kt
1099098308
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui import android.os.Bundle import android.view.inputmethod.EditorInfo import androidx.appcompat.app.AppCompatActivity import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.commit import ru.alexadler9.weatherfetcher.R import ru.alexadler9.weatherfetcher.base.hideKeyboard import ru.alexadler9.weatherfetcher.base.toEditable import ru.alexadler9.weatherfetcher.databinding.ActivityMainBinding import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment.ForecastFragment import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment.WeatherFragment /** * The activity controls weather/forecast fragments. Also responsible for shared elements such as: * - location input field; * - location search button. */ class MainActivity : AppCompatActivity(), WeatherScreenContract.ActivityCallbacks { private lateinit var binding: ActivityMainBinding private val fragmentCallbacks: WeatherScreenContract.FragmentCallbacks? get() = supportFragmentManager.findFragmentById(R.id.fragmentContainerView).let { it as WeatherScreenContract.FragmentCallbacks? } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) with(binding) { bottomNav.setOnItemSelectedListener { when (it.itemId) { R.id.weatherFragment -> { selectTab(WeatherFragment()) } R.id.forecastFragment -> { selectTab(ForecastFragment()) } else -> {} } true } etCitySearch.setOnFocusChangeListener { view, hasFocus -> if (!hasFocus) { hideKeyboard() } } etCitySearch.doAfterTextChanged { text -> fragmentCallbacks?.onCitySearchEdited(text.toString()) } val search = { fragmentCallbacks?.onCitySearchButtonClicked() etCitySearch.clearFocus() } etCitySearch.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_SEARCH && etCitySearch.text.isNotEmpty()) { search() return@setOnEditorActionListener true } return@setOnEditorActionListener false } ivCitySearch.setOnClickListener { search() } } } private fun selectTab(fragment: Fragment) { supportFragmentManager.commit { replace(R.id.fragmentContainerView, fragment) } } override fun onCitySearchUpdated(text: String) { if (binding.etCitySearch.text.toString() != text) { binding.etCitySearch.text = text.toEditable() } binding.ivCitySearch.isEnabled = text.isNotEmpty() } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/MainActivity.kt
3878950754
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import ru.alexadler9.weatherfetcher.base.Action import ru.alexadler9.weatherfetcher.base.BaseViewModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.WeatherInteractor class WeatherViewModel(private val interactor: WeatherInteractor) : BaseViewModel<ViewState, ViewEvent>() { override val initialViewState = ViewState( cityEditable = "", city = interactor.getCity(), state = State.Load ) init { weatherLoad(interactor.getCity()) } override fun reduce(action: Action, previousState: ViewState): ViewState? { return when (action) { is UiAction.OnUpdateButtonClicked -> { weatherLoad(previousState.city) previousState.copy(state = State.Load) } is UiAction.OnCitySearchEdited -> { previousState.copy(cityEditable = action.text) } is UiAction.OnCitySearchButtonClicked -> { interactor.setCity(previousState.cityEditable) weatherLoad(previousState.cityEditable) previousState.copy( cityEditable = "", city = previousState.cityEditable, state = State.Load ) } is DataAction.OnWeatherLoadSucceed -> { previousState.copy(state = State.Content(action.weatherModel)) } is DataAction.OnWeatherLoadFailed -> { previousState.copy(state = State.Error(action.error)) } is DataAction.OnWeatherNotFound -> { previousState.copy(state = State.NotFound) } else -> null } } private fun weatherLoad(city: String) = viewModelScope.launch { interactor.getCoordinates(city).fold( onError = { processDataAction(DataAction.OnWeatherLoadFailed(error = it)) }, onSuccess = { geoModel -> if (geoModel.isEmpty() || !geoModel.first().localNames.containsKey("ru") || !geoModel.first().localNames["ru"].equals(city, true) ) { processDataAction(DataAction.OnWeatherNotFound) } else { val geo = geoModel.first() interactor.getWeather( geo.latitude.toString(), geo.longitude.toString() ).fold( onError = { processDataAction(DataAction.OnWeatherLoadFailed(error = it)) }, onSuccess = { processDataAction(DataAction.OnWeatherLoadSucceed(weatherModel = it)) } ) } } ) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/weatherfragment/WeatherViewModel.kt
3008060625
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.koin.androidx.viewmodel.ext.android.viewModel import ru.alexadler9.weatherfetcher.R import ru.alexadler9.weatherfetcher.databinding.FragmentWeatherBinding import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.WeatherScreenContract /** * Fragment is responsible for loading and displaying the current weather for the specified location. */ class WeatherFragment : Fragment(), WeatherScreenContract.FragmentCallbacks { private val viewModel: WeatherViewModel by viewModel() private var hostCallbacks: WeatherScreenContract.ActivityCallbacks? = null private var _binding: FragmentWeatherBinding? = null private val binding get() = _binding!! override fun onAttach(context: Context) { super.onAttach(context) hostCallbacks = context as WeatherScreenContract.ActivityCallbacks? } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentWeatherBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.viewState .onEach(::render) .launchIn(viewLifecycleOwner.lifecycleScope) binding.fabWeatherUpdate.setOnClickListener { viewModel.processUiAction(UiAction.OnUpdateButtonClicked) } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onDetach() { super.onDetach() hostCallbacks = null } private fun render(viewState: ViewState) { hostCallbacks?.onCitySearchUpdated(viewState.cityEditable) with(binding) { tvCity.text = viewState.city.uppercase() when (viewState.state) { is State.Load -> { layoutError.isVisible = false layoutNotFound.isVisible = false pbWeather.isVisible = true fabWeatherUpdate.isEnabled = false tvDateTime.isVisible = false layoutWeather.isVisible = false } is State.Content -> { layoutError.isVisible = false layoutNotFound.isVisible = false pbWeather.isVisible = false fabWeatherUpdate.isEnabled = true tvDateTime.isVisible = true layoutWeather.isVisible = true val weather = viewState.state.weatherModel tvDateTime.text = weather.datetime tvDescription.text = if (weather.details.isEmpty()) "" else weather.details[0].description.uppercase() tvTemp.text = if (weather.temp.isEmpty()) "" else getString( R.string.temperature_value, weather.temp.toFloat() ).replace(',', '.') tvWindSpeed.text = if (weather.windSpeed.isEmpty()) "" else getString( R.string.wind_speed_value, weather.windSpeed.toFloat() ).replace(',', '.') tvHumidity.text = if (weather.humidity.isEmpty()) "" else getString( R.string.humidity_value, weather.humidity.toInt() ) tvTempFeelsLike.text = if (weather.tempFeelsLike.isEmpty()) "" else getString( R.string.temperature_value, weather.tempFeelsLike.toFloat() ).replace(',', '.') } is State.Error, is State.NotFound -> { layoutError.isVisible = viewState.state is State.Error layoutNotFound.isVisible = viewState.state is State.NotFound pbWeather.isVisible = false fabWeatherUpdate.isEnabled = true layoutWeather.isVisible = false tvDateTime.isVisible = false layoutWeather.isVisible = false } } } } override fun onCitySearchEdited(text: String) { viewModel.processUiAction(UiAction.OnCitySearchEdited(text)) } override fun onCitySearchButtonClicked() { viewModel.processUiAction(UiAction.OnCitySearchButtonClicked) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/weatherfragment/WeatherFragment.kt
1767763113
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment import ru.alexadler9.weatherfetcher.base.Action import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.WeatherModel sealed class State { object Load : State() data class Content(val weatherModel: WeatherModel) : State() data class Error(val throwable: Throwable) : State() object NotFound : State() } data class ViewState( val cityEditable: String, val city: String, val state: State ) sealed class ViewEvent { } sealed class UiAction() : Action { data class OnCitySearchEdited(val text: String) : UiAction() object OnCitySearchButtonClicked : UiAction() object OnUpdateButtonClicked : UiAction() } sealed class DataAction() : Action { data class OnWeatherLoadSucceed(val weatherModel: WeatherModel) : DataAction() data class OnWeatherLoadFailed(val error: Throwable) : DataAction() object OnWeatherNotFound : DataAction() }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/weatherfragment/Contract.kt
2104494663
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.koin.androidx.viewmodel.ext.android.viewModel import ru.alexadler9.weatherfetcher.databinding.FragmentForecastBinding import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.WeatherScreenContract /** * Fragment is responsible for loading and displaying the list of daily forecasts for the specified location. */ class ForecastFragment : Fragment(), WeatherScreenContract.FragmentCallbacks { private val viewModel: ForecastViewModel by viewModel() private var hostCallbacks: WeatherScreenContract.ActivityCallbacks? = null private var _binding: FragmentForecastBinding? = null private val binding get() = _binding!! private val forecastsAdapter: ForecastsAdapter by lazy { ForecastsAdapter() } override fun onAttach(context: Context) { super.onAttach(context) hostCallbacks = context as WeatherScreenContract.ActivityCallbacks? } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentForecastBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.rvForecasts.adapter = forecastsAdapter viewModel.viewState .onEach(::render) .launchIn(viewLifecycleOwner.lifecycleScope) binding.fabForecastUpdate.setOnClickListener { viewModel.processUiAction(UiAction.OnUpdateButtonClicked) } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onDetach() { super.onDetach() hostCallbacks = null } private fun render(viewState: ViewState) { hostCallbacks?.onCitySearchUpdated(viewState.cityEditable) with(binding) { tvCity.text = viewState.city.uppercase() when (viewState.state) { is State.Load -> { layoutError.isVisible = false layoutNotFound.isVisible = false pbForecast.isVisible = true fabForecastUpdate.isEnabled = false rvForecasts.isVisible = false } is State.Content -> { layoutError.isVisible = false layoutNotFound.isVisible = false pbForecast.isVisible = false fabForecastUpdate.isEnabled = true rvForecasts.isVisible = true val forecast = viewState.state.forecastModel forecastsAdapter.data = forecast.weather } is State.Error, is State.NotFound -> { layoutError.isVisible = viewState.state is State.Error layoutNotFound.isVisible = viewState.state is State.NotFound pbForecast.isVisible = false fabForecastUpdate.isEnabled = true rvForecasts.isVisible = false } } } } override fun onCitySearchEdited(text: String) { viewModel.processUiAction(UiAction.OnCitySearchEdited(text)) } override fun onCitySearchButtonClicked() { viewModel.processUiAction(UiAction.OnCitySearchButtonClicked) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/forecastfragment/ForecastFragment.kt
942321844
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import ru.alexadler9.weatherfetcher.R import ru.alexadler9.weatherfetcher.databinding.ItemForecastBinding import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.ForecastWeatherModel class ForecastsAdapter : RecyclerView.Adapter<ForecastsAdapter.ForecastViewHolder>() { var data = listOf<ForecastWeatherModel>() // No need to use DiffUtil @SuppressLint("NotifyDataSetChanged") set(value) { field = value notifyDataSetChanged() } class ForecastViewHolder(private val binding: ItemForecastBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: ForecastWeatherModel) { with(binding) { tvDayOfWeek.text = item.dayOfWeek.uppercase() tvDate.text = item.date tvDayTemp.text = root.context.getString( R.string.temperature_value, item.tempDay.toFloat() ).replace(',', '.') tvNightTemp.text = root.context.getString( R.string.temperature_value, item.tempNight.toFloat() ).replace(',', '.') Glide.with(root.context) .load(item.details.first().icon) .circleCrop() .placeholder(R.drawable.ic_baseline_image_search_24) .into(ivIcon) } } companion object { fun inflateFrom(parent: ViewGroup): ForecastViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = ItemForecastBinding.inflate(layoutInflater, parent, false) return ForecastViewHolder(binding) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForecastViewHolder { return ForecastViewHolder.inflateFrom(parent) } override fun onBindViewHolder(holder: ForecastViewHolder, position: Int) { val item = data[position] holder.bind(item) } override fun getItemCount() = data.size }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/forecastfragment/ForecastsAdapter.kt
1558363488
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment import ru.alexadler9.weatherfetcher.base.Action import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.ForecastModel sealed class State { object Load : State() data class Content(val forecastModel: ForecastModel) : State() data class Error(val throwable: Throwable) : State() object NotFound : State() } data class ViewState( val cityEditable: String, val city: String, val state: State ) sealed class ViewEvent { } sealed class UiAction() : Action { data class OnCitySearchEdited(val text: String) : UiAction() object OnCitySearchButtonClicked : UiAction() object OnUpdateButtonClicked : UiAction() } sealed class DataAction() : Action { data class OnForecastLoadSucceed(val forecastModel: ForecastModel) : DataAction() data class OnForecastLoadFailed(val error: Throwable) : DataAction() object OnForecastNotFound : DataAction() }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/forecastfragment/Contract.kt
2979615565
package ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import ru.alexadler9.weatherfetcher.base.Action import ru.alexadler9.weatherfetcher.base.BaseViewModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.WeatherInteractor class ForecastViewModel(private val interactor: WeatherInteractor) : BaseViewModel<ViewState, ViewEvent>() { override val initialViewState = ViewState( cityEditable = "", city = interactor.getCity(), state = State.Load ) init { forecastLoad(interactor.getCity()) } override fun reduce(action: Action, previousState: ViewState): ViewState? { return when (action) { is UiAction.OnUpdateButtonClicked -> { forecastLoad(previousState.city) previousState.copy(state = State.Load) } is UiAction.OnCitySearchEdited -> { previousState.copy(cityEditable = action.text) } is UiAction.OnCitySearchButtonClicked -> { interactor.setCity(previousState.cityEditable) forecastLoad(previousState.cityEditable) previousState.copy( cityEditable = "", city = previousState.cityEditable, state = State.Load ) } is DataAction.OnForecastLoadSucceed -> { previousState.copy(state = State.Content(action.forecastModel)) } is DataAction.OnForecastLoadFailed -> { previousState.copy(state = State.Error(action.error)) } is DataAction.OnForecastNotFound -> { previousState.copy(state = State.NotFound) } else -> null } } private fun forecastLoad(city: String) = viewModelScope.launch { interactor.getCoordinates(city).fold( onError = { processDataAction(DataAction.OnForecastLoadFailed(error = it)) }, onSuccess = { geoModel -> if (geoModel.isEmpty() || !geoModel.first().localNames.containsKey("ru") || !geoModel.first().localNames["ru"].equals(city, true) ) { processDataAction(DataAction.OnForecastNotFound) } else { val geo = geoModel.first() interactor.getForecast( geo.latitude.toString(), geo.longitude.toString() ).fold( onError = { processDataAction(DataAction.OnForecastLoadFailed(error = it)) }, onSuccess = { processDataAction(DataAction.OnForecastLoadSucceed(forecastModel = it)) } ) } } ) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/ui/forecastfragment/ForecastViewModel.kt
1396180143
package ru.alexadler9.weatherfetcher.feature.weatherscreen.di import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.WeatherInteractor import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.forecastfragment.ForecastViewModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.ui.weatherfragment.WeatherViewModel val weatherModule = module { single<WeatherInteractor> { WeatherInteractor( get<WeatherRepository>(), get<PreferencesRepository>() ) } viewModel<WeatherViewModel> { WeatherViewModel(get<WeatherInteractor>()) } viewModel<ForecastViewModel> { ForecastViewModel(get<WeatherInteractor>()) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/di/Module.kt
3789126030
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.ForecastModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.GeoModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.WeatherModel /** * Repository for working with weather data. */ interface WeatherRepository { /** * Get current weather data for any location. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getWeather(latitude: String, longitude: String): WeatherModel /** * Get a 3-day forecast for any location. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getForecast(latitude: String, longitude: String): ForecastModel /** * Get coordinates for a given geographical name. * Can return more than one element if the specified geographical name is present in multiple countries. * @param city City name, state code (only for the US) and country code divided by comma. */ suspend fun getCoordinates(city: String): List<GeoModel> }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/WeatherRepository.kt
296626736
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.WeatherRemoteSource class WeatherRepositoryImpl(private val weatherRemoteSource: WeatherRemoteSource) : WeatherRepository { override suspend fun getWeather(latitude: String, longitude: String) = weatherRemoteSource.getWeather(latitude, longitude).toDomain() override suspend fun getForecast(latitude: String, longitude: String) = weatherRemoteSource.getForecast(latitude, longitude).toDomain() override suspend fun getCoordinates(city: String) = weatherRemoteSource.getCoordinates(city).map { it.toDomain() } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/WeatherRepositoryImpl.kt
2840755095
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.GeoRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.WeatherRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.* import java.text.SimpleDateFormat import java.util.* /** * Mappers from remote weather models to local models. */ private const val DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm" private fun convertTimestampToDateString(timestamp: Long, pattern: String = DATE_TIME_PATTERN) = SimpleDateFormat(pattern, Locale.getDefault()) .apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(timestamp * 1000L)) private fun convertTimestampToCalendar(timestamp: Long) = GregorianCalendar.getInstance().apply { timeZone = TimeZone.getTimeZone("UTC") time = Date(timestamp * 1000L) } fun WeatherRemoteModel.toDomain() = WeatherModel( datetime = convertTimestampToDateString(this.dt + this.timezone), temp = this.main.temp, tempFeelsLike = this.main.tempFeelsLike, humidity = this.main.humidity, windSpeed = this.wind.speed, details = this.details.map { WeatherDetailsModel( description = it.description, icon = BuildConfig.WEATHER_ICON_URL.format(it.icon) ) } ) fun ForecastRemoteModel.toDomain(): ForecastModel { // Let's try to convert the forecast-every-three-hours into a forecast-daily for the next three days val dailyForecast: MutableList<ForecastWeatherModel> = mutableListOf() // Group hourly forecasts by day of the month val detailsForecast = this.weather.groupBy { convertTimestampToCalendar(it.dt + this.city.timezone)[Calendar.DAY_OF_MONTH] } for ((_, forecasts) in detailsForecast) { if (forecasts.size != 8) { // Forecast data is incomplete continue } val forecastNight = forecasts[0] val forecastDay = forecasts[4] val calendar = convertTimestampToCalendar(forecastDay.dt + this.city.timezone) dailyForecast.add( ForecastWeatherModel( date = "${calendar[Calendar.DAY_OF_MONTH]} ${ calendar.getDisplayName( Calendar.MONTH, Calendar.SHORT, Locale("ru") ) }", dayOfWeek = calendar.getDisplayName( Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale("ru") )!!, tempDay = forecastDay.main.temp, tempNight = forecastNight.main.temp, humidity = forecastDay.main.humidity, windSpeed = forecastDay.wind.speed, details = forecastDay.details.map { WeatherDetailsModel( description = it.description, icon = BuildConfig.WEATHER_ICON_URL.format(it.icon) ) } ) ) if (dailyForecast.size == 3) { break } } return ForecastModel(weather = dailyForecast) } fun GeoRemoteModel.toDomain() = GeoModel( latitude = this.lat, longitude = this.lon, country = this.country, localNames = this.localNames )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/Mapper.kt
960665913
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class ForecastWeatherRemoteModel( /** Time of data forecasted, unix, UTC. */ @SerializedName("dt") val dt: Long, /** Main weather data. */ @SerializedName("main") val main: WeatherMainRemoteModel, /** Wind data. */ @SerializedName("wind") val wind: WeatherWindRemoteModel, /** List of weather conditions data. */ @SerializedName("weather") val details: List<WeatherDetailsRemoteModel> )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/ForecastWeatherRemoteModel.kt
1013315945
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class GeoRemoteModel( /** Name of the found location. */ @SerializedName("name") val name: String, /** Name of the found location in different languages. Pairs of the type "language code - name". */ @SerializedName("local_names") val localNames: Map<String, String>, /** Geographical coordinates of the found location (latitude). */ @SerializedName("lat") val lat: Double, /** Geographical coordinates of the found location (longitude). */ @SerializedName("lon") val lon: Double, /** Country of the found location. */ @SerializedName("country") val country: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/GeoRemoteModel.kt
693856817
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class ForecastCityRemoteModel( /** Shift in seconds from UTC. */ @SerializedName("timezone") val timezone: Int )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/ForecastCityRemoteModel.kt
2935557023
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class WeatherDetailsRemoteModel( /** Weather condition id. */ @SerializedName("id") val id: Int, /** Group of weather parameters (Rain, Snow, Clouds etc.). */ @SerializedName("main") val main: String, /** Weather condition within the group. */ @SerializedName("description") val description: String, /** Weather icon id. */ @SerializedName("icon") val icon: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/WeatherDetailsRemoteModel.kt
3577971996
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class ForecastRemoteModel( /** A number of timestamps returned in the API response. */ @SerializedName("cnt") val cnt: Int, /** City data. */ @SerializedName("city") val city: ForecastCityRemoteModel, /** List of forecast data ([cnt] records with 3-hour step). */ @SerializedName("list") val weather: List<ForecastWeatherRemoteModel> )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/ForecastRemoteModel.kt
2760291878
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class WeatherMainRemoteModel( /** Temperature. */ @SerializedName("temp") val temp: String, /** Temperature. This temperature parameter accounts for the human perception of weather. */ @SerializedName("feels_like") val tempFeelsLike: String, /** Humidity, %. */ @SerializedName("humidity") val humidity: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/WeatherMainRemoteModel.kt
1607068704
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class WeatherWindRemoteModel( /** Wind speed. */ @SerializedName("speed") val speed: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/WeatherWindRemoteModel.kt
2168321208
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model import com.google.gson.annotations.SerializedName data class WeatherRemoteModel( /** Time of data calculation, unix, UTC. */ @SerializedName("dt") val dt: Long, /** Shift in seconds from UTC. */ @SerializedName("timezone") val timezone: Int, /** Main weather data. */ @SerializedName("main") val main: WeatherMainRemoteModel, /** Wind data. */ @SerializedName("wind") val wind: WeatherWindRemoteModel, /** List of weather conditions data. */ @SerializedName("weather") val details: List<WeatherDetailsRemoteModel> )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/model/WeatherRemoteModel.kt
3559017720
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.GeoRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.WeatherRemoteModel /** * Source for accessing the remote weather API. */ class WeatherRemoteSource(private val api: WeatherApi) { /** * Get current weather data for any location. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getWeather(latitude: String, longitude: String): WeatherRemoteModel { return api.getWeather( lat = latitude, lon = longitude ) } /** * Get a 5-day forecast including weather data with 3-hour step. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getForecast(latitude: String, longitude: String): ForecastRemoteModel { return api.getForecast( lat = latitude, lon = longitude ) } /** * Get coordinates for a given geographical name. * Can return more than one element if the specified geographical name is present in multiple countries. * @param city City name, state code (only for the US) and country code divided by comma. */ suspend fun getCoordinates(city: String): List<GeoRemoteModel> { return api.getCoordinates(city) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/WeatherRemoteSource.kt
4146538767
package ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote import retrofit2.http.GET import retrofit2.http.Query import ru.alexadler9.weatherfetcher.BuildConfig import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.ForecastRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.GeoRemoteModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.remote.model.WeatherRemoteModel /** * API for accessing weather data (based on OpenWeather API). */ interface WeatherApi { /** * Get current weather data for any location. * @param lat Latitude. * @param lon Longitude. * @param units Units of measurement. standard, metric and imperial units are available. * @param lang Output language. * @param apiKey Unique API key. */ @GET("data/2.5/weather") suspend fun getWeather( @Query("lat") lat: String, @Query("lon") lon: String, @Query("units") units: String = "metric", @Query("lang") lang: String = "ru", @Query("appid") apiKey: String = BuildConfig.WEATHER_API_KEY ): WeatherRemoteModel /** * Get a 5-day forecast including weather data with 3-hour step. * @param lat Latitude. * @param lon Longitude. * @param units Units of measurement. standard, metric and imperial units are available. * @param lang Output language. * @param apiKey Unique API key. */ @GET("data/2.5/forecast") suspend fun getForecast( @Query("lat") lat: String, @Query("lon") lon: String, @Query("units") units: String = "metric", @Query("lang") lang: String = "ru", @Query("appid") apiKey: String = BuildConfig.WEATHER_API_KEY ): ForecastRemoteModel /** * Get coordinates for a given geographical name. * @param city City name, state code (only for the US) and country code divided by comma. * @param apiKey Unique API key. */ @GET("geo/1.0/direct") suspend fun getCoordinates( @Query("q") city: String, @Query("appid") apiKey: String = BuildConfig.WEATHER_API_KEY ): List<GeoRemoteModel> }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/data/remote/WeatherApi.kt
1775697025
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain import ru.alexadler9.weatherfetcher.base.Either import ru.alexadler9.weatherfetcher.base.attempt import ru.alexadler9.weatherfetcher.data.PreferencesRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.data.WeatherRepository import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.ForecastModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.GeoModel import ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model.WeatherModel /** * Weather interactor. */ class WeatherInteractor( private val weatherRepository: WeatherRepository, private val preferencesRepository: PreferencesRepository ) { /** * Get current weather data for any location. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getWeather(latitude: String, longitude: String): Either<Throwable, WeatherModel> { return attempt { weatherRepository.getWeather(latitude, longitude) } } /** * Get a 3-day forecast for any location. * @param latitude Latitude. * @param longitude Longitude. */ suspend fun getForecast(latitude: String, longitude: String): Either<Throwable, ForecastModel> { return attempt { weatherRepository.getForecast(latitude, longitude) } } /** * Get coordinates for a given geographical name. * Can return more than one element if the specified geographical name is present in multiple countries. * @param city City name, state code (only for the US) and country code divided by comma. */ suspend fun getCoordinates(city: String): Either<Throwable, List<GeoModel>> { return attempt { weatherRepository.getCoordinates(city) } } /** * Get the last city specified by user. */ fun getCity() = preferencesRepository.getCity() /** * Save the city. * @param city City name. */ fun setCity(city: String) { preferencesRepository.setCity(city) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/WeatherInteractor.kt
1689575400
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model data class ForecastWeatherModel( /** Day and month of weather calculation (for example "1 дек."). */ val date: String = "", /** Day of the week (for example "ПН"). */ val dayOfWeek: String = "", /** Day temperature. */ val tempDay: String = "", /** Night temperature. */ val tempNight: String = "", /** Humidity. */ val humidity: String = "", /** Wind speed. */ val windSpeed: String = "", /** List of weather conditions data. */ val details: List<WeatherDetailsModel> = emptyList() )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/model/ForecastWeatherModel.kt
2917875951
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model data class WeatherDetailsModel( /** Weather condition within the group. */ val description: String, /** Weather icon url. */ val icon: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/model/WeatherDetailsModel.kt
118053761
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model data class ForecastModel( /** List of daily forecasts. */ val weather: List<ForecastWeatherModel> = emptyList() )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/model/ForecastModel.kt
824791777
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model data class GeoModel( /** Geographical coordinates of the found location (latitude). */ val latitude: Double, /** Geographical coordinates of the found location (longitude). */ val longitude: Double, /** Country of the found location. */ val country: String, /** Name of the found location in different languages. Pairs of the type "language code - name". */ val localNames: Map<String, String> )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/model/GeoModel.kt
2208091388
package ru.alexadler9.weatherfetcher.feature.weatherscreen.domain.model data class WeatherModel( /** Date and time of weather calculation (dd.MM.yyyy HH:mm). */ val datetime: String = "", /** Temperature. */ val temp: String = "", /** Temperature. This temperature parameter accounts for the human perception of weather. */ val tempFeelsLike: String = "", /** Humidity. */ val humidity: String = "", /** Wind speed. */ val windSpeed: String = "", /** List of weather conditions data. */ val details: List<WeatherDetailsModel> = emptyList() )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/feature/weatherscreen/domain/model/WeatherModel.kt
2791903077
package ru.alexadler9.weatherfetcher.data import ru.alexadler9.weatherfetcher.data.local.AppPreferencesSource class PreferencesRepositoryImpl(private val appPreferencesSource: AppPreferencesSource) : PreferencesRepository { override fun getCity() = appPreferencesSource.getCity() override fun setCity(city: String) { appPreferencesSource.setCity(city) } }
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/data/PreferencesRepositoryImpl.kt
1371533241
package ru.alexadler9.weatherfetcher.data.local import co.windly.ktxprefs.annotation.DefaultString import co.windly.ktxprefs.annotation.Prefs @Prefs(value = "AppPreferences") class AppPreferences( /** Last city specified by user. */ @DefaultString(value = "Москва") internal val city: String )
weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/data/local/AppPreferences.kt
591057286