How to highlight days from API in highlighable calendar in Kotlin? - java

I have API that post and get dates:
this is the data class:
data class PlannerGet(
val date: String,
val endTime: String,
val id: Int,
val location: String,
val note: String,
val startTime: String,
val title: String
)
and i am using this library for the calendar:
https://github.com/VarunBarad/Highlightable-Calendar-View
now in the fragment i was able to highlight certain days like this:
HighlightableCalendarView.dayDecorators = listOf(
DayDecorator(
Calendar.getInstance().apply {
set(Calendar.DAY_OF_MONTH, 4)
},
Color.parseColor("#ffffff"),
Color.parseColor("#ff0000")
),
)
but i want to highlight the days from API
i tried to make it like this:
HighlightableCalendarView.dayDecorators = listOf(
DayDecorator(
Calendar.getInstance().apply {
set(PlannerGet.date)
},
Color.parseColor("#ffffff"),
Color.parseColor("#ff0000")
),
)
but i am having a problem with "set" it show "None of the following functions can be called with the arguments supplied."
i tried to add "toInt()" and still the same problem.
what is the correct way to achieve this?

This is because the params which you are passing do not match the required params.
Calendar.getInstance().apply {
set(Calendar.DAY_OF_MONTH, 4)
}
The set functions accept the int field, int value but you are passing the params as the string
PlannerGet.date
The function set
public void set(int field, int value) {
throw new RuntimeException("Stub!");
}
If you want the date to be passed from the API dates please convert the string dates to java Date object.

SOLUTION:
if (response?.body().toString() == "[]") {
}
else if (response.isSuccessful) {
response.body()?.forEach {
getplanner.add(it)
Log.e("gggg gggg",getplanner.toString())
Log.e("gggg ddddd",getplanner[0].date)
}
val list = arrayListOf<DayDecorator>()
for (dsds in getplanner) {
list.add( DayDecorator(
Calendar.getInstance().apply {
// getplanner[0].date
val input_date = dsds.date
val format1 = SimpleDateFormat("yyyy-MM-dd")
var dt1: Date? = null
dt1 = format1.parse(input_date)
val format2: DateFormat = SimpleDateFormat("dd")
val strMonth: String = format2.format(dt1)
val month = strMonth.toInt()
Log.e("dateinplanner", "" + month)
set(Calendar.DAY_OF_MONTH, month)
},
Color.parseColor("#ffffff"),
Color.parseColor("#1AB7B8")
))
}
HighlightableCalendarView.dayDecorators = list

Related

Bluetooth LE - How do i get Advertisement Interval in milliseconds?

I have to get the Advertisement Interval in milliseconds. I used result.periodicAdvertisingInterval but this returns 0. I have to implement something like this:
private val scanCallback = object : ScanCallback(){
#RequiresApi(Build.VERSION_CODES.N)
#SuppressLint("MissingPermission", "NotifyDataSetChanged")
override fun onScanResult(callbackType: Int, result: ScanResult) {
val scanJob = CoroutineScope(Dispatchers.Main).launch {
val tag = deviceMap.computeIfAbsent(result.device.address) {
val newTag = BleTag(result.device.name ?: "Unbekannt", result.device.address, result.rssi , result.scanRecord?.bytes, "")
deviceList.add(newTag)
newTag
}
tag.name = result.device.name ?: "Unbekannt"
tag.rssi = result.rssi
tag.advertisementData = result.scanRecord?.bytes
}
deviceList.sortBy {result.rssi }
recyclerView.adapter?.notifyDataSetChanged()
menu.findItem(R.id.count).title = "Geräte: " + deviceList.size
super.onScanResult(callbackType, result)
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Log.e("Scan failed","")
}
}
This result is obtained by subtracting the timestamps of two consecutive advertisements of the same device.

Date Format issue in Android 12 & 13

I am using dd-MMM-yyyy format in String format in kotlin in android.
It returns "01-Sept-2022" as a result.
I want "01-Sep-2022" as result.
This issue shows up in android 12 & 13.
#JvmStatic
fun getCurrentDate(format: String): String {
val sdf = SimpleDateFormat(format)
val currentDate = sdf.format(Date())
return currentDate
}
How can I get my desired return value in all versions?
According to #deHaar SimpleDateFormat returns the formatted string depending on the Locale. Take a look at all locales and you will find the correct form you want. Below I added a snippet where you can easily find it. If you develop this app for the app store or for other public users you shouldn't change the Locale in SimpleDateFormat because the user in this region normally knows this format. The Locale.getDefault is also influenced by the Android system settings.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val out = findViewById<TextView>(R.id.out)
out.text = getCurrentDate("dd-MMM-yyyy")
}
fun getCurrentDate(format: String): String {
var result = ""
val locales = listOf<Locale>(Locale.CANADA, Locale.CANADA_FRENCH, Locale.CHINA, Locale.CHINESE,
Locale.ENGLISH, Locale.FRANCE, Locale.FRENCH, Locale.GERMAN, Locale.GERMANY, Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN, Locale.JAPANESE, Locale.KOREA, Locale.KOREAN, Locale.PRC,
Locale.ROOT, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE, Locale.UK, Locale.US)
locales.forEach {
val sdf = SimpleDateFormat(format, it)
result += sdf.format(Date()) + "\n"
}
return result
}
returns
04-Sep.-2022
04-sept.-2022
04-9月-2022
04-9月-2022
04-Sep-2022
04-sept.-2022
04-sept.-2022
04-Sept.-2022
04-Sept.-2022
04-set-2022
04-set-2022
04-9月-2022
04-9月-2022
04-9월-2022
04-9월-2022
04-9月-2022
04-Sep-2022
04-9月-2022
04-9月-2022
04-9月-2022
04-Sep-2022
04-Sep-2022

