path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
advent_of_code23/src/main/kotlin/org/rgoussey/aoc2023/day3/Main.kt | 3997070164 | package org.rgoussey.aoc2023.day3
import java.io.File
import kotlin.math.max
import kotlin.math.min
fun main() {
val lines = File({}.javaClass.getResource("/day3/input.txt")!!.toURI()).readLines();
process(lines);
}
fun process(lines: List<String>) {
val characters = mutableListOf<MutableList<Char>>()
val symbols = mutableListOf<MutableList<Boolean>>()
val numbers = mutableListOf<MutableList<Boolean>>()
val closeToSymbol = mutableListOf<MutableList<Boolean>>()
for (i in lines.indices) {
characters.add(i, mutableListOf())
symbols.add(i, mutableListOf())
numbers.add(i, mutableListOf())
closeToSymbol.add(i, mutableListOf())
for (j in lines[i].indices) {
val currentChar = lines[i][j]
characters[i].add(j, currentChar)
val isSymbol = isSymbol(currentChar)
symbols[i].add(j, isSymbol)
numbers[i].add(j, isNumber(currentChar))
}
}
for (i in lines.indices) {
for (j in lines[i].indices) {
closeToSymbol[i].add(j, adjacentToSymbol(symbols, i, j))
}
}
printMap(symbols)
printMap(numbers)
printMap(closeToSymbol)
var sum = 0;
for (i in characters.indices) {
var currentNumber = "";
var lastNumberIndex = 0;
var numberIsValid = false;
for (j in characters[i].indices) {
val isNumber = numbers[i][j]
if (isNumber) {
numberIsValid = numberIsValid or adjacentToSymbol(symbols, i, j)
lastNumberIndex = j
currentNumber += characters[i][j]
val endOfLine = j == characters[i].size-1
if (endOfLine) {
val number = Integer.parseInt(currentNumber)
if (numberIsValid) {
// println("Valid number $number")
sum += number;
} else {
// println(" Not valid number $number")
}
currentNumber = ""
lastNumberIndex = 0;
}
} else {
val numberEnded = lastNumberIndex + 1 == j
if (numberEnded && currentNumber != "") {
val number = Integer.parseInt(currentNumber)
// println("Number is detected %s".format(number))
if (numberIsValid) {
// println("Valid number $number")
sum += number;
} else {
// println(" Not valid number $number")
}
currentNumber = "";
numberIsValid=false
}
lastNumberIndex = 0;
}
}
}
println("Sum is $sum")
}
fun printMap(map: MutableList<MutableList<Boolean>>) {
for (i in map.indices) {
for (j in map[i].indices) {
if (map[i][j]) {
print('x')
} else {
print('.')
}
}
print("\n");
}
print("\n");
}
fun adjacentToSymbol(symbols: MutableList<MutableList<Boolean>>, x: Int, y: Int): Boolean {
for (i in max(x - 1, 0)..min(x + 1, symbols.size - 1)) {
for (j in max(y - 1, 0)..min(y + 1, symbols[x].size - 1)) {
if (symbols[i][j]) {
return true
}
}
}
return false;
}
fun isSymbol(char: Char): Boolean {
return !isNumber(char) && char != '.';
}
fun isNumber(char: Char): Boolean {
return char in '0'..'9';
}
|
MapPlatform/app/src/androidTest/java/com/hezd/test/ExampleInstrumentedTest.kt | 1320207124 | package com.hezd.test
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.hezd.mapplatform", appContext.packageName)
}
} |
MapPlatform/app/src/test/java/com/hezd/test/ExampleUnitTest.kt | 3074187498 | package com.hezd.test
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)
}
} |
MapPlatform/app/src/main/java/com/hezd/test/map/MainActivity.kt | 3345568243 | package com.hezd.test.map
import android.os.Bundle
import android.view.ViewGroup.LayoutParams
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.hezd.map.platform.CalcRoteError
import com.hezd.map.platform.Map
import com.hezd.map.platform.MapCalcRouteCallback
import com.hezd.map.platform.MapPlatform
import com.hezd.map.platform.bean.GCJLatLng
import com.hezd.map.platform.bean.PathInfo
import com.hezd.test.map.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var mapPlatform: MapPlatform
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initMap(savedInstanceState)
}
private fun initMap(savedInstanceState: Bundle?) {
mapPlatform = MapPlatform.Builder(Map.TencentMap())
.build()
mapPlatform.init(this,savedInstanceState)
val mapView = mapPlatform.getMapView(this)
val layoutParams = LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)
mapView.layoutParams = layoutParams
binding.mapLayout.addView(mapView)
mapPlatform.startCalculatePath(GCJLatLng(40.007056,116.389895), GCJLatLng(39.894551,116.321515),object :
MapCalcRouteCallback {
override fun onSuccess(paths: List<PathInfo>) {
if(paths.size>0){
mapPlatform.setRouteZoomToSpan(0)
}
}
override fun onError(calcRoteError: CalcRoteError) {
calcRoteError.errorCode
}
})
}
override fun onStart() {
super.onStart()
mapPlatform.onStart()
}
override fun onRestart() {
super.onRestart()
mapPlatform.onRestart()
}
override fun onResume() {
super.onResume()
mapPlatform.onResume()
}
override fun onPause() {
super.onPause()
mapPlatform.onPause()
}
override fun onStop() {
super.onStop()
mapPlatform.onStop()
}
override fun onDestroy() {
super.onDestroy()
mapPlatform.onDestroy()
}
} |
MapPlatform/app/src/main/java/com/hezd/test/map/MapPlatformApplication.kt | 3003013967 | package com.hezd.test.map
import android.app.Application
import com.tencent.navix.api.NavigatorConfig
import com.tencent.navix.api.NavigatorZygote
import com.tencent.tencentmap.mapsdk.maps.TencentMapInitializer
/**
* @author hezd
* @date 2024/1/23 18:00
* @description
*/
class MapPlatformApplication : Application() {
override fun onCreate() {
super.onCreate()
// 设置同意地图SDK隐私协议
TencentMapInitializer.setAgreePrivacy(this, true)
// 初始化导航SDK
NavigatorZygote.with(this).init(
NavigatorConfig.builder() // 设置同意导航SDK隐私协议
.setUserAgreedPrivacy(true) // 设置自定义的可区分设备的ID
.setDeviceId("tyt_custom_id_123456")
.experiment().setUseSharedMap(false) // 单实例有泄漏问题,使用多实例
.build())
}
} |
MapPlatform/map-platform/src/androidTest/java/com/hezd/test/platform/ExampleInstrumentedTest.kt | 2465628214 | package com.hezd.test.platform
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.hezd.map.platform", appContext.packageName)
}
} |
MapPlatform/map-platform/src/test/java/com/hezd/test/platform/ExampleUnitTest.kt | 482869933 | package com.hezd.test.platform
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)
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapStrategy.kt | 2192100500 | package com.hezd.map.platform
import android.content.Context
import android.os.Bundle
import android.view.View
import com.hezd.map.platform.bean.GCJLatLng
import com.hezd.map.platform.bean.TruckInfo
/**
* @author hezd
* @date 2024/1/10 14:27
* @description 路径规划策略
*/
interface MapStrategy : UiLifecycle {
/**
* 初始化
*/
fun init(context: Context, savedInstanceState: Bundle? = null,markOptions: MarkOptions?)
/**
* 获取地图View
*/
fun getMapView(context: Context): View
/**
* 开始路径规划
*/
fun startCalculatePath(
start: GCJLatLng,
end: GCJLatLng,
truckInfo: TruckInfo?=null,
calcRoteCallback: MapCalcRouteCallback?,
)
/**
* 开始定位
*/
fun startLocation()
/**
* 导航路线被点击时回调
*/
fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener)
/**
* 设置某个路线图层以自适应缩放
*/
fun setRouteZoomToSpan(index:Int)
/**
* 地图放大
*/
fun setZoomIn()
/**
* 地图缩小
*/
fun setZoomOut()
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/Map.kt | 668386607 | package com.hezd.map.platform
import com.hezd.map.platform.amap.AMapStrategy
import com.hezd.map.platform.tencentmap.TencentMapStrategy
/**
* @author hezd
* @date 2024/1/12 14:30
* @description 地图平台
*/
sealed class Map : IMap {
open class AMap : Map() {
override fun getPlatForm() = AMapStrategy()
}
open class TencentMap : Map() {
override fun getPlatForm(): MapStrategy = TencentMapStrategy()
}
}
interface IMap {
fun getPlatForm(): MapStrategy
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/CalcRoteError.kt | 3401482951 | package com.hezd.map.platform
/**
* @author hezd
* @date 2024/1/10 17:39
* @description
*/
data class CalcRoteError(val errorCode:Int,val message:String)
|
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/GCJLatLng.kt | 1667111976 | package com.hezd.map.platform.bean
import com.amap.api.navi.model.NaviLatLng
import com.tencent.navix.api.model.NavSearchPoint
/**
* @author hezd
* @date 2024/1/10 16:54
* @description GCJ-02 - 国测局坐标
*/
data class GCJLatLng(val latitude: Double, val longitude: Double) {
/**
* 转化为高德坐标
*/
fun toAMapLatLng(): NaviLatLng = NaviLatLng(latitude, longitude)
/**
* 转化为腾讯坐标
*/
fun toTencentMapLatLng(): NavSearchPoint = NavSearchPoint(latitude, longitude)
}
|
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/PathInfo.kt | 3150126082 | package com.hezd.map.platform.bean
/**
* @author hezd
* @date 2024/1/10 17:36
* @description
*/
data class PathInfo(val title:String,val navTime:String,val distanceInfo:String)
|
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/bean/TruckInfo.kt | 1436276509 | package com.hezd.map.platform.bean
import com.amap.api.navi.model.AMapCarInfo
/**
* @author hezd
* @date 2024/1/10 18:21
* @description 货车信息
*/
data class TruckInfo @JvmOverloads constructor(
/**
* Unknown,
* Mini,
* Light,
* Medium,
* Heavy;
* 车辆类型,0未,1迷你型 2轻型 3中型 4重型
*/
val carType: String?,
/**
* 车牌号
*/
val carNumber: String?,
/**
* 货车长度
*/
val truckLong: String?,
/**
* 货车宽
*/
val truckWidth: String?,
/**
* 货车高
*/
val truckHigh: String?,
/**
* 总重量
*/
val truckWeight: String?,
/**
* 货车核定载重
*/
val truckApprovedLoad: String?,
/**
* 轴数
*/
val axesNumber: String?,
/**
* Unknown,
* I,
* II,
* III,
* IV,
* V,
* VI;
* 排放标准 0未知 1国一 2国二 3国三 4国四 5国五 6国六
*/
val emissionStandards: String?,
/**
* Unknown,
* Blue,
* Yellow,
* Black,
* White,
* Green,
* YellowGreen;
* 车牌颜色 0未知 1蓝牌 2黄牌 3黑牌 4白牌 5绿牌 6黄绿牌
*/
val licensePlateColor: String? = null,
/**
* 货车类型
* 例如高德1-微型货车 2-轻型/小型货车 3-中型货车 4-重型货车 默认取值4,目前不可更改
* 腾讯地图枚举类型 微型,轻型,中型,重型,没有默认值需要选择
*/
val mVehicleSize: String?,
) {
fun toAMapCarInfo(): AMapCarInfo {
return AMapCarInfo().apply {
carType = [email protected]
carNumber = [email protected]
vehicleSize = "4"
vehicleLoad = [email protected]
vehicleWeight = [email protected]
vehicleLength = [email protected]
vehicleWidth = [email protected]
vehicleHeight = [email protected]
vehicleAxis = [email protected]
isVehicleLoadSwitch = true
isRestriction = true
}
}
class Builder {
/**
* 车辆类型,0小车,1货车
*/
private var carType: String? = null
/**
* 车牌号
*/
private var carNumber: String? = null
/**
* 货车长度
*/
private var truckLong: String? = null
/**
* 货车宽
*/
private var truckWidth: String? = null
/**
* 货车高
*/
private var truckHigh: String? = null
/**
* 总重量
*/
private var truckWeight: String? = null
/**
* 货车核定载重
*/
private var truckApprovedLoad: String? = null
/**
* 轴数
*/
private var axesNumber: String? = null
/**
* 排放标准
*/
private var emissionStandards: String? = null
/**
* 车牌颜色
*/
private var licensePlateColor: String? = null
/**
* 货车类型
* 例如高德1-微型货车 2-轻型/小型货车 3-中型货车 4-重型货车 默认取值4,目前不可更改
* 腾讯地图枚举类型 微型,轻型,中型,重型,没有默认值需要选择
*/
private var mVehicleSize: String? = null
fun carType(carType: String): Builder {
this.carType = carType
return this
}
fun carNumber(carNumber: String): Builder {
this.carNumber = carNumber
return this
}
fun truckLong(truckLong: String): Builder {
this.truckLong = truckLong
return this
}
fun truckWidth(truckWidth: String): Builder {
this.truckWidth = truckWidth
return this
}
fun truckHigh(truckHigh: String): Builder {
this.truckHigh = truckHigh
return this
}
fun truckWeight(truckWeight: String): Builder {
this.truckWeight = truckWeight
return this
}
fun truckApprovedLoad(truckApprovedLoad: String): Builder {
this.truckApprovedLoad = truckApprovedLoad
return this
}
fun axesNumber(axesNumber: String): Builder {
this.axesNumber = axesNumber
return this
}
fun emissionStandards(emissionStandards: String): Builder {
this.emissionStandards = emissionStandards
return this
}
fun licensePlateColor(licensePlateColor: String): Builder {
this.licensePlateColor = licensePlateColor
return this
}
fun mVehicleSize(mVehicleSize: String): Builder {
this.mVehicleSize = mVehicleSize
return this
}
fun build(): TruckInfo {
return TruckInfo(
carType = carType,
carNumber = carNumber,
truckLong = truckLong,
truckWidth = truckWidth,
truckHigh = truckHigh,
truckWeight = truckWeight,
truckApprovedLoad = truckApprovedLoad,
axesNumber = axesNumber,
emissionStandards = emissionStandards,
licensePlateColor = licensePlateColor,
mVehicleSize = mVehicleSize
)
}
}
}
|
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/tencentmap/RouteView.kt | 753910043 | package com.hezd.map.platform.tencentmap
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.hezd.map.platform.MarkOptions
import com.hezd.map.platform.OnRouteLineClickListener
import com.hezd.map.platform.R
import com.tencent.navix.api.map.MapApi
import com.tencent.navix.api.model.NavRoutePlan
import com.tencent.navix.core.NavigatorContext
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory
import com.tencent.tencentmap.mapsdk.maps.TencentMap
import com.tencent.tencentmap.mapsdk.maps.TencentMap.OnPolylineClickListener
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory
import com.tencent.tencentmap.mapsdk.maps.model.LatLng
import com.tencent.tencentmap.mapsdk.maps.model.LatLngBounds
import com.tencent.tencentmap.mapsdk.maps.model.Marker
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions
import com.tencent.tencentmap.mapsdk.maps.model.OverlayLevel
import com.tencent.tencentmap.mapsdk.maps.model.Polyline
import com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions
class RouteView(context: Context, attrs: AttributeSet?) :
LinearLayout(context, attrs) {
private var selectIndex = 0
private var marker: Marker? = null
private lateinit var tencentMap: MapApi
private var plan: NavRoutePlan<*>? = null
private var markOptions: MarkOptions? = null
private val DP_20 =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
20f,
NavigatorContext.share().applicationContext.resources.displayMetrics
).toInt()
private val ROUTE_COLOR_MAIN: Int = 0xFF00CC66.toInt()
private val ROUTE_COLOR_MAIN_STROKE: Int = 0xFF009449.toInt()
private val ROUTE_COLOR_BACKUP: Int = 0xFFAFDBC7.toInt()
private val ROUTE_COLOR_BACKUP_STROKE: Int = 0xFF8BB8A3.toInt()
private var onPolylineClickListener: TencentMap.OnPolylineClickListener? = null
init {
LayoutInflater.from(context).inflate(R.layout.view_route, this)
}
fun injectMap(map: MapApi, markOptions: MarkOptions? = null) {
tencentMap = map
this.markOptions = markOptions
}
fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) {
removeOnPolyLineClickListener()
onPolylineClickListener =
OnPolylineClickListener { polyLine, _ ->
polylineMap.onEachIndexed { index, entry ->
if (entry.value == polyLine) {
selectIndex = index
drawRoute()
onRouteLineClickListener.onClick(index)
return@OnPolylineClickListener
}
}
}
tencentMap.addOnPolylineClickListener(onPolylineClickListener)
}
fun removeOnPolyLineClickListener() {
onPolylineClickListener?.let {
tencentMap.removeOnPolylineClickListener(it)
}
}
fun currentIndex(): Int {
return selectIndex
}
fun selectRoute(index: Int) {
selectIndex = index
drawRoute()
}
fun updateRoutePlan(routePlan: NavRoutePlan<*>?) {
plan = routePlan
selectIndex = 0
drawRoute()
}
fun clear() {
polylineMap.forEach {
it.value.remove()
}
polylineMap.clear()
startMarker?.remove()
startMarker = null
endMarker?.remove()
endMarker = null
}
private val polylineMap = mutableMapOf<Int, Polyline>()
private var startMarker: Marker? = null
private var endMarker: Marker? = null
private fun drawRoute() {
clear()
plan?.apply {
val startIconId = markOptions?.startIconId ?: R.mipmap.app_icon_start_point
val endIconId = markOptions?.endIconId ?: R.mipmap.app_icon_end_point
startMarker = tencentMap.addMarker(
MarkerOptions(LatLng(startPoi.latitude, startPoi.longitude))
.icon(
BitmapDescriptorFactory.fromBitmap(
BitmapFactory.decodeResource(
resources,
startIconId
)
)
)
)
endMarker = tencentMap.addMarker(
MarkerOptions(LatLng(endPoi.latitude, endPoi.longitude))
.icon(
BitmapDescriptorFactory.fromBitmap(
BitmapFactory.decodeResource(
resources,
endIconId
)
)
)
)
}
val builder = LatLngBounds.Builder()
plan?.routeDatas?.forEachIndexed { index, routeData ->
var zIndex = 100
val indexes = intArrayOf(0, routeData.routePoints.size)
var colors = intArrayOf(ROUTE_COLOR_BACKUP, ROUTE_COLOR_BACKUP)
var borderColors = intArrayOf(ROUTE_COLOR_BACKUP_STROKE, ROUTE_COLOR_BACKUP_STROKE)
if (index == selectIndex) {
colors = intArrayOf(ROUTE_COLOR_MAIN, ROUTE_COLOR_MAIN)
borderColors = intArrayOf(ROUTE_COLOR_MAIN_STROKE, ROUTE_COLOR_MAIN_STROKE)
zIndex = 200
}
builder.include(routeData.routePoints)
val options = PolylineOptions()
options.addAll(routeData.routePoints)
.arrow(true)
.arrowTexture(
BitmapDescriptorFactory.fromBitmap(
BitmapFactory.decodeResource(
resources,
R.mipmap.app_arrow_texture
)
)
)
.color(Color.GREEN)
.lineType(0)
.arrowSpacing(150)
.zIndex(zIndex)
.level(OverlayLevel.OverlayLevelAboveBuildings)
.width(32f)
.clickable(true)
.borderWidth(4f)
.borderColors(borderColors)
.colors(colors, indexes)
polylineMap[index] = tencentMap.addPolyline(options)
}
tencentMap.moveCamera(
CameraUpdateFactory.newLatLngBoundsRect(
builder.build(),
DP_20,
DP_20,
DP_20,
DP_20
)
)
}
fun showLocation(latLng: LatLng) {
clear()
// 创建 MarkerOptions 对象
val markerOptions: MarkerOptions = MarkerOptions(latLng)
.title("Current Location")
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location))
// 添加 Marker 到地图上
marker = tencentMap.addMarker(markerOptions)
tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
}
fun zoomIn() {
tencentMap.moveCamera(CameraUpdateFactory.zoomIn())
}
fun zoomOut() {
tencentMap.moveCamera(CameraUpdateFactory.zoomOut())
}
fun removeMarker() {
marker?.remove()
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/tencentmap/TencentMapStrategy.kt | 1660855229 | package com.hezd.map.platform.tencentmap
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hezd.map.platform.CalcRoteError
import com.hezd.map.platform.MapCalcRouteCallback
import com.hezd.map.platform.MapStrategy
import com.hezd.map.platform.MarkOptions
import com.hezd.map.platform.OnRouteLineClickListener
import com.hezd.map.platform.R
import com.hezd.map.platform.bean.GCJLatLng
import com.hezd.map.platform.bean.PathInfo
import com.hezd.map.platform.bean.TruckInfo
import com.hezd.map.platform.formatSToHMStr
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.navix.api.NavigatorZygote
import com.tencent.navix.api.layer.NavigatorLayerRootDrive
import com.tencent.navix.api.layer.NavigatorViewStub
import com.tencent.navix.api.model.NavDriveRoute
import com.tencent.navix.api.model.NavError
import com.tencent.navix.api.model.NavRoutePlan
import com.tencent.navix.api.model.NavRouteReqParam
import com.tencent.navix.api.model.NavSearchPoint
import com.tencent.navix.api.navigator.NavigatorDrive
import com.tencent.navix.api.observer.SimpleNavigatorDriveObserver
import com.tencent.navix.api.plan.DriveRoutePlanOptions
import com.tencent.navix.api.plan.DriveRoutePlanRequestCallback
import com.tencent.navix.api.plan.RoutePlanRequester
import com.tencent.navix.ui.NavigatorLayerViewDrive
import com.tencent.tencentmap.mapsdk.maps.model.LatLng
/**
* @author hezd
* @date 2024/1/11 18:16
* @description
*/
class TencentMapStrategy : MapStrategy {
private var navigatorDrive: NavigatorDrive? = null
private var layerRootDrive: NavigatorLayerRootDrive? = null
private var layerViewDrive: NavigatorLayerViewDrive? = null
private var routeView: RouteView? = null
private var mapView: View? = null
private var locationManager: TencentLocationManager? = null
private val driveObserver: SimpleNavigatorDriveObserver =
object : SimpleNavigatorDriveObserver() {
override fun onWillArriveDestination() {
super.onWillArriveDestination()
if (navigatorDrive != null) {
navigatorDrive!!.stopNavigation()
}
}
}
@SuppressLint("InflateParams")
override fun init(context: Context, savedInstanceState: Bundle?,markOptions: MarkOptions?) {
// 创建驾车 NavigatorDrive
navigatorDrive = NavigatorZygote.with(context.applicationContext).navigator(
NavigatorDrive::class.java
)
// 创建导航地图层 NavigatorLayerRootDrive
mapView = LayoutInflater.from(context).inflate(R.layout.layout_nav, null)
val navigatorViewStub = mapView?.findViewById<NavigatorViewStub>(R.id.navigator_view_stub)
navigatorViewStub?.setTravelMode(NavRouteReqParam.TravelMode.TravelModeDriving)
navigatorViewStub?.inflate()
layerRootDrive = navigatorViewStub?.getNavigatorView()
// 创建默认面板 NavigatorLayerViewDrive,并添加到导航地图层
layerViewDrive = NavigatorLayerViewDrive(context)
layerRootDrive?.addViewLayer(layerViewDrive)
// 将导航地图层绑定到Navigator
navigatorDrive?.bindView(layerRootDrive)
// 注册导航监听
navigatorDrive?.registerObserver(driveObserver)
initRouteView(context,markOptions)
// 单次定位
locationManager = TencentLocationManager.getInstance(context.applicationContext, null)
}
private fun initRouteView(context: Context,markOptions: MarkOptions?) {
routeView = RouteView(context, null)
routeView?.injectMap(layerRootDrive!!.mapApi,markOptions)
}
override fun getMapView(context: Context): View {
if (mapView == null)
throw RuntimeException("map view not initialization,invoke init method first")
return mapView!!
}
override fun startCalculatePath(
start: GCJLatLng,
end: GCJLatLng,
truckInfo: TruckInfo?,
calcRoteCallback: MapCalcRouteCallback?,
) {
routeView?.removeMarker()
routeView?.clear()
val routePlanRequesterBuilder =
RoutePlanRequester.Companion.newBuilder(NavRouteReqParam.TravelMode.TravelModeDriving)
.start(NavSearchPoint(start.latitude, start.longitude))
.end(NavSearchPoint(end.latitude, end.longitude))
if (truckInfo != null) {
val truckType = when (truckInfo.carType) {
"0" -> DriveRoutePlanOptions.TruckOptions.TruckType.Unknown
"1" -> DriveRoutePlanOptions.TruckOptions.TruckType.Mini
"2" -> DriveRoutePlanOptions.TruckOptions.TruckType.Light
"3" -> DriveRoutePlanOptions.TruckOptions.TruckType.Medium
"4" -> DriveRoutePlanOptions.TruckOptions.TruckType.Heavy
else -> DriveRoutePlanOptions.TruckOptions.TruckType.Heavy
}
val plateColor = when (truckInfo.licensePlateColor) {
"0" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Unknown
"1" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Blue
"2" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Yellow
"3" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Black
"4" -> DriveRoutePlanOptions.TruckOptions.PlateColor.White
"5" -> DriveRoutePlanOptions.TruckOptions.PlateColor.Green
"6" -> DriveRoutePlanOptions.TruckOptions.PlateColor.YellowGreen
else -> DriveRoutePlanOptions.TruckOptions.PlateColor.Yellow
}
val emissionStandards = when (truckInfo.emissionStandards) {
"0" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.Unknown
"1" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.I
"2" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.II
"3" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.III
"4" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.IV
"5" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.V
"6" -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.VI
else -> DriveRoutePlanOptions.TruckOptions.EmissionStandard.V
}
routePlanRequesterBuilder
.options(
DriveRoutePlanOptions.Companion.newBuilder()
.licenseNumber(truckInfo.carNumber) // 车牌号
.truckOptions(
DriveRoutePlanOptions.TruckOptions.newBuilder()
.setHeight(truckInfo.truckHigh?.toFloat() ?: 0f) // 设置货车高度。单位:m
.setLength(truckInfo.truckLong?.toFloat() ?: 0f) // 设置货车长度。单位:m
.setWidth(truckInfo.truckWidth?.toFloat() ?: 0f) // 设置货车宽度。单位:m
.setWeight(truckInfo.truckWeight?.toFloat() ?: 0f) // 设置货车重量。单位:t
.setAxisCount(truckInfo.axesNumber?.toInt() ?: 0) // 设置货车轴数
// .setAxisLoad(
// 4f
// ) // 设置货车轴重。单位:t
.setPlateColor(plateColor) // 设置车牌颜色。
.setTrailerType(DriveRoutePlanOptions.TruckOptions.TrailerType.Container) // 设置是否是拖挂车。
.setTruckType(truckType) // 设置货车类型。
// .setEmissionStandard(emissionStandards) // 设置排放标准
.setPassType(DriveRoutePlanOptions.TruckOptions.PassType.NoNeed) // 设置通行证。
.setEnergyType(DriveRoutePlanOptions.TruckOptions.EnergyType.Diesel) // 设置能源类型。
.setFunctionType(DriveRoutePlanOptions.TruckOptions.FunctionType.Normal) // 设置
.build()
)
.build()
)
}
val routePlanRequester = routePlanRequesterBuilder.build()
navigatorDrive?.searchRoute(routePlanRequester,
DriveRoutePlanRequestCallback { navRoutePlan: NavRoutePlan<NavDriveRoute?>?, error: NavError? ->
if (error != null) {
// handle error
calcRoteCallback?.onError(CalcRoteError(error.errorCode, error.message))
return@DriveRoutePlanRequestCallback
}
if (navRoutePlan != null) {
// handle result
routeView?.let {
it.updateRoutePlan(navRoutePlan)
val routes = navRoutePlan.routes
val paths = routes.map {
it ?: return@map null
val title = it.tag
val time = formatSToHMStr(it.getTime() * 60)
val distance = it.distance / 1000
val distanceInfo = "${distance}公里 ¥${it.fee}"
return@map PathInfo(
title = title,
navTime = time,
distanceInfo = distanceInfo
)
}.filterNotNull()
calcRoteCallback?.onSuccess(paths)
}
}
})
}
override fun startLocation() {
routeView?.clear()
locationManager?.requestSingleLocationFresh(object : TencentLocationListener {
override fun onLocationChanged(
tencentLocation: TencentLocation,
errorCode: Int,
reason: String,
) {
if (errorCode == TencentLocation.ERROR_OK) {
// 获取到位置信息,更新地图
val currentLatLng = LatLng(tencentLocation.latitude, tencentLocation.longitude)
// 在地图上添加标记表示当前位置
addMarker(currentLatLng)
}
}
override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
}
override fun onGnssInfoChanged(p0: Any?) {
}
override fun onNmeaMsgChanged(p0: String?) {
}
}, Looper.getMainLooper())
}
private fun addMarker(currentLatLng: LatLng) {
// 获取当前位置坐标,这里假设定位成功后获取到经纬度
routeView?.showLocation(currentLatLng)
}
/**
* 腾讯地图demo中是不支持,需要在调研一下,暂时空实现
*/
override fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) {
routeView?.setOnRouteLineClickListener(onRouteLineClickListener)
}
override fun setRouteZoomToSpan(index: Int) {
routeView?.selectRoute(index)
}
override fun setZoomIn() {
routeView?.zoomIn()
}
override fun setZoomOut() {
routeView?.zoomOut()
}
override fun onStart() {
layerRootDrive?.onStart()
}
override fun onRestart() {
layerRootDrive?.onRestart()
}
override fun onPause() {
layerRootDrive?.onPause()
}
override fun onResume() {
layerRootDrive?.onResume()
}
override fun onStop() {
layerRootDrive?.onStop()
}
override fun onDestroy() {
layerRootDrive?.onDestroy()
// 移除导航监听
navigatorDrive?.unregisterObserver(driveObserver)
// 移除默认面板
layerRootDrive?.removeViewLayer(layerViewDrive)
// 解绑导航地图
navigatorDrive?.unbindView(layerRootDrive)
// 移除mapView
(mapView?.parent as ViewGroup).removeView(mapView)
// 关闭导航
navigatorDrive?.stopNavigation()
// 移除监听器
routeView?.removeOnPolyLineClickListener()
layerRootDrive = null
navigatorDrive = null
routeView = null
mapView = null
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/UiLifecycle.kt | 1705012168 | package com.hezd.map.platform
/**
* @author hezd
* @date 2024/1/10 15:36
* @description
*/
interface UiLifecycle {
fun onStart()
fun onRestart()
fun onPause()
fun onResume()
fun onStop()
fun onDestroy()
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapCalcRouteCallback.kt | 1968919260 | package com.hezd.map.platform
import com.hezd.map.platform.bean.PathInfo
/**
* @author hezd
* @date 2024/1/10 17:15
* @description 路径规划回调
*/
interface MapCalcRouteCallback {
fun onSuccess(paths: List<PathInfo>)
fun onError(calcRoteError: CalcRoteError)
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/amap/AMapStrategy.kt | 832534581 | package com.hezd.map.platform.amap
import android.content.Context
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.View
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.enums.PathPlanningStrategy
import com.amap.api.navi.model.AMapCalcRouteResult
import com.amap.api.navi.model.AMapCarInfo
import com.amap.api.navi.model.RouteOverlayOptions
import com.amap.api.navi.view.RouteOverLay
import com.hezd.map.platform.MapCalcRouteCallback
import com.hezd.map.platform.MapStrategy
import com.hezd.map.platform.MarkOptions
import com.hezd.map.platform.OnRouteLineClickListener
import com.hezd.map.platform.R
import com.hezd.map.platform.ROUTE_SELECTED_TRANSPARENCY
import com.hezd.map.platform.ROUTE_UNSELECTED_TRANSPARENCY
import com.hezd.map.platform.TAG
import com.hezd.map.platform.bean.GCJLatLng
import com.hezd.map.platform.bean.PathInfo
import com.hezd.map.platform.bean.TruckInfo
import com.hezd.map.platform.formatSToHMStr
import kotlin.math.floor
/**
* @author hezd
* @date 2024/1/10 14:30
* @description 高德路径规划
*/
class AMapStrategy : MapStrategy, AMapLocationListener {
private var mapView: MapView? = null
private var aMap: AMap? = null
private lateinit var aMapNavi: AMapNavi
private lateinit var locationClientSingle: AMapLocationClient
private var route1OverLay: RouteOverLay? = null
private var route2OverLay: RouteOverLay? = null
private var route3OverLay: RouteOverLay? = null
private var locationMarker: Marker? = null
private var aMapNaviListener: AMapNaviListener? = null
override fun init(context: Context, savedInstanceState: Bundle?, markOptions: MarkOptions?) {
mapView = MapView(context)
mapView?.onCreate(savedInstanceState)
aMap = mapView?.map
aMapNavi = AMapNavi.getInstance(context.applicationContext)
locationClientSingle = AMapLocationClient(context.applicationContext)
val locationClientSingleOption = AMapLocationClientOption()
locationClientSingleOption.setOnceLocation(true)
locationClientSingleOption.setLocationCacheEnable(false)
locationClientSingle.setLocationOption(locationClientSingleOption)
locationClientSingle.setLocationListener(this)
route1OverLay = RouteOverLay(aMap, null, context)
route2OverLay = RouteOverLay(aMap, null, context)
route3OverLay = RouteOverLay(aMap, null, context)
val overlayOptions = RouteOverlayOptions()
overlayOptions.lineWidth = 70f
val startBitmap = if (markOptions == null) BitmapFactory.decodeResource(
context.resources,
R.mipmap.app_icon_start_point
) else {
BitmapFactory.decodeResource(context.resources, markOptions.startIconId)
}
val endBitmap = if (markOptions == null) BitmapFactory.decodeResource(
context.resources,
R.mipmap.app_icon_end_point
) else {
BitmapFactory.decodeResource(context.resources, markOptions.endIconId)
}
route1OverLay?.setStartPointBitmap(startBitmap)
route1OverLay?.setEndPointBitmap(endBitmap)
route2OverLay?.setStartPointBitmap(startBitmap)
route2OverLay?.setEndPointBitmap(endBitmap)
route3OverLay?.setStartPointBitmap(startBitmap)
route3OverLay?.setEndPointBitmap(endBitmap)
route1OverLay?.showRouteStart(false)
route2OverLay?.showRouteStart(false)
route3OverLay?.showRouteStart(false)
route1OverLay?.showRouteEnd(false)
route2OverLay?.showRouteEnd(false)
route3OverLay?.showRouteEnd(false)
route1OverLay?.routeOverlayOptions = overlayOptions
route2OverLay?.routeOverlayOptions = overlayOptions
route3OverLay?.routeOverlayOptions = overlayOptions
route1OverLay?.showForbiddenMarker(false)
route2OverLay?.showForbiddenMarker(false)
route3OverLay?.showForbiddenMarker(false)
}
override fun getMapView(context: Context): View {
if (mapView == null)
throw RuntimeException("map view not initialization,invoke init method first")
return mapView!!
}
override fun startCalculatePath(
start: GCJLatLng,
end: GCJLatLng,
truckInfo: TruckInfo?,
calcRoteCallback: MapCalcRouteCallback?,
) {
clearRouteOverlay()
val aMapStart = start.toAMapLatLng()
val aMapEnd = end.toAMapLatLng()
aMapNaviListener = object : AMapNaviAdaptListener() {
override fun onCalculateRouteFailure(error: AMapCalcRouteResult) {
Log.e(
TAG,
"amap calculate error,code=${error.errorCode},message=${error.errorDescription}"
)
}
override fun onCalculateRouteSuccess(result: AMapCalcRouteResult) {
val pathList = aMapNavi.naviPaths.map { it.value }.map {
val title = it.labels
val time = formatSToHMStr(it.allTime)
val length = (it.allLength / 1000.0 * 10).toInt() / 10.0
val distance = floor(length).toInt().toString()
val formatDistance = distance + "公里 ¥" + it.tollCost
PathInfo(title, time, formatDistance)
}
drawNaviPath()
calcRoteCallback?.onSuccess(pathList)
}
private fun drawNaviPath() {
val naviPaths = aMapNavi.naviPaths.values.toList()
if (naviPaths.isNotEmpty()) {
route1OverLay?.aMapNaviPath = naviPaths[0]
route1OverLay?.setTransparency(1f)
route1OverLay?.setLightsVisible(false)
route1OverLay?.addToMap()
route1OverLay?.zoomToSpan()
}
if (naviPaths.size >= 2) {
route2OverLay?.aMapNaviPath = naviPaths[1]
route2OverLay?.setTransparency(0.3f)
route2OverLay?.setLightsVisible(false)
route2OverLay?.addToMap()
route2OverLay?.zoomToSpan()
}
if (naviPaths.size >= 3) {
route3OverLay?.aMapNaviPath = naviPaths[2]
route3OverLay?.setTransparency(0.3f)
route3OverLay?.setLightsVisible(false)
route3OverLay?.addToMap()
route3OverLay?.zoomToSpan()
}
}
}
aMapNavi.addAMapNaviListener(aMapNaviListener)
val aMapCarInfo: AMapCarInfo
if (truckInfo == null) {
aMapCarInfo = AMapCarInfo().apply {
carType = "0" // 设置车辆类型,0小车,1货车
}
} else {
aMapCarInfo = truckInfo.toAMapCarInfo()
}
aMapNavi.setCarInfo(aMapCarInfo)
aMapNavi.calculateDriveRoute(
arrayListOf(aMapStart), arrayListOf(aMapEnd), null,
PathPlanningStrategy.DRIVING_MULTIPLE_ROUTES_DEFAULT
)
}
override fun startLocation() {
locationClientSingle.startLocation()
}
private fun setOverlayTransparency(route1: Float, route2: Float, route3: Float) {
route1OverLay?.setTransparency(route1)
route2OverLay?.setTransparency(route2)
route3OverLay?.setTransparency(route3)
}
override fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) {
aMap?.setOnPolylineClickListener {
if (route1OverLay?.polylineIdList?.contains(it.id) == true) {
onRouteLineClickListener.onClick(0)
} else if (route2OverLay?.polylineIdList?.contains(it.id) == true) {
onRouteLineClickListener.onClick(1)
} else if (route2OverLay?.polylineIdList?.contains(it.id) == true) {
onRouteLineClickListener.onClick(2)
}
}
}
override fun setRouteZoomToSpan(index: Int) {
when (index) {
0 -> {
route1OverLay?.zoomToSpan()
setOverlayTransparency(
ROUTE_SELECTED_TRANSPARENCY,
ROUTE_UNSELECTED_TRANSPARENCY,
ROUTE_UNSELECTED_TRANSPARENCY
)
}
1 -> {
route2OverLay?.zoomToSpan()
setOverlayTransparency(
ROUTE_UNSELECTED_TRANSPARENCY,
ROUTE_SELECTED_TRANSPARENCY,
ROUTE_UNSELECTED_TRANSPARENCY
)
}
2 -> {
route3OverLay?.zoomToSpan()
setOverlayTransparency(
ROUTE_UNSELECTED_TRANSPARENCY,
ROUTE_UNSELECTED_TRANSPARENCY,
ROUTE_SELECTED_TRANSPARENCY
)
}
}
}
override fun setZoomIn() {
aMap?.animateCamera(CameraUpdateFactory.zoomIn())
}
override fun setZoomOut() {
aMap?.animateCamera(CameraUpdateFactory.zoomOut())
}
override fun onStart() = Unit
override fun onRestart() = Unit
override fun onStop() = Unit
private fun clearRouteOverlay() {
route1OverLay?.removeFromMap()
route2OverLay?.removeFromMap()
route3OverLay?.removeFromMap()
}
override fun onPause() {
mapView?.onPause()
}
override fun onResume() {
mapView?.onResume()
}
override fun onDestroy() {
mapView?.onDestroy()
mapView = null
route1OverLay?.destroy()
route1OverLay = null
route2OverLay?.destroy()
route2OverLay = null
route3OverLay?.destroy()
route3OverLay = null
aMapNavi.removeAMapNaviListener(aMapNaviListener)
aMapNavi.stopNavi()
AMapNavi.destroy()
locationClientSingle.onDestroy()
}
/**
* 定位回调
*/
override fun onLocationChanged(amapLocation: AMapLocation) {
if (amapLocation.errorCode == 0) {
val mCurrentLatLng = LatLng(amapLocation.latitude, amapLocation.longitude)
if (locationMarker == null) {
locationMarker = aMap?.addMarker(
MarkerOptions().position(mCurrentLatLng).icon(
BitmapDescriptorFactory.fromResource(R.mipmap.ic_location)
)
)
} else {
locationMarker?.position = mCurrentLatLng
}
aMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng, 15f))
}
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/amap/AMapNaviAdaptListener.kt | 2949589894 | package com.hezd.map.platform.amap
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.model.AMapLaneInfo
import com.amap.api.navi.model.AMapModelCross
import com.amap.api.navi.model.AMapNaviCameraInfo
import com.amap.api.navi.model.AMapNaviCross
import com.amap.api.navi.model.AMapNaviLocation
import com.amap.api.navi.model.AMapNaviRouteNotifyData
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo
import com.amap.api.navi.model.AMapServiceAreaInfo
import com.amap.api.navi.model.AimLessModeCongestionInfo
import com.amap.api.navi.model.AimLessModeStat
import com.amap.api.navi.model.NaviInfo
/**
* @author hezd
* @date 2024/1/10 18:48
* @description
*/
abstract class AMapNaviAdaptListener : AMapNaviListener {
override fun onInitNaviFailure() {
}
override fun onInitNaviSuccess() {
}
override fun onStartNavi(p0: Int) {
}
override fun onTrafficStatusUpdate() {
}
override fun onLocationChange(p0: AMapNaviLocation?) {
}
override fun onGetNavigationText(p0: Int, p1: String?) {
}
override fun onGetNavigationText(p0: String?) {
}
override fun onEndEmulatorNavi() {
}
override fun onArriveDestination() {
}
override fun onCalculateRouteFailure(p0: Int) {
}
override fun onReCalculateRouteForYaw() {
}
override fun onReCalculateRouteForTrafficJam() {
}
override fun onArrivedWayPoint(p0: Int) {
}
override fun onGpsOpenStatus(p0: Boolean) {
}
override fun onNaviInfoUpdate(p0: NaviInfo?) {
}
override fun updateCameraInfo(p0: Array<out AMapNaviCameraInfo>?) {
}
override fun updateIntervalCameraInfo(
p0: AMapNaviCameraInfo?,
p1: AMapNaviCameraInfo?,
p2: Int,
) {
}
override fun onServiceAreaUpdate(p0: Array<out AMapServiceAreaInfo>?) {
}
override fun showCross(p0: AMapNaviCross?) {
}
override fun hideCross() {
}
override fun showModeCross(p0: AMapModelCross?) {
}
override fun hideModeCross() {
}
override fun showLaneInfo(p0: Array<out AMapLaneInfo>?, p1: ByteArray?, p2: ByteArray?) {
}
override fun showLaneInfo(p0: AMapLaneInfo?) {
}
override fun hideLaneInfo() {
}
override fun onCalculateRouteSuccess(p0: IntArray?) {
}
override fun notifyParallelRoad(p0: Int) {
}
override fun OnUpdateTrafficFacility(p0: Array<out AMapNaviTrafficFacilityInfo>?) {
}
override fun OnUpdateTrafficFacility(p0: AMapNaviTrafficFacilityInfo?) {
}
override fun updateAimlessModeStatistics(p0: AimLessModeStat?) {
}
override fun updateAimlessModeCongestionInfo(p0: AimLessModeCongestionInfo?) {
}
override fun onPlayRing(p0: Int) {
}
override fun onNaviRouteNotify(p0: AMapNaviRouteNotifyData?) {
}
override fun onGpsSignalWeak(p0: Boolean) {
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MarkOptions.kt | 3677207054 | package com.hezd.map.platform
import androidx.annotation.DrawableRes
/**
* @author hezd
* @date 2024/1/19 17:35
* @description
*/
class MarkOptions private constructor(
/**
* 起始点marker图标
*/
@DrawableRes val startIconId: Int = R.mipmap.app_icon_start_point,
/**
* 目的地marker图标
*/
@DrawableRes val endIconId: Int = R.mipmap.app_icon_end_point,
/**
* 当前定位点marker图标
*/
@DrawableRes val locationIconId: Int = R.mipmap.ic_location,
) {
class Builder {
/**
* 起始点marker图标
*/
private var startIconId: Int = R.mipmap.app_icon_start_point
/**
* 目的地marker图标
*/
private var endIconId: Int = R.mipmap.app_icon_end_point
/**
* 当前定位点marker图标
*/
private var locationIconId: Int = R.mipmap.ic_location
fun startIconId(@DrawableRes startIconId: Int): Builder {
this.startIconId = startIconId
return this
}
fun destIconId(@DrawableRes destIconId: Int): Builder {
this.endIconId = destIconId
return this
}
fun locationIconId(@DrawableRes locationIconId: Int): Builder {
this.locationIconId = locationIconId;
return this
}
fun build(): MarkOptions {
return MarkOptions(startIconId, endIconId, locationIconId)
}
}
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapStrategyExtensions.kt | 3038502687 | package com.hezd.map.platform
/**
* @author hezd
* @date 2024/1/12 14:14
* @description
*/
/**
* 时间转化
* @param 秒数
*/
fun formatSToHMStr(second: Int): String {
val hour = second / 3600
val minute = second % 3600 / 60
return if (hour > 0) {
hour.toString() + "小时" + minute + "分钟"
} else minute.toString() + "分钟"
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/ConstantValues.kt | 1995606395 | package com.hezd.map.platform
/**
* @author hezd
* @date 2024/1/10 18:53
* @description
*/
const val TAG:String = "tytMap"
const val ROUTE_UNSELECTED_TRANSPARENCY = 0.3f
const val ROUTE_SELECTED_TRANSPARENCY = 1f |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/OnRouteLineClickListener.kt | 3663837097 | package com.hezd.map.platform
/**
* @author hezd
* @date 2024/1/11 14:29
* @description
*/
interface OnRouteLineClickListener {
/**
* @param index 被点击的路线下标
*/
fun onClick(index:Int)
} |
MapPlatform/map-platform/src/main/java/com/hezd/map/platform/MapPlatform.kt | 3089644000 | package com.hezd.map.platform
import android.content.Context
import android.os.Bundle
import android.view.View
import com.hezd.map.platform.bean.GCJLatLng
import com.hezd.map.platform.bean.TruckInfo
/**
* @author hezd
* @date 2024/1/10 14:10
* @description
*/
class MapPlatform private constructor(
/**
* 导航策略
*/
private val strategy: MapStrategy,
private val markOptions: MarkOptions? = null,
) {
/**
* 路径规划初始化
*/
fun init(context: Context, savedInstanceState: Bundle? = null) {
strategy.init(context, savedInstanceState, markOptions)
}
/**
* 获取地图View
*/
fun getMapView(context: Context): View = strategy.getMapView(context)
/**
* 开始路径规划
* @param start 起始点经纬度
* @param end 终点经纬度
* @param calcRoteCallback 路径规划回调
*/
fun startCalculatePath(
start: GCJLatLng,
end: GCJLatLng,
calcRoteCallback: MapCalcRouteCallback?,
truckInfo: TruckInfo? = null,
) {
strategy.startCalculatePath(start, end, truckInfo, calcRoteCallback)
}
/**
* 定位
*/
fun startLocation() {
strategy.startLocation()
}
/**
* 导航路线被点击时回调
*/
fun setOnRouteLineClickListener(onRouteLineClickListener: OnRouteLineClickListener) {
strategy.setOnRouteLineClickListener(onRouteLineClickListener)
}
/**
* 设置某个路线图层以自适应缩放
*/
fun setRouteZoomToSpan(index: Int) {
strategy.setRouteZoomToSpan(index)
}
/**
* 地图放大
*/
fun setZoomIn() {
strategy.setZoomIn()
}
/**
* 地图缩小
*/
fun setZoomOut() {
strategy.setZoomOut()
}
fun onStart() {
strategy.onStart()
}
fun onRestart() {
strategy.onRestart()
}
fun onResume() {
strategy.onResume()
}
fun onPause() {
strategy.onPause()
}
fun onStop() {
strategy.onStop()
}
fun onDestroy() {
strategy.onDestroy()
}
class Builder constructor(private val map: Map) {
/**
* 车辆信息json数据
*/
private var markOptions: MarkOptions? = null
fun markOptions(markOptions: MarkOptions): Builder {
this.markOptions = markOptions
return this
}
fun build(): MapPlatform {
return MapPlatform(map.getPlatForm(), markOptions)
}
}
} |
Dzhiadze/app/src/androidTest/java/com/example/dzhiadze/ExampleInstrumentedTest.kt | 1903341849 | package com.example.dzhiadze
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.dzhiadze", appContext.packageName)
}
} |
Dzhiadze/app/src/test/java/com/example/dzhiadze/ExampleUnitTest.kt | 3800925079 | package com.example.dzhiadze
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)
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/ActivityViewModel.kt | 3988525223 | package com.example.dzhiadze
import android.app.Activity
import android.view.View
import android.view.View.VISIBLE
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.dzhiadze.models.MovieModel
import com.example.dzhiadze.retrofit.RetrofitClass
import com.example.dzhiadze.retrofit.models.Movies
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
open class ActivityViewModel : ViewModel() {
val filmCardState:MutableLiveData<Int> by lazy {
MutableLiveData<Int>(VISIBLE)
}
val reddy:MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>(false)
}
val internetConection:MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>(false)
}
val movies:MutableLiveData<MutableList<MovieModel>> by lazy {
MutableLiveData<MutableList<MovieModel>>()
}
val favesMovies:MutableLiveData<MutableList<MovieModel>> by lazy {
MutableLiveData<MutableList<MovieModel>>()
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/App.kt | 2806820859 | package com.example.dzhiadze
import android.app.Application
import androidx.room.Room
import com.example.dzhiadze.movies.room.RoomFavesRepository
class App : Application() {
companion object{
const val FROM="Faves"
}
lateinit var service: Service
private lateinit var db: AppDatabase
override fun onCreate() {
super.onCreate()
db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "Faves.db"
)
.createFromAsset("favesMov.db")//.fallbackToDestructiveMigration()
.build()
val repositoryFaves = RoomFavesRepository(db.getMoviesDao())
service = Service(repositoryFaves)
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/MainActivity.kt | 2316927858 | package com.example.dzhiadze
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.example.dzhiadze.databinding.ActivityMainBinding
import com.example.dzhiadze.models.MovieModel
import com.example.dzhiadze.retrofit.RetrofitClass
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private val controller by lazy {
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
navHostFragment.navController
}
private val service: Service
get() = (applicationContext as App).service
private val datamodel: ActivityViewModel by viewModels()
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
datamodel.internetConection.value=hasConnection()
datamodel.filmCardState.observe(this) { state ->
binding.navView.visibility = datamodel.filmCardState.value!!
}
datamodel.internetConection.observe(this) { state ->
if (state == true) {
val navView: BottomNavigationView = binding.navView
navView.setupWithNavController(controller)
binding.normalCont.visibility = VISIBLE
binding.internetProbCont.visibility = GONE
binding.topBar.setupWithNavController(controller)
val appBarConfiguration = AppBarConfiguration(setOf(R.id.homeFragment, R.id.profileFragment))
binding.topBar.setupWithNavController(controller, appBarConfiguration)
if (datamodel.reddy.value==false and state){
loadData()
}
}
else{
binding.normalCont.visibility = GONE
binding.internetProbCont.visibility = VISIBLE
binding.update.setOnClickListener{
val tmp=hasConnection()
if (tmp != datamodel.internetConection.value)
datamodel.internetConection.value=tmp
}
}
}
}
private fun loadData(){
val apiOb = RetrofitClass()
val k = mutableListOf<Int>()
var s = listOf<MovieModel>()
val faves = mutableListOf<MovieModel>()
lifecycleScope.launch(Dispatchers.IO) {
for (i in 1..5) {
s = s + apiOb.getMoviesFromApi(i)
}
val t = service.getFavsMoviesId()
launch(Dispatchers.Main) {
for (i in t)
k.add(i.movieId)
for (i in 0 until s.size)
if (s[i].kinopoiskId in k) {
s[i].isFavs = VISIBLE
faves.add(s[i])
}
datamodel.favesMovies.value = faves
datamodel.movies.value = s.toMutableList()
datamodel.reddy.value=true
}
}
}
private fun hasConnection(): Boolean {
val cm: ConnectivityManager =
this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var wifiInfo: NetworkInfo? = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (wifiInfo != null && wifiInfo.isConnected) {
return true
}
wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
if (wifiInfo != null && wifiInfo.isConnected) {
return true
}
wifiInfo = cm.activeNetworkInfo
return wifiInfo != null && wifiInfo.isConnected
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/home/HomeViewModel.kt | 3817943258 | package com.example.dzhiadze.fragments.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class HomeViewModel : ViewModel() {
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/home/HomeFragment.kt | 1376882678 | package com.example.dzhiadze.fragments.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.App
import com.example.dzhiadze.adapters.HomeAdapter
import com.example.dzhiadze.Service
import com.example.dzhiadze.adapters.CinemasHomeAdapter
import com.example.dzhiadze.adapters.FavesAdapter
import com.example.dzhiadze.databinding.FragmentHomeBinding
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var adapter: HomeAdapter
private val datamodel: ActivityViewModel by activityViewModels()
private val service: Service
get() = (context?.applicationContext as App).service
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
datamodel.filmCardState.value= View.VISIBLE
binding = FragmentHomeBinding.inflate(inflater, container, false)
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
if (datamodel.reddy.value==false) {
datamodel.reddy.observe(viewLifecycleOwner) { state ->
if (state == true) {
loadRecycler()
}
}
}
else
{
loadRecycler()
}
return binding.root
}
private fun loadRecycler()
{
val controller = findNavController()
adapter = HomeAdapter(controller, datamodel, service)
adapter.movies = datamodel.movies.value!!
val layoutManagerTomorrow =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.recyclerToday.layoutManager = layoutManagerTomorrow
binding.progressBar.visibility=GONE
binding.recyclerToday.adapter = adapter
//////////////////////////
val adapter2 = CinemasHomeAdapter()
adapter2.cinemas = datamodel.movies.value!!
val layoutManagerCinemas =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.recyclerCinemas.layoutManager = layoutManagerCinemas
binding.recyclerCinemas.adapter = adapter2
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/movie/MovieFragment.kt | 3709766421 | package com.example.dzhiadze.fragments.movie
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.databinding.FragmentMovieBinding
import com.example.dzhiadze.retrofit.RetrofitClass
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MovieFragment : Fragment() {
private lateinit var binding: FragmentMovieBinding
private val datamodel: ActivityViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMovieBinding.inflate(inflater, container, false)
val movieViewModel =
ViewModelProvider(this).get(MovieViewModel::class.java)
val id = arguments?.getInt("id")
datamodel.internetConection.value=hasConnection()
datamodel.internetConection.observe(viewLifecycleOwner) { state ->
if (state == true) {
loadData(id!!)
}
}
return binding.root
}
private fun loadData(id:Int) {
val apiOb = RetrofitClass()
var genres=""
var countries=""
var year=""
lifecycleScope.launch(Dispatchers.IO) {
val s = apiOb.getMovieByIdFromApi(id)
launch(Dispatchers.Main) {
Glide.with(binding.poster.context)
.load(s.posterUrl)
.transition(DrawableTransitionOptions.withCrossFade())
.into(binding.poster)
binding.movieName.text=s.nameRu
binding.description.text=s.description
if (s.year!=0) {
year = s.year.toString()
}else {
year = "Неизвестно"
}
binding.year.text=year
if (s.filmLength!=0) {
binding.length.text=s.filmLength.toString()+ " минут"
}else {
binding.length.text="Неизвестно"
}
if (s.countries.isNotEmpty()){
countries += s.countries[0].country
for (i in 1 until s.countries.size)
countries+=", " + s.countries[i].country
}
else
{
countries = "Неизвестно"
}
binding.country.text=countries
if (s.genres.isNotEmpty()){
genres += s.genres[0].genre
for (i in 1 until s.genres.size)
genres+=", " + s.genres[i].genre
}
else
{
genres = "Неизвестно"
}
binding.genre.text=genres
binding.movFr.visibility=VISIBLE
binding.progressBar.visibility= GONE
}
}
}
private fun hasConnection(): Boolean {
val cm: ConnectivityManager =
requireActivity().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var wifiInfo: NetworkInfo? = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (wifiInfo != null && wifiInfo.isConnected) {
return true
}
wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
if (wifiInfo != null && wifiInfo.isConnected) {
return true
}
wifiInfo = cm.activeNetworkInfo
return wifiInfo != null && wifiInfo.isConnected
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/movie/MovieViewModel.kt | 3120644447 | package com.example.dzhiadze.fragments.movie
import androidx.lifecycle.ViewModel
class MovieViewModel: ViewModel() {
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/favourites/FavoritesFragment.kt | 1559895464 | package com.example.dzhiadze.fragments.favourites
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.App
import com.example.dzhiadze.R
import com.example.dzhiadze.adapters.FavesAdapter
import com.example.dzhiadze.Service
import com.example.dzhiadze.databinding.FragmentFavoritesBinding
class FavoritesFragment : Fragment() {
private lateinit var binding: FragmentFavoritesBinding
private val datamodel: ActivityViewModel by activityViewModels()
private lateinit var adapter: FavesAdapter
private val service: Service
get() = (context?.applicationContext as App).service
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFavoritesBinding.inflate(inflater, container, false)
val controller = findNavController()
adapter = FavesAdapter(controller, datamodel, service)
adapter.movies = datamodel.favesMovies.value!!
val layoutManagerTomorrow =
LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
binding.recyclerToday.layoutManager = layoutManagerTomorrow
binding.progressBar.visibility= View.GONE
binding.recyclerToday.adapter = adapter
return binding.root
}
override fun onDestroy() {
super.onDestroy()
datamodel.filmCardState.value= VISIBLE
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/profile/ProfileViewModel.kt | 1299102008 | package com.example.dzhiadze.fragments.profile
import androidx.lifecycle.ViewModel
class ProfileViewModel : ViewModel() {
// TODO: Implement the ViewModel
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/fragments/profile/ProfileFragment.kt | 3759053396 | package com.example.dzhiadze.fragments.profile
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.R
import com.example.dzhiadze.databinding.FragmentProfileBinding
class ProfileFragment : Fragment() {
private var _binding: FragmentProfileBinding? = null
private val binding get() = _binding!!
private lateinit var viewModel: ProfileViewModel
private val datamodel: ActivityViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentProfileBinding.inflate(inflater, container, false)
val controller = findNavController()
binding.favesBut.setOnClickListener {
datamodel.filmCardState.value=INVISIBLE
controller.navigate(R.id.action_profileFragment_to_favoritesFragment)
}
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(ProfileViewModel::class.java)
// TODO: Use the ViewModel
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/models/MovieInfoModel.kt | 3612613929 | package com.example.dzhiadze.models
import android.view.View
import com.example.dzhiadze.retrofit.models.Country
import com.example.dzhiadze.retrofit.models.Genre
data class MovieInfoModel(
val nameRu: String,
val description:String,
val filmLength: Int,
val genres: List<Genre>,
val posterUrl: String,
val year: Int,
val countries: List<Country>
)
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/models/MovieModel.kt | 618140567 | package com.example.dzhiadze.models
import android.view.View.INVISIBLE
import com.example.dzhiadze.retrofit.models.Genre
data class MovieModel(
val kinopoiskId: Int,
val nameRu: String,
val genres: List<Genre>,
val posterUrl: String,
val posterUrlPreview: String,
val year: Int,
var isFavs: Int =INVISIBLE
)
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/RetrofitRepository.kt | 3771452362 | package com.example.dzhiadze.retrofit
import com.example.dzhiadze.retrofit.models.MovieInfo
import com.example.dzhiadze.retrofit.models.Movies
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Headers
import retrofit2.http.Path
import retrofit2.http.Query
interface RetrofitRepository {
@Headers("Content-Type: application/json")
@GET("/api/v2.2/films/{id}")
suspend fun getMovieById(
@Header("x-api-key") token: String,
@Path("id") id: Int
) : MovieInfo
@Headers("Content-Type: application/json")
@GET("/api/v2.2/films/top?type=TOP_100_POPULAR_FILMS")
suspend fun searchMovies(
@Header("x-api-key") token: String,
@Query("page") page: Int
//@Query("type") type: String
) : Movies
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Movie.kt | 3510022963 | package com.example.dzhiadze.retrofit.models
import com.example.dzhiadze.models.MovieModel
data class Movie(
val filmId: Int,
val nameRu: String?,
val nameEn: String?,
val genres: List<Genre>,
val posterUrl: String,
val posterUrlPreview: String,
val year: Int
) {
fun toMovieModel(): MovieModel = MovieModel(
kinopoiskId = filmId,
nameRu = nameRu ?: nameEn ?: "-",
genres = genres,
posterUrl = posterUrl,
posterUrlPreview = posterUrlPreview,
year = year
)
}
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Country.kt | 1988502042 | package com.example.dzhiadze.retrofit.models
data class Country(
val country: String
)
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Genre.kt | 3702203925 | package com.example.dzhiadze.retrofit.models
data class Genre(
val genre : String
) |
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/Movies.kt | 2815690306 | package com.example.dzhiadze.retrofit.models
data class Movies(
val films: List<Movie>
)
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/models/MovieInfo.kt | 2312313316 | package com.example.dzhiadze.retrofit.models
import com.example.dzhiadze.models.MovieInfoModel
import com.example.dzhiadze.models.MovieModel
data class MovieInfo(
val nameRu: String?,
val nameEn: String?,
val genres: List<Genre>,
val description:String?,
val filmLength: Int?,
val posterUrl: String,
val year: Int?,
val countries: List<Country>
) {
fun toMovieInfoModel(): MovieInfoModel = MovieInfoModel(
nameRu = nameRu ?: nameEn ?: "Неизвестно",
genres = genres,
description = description?: "Неизвестно",
filmLength = filmLength?: 0,
posterUrl = posterUrl,
year = year?: 0,
countries = countries
)
}
|
Dzhiadze/app/src/main/java/com/example/dzhiadze/retrofit/RetrofitClass.kt | 3018664822 | package com.example.dzhiadze.retrofit
import com.example.dzhiadze.models.MovieInfoModel
import com.example.dzhiadze.models.MovieModel
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RetrofitClass {
val token = "e30ffed0-76ab-4dd6-b41f-4c9da2b2735b"
val apiService = Retrofit.Builder()
.baseUrl("https://kinopoiskapiunofficial.tech")
.addConverterFactory(GsonConverterFactory.create())
.build().create(RetrofitRepository::class.java)
suspend fun getMovieByIdFromApi(id:Int):MovieInfoModel{
val response = apiService.getMovieById(
token = token,
id = id
)
return response.toMovieInfoModel()
}
suspend fun getMoviesFromApi(page :Int):List<MovieModel> {
val response = apiService.searchMovies(
token = token,
page = page
)
val movies: MutableList<MovieModel> = mutableListOf()
for (i in 0 until response.films.size) {
val movie = response.films[i].toMovieModel()
movies.add(movie)
}
return movies
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/adapters/CinemasHomeAdapter.kt | 4216051565 | package com.example.dzhiadze.adapters
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.dzhiadze.R
import com.example.dzhiadze.databinding.CinemaCardBinding
import com.example.dzhiadze.databinding.MovieCardMainBinding
import com.example.dzhiadze.models.MovieModel
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class CinemasHomeAdapter: RecyclerView.Adapter<CinemasHomeAdapter.CinemasHomeViewHolder>() {
var cinemas: List<MovieModel> = emptyList()
set(newValue) {
field = newValue
notifyDataSetChanged()
}
override fun getItemCount(): Int = cinemas.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CinemasHomeViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = CinemaCardBinding.inflate(inflater, parent, false)
return CinemasHomeViewHolder(binding)
}
override fun onBindViewHolder(holder: CinemasHomeViewHolder, position: Int) {
val movie = cinemas[position]
}
class CinemasHomeViewHolder(
val binding: CinemaCardBinding
) : RecyclerView.ViewHolder(binding.root) {
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/adapters/HomeAdapter.kt | 2458875509 | package com.example.dzhiadze.adapters
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.R
import com.example.dzhiadze.Service
import com.example.dzhiadze.databinding.MovieCardMainBinding
import com.example.dzhiadze.models.MovieModel
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class HomeAdapter(val controller: NavController, val datamodel: ActivityViewModel, val service: Service) :
RecyclerView.Adapter<HomeAdapter.MovieViewHolder>() {
var movies: List<MovieModel> = emptyList()
set(newValue) {
field = newValue
notifyDataSetChanged()
}
override fun getItemCount(): Int = movies.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = MovieCardMainBinding.inflate(inflater, parent, false)
return MovieViewHolder(binding)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val movie = movies[position]
with(holder.binding) {
mvname.text = movie.nameRu
if (!movie.genres.isEmpty())
genre.text = movie.genres[0].genre.substring(0, 1).toUpperCase() + movie.genres[0].genre.substring(1)+" ("+movie.year+")"
if (movie.posterUrlPreview!="")
Glide.with(movieImage.context).load(movie.posterUrlPreview)
.transition(DrawableTransitionOptions.withCrossFade())
.into(movieImage)
imageStar.visibility=movie.isFavs
val bundle = Bundle()
holder.itemView.setOnClickListener {
bundle.putInt("id",movie.kinopoiskId)
datamodel.filmCardState.value= View.INVISIBLE
controller.navigate(
R.id.action_homeFragment_to_movieFragment,
bundle
)
}
holder.itemView.setOnLongClickListener {
if (movie.isFavs== VISIBLE) {
movie.isFavs = INVISIBLE
datamodel.favesMovies.value!!.removeAll{it == movie}
GlobalScope.launch(Dispatchers.IO) { deleteFavesId(FavsDbEntity(movie.kinopoiskId)) }
}
else {
movie.isFavs = VISIBLE
datamodel.favesMovies.value!!.add(movie)
GlobalScope.launch(Dispatchers.IO) { insertFavesId(FavsDbEntity(movie.kinopoiskId)) }
}
imageStar.visibility = movie.isFavs
movies[position].isFavs = movie.isFavs
true
}
datamodel.movies.value=movies.toMutableList()
}
}
class MovieViewHolder(
val binding: MovieCardMainBinding
) : RecyclerView.ViewHolder(binding.root)
suspend fun insertFavesId(favesEntity: FavsDbEntity){
service.insertFavsMoviesId(favesEntity)
}
suspend fun deleteFavesId(favesEntity: FavsDbEntity){
service.deleteFavsMoviesId(favesEntity)
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/adapters/FavesAdapter.kt | 2504906898 | package com.example.dzhiadze.adapters
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.dzhiadze.ActivityViewModel
import com.example.dzhiadze.R
import com.example.dzhiadze.Service
import com.example.dzhiadze.databinding.MovieCardFavesBinding
import com.example.dzhiadze.models.MovieModel
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class FavesAdapter(val controller: NavController, val datamodel: ActivityViewModel, val service: Service) :
RecyclerView.Adapter<FavesAdapter.MovieViewHolder>() {
var movies: MutableList<MovieModel> = mutableListOf()
set(newValue) {
field = newValue
notifyDataSetChanged()
}
override fun getItemCount(): Int = movies.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = MovieCardFavesBinding.inflate(inflater, parent, false)
return MovieViewHolder(binding)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val movie = movies[position]
with(holder.binding) {
mvname.text = movie.nameRu
if (!movie.genres.isEmpty())
genre.text = movie.genres[0].genre.substring(0, 1).toUpperCase() + movie.genres[0].genre.substring(1)+" ("+movie.year+")"
if (movie.posterUrlPreview!="")
Glide.with(movieImage.context).load(movie.posterUrlPreview).transition(
DrawableTransitionOptions.withCrossFade()).into(movieImage)
imageStar.visibility=movie.isFavs
val bundle = Bundle()
holder.itemView.setOnClickListener {
bundle.putInt("id",movie.kinopoiskId)
controller.navigate(
R.id.action_favoritesFragment_to_movieFragment,
bundle
)
datamodel.filmCardState.value= View.INVISIBLE
}
holder.itemView.setOnLongClickListener() {
if (movie.isFavs== VISIBLE) {
movie.isFavs = INVISIBLE
GlobalScope.launch(Dispatchers.IO) { deleteFavesId(FavsDbEntity(movie.kinopoiskId)) }
}
else {
movie.isFavs = VISIBLE
GlobalScope.launch(Dispatchers.IO) { insertFavesId(FavsDbEntity(movie.kinopoiskId)) }
}
imageStar.visibility = movie.isFavs
movies[position].isFavs = movie.isFavs
for (i in 0 until (datamodel.movies.value!!.size)){
if (datamodel.movies.value?.get(i)!!.kinopoiskId == movies[position].kinopoiskId)
datamodel.movies.value?.get(i)!!.isFavs=movie.isFavs
break
}
movies.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, movies.size - position)
true
}
}
}
class MovieViewHolder(
val binding: MovieCardFavesBinding
) : RecyclerView.ViewHolder(binding.root)
suspend fun insertFavesId(favesEntity: FavsDbEntity){
service.insertFavsMoviesId(favesEntity)
}
suspend fun deleteFavesId(favesEntity: FavsDbEntity){
service.deleteFavsMoviesId(favesEntity)
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/AppDatabase.kt | 3433014593 | package com.example.dzhiadze
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.dzhiadze.movies.room.MoviesDao
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
@Database(
version = 1,
entities = [
FavsDbEntity::class,
]
)
abstract class AppDatabase : RoomDatabase() {
abstract fun getMoviesDao(): MoviesDao
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/movies/room/RoomFavesRepository.kt | 1382464592 | package com.example.dzhiadze.movies.room
import com.example.dzhiadze.movies.MoviesRepository
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
class RoomFavesRepository(private val moviesDao:MoviesDao): MoviesRepository {
override suspend fun getFavesId(): List<FavsDbEntity> {
return moviesDao.getAllNow()?: ArrayList<FavsDbEntity>()
}
override suspend fun insertFavesId(favsDbEntity: FavsDbEntity){
moviesDao.insertMovie(favsDbEntity)
}
override suspend fun deleteFavesId(favsDbEntity: FavsDbEntity) {
moviesDao.deleteMovie(favsDbEntity)
}
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/movies/room/MoviesDao.kt | 1669209259 | package com.example.dzhiadze.movies.room
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
@Dao
interface MoviesDao {
@Query("SELECT * FROM movies")
fun getAllNow() : List<FavsDbEntity>?
@Insert
fun insertMovie(movie: FavsDbEntity)
@Delete
fun deleteMovie(movie: FavsDbEntity)
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/movies/room/entities/FavsDbEntity.kt | 1096628214 | package com.example.dzhiadze.movies.room.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(
tableName = "movies"
)
data class FavsDbEntity(
@PrimaryKey val movieId: Int,
) |
Dzhiadze/app/src/main/java/com/example/dzhiadze/movies/MoviesRepository.kt | 3424570135 | package com.example.dzhiadze.movies
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
interface MoviesRepository {
suspend fun getFavesId(): List<FavsDbEntity>
suspend fun insertFavesId(favsDbEntity: FavsDbEntity)
suspend fun deleteFavesId(favsDbEntity: FavsDbEntity)
} |
Dzhiadze/app/src/main/java/com/example/dzhiadze/Service.kt | 3412315884 | package com.example.dzhiadze
import com.example.dzhiadze.movies.MoviesRepository
import com.example.dzhiadze.movies.room.RoomFavesRepository
import com.example.dzhiadze.movies.room.entities.FavsDbEntity
class Service(private val favesRepository: RoomFavesRepository) {
suspend fun getFavsMoviesId(): MutableList<FavsDbEntity> {
return favesRepository.getFavesId().toMutableList()
}
suspend fun insertFavsMoviesId(entity: FavsDbEntity){
favesRepository.insertFavesId(entity)
}
suspend fun deleteFavsMoviesId(entity: FavsDbEntity){
favesRepository.deleteFavesId(entity)
}
} |
bird-category-app/shared/src/iosMain/kotlin/main.ios.kt | 169375472 | import androidx.compose.ui.window.ComposeUIViewController
actual fun getPlatformName(): String = "iOS"
fun MainViewController() = ComposeUIViewController { App() } |
bird-category-app/shared/src/commonMain/kotlin/App.kt | 2935770902 | import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
@OptIn(ExperimentalResourceApi::class)
@Composable
fun App() {
MaterialTheme {
var greetingText by remember { mutableStateOf("Hello, World!") }
var showImage by remember { mutableStateOf(false) }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Button(onClick = {
greetingText = "Hello, ${getPlatformName()}"
showImage = !showImage
}) {
Text(greetingText)
}
AnimatedVisibility(showImage) {
Image(
painterResource("compose-multiplatform.xml"),
null
)
}
}
}
}
expect fun getPlatformName(): String |
bird-category-app/shared/src/androidMain/kotlin/main.android.kt | 237735183 | import androidx.compose.runtime.Composable
actual fun getPlatformName(): String = "Android"
@Composable fun MainView() = App()
|
bird-category-app/androidApp/src/androidMain/kotlin/com/myapplication/MainActivity.kt | 3822282313 | package com.myapplication
import MainView
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MainView()
}
}
} |
BelajarCompose/app/src/androidTest/java/com/example/belajarcompose/ExampleInstrumentedTest.kt | 197378927 | package com.example.belajarcompose
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.belajarcompose", appContext.packageName)
}
} |
BelajarCompose/app/src/test/java/com/example/belajarcompose/ExampleUnitTest.kt | 3075561436 | package com.example.belajarcompose
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)
}
} |
BelajarCompose/app/src/main/java/com/example/belajarcompose/ui/theme/Color.kt | 4181412951 | package com.example.belajarcompose.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) |
BelajarCompose/app/src/main/java/com/example/belajarcompose/ui/theme/Theme.kt | 3719125922 | package com.example.belajarcompose.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 BelajarComposeTheme(
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
)
} |
BelajarCompose/app/src/main/java/com/example/belajarcompose/ui/theme/Type.kt | 1475633540 | package com.example.belajarcompose.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
)
*/
) |
BelajarCompose/app/src/main/java/com/example/belajarcompose/MainActivity.kt | 3030343069 | package com.example.belajarcompose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.belajarcompose.ui.theme.BelajarComposeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column(
modifier = Modifier.padding(16.dp)
) {
Column(
modifier = Modifier
.border(width = 1.dp, color = Color.Red)
.fillMaxWidth() // Untuk mengisi lebar penuh
.height(200.dp), // Untuk mengatur tinggi
horizontalAlignment = Alignment.CenterHorizontally, // Untuk mengatur posisi horizontal
verticalArrangement = Arrangement.Center // Untuk mengatur posisi vertikal
) {// Column disusun secara vertikal (atas ke bawah)
Text(text = "Ini dibuat dengan column")
Text(
text = "Jetpack Compose",
//modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
Spacer(modifier = Modifier.padding(16.dp)) // Untuk membuat spasi antar komponen
Row(
modifier = Modifier
.border(width = 1.dp, color = Color.Blue)
.fillMaxWidth() // Untuk mengisi lebar penuh
.height(200.dp), // Untuk mengatur tinggi
horizontalArrangement = Arrangement.Center // Untuk mengatur posisi horizontal
) {// Row disusun secara horizontal (kiri ke kanan)
Text(
text = "Ini dibuat dengan row",
modifier = Modifier.align(Alignment.CenterVertically)
)
Text(
text = "Jetpack Compose",
modifier = Modifier.align(Alignment.CenterVertically)
)
}
}
}
}
}
/*
* Catatan :
* 1. Kalau horizontalAlignment dari alignment sendiri yang hanya bisa rata kiri, kanan, atau tengah (lebih terbatas), sedangkan alau horizontalArrangement dari arrangement sendiri yang bisa rata kiri, kanan, tengah, atau spasi diantara (lebih fleksibel)
* */ |
aplikasitask/app/src/androidTest/java/com/D121211001/task/ExampleInstrumentedTest.kt | 1012153796 | package com.D121211001.task
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.D121211001.task", appContext.packageName)
}
} |
aplikasitask/app/src/test/java/com/D121211001/task/ExampleUnitTest.kt | 3116581161 | package com.D121211001.task
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)
}
} |
aplikasitask/app/src/main/java/com/D121211001/task/ui/theme/Color.kt | 1680617753 | package com.D121211001.task.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) |
aplikasitask/app/src/main/java/com/D121211001/task/ui/theme/Theme.kt | 1761614050 | package com.D121211001.task.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 AplikasiTaskTheme(
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
)
} |
aplikasitask/app/src/main/java/com/D121211001/task/ui/theme/Type.kt | 3105191740 | package com.D121211001.task.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
)
*/
) |
aplikasitask/app/src/main/java/com/D121211001/task/MainActivity.kt | 3673182028 | package com.D121211001.task
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.D121211001.task.layar.QuoteDetail
import com.D121211001.task.ui.theme.AplikasiTaskTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuoteDetail()
}
}
}
|
aplikasitask/app/src/main/java/com/D121211001/task/layar/QuoteListItem.kt | 33815817 | package com.D121211001.task.layar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material3.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FormatQuote
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.colorFilter
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun QuoteListItem() {
Card(
elevation = 4.dp,
modifier = Modifier
.padding(8.dp)
) {
Row(
modifier = Modifier
.padding(16.dp)
) {
Image(
imageVector = Icons.Default.FormatQuote,
contentDescription = "Quote",
modifier = Modifier
.size(48.dp)
.background(Color.Black)
.padding(4.dp)
)
Spacer(modifier = Modifier.padding(4.dp))
Column(modifier = Modifier.weight(1F)) {
Text(
text = "Time is the most valuable thing a man can spend.",
style = MaterialTheme.typography.body2,
modifier = Modifier.padding(0.dp, 0.dp, 0.dp, 8.dp)
)
Box(
modifier = Modifier
.background(Color(0xFEEEEEE))
.fillMaxWidth(0.4f)
.height(1.dp)
)
Text(
text = "Theophrastus",
style = MaterialTheme.typography.body2,
fontWeight = FontWeight.Thin,
modifier = Modifier.padding(top = 4.dp)
)
}
}
}
}
@Preview
@Composable
fun QuoteDetail() {
// Detail implementation, if needed
}
|
AppByBit/app/src/androidTest/java/com/example/appbybit/ExampleInstrumentedTest.kt | 3208580361 | package com.example.appbybit
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.appbybit", appContext.packageName)
}
} |
AppByBit/app/src/test/java/com/example/appbybit/ExampleUnitTest.kt | 2749604113 | package com.example.appbybit
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)
}
} |
AppByBit/app/src/main/java/com/example/appbybit/ui/theme/Color.kt | 285916564 | package com.example.appbybit.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val GreyTag = Color(0xFF71757A)
val GreyBorder = Color(0xFFD5DAE0)
val BtnYellow = Color ( 0xFFF7A600)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) |
AppByBit/app/src/main/java/com/example/appbybit/ui/theme/Theme.kt | 2615510226 | package com.example.appbybit.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 AppByBitTheme(
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
)
} |
AppByBit/app/src/main/java/com/example/appbybit/ui/theme/Type.kt | 4161256255 | package com.example.appbybit.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.appbybit.R
val IBMPlexSans = FontFamily(
Font(R.font.imbplexsans_medium, FontWeight.Medium),
Font(R.font.imbplexsans_regular, FontWeight.Normal),
Font(R.font.imbplexsans_semibold, FontWeight.SemiBold),
)
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = IBMPlexSans,
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
)
*/
) |
AppByBit/app/src/main/java/com/example/appbybit/MainActivity.kt | 147183149 | package com.example.appbybit
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.appbybit.screen.MainScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "route_screen", builder ={
composable("route_screen") {
MainScreen(navController)
}
}
)
}
}
}
|
AppByBit/app/src/main/java/com/example/appbybit/screen/LoadedScreen.kt | 3782240545 | package com.example.appbybit.screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.appbybit.ui.theme.BtnYellow
@Composable
fun LoadedScreen(){
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.size(100.dp)
.background(BtnYellow)
.padding(16.dp)
) {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.rotate(if (true) 0f else 360f),
color = Color.White
)
}
}
} |
AppByBit/app/src/main/java/com/example/appbybit/screen/MainScreen.kt | 3788537342 |
package com.example.appbybit.screen
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.appbybit.AnnouncementsViewModel
import com.example.appbybit.data.models.ModifAnnouncementsItem
import com.example.appbybit.ui.theme.BtnYellow
import com.example.appbybit.ui.theme.GreyBorder
import com.example.appbybit.ui.theme.GreyTag
@Composable
fun MainScreen(navController: NavController = rememberNavController(), viewModel: AnnouncementsViewModel = viewModel()
) {
val dataLoaded = remember {
viewModel.dataLoaded
}
when(dataLoaded.value){
"start" -> LoadedScreen()
"loaded" -> AnnouncementsScreen()
"error" -> ErrorScreen()
}
}
@Composable
fun AnnouncementsScreen(viewModel: AnnouncementsViewModel = viewModel()
) {
val ListLoaded = remember {
viewModel.liveDataList
}
LazyColumn(
modifier = Modifier.fillMaxSize()
){
itemsIndexed(
ListLoaded.value
) { _, item ->
ItemCard(item)
}
}
}
@Composable
fun ErrorScreen(viewModel: AnnouncementsViewModel = viewModel()
) {
Box(
modifier = Modifier
.fillMaxSize()
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxSize()
) {
Text(text = "Error! Please click on Refresh Button", fontSize = 20.sp)
Button(
onClick = { viewModel.loadData() },
colors = ButtonDefaults.buttonColors(
containerColor = BtnYellow,
contentColor = Color.Black
)
) {
Text(text = "Refresh", fontSize = 20.sp)
}
}
}
}
@Composable
fun ItemCard(daysList: ModifAnnouncementsItem
) {
val handlerOpener = LocalUriHandler.current
Card(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 10.dp
),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(
containerColor = Color.White)
){
Box(
modifier = Modifier
.fillMaxWidth()
){
Row(
verticalAlignment = Alignment.CenterVertically
) {
Column(
modifier = Modifier.padding(start = 16.dp)
) {
Text(text = daysList.dateTimestamp)
Spacer(modifier = Modifier.height(7.dp))
Text(text = daysList.title, fontSize = 18.sp, fontWeight = FontWeight.Bold)
Row {
for (i in 0..daysList.tags.size-1){
Text(text = daysList.tags[i],
fontSize = 14.sp,
fontWeight = FontWeight.SemiBold,
color = GreyTag,
modifier = Modifier
.border(2.dp, GreyBorder, RoundedCornerShape(5.dp))
.padding(4.dp)
)
}
}
Spacer(modifier = Modifier.height(3.dp))
Text(text = daysList.description)
Spacer(modifier = Modifier.height(7.dp))
Text(text = "Event Period:")
Row {
Text(text = daysList.startDateTimestamp)
Text(text = " - ")
Text(text = daysList.endDateTimestamp)
}
Spacer(modifier = Modifier.height(7.dp))
Row ( horizontalArrangement = Arrangement.End, modifier = Modifier
.fillMaxWidth()
.padding(end = 15.dp))
{
Button(onClick = { handlerOpener.openUri(daysList.url) }, colors = ButtonDefaults.buttonColors(containerColor = BtnYellow, contentColor = Color.Black)) {
Text(text = "Open")
}
}
}
}
}
}
} |
AppByBit/app/src/main/java/com/example/appbybit/AnnouncementsViewModel.kt | 59717765 | package com.example.appbybit
import androidx.lifecycle.ViewModel
import com.example.appbybit.data.adapterAnnouncementsApi2
import com.example.appbybit.data.models.AnnounceItem
import kotlinx.coroutines.launch
import android.icu.text.SimpleDateFormat
import android.icu.util.TimeZone
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.example.appbybit.data.API_LIMIT
import com.example.appbybit.data.API_LOCALE
import com.example.appbybit.data.models.ModifAnnouncementsItem
import java.sql.Date
import java.util.Locale
class AnnouncementsViewModel(): ViewModel()
{
var api = adapterAnnouncementsApi2()
var liveDataList = mutableStateOf<List<ModifAnnouncementsItem>>(listOf())
var dataLoaded = mutableStateOf("start")
init{
loadData()
Log.d("TagStarted","Start")
}
fun loadData(){
viewModelScope.launch {
try {
val call = api.getAnnouncementsData(
locale = API_LOCALE,
limit = API_LIMIT,
)
formateRespone(call.result.list)
dataLoaded.value = "loaded"
Log.d("TagStart","$dataLoaded")
} catch (e: Exception){
dataLoaded.value = "error"
}
}
}
fun formateRespone(responsetItem: List<AnnounceItem>){
val announcementsModif =
responsetItem.mapIndexed { _, item ->
ModifAnnouncementsItem(
item.title,
item.description,
item.type,
item.tags,
item.url,
formateDate(item.dateTimestamp),
formateDate(item.startDateTimestamp),
formateDate(item.endDateTimestamp)
)
}
liveDataList.value = announcementsModif
}
fun formateDate(startDateTimestamp: Long): String {
val dateFormat = SimpleDateFormat("MMM d, yyyy, hh:mm a 'UTC'", Locale.US)
dateFormat.timeZone = TimeZone.getTimeZone("UTC")
val startDate = dateFormat.format(Date(startDateTimestamp))
return startDate
}
}
|
AppByBit/app/src/main/java/com/example/appbybit/data/models/ModifAnnouncementsItem.kt | 1622550 | package com.example.appbybit.data.models
data class ModifAnnouncementsItem(
val title: String,
val description: String,
val type: TypeAnnounce,
val tags: List<String>,
val url: String,
val dateTimestamp: String,
val startDateTimestamp: String,
val endDateTimestamp: String,
) |
AppByBit/app/src/main/java/com/example/appbybit/data/models/Announcements.kt | 3794242340 | package com.example.appbybit.data.models
data class Announcements(
val retCode: Int,
val retMsg: String,
val result: ResultItem,
val retExtInfo: ExtInfo,
val time: Long
)
class ExtInfo(
)
|
AppByBit/app/src/main/java/com/example/appbybit/data/models/ResultItem.kt | 3286869972 | package com.example.appbybit.data.models
data class ResultItem(
val total: Int,
val list: List<AnnounceItem>
)
data class AnnounceItem(
val title: String,
val description: String,
val type: TypeAnnounce,
val tags: List<String>,
val url: String,
val dateTimestamp: Long,
val startDateTimestamp: Long,
val endDateTimestamp: Long,
)
data class TypeAnnounce(
val title: String,
val key: String,
)
|
AppByBit/app/src/main/java/com/example/appbybit/data/AdapterApi.kt | 2307243670 | package com.example.appbybit.data
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
const val API_LIMIT = 10
const val API_LOCALE = "en-US"
fun adapterAnnouncementsApi2() : ByBitApi {
val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
val gson: Gson = GsonBuilder().create()
val retrofit = Retrofit.Builder()
.baseUrl("https://api.bybit.com/v5/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build()
return retrofit.create<ByBitApi>()
} |
AppByBit/app/src/main/java/com/example/appbybit/data/ByBitApi.kt | 204039183 | package com.example.appbybit.data
import com.example.appbybit.data.models.Announcements
import retrofit2.http.GET
import retrofit2.http.Query
interface ByBitApi {
@GET("announcements/index")
suspend fun getAnnouncementsData(
@Query("locale") locale: String,
@Query("limit") limit: Int,
): Announcements
} |
practicaexamen/app/src/androidTest/java/com/example/practicaexamen/ExampleInstrumentedTest.kt | 1891155018 | package com.example.practicaexamen
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.practicaexamen", appContext.packageName)
}
} |
practicaexamen/app/src/test/java/com/example/practicaexamen/ExampleUnitTest.kt | 2216828851 | package com.example.practicaexamen
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)
}
} |
practicaexamen/app/src/main/java/com/example/practicaexamen/activities/Datos/Movimientos.kt | 2903066732 | package com.example.practicaexamen.activities.Datos
import android.content.Context
import android.util.Log
class Movimiento () {
var id:Int=0
var cantidad:Float=0F
var fecha:String=""
constructor(i:Int,c:Float,f:String) : this() {
id=i
cantidad=c
fecha=f
}
/**
* Función para insertar una lista de Movimientos en la BBDD
* @param context Contexto de la operación
* @return true si no ha habido errores
*/
fun insert(context: Context, m:Movimiento):Boolean {
var db= Database(context)
var ok:Boolean=false
ok = db.insertMovimiento(m)
Log.i("DATOS", "La insercción ha sido " + ok.toString())
return ok
}
fun queryAll(context:Context):List<Movimiento> {
var db= Database(context)
val lm=db.searchAll()
return lm
}
fun sumaCantidad(context:Context): Float {
var db= Database(context)
val lm=db.sumnaCantidad()
return lm
}
} |
practicaexamen/app/src/main/java/com/example/practicaexamen/activities/Datos/Database.kt | 465617389 | package com.example.practicaexamen.activities.Datos
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
class Database (context: Context): SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION){
override fun onCreate(db: SQLiteDatabase?) {
db?.execSQL(SQL_CREATE_ENTRIES_MOV)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
destroyDatabase(db)
onCreate(db)
}
override fun onDowngrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
destroyDatabase(db)
onCreate(db)
}
private fun destroyDatabase(db: SQLiteDatabase?){
db?.execSQL(SQL_DELETE_TABLE_MOV)
}
/**
* Insert new row in DB, returning true if the primary key value is over 0
* @param r Recipe to insert in DB
* @return true if insert
*/
fun insertMovimiento(r:Movimiento):Boolean{
// Create a new map of values, where column names are the key
val values= asigValues(r)
// Insert the new row, returning true if the primary key value is over 0
val db=this.writableDatabase
val newRowId = db.insert(TABLE_NAME, null, values)
db.close()
return (newRowId>0)
}
/**
* Delete record by Id
* @param i: Id of Move to delete
* @return: True if the delete is done.
*/
fun deleteById(i:Int):Boolean{
// Delete row by id
val db=this.writableDatabase
val rowDel = db.delete(TABLE_NAME, "ID=$i",null)
db.close()
Log.i("DB","Eliminado $rowDel registro")
return (rowDel>0)
}
/**
* Devuelve una lista con 1 elemento que corresponde con el ID Buscado
* @param k Id a buscar
* @return Lista con las recetas
*/
fun searchById(k:Int): List<Movimiento>? {
// Search by id
val av=arrayOf<String>(k.toString())
val db=this.writableDatabase
val cursor: Cursor = db.query(TABLE_NAME,null,"ID = ?",av,
null,null,null)
// Llama a la función para crear la lista con los datos recuperados
val lm:MutableList<Movimiento> = recupDatos(cursor)
// Cierra cursor y BBDD
cursor.close()
db.close()
return lm
}
/**
* Devuelve la suma de las cantidades de los movimientos en la BD
* @param res resultado de la suma de cantidades
* @return Float con el importe de la suma
*/
@SuppressLint("Range")
fun sumnaCantidad():Float{
val db=this.writableDatabase
var res:Float=0F
var sqlSentence = "SELECT SUM(cantidad) as Total FROM "+TABLE_NAME
val cur = db.rawQuery(sqlSentence, null)
if (cur.moveToFirst()) {
if(cur.getColumnIndex("Total")>-1) {
res = cur.getFloat(cur.getColumnIndex("Total"))
}
}
cur.close()
db.close()
return res
}
/**
* Devuelve una lista con todos los elementos de la BBDD
* @return Lista con las recetas
*/
fun searchAll():List<Movimiento>{
val db=this.writableDatabase
val cursor:Cursor = db.query(TABLE_NAME,null,null,null,
null,null,null)
// Llama a la función para crear la lista con los datos recuperados
val lm:MutableList<Movimiento> = recupDatos(cursor)
// Cierra cursor y BBDD
cursor.close()
db.close()
return lm
}
/**
* Crea una lista de movimientos con los datos devueltos por la base de datos.
* @param c Cursor de la BBDD
* @return Lista de Movimientos MutableList<Movimiento>
*/
fun recupDatos (c:Cursor):MutableList<Movimiento>{
val lm:MutableList<Movimiento> = mutableListOf<Movimiento>()
while (c.moveToNext()) {
val m=Movimiento(c.getInt(0),c.getFloat(1),
c.getString(2))
lm.add(m)
}
return lm
}
/**
* Crea un ContentValues (Clave,Valor) con los nombres de los campos de la BD y
* los valores pasados en la receta.
* @param mo Movimiento para asignar los valores.
* @return ContentValues (Clave,Valor) (Columna DB,Valor de Movimiento)
*/
fun asigValues(mo:Movimiento):ContentValues{
val values=ContentValues()
values.put(SQL_MOV_COLUMS[0],mo.cantidad)
values.put(SQL_MOV_COLUMS[1],mo.fecha)
return values
}
companion object {
const val DATABASE_NAME="Movimientos.db"
const val DATABASE_VERSION=1
const val TABLE_NAME="Importes"
const val SQL_DELETE_TABLE_MOV="DROP TABLE IF EXISTS $TABLE_NAME"
const val SQL_CREATE_ENTRIES_MOV ="CREATE TABLE $TABLE_NAME "+
"(Id INTEGER PRIMARY KEY AUTOINCREMENT,cantidad FLOAT,fecha String)"
val SQL_MOV_COLUMS:List<String> = listOf("cantidad","fecha")
}
} |
practicaexamen/app/src/main/java/com/example/practicaexamen/activities/adapter/ReciclerAdapter.kt | 2674161189 | package com.example.preacticaexamen.activities.adapter
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.view.LayoutInflater
import com.example.practicaexamen.R
import com.example.practicaexamen.activities.Datos.Movimiento
import com.example.practicaexamen.activities.activities.MainActivity.Companion.dataSet
import com.example.practicaexamen.databinding.MoveListBinding
class ReciclerAdapter (val onClickListener: (position:Int) -> Unit ) :
RecyclerView.Adapter<ReViewHolder>() {
lateinit var bindingMoveList:MoveListBinding
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReViewHolder {
// Prepara el binding de recipe_list
bindingMoveList = MoveListBinding.inflate(LayoutInflater.from(parent.context),
parent, false)
//Devuelve el viewholder construido
return ReViewHolder(bindingMoveList)
}
/**
* Sobre escritura de onBindViewHolder
* Pasa el evento OnClick al Holder y renderiza la linea.
* @param holder Holder del ReciclerView
* @param position Linea a renderizar
*/
override fun onBindViewHolder(holder: ReViewHolder, position: Int) {
holder.render(dataSet[position])
holder.itemView.setOnClickListener { onClickListener(position) }
}
/**
* Sobre escritura de getItemCount
* Devuelve la longitud de la lista
*/
override fun getItemCount(): Int = dataSet.size
/**
* Actualiza los valores del dataset utilizado para el ReciclerView
* Notifica el cambio de los datos para que se actualice la visualización
*/
fun updateItems(results: List<Movimiento>) {
dataSet = results
notifyDataSetChanged()
}
}
class ReViewHolder(val binding: MoveListBinding) :
RecyclerView.ViewHolder(binding.root) {
fun render(mov: Movimiento) {
//Visualiza el contenido de la receta.
if (mov.cantidad>0) {
binding.simbolIcon.setImageDrawable(binding.root.context.getDrawable(R.drawable.add_24))
}else {
binding.simbolIcon.setImageDrawable(binding.root.context.getDrawable(R.drawable.less_24))
}
binding.identi.setText(mov.id.toString())
binding.cantidad.setText(mov.cantidad.toString())
binding.fecha.setText(mov.fecha.toString())
}
} |
practicaexamen/app/src/main/java/com/example/practicaexamen/activities/activities/AddActivity.kt | 1592191799 | package com.example.practicaexamen.activities.activities
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.practicaexamen.R
import com.example.practicaexamen.activities.Datos.Movimiento
import com.example.practicaexamen.databinding.ActivityAddBinding
import com.example.practicaexamen.databinding.ActivityAddBinding.*
import java.text.SimpleDateFormat
import java.util.Date
class AddActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_add)
// Enicializar binding para acceso a los componentes
var bindin = inflate(layoutInflater)
setContentView(bindin.root)
bindin.guardarButton.setOnClickListener({onClickSave(bindin)})
val sdf = SimpleDateFormat("dd/MM/yyyy")
val resultdate = Date(System.currentTimeMillis())
val f=sdf.format(resultdate)
bindin.fec.setText(f)
}
fun onClickSave(b:ActivityAddBinding){
var f=b.fec.text.toString()
var c=b.cant.text.toString().toFloat()
val mov= Movimiento(0,c,f)
mov.insert(b.root.context,mov)
finish()
}
} |
practicaexamen/app/src/main/java/com/example/practicaexamen/activities/activities/MainActivity.kt | 1939271 | package com.example.practicaexamen.activities.activities
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.practicaexamen.R
import com.example.practicaexamen.activities.Datos.Movimiento
import com.example.practicaexamen.databinding.ActivityMainBinding
import com.example.preacticaexamen.activities.adapter.ReciclerAdapter
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
lateinit var adapter: ReciclerAdapter
/**
* on Create se ejecuta al iniciar la Actividad
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Enicializar binding para acceso a los componentes
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Obtener de la BBDD datos y saldo
dataSet =Movimiento().queryAll(binding.root.context)
var saldo=Movimiento().sumaCantidad(binding.root.context)
//Inicializar adapter
adapter = ReciclerAdapter{ onClick(it) }
// Asignar el adapter al reciclerView
binding.reciclerW.adapter = adapter
binding.reciclerW.layoutManager = LinearLayoutManager(this)
binding.balance.text=saldo.toString()
binding.addMovimiento.setOnClickListener({onClickAdd()})
}
override fun onResume() {
super.onResume()
binding.balance.text=Movimiento().sumaCantidad(binding.root.context).toString()
dataSet =Movimiento().queryAll(binding.root.context)
updateView(dataSet,adapter)
}
/**
* Función OnClick para el adapter del ReciclerView
* Recibe la posición (Elemento) al que se ha hecho click y carga la
* pantalla de detalle (DetaidActivity) de dicho elemento.
*/
fun onClick(posi:Int){
return
}
/**
* Función OnClick para añadir movimiento
*
* pantalla de detalle (DetaidActivity) de dicho elemento.
*/
fun onClickAdd(){
val intent = Intent(this, AddActivity::class.java)
startActivity(intent)
}
/**
* Actualiza el Reciclerview
* @param data: Nuevos datos con los que actualizar la vista
* @param adap: Adapter de la vista
*/
fun updateView(data:List<Movimiento>,adap:ReciclerAdapter){
adap.updateItems(data)
}
// Objeto para almacenar los datos a mostrar en ReciclerView
companion object{
var dataSet: List<Movimiento> = listOf<Movimiento>()
}
} |
Project3_CatApp/app/src/androidTest/java/com/example/project3/ExampleInstrumentedTest.kt | 2441137492 | package com.example.project3
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.project3", appContext.packageName)
}
} |
Project3_CatApp/app/src/test/java/com/example/project3/ExampleUnitTest.kt | 3433235972 | package com.example.project3
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)
}
} |
Project3_CatApp/app/src/main/java/com/example/project3/MainActivity.kt | 2847476269 | package com.example.project3
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.example.project3.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity(), SpinnerFragment.OnBreedSelectedListener {
private lateinit var binding : ActivityMainBinding
lateinit var requestQueue: RequestQueue
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
requestQueue = Volley.newRequestQueue(this)
viewModel= ViewModelProvider(this).get(SharedViewModel::class.java)
getCatData() // calling api to get cat data
}
// Function to get cat information from the cat API
private fun getCatData(){
val catList = ArrayList<Cat>() // initializing an ArrayList to hold Cat objects
val catURL = "https://api.thecatapi.com/v1/breeds" + "?api_key=live_WI89Y6HP6gN1kQjAOgrpL4mzOP8zEW9T1WQfbfP0PK43xRkZMUdzCvpfUzCFJW83"
// Requesting JSON array from the catURL
val jsonArrayRequest = JsonArrayRequest (Request.Method.GET, catURL, null,
{ response ->
Log.d("MainActivityDATA", "JSON Response: $response") // logging response
// Iterating thru the json response storing info from the JSON object
for (i in 0 until response.length()) {
val catObject = response.getJSONObject(i)
val id = catObject.getString("id")
val name = catObject.getString("name")
val temperament = catObject.getString("temperament")
val origin = catObject.getString("origin")
val description = catObject.getString("description")
// storing image url to be used to load image of cat in an image view
val imageUrl = if (catObject.has("image")) {catObject.getJSONObject("image").getString("url")} else {
"https://i.pinimg.com/564x/b0/e6/5f/b0e65f2b910ae5cdb30f2551a819471f.jpg" // no cat image replacement, see European Burmese for example
}
// Stores json values we want saved into our catList
catList.add(Cat(id, name, temperament, origin, description, imageUrl ))
}
viewModel.updateCatList(catList)
},
{error->
Log.i("MainActivity", "Error fetching cat data: ${error.message}")
})
requestQueue.add(jsonArrayRequest)
} // end of getCatData
override fun onBreedSelected(breedName: String) {
}
} |
Project3_CatApp/app/src/main/java/com/example/project3/InfoFragment.kt | 3673924672 | package com.example.project3
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.example.project3.databinding.FragmentInfoBinding
class InfoFragment : Fragment() {
private lateinit var viewModel: SharedViewModel
private var _binding: FragmentInfoBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel= ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
} // end of onCreate
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentInfoBinding.inflate(inflater, container, false)
return binding.root
}
// When the view is created we want to set our textview and our image view with the current selected cat from the API
@SuppressLint("SetTextI18n")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.selectedCat.observe(viewLifecycleOwner){
selectedCat->
binding.ConciseTextView.text =
"Cat Name: ${selectedCat.name}\n" +
"Cat Origin: ${selectedCat.origin}\n" +
"Cat Temperament: ${selectedCat.temperament}\n" +
"Cat Description: ${selectedCat.description}"
// Using Glide to load the image of the cat into our catImageView
Glide.with(requireContext())
.load(selectedCat.imageUrl) // the imageUrl is saved in each cat json response
.into(binding.catImageView)
} // end of our observe method
} // end of onViewCreated
override fun onDestroyView() {
super.onDestroyView()
_binding = null // Avoid memory leaks
} // end of onDestroyView
}
|
Project3_CatApp/app/src/main/java/com/example/project3/Cat.kt | 1301865022 | package com.example.project3
/*
Cat class contains:
name : String
temperament : String
origin : String
description : String
imageUrl : String
All of these are holding values from our json response from the API call, storing info on each cat
*/
class Cat(id:String, name: String, temperament: String, origin: String, description: String, imageUrl : String) {
var id: String = id
get() = field
set(value) {
field = value
}
var name: String = name
get() = field
set(value) {
field = value
}
var temperament: String = temperament
get() = field
set(value) {
field = value
}
var origin: String = origin
get() = field
set(value) {
field = value
}
var description: String = description
get() = field
set(value) {
field = value
}
// adding a way to store the image url from the json info
var imageUrl : String = imageUrl
get() = field
set(value) {
field = value
}
}
|
Project3_CatApp/app/src/main/java/com/example/project3/SpinnerFragment.kt | 1019288086 | package com.example.project3
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.lifecycle.ViewModelProvider
import com.example.project3.databinding.FragmentSpinnerBinding
class SpinnerFragment : Fragment() {
private lateinit var binding: FragmentSpinnerBinding
private lateinit var viewModel: SharedViewModel
private var listener: OnBreedSelectedListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel= ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
} // end of onCreate
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSpinnerBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
viewModel.catList.observe(viewLifecycleOwner){
catList->
catList.forEach { cat ->
Log.d("SpinnerFragment", "Cat Name: ${cat.name}, Cat orgin: ${cat.origin} ") // log each cat name and origin to see in logcat later
}
val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, catList.map { it.name })
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.catSpinner.adapter = adapter
}
// Handling cat selection with the spinner
binding.catSpinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
viewModel.catList.value?.let { catList ->
val selectedCat = catList[position] // get the selected cat
Log.d("SpinnerFragmentSelected", "Selected Cat Name: ${selectedCat.name}, origin check: ${selectedCat.origin}") // Correctly log the cat's name
viewModel.selectCat(selectedCat) // Pass the Cat object to the ViewModel
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
} // end of onNothingSelected
}
} // end of onViewCreated
interface OnBreedSelectedListener {
fun onBreedSelected(breedName: String)
}
} |
Project3_CatApp/app/src/main/java/com/example/project3/SharedViewModel.kt | 407996557 | package com.example.project3
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class SharedViewModel : ViewModel() {
private val _catList = MutableLiveData<ArrayList<Cat>>()// mutable array, can be updated once the file is fetched from the API
private val _selectedCat = MutableLiveData<Cat>()
val catList: LiveData<ArrayList<Cat>> = _catList // immutable, this is what will be shared with other fragments (Read-only)
val selectedCat: LiveData<Cat> = _selectedCat
fun updateCatList(newCatList: ArrayList<Cat>) {
_catList.value = newCatList
}
fun selectCat(cat: Cat) {
_selectedCat.value = cat
}
} |
StudentNotes/app/src/androidTest/java/com/example/studentnotes/ExampleInstrumentedTest.kt | 3506683016 | package com.example.studentnotes
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.studentnotes", appContext.packageName)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.