Kotlin: How to format a list of LocalDateTime to String?

I have succedded to format LocalDateTime to String but now how can I do the same for a list ?
The first function works but the second one doesn't work.
Here my class
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.forEach {
format(formatter)
}
}
}
}
to return a list of strings you could do this
fun formatList(date: List<LocalDateTime>): List<String> {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.map { it.format(formatter) }
}
or even shorter by referring to your other function like this:
fun formatList(date: List<LocalDateTime>): List<String> {
return date.map { format(it)}
}
or even this to make it super short
fun formatList(date: List<LocalDateTime>) = date.map { format(it)}
Edit:
realized you could even write this
fun formatList(date: List<LocalDateTime>) = date.map(::format)
Based on your second method implementation, you should return list of string instead of single result.
Also I have updated argument for first method to accept DateTimeFormatter, which will be useful while calling from second method.
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime, formatter: DateTimeFormatter): String {
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): List<String> {
val listResult = listOf<String>()
val formatter = DateTimeFormatter.ofPattern(PATTERN)
date.forEach {
listResult.add(format(formatter))
}
return listResult
}
}
}
You would need to join your list elements to String. How a "good format" looks like is up to you, the example below will output your dates separated by a "|" - you can use any separator you want (note: this calls your first format function):
fun formatList(date: List<LocalDateTime>): String =
date.joinToString(separator = "|") { format(it) }
EDIT: if you are on Android, note that the usage of DateTimeFormatter requires API level 26.

Mocck issue with Instant.now().toString()

I have implemented an interface. There I am passing timestamp as parameter to a function. For geting the current time, I have used Instant.now().toString().
The function looks like this:
fun createId() {
val values = Record(name = "ABC", timestamp = Instant.now().toString())
interface_name.store(values)
}
#Test
fun `test1 for createId`() {
val values = Record(name = "ABC", timestamp = "2020-12-28")
every { interface_name.store(values) } just runs
}
This is giving me: Verification failed because the timestamp is different. I am unable to figure out how do I mock the Instant.now() so that I get the static timestamp while testing. Any help is appreciated.
Unit testing is easy when all the dependencies are passed as parameters. Hence instead of creating objects within the function, it is always good to design the function based on abstraction and pass the dependency as arguments.
fun createId(clock: Clock = Clock.systemUTC()): Record {
val values = Record(name = "ABC", timestamp = Instant.now(clock).toString())
interface_name.store(values)
return values
}
#Test
fun `test1 for createId`() {
val clock = Clock.fixed(Instant.parse("2021-01-01T00:00:00Z"), UTC)
val record = createId(clock)
assertEquals(Record(name = "ABC", timestamp = "2021-01-01T00:00:00Z"), record)
}

“can't convert from BSON type String to Date” MongoDB for Java 3.5

Here the query in Bson :
var match = {
$match : {
"dt_extract": {
"$gte": new ISODate("2016-12-05T13:29:28.737+01:00"),
"$lte": new ISODate("2017-12-11T13:29:29.929+01:00")
}
}
}
var group = {
$group :{
"_id":{
weekNum : {"$isoWeek" :"$dt_extract"} ,
year :{"$isoWeekYear": "$dt_extract"},
dt_extract_date: "$dt_extract"
},
"Sum_Reliability_Rate_Numerator":{
"$sum":"$mlf16_txfiabnum"
}
}
}
var project = {
$project: {
"Sum_Reliability_Rate_Numerator":1
}
}
var sort = {
$sort :{_id : -1}
}
db.mplf_tmp_v3.aggregate([match,group,project,sort])
this request work and i didn't have any problem but when i want to write it in Mongo for Java 3.5 i got the problem to convert Bson type String to Date .
private List<Bson> filtersQueryCard(QueryParamWarningDto queryParamWarningDto) {
List<Bson> filters = new ArrayList<>();
LocalDate localDate = LocalDate.now();
Date date = new Date() ;
DateTimeFormatter sdf1 = DateTimeFormat.forPattern("yyyy-MM-dd");
localDate = LocalDate.parse(localDate.toString(), sdf1);
LocalDate localDateMin = localDate.minusWeeks(53);
LocalDate localDateMax = localDate;
DateTime dateTimeMin = localDateMin.toDateTimeAtCurrentTime();
DateTime dateTimeMax = localDateMax.toDateTimeAtCurrentTime();
if (queryParamWarningDto.getIdRefNum() != null) {
filters.add(eq(SupplierIndicatorFieldEnum.MLF16_CODRAFT.getLabel(), queryParamWarningDto.getIdRefNum()));
filters.add(gte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLabel(), "new ISODate('"+dateTimeMin.toString()+"')"));
filters.add(lte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLabel(),"new ISODate('"+dateTimeMax.toString()+"')"));
} else {
filters.add(eq(SupplierIndicatorFieldEnum.MLF16_CPTFOU_SIX.getLabel(), queryParamWarningDto.getIdSupNum()));
filters.add(eq(SupplierIndicatorFieldEnum.MLF16_CODADRES.getLabel(), queryParamWarningDto.getCodeSuppNum()));
filters.add(gte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLabel(),"new ISODate('"+dateTimeMin.toString()+"')"));
filters.add(lte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLabel(),"new ISODate('"+dateTimeMax.toString()+"')"));
}
return filters;
}
private List<SupplierIndicatorDTOM> getAllIndicatorForSupp(QueryParamWarningDto queryParamWarningDto) {
List<SupplierIndicatorDTOM> results = new ArrayList<>();
List<Bson> filters = filtersQueryCard(queryParamWarningDto);
MongoDatabase database = mongoUtil.mongoClient();
MongoCollection<Document> collection = database.getCollection("mplf_tmp_v3");
try {
AggregateIterable<Document> resultMongo = collection.aggregate(Arrays.asList(
Aggregates.match(and(filters)),
Aggregates.group(and(eq("weekNum", eq("$isoWeek", "$dt_extract"))
, eq("year", eq("$isoWeekYear","$dt_extract")),
eq("dt_extract_date", "$dt_extract"),
eq(SupplierIndicatorFieldEnum.MLF16_TXFIABNUM.getLabel(), SupplierIndicatorFieldEnum.MLF16_TXFIABNUM.getLabel()),
eq(SupplierIndicatorFieldEnum.MLF16_TXFIABDEN.getLabel(), SupplierIndicatorFieldEnum.MLF16_TXFIABDEN.getLabel())
), Accumulators.sum("Sum_Reliability_Rate_Numerator", SupplierIndicatorFieldEnum.MLF16_TXFIABNUM.getLabel())
, Accumulators.sum("Sum_Reliability_Rate_Denominator", SupplierIndicatorFieldEnum.MLF16_TXFIABDEN.getLabel())
, Accumulators.sum("Sum_Doc_Rate_Numerator", SupplierIndicatorFieldEnum.MLF16_TXDOCNUM.getLabel())
, Accumulators.sum("Sum_Doc_Rate_Denominator", SupplierIndicatorFieldEnum.MLF16_TXDOCDEN.getLabel())
, Accumulators.sum("Sum_Service_Rate_Numerator", SupplierIndicatorFieldEnum.MLF16_TXSERVNUM.getLabel())
, Accumulators.sum("Sum_Service_Rate_Denominator", SupplierIndicatorFieldEnum.MLF16_TXSERVDEN.getLabel())),
Aggregates.project(include("Sum_Reliability_Rate_Numerator", "Sum_Reliability_Rate_Denominator", "Sum_Doc_Rate_Numerator"
, "Sum_Doc_Rate_Denominator", "Sum_Service_Rate_Numerator", "Sum_Service_Rate_Denominator"))));
Summarizing issues from posted comments.
ISODate is a shell type. You need to use java.util.Date type when passing the criteria values to filters
Convert the jodatime to Date using DateTime.toDate()
filters.add(gte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLab‌​‌​‌​el(),dateTimeMin‌​.toDate()))‌​; filters.add(lte(SupplierIndicatorFieldEnum.DT_EXTRACT.getLab‌​‌​‌​el(),dateTimeMax‌​.toDate()))‌​;
Include $ in the constants to evaluate the string as variable in mongodb.
and(eq("weekNum", eq("$isoWeek", "$" + SupplierIndicatorFieldEnum.DT_EXTRACT.getLabel())) , eq("year", eq("$isoWeekYear","$" + SupplierIndicatorFieldEnum.DT_EXTRACT.getL‌​abel())

Categories

Resources