Why is the following code returning 0 yet the variable cash should be updated? - kotlin

I have made sure that the list aren't null. They have values that prints in logcat yet the cash variable isn't updated.
var cash = 0
val intent = intent
group = intent.getParcelableExtra("group")
viewModel.getBank(group).observe(this, Observer {
for (i in it) {
Log.d("DashBoard", "Bank Amount ${i.bank_amount}")
cash += i.bank_amount!!.toInt()
}
})
viewModel.getMpesa(group).observe(this, Observer {
for (i in it) {
Log.d("DashBoard", "Mpesa Amount ${i.mpesa_amount}")
cash += i.mpesa_amount!!.toInt()
}
})
binding.textViewCash.text = cash.toString()

Related

Catch StatusCode from execution value in Xunit

I want to compare the return value from controller execution whether that fulfill the condition or not. From debugging I noticed the 'StatusCode' but not got an way to catch that value for comparing. My Code for testing is
public void PostAmount_Withdraw_Returns_Null()
{
// Arrange
Amount amount = new Amount() { Id = 0, PaymentDate = DateTime.Today,
PaymentTypeId = 3, PaymentAmount = 500, ClientId = 1, Balance = 0 };
_accountServiceMock.Setup(s => s.Withdraw(amount)).Throws(new Exception());
var target = SetupAmountsController();
//Act
var actual = target.PostAmount(amount);
//Assert
actual.ShouldNotBeNull();
//actual.Value.ShouldBe(response);
}
What call controller methods below : -
public ActionResult<Amount> PostAmount(Amount amount)
{
try
{
if (amount.PaymentTypeId == 1)
{
_accountService.Deposit(amount);
}
else if (amount.PaymentTypeId == 2)
{
_accountService.Withdraw(amount);
}
else
{
return Problem("Model 'Amounts' is null.");
}
return new OkObjectResult(new { Message = "Payment Success!" });
}
catch (DbUpdateConcurrencyException)
{
return Problem("There was error for updating model Payment");
}
}
And, returned the value after execution from Unit Test
I want to give condition likes below: -
actual.Result.StatusCode = HttpStatusCode.BadRequest or
actual.Result.StatusCode = 500
Just got the answer. It will be likes below: -
(actual.Result as ObjectResult).StatusCode.ShouldBe((int)HttpStatusCode.InternalServerError);
you need to define here 'status code' what want to compare. In my case it was 500.

Kotlin ListView IndexOutOfBoundsException

(new to kotlin) I'm making my own music app but i'm having an error that i don't understand :
in the bit of code where i try to access a random view (shuffle), i get the java.lang.IndexOutOfBoundsException: Index:96 Size:11.
96 in this example is the view in the listview that i'm trying to access.
It happens in this line : var iView = listViewMusic.get(idShuffle)
Same if i use listViewMusic[idShuffle]
EDIT : Turns out that 11 is only the 11 visible items on screen at any given moment, even if the list contains hundreds of items. When i use listViewMusic.smoothscrolltoposition(idShuffle) it works, but the size of 11 now relates to the 11 on screen after the scrolling
The function playNext() inside the activity, called when clicking on the shuffle button:
fun playNext(){
try {
// Find the order of the next song to play
var idShuffle = musicAdapter!!.getIdofItem(listMusicShuffled.get(musicNextToPlay).title)
// Find the right record in the list
//var iView = listViewMusic[idShuffle]
//toastIt(applicationContext, "adapter count ${listViewMusic.adapter.count}")
//toastIt(applicationContext, "listview count ${listViewMusic.count}")
var iView = listViewMusic.get(idShuffle) //throws the error
// Play it
playOrPause(iView)
// Prepare the next track
musicNextToPlay += 1
if (musicNextToPlay >= listMusicShuffled.size) {
musicNextToPlay = -1
}
} catch (e:Exception) {toastException(applicationContext, "playnext", e) }
}
The part of the function onCreate that fills in the listViewMusic:
// Retrieve the data
val mediaStoreUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor = contentResolver.query(mediaStoreUri, null, "", null, null)
//Browse the data
listMusic = mutableListOf()
val listMusicJson = getMusicFromJson()
while (cursor!!.moveToNext()) {
val musicName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
val musicArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
val musicUrl = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
val musicType:String =
if (musicArtist.contains("lmdmf", true)) { "LMDMF" }
else if (musicName.contains("slack", true)) { "SLACK" }
else { "MUSIC" }
listMusic.add(
MusicTrack(
musicName,
musicPlayCount,
musicUrl,
musicType
)
)
}
cursor.close()
musicAdapter = MusicAdapter(listMusic.sortedWith(compareBy<MusicTrack>{ it.title }).filter { it.type == "MUSIC"}.toMutableList())
listViewMusic.adapter = musicAdapter

How do I get a single document from a Firestore query within a loop

In my app I am running a for loop in my Firestore query. this query itself is meant to only return documents where the criteria of brand and location are met (String values) AND where a counter ("deal_number") located in the document is > than a comparative counter in users collections (Login.deal_number).
So essentially, I search the user collection for the last counter number and use that as a logical check against the counter in the deal id
menuref = FirebaseFirestore.getInstance()
menuref.collection("Users").whereEqualTo("uid", userid)
.addSnapshotListener { value, task ->
if (task != null) {
return#addSnapshotListener
}
for (document in value!!) {
val seller_brand = document.getString("brand")!!
val seller_location = document.getString("location")!!
val deal_num = document.getLong("last_deal_num")!!
//Login.deal_number is a companion object
Login.deal_number = deal_num
Log.d("Firestore_brand", seller_brand)
Log.d("Firestore_location", seller_location)
Log.d("lastdealnum", "${Login.deal_number}")
menuref.collection("Car_Deals").whereEqualTo("brand", seller_brand).whereEqualTo(seller_location, "True").whereGreaterThan("deal_number",Login.deal_number)
.addSnapshotListener { value, task ->
if (task != null) {
return#addSnapshotListener
}
counter_deal = 0
for (document in value!!) {
val new_deal_num = document.getLong("deal_number")!!
Log.d("dealnumnew", "$new_deal_num")
if (new_deal_num == Login.deal_number) {
counter_deal = counter_deal + 1
break
} else if (new_deal_num < Login.deal_number) {
counter_deal = counter_deal + 1
break
}
else if (new_deal_num > Login.deal_number && counter_deal < 1) {
Log.d("Tag_counter_deal","${counter_deal}")
Log.d("Tag_newdeal_num","${new_deal_num}")
Log.d("Tag_userdeal_num","${Login.deal_number}")
counter_deal = counter_deal + 1
newdealnumref =
FirebaseFirestore.getInstance().collection("Users")
newdealnumref.document(userid)
.update("last_deal_num", new_deal_num)
.addOnSuccessListener {
}.addOnFailureListener { e ->
Log.w(
"firestore_create_error",
"Error writing to document",
e
)
}
Log.d("newdealbrand", "$seller_brand $seller_location")
Log.d("newdeal", "New deal found")
dealCreatedNotificationChannel() // this is the android O channel creation
CodetoRunforNotification() // this is the code to run for the notification. generic, havent changed anything according to normal notification creation
with(NotificationManagerCompat.from(this)) {
notify(notify_counter, builder)
notify_counter++
}
counter_deal = 0
break
}
}
}
}
}
For the above, why does Firestore create multiple notifications when there should only be a single event, is it because of the way the filter does not seem to apply correctly. Is it due to the same effect as you would have with a recyclerview/listview whereby you need to clear an array do prevent duplicates that meet the criteria?
This seems to be a common trend with running a notification based on a Firestore query. Is this even possible? I have tried all sorts of breaks in the for loop but keep getting multiple hits on the same document. I tried use the counter_deal to limit the amount of notifications sent once the snapshot is triggered with no luck.

Get price in-app Billing Library

My apk is uploaded in the alpha channel, my products created, the buy button if it works.
I'm trying to show several products to buy in a RecyclerView. The purchases work for me. What I could not do is show the price and title of the products.
In my myadapter.kt file I have the following var var p = ArrayList<String>() and function:
fun queryskudetails() {
billingClient = BillingClient.newBuilder(context).setListener(this).build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingServiceDisconnected() {
Log.i("Disconnected", "billing client")
}
override fun onBillingSetupFinished(responseCode: Int) {
billingClient.let { billingClient ->
val skulist = ArrayList<String>()
skulist.add("books")
skulist.add("pens")
skulist.add("keychains")
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skulist).setType(BillingClient.SkuType.INAPP)
billingClient.querySkuDetailsAsync(params.build(), { responseCode, skuDetailsList ->
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
for (skuDetails in skuDetailsList) {
val sku = skuDetails.sku
val price = skuDetails.price
Log.i("skudetails", sku)
Log.i("skuprice", price)
hashMap[sku] = price
println("===== price and sku ======")
println(price)
println(sku)
println("===== /proce and sku ======")
// add price to array p1 (defined as a global variable)
p1.add(price)
}
p = precios
}
})
}
}
})
}
In the section onBindViewHolder which is where I assign the price and title to a textView:
override fun onBindViewHolder(holder: Vholder, position: Int) {
queryskudetails()
print("-----Here array price print [] -----")
println (p)
var text: String = array[position]
Log.i("text", text)
holder.textView.text = text
holder.Price.text = hashMap[text.toLowerCase()].toString() // this does not work for me, retun null
Log.i("price", hashMap["books"].toString())
println(hashMap[array[position]]) // retunr null
holder.btn.setOnClickListener(View.OnClickListener {
Log.i("button", text.toLowerCase())
var skuid = hashMap2[text]
val flowParams = BillingFlowParams.newBuilder()
.setSku(text.toLowerCase())
.setType(BillingClient.SkuType.INAPP)
.build()
val responseCode = billingClient.launchBillingFlow(context as Activity?, flowParams)
})
}
When I show the price in a textview the following code does not work for me:
holder.Price.text = hashMap[text.toLowerCase()].toString() where Price is var Price: TextView = itemView.findViewById(R.id.price)
As a second option I try to use the matrix p1 where I stored all the prices in thequeryskudetails ()function but it returns empty.
How can I do to use the content of the array p1?
The price is stored in the Map: hashMap, to recover it use the sku (identifier in google play console)
hashMap = {sku1=USD 3.99, sku2=USD 1.99, sku3=USD 3.99}
//to recover the values according to the sku (key)
hashMap[sku1] = USD 3.99
hashMap[sku2] = USD 1.99
As I see in your code holder.Price.text = hashMap[text.toLowerCase()].toString() (in the variable Text you must have the identifier (identifier = sku) in order to recover the price of each product ), it is correct, check that in another part is not making conflict or has repeated.

What is bloomberg's response when one of a few fields is not found?

I have a Java code that uses blpapi to request specific fields of specific securities. My code runs fine now. However, I have thought of a case that is not being handled by my current code.
Say, for example, I am requesting 'CUR_MKT_CAP', 'PX_LAST', and 'EQY_SH_OUT' for a specific security. What if Bloomberg does not have the value for 'PX_LAST'? What will Bloomberg give me then?
(a) Will it give me a field Element where PX_LAST = 0?
(b) Will it give me a field Element where PX_LAST = NULL?
(c) Will it not include PX_LAST to the response that I will receive? Thus, the response will look like this?
HistoricalDataResponse (choice) = {
securityData = {
security = XXXXX Equity
sequenceNumber = 0
fieldData[] = {
fieldData = {
date = YYYY-MM-DD
CUR_MKT_CAP = XX.XXXX
EQY_SH_OUT = XX.XXXX
}
}
} }
Basically, I just want to know how I should handle if one of the fields I need is not given by Bloomberg.
You are correct, if a field returns no data, it will be omitted from the fieldData element. If none of the fields returns data, the fieldData will be empty:
ReferenceDataResponse = {
securityData[] = {
securityData = {
security = "MSFT US Equity"
eidData[] = {
}
fieldExceptions[] = {
}
sequenceNumber = 0
fieldData = {
}
}
}
}
You can easily test this, for example using MSFT US Equity / YAS_BOND_YLD.
I tested it using #assylias's answer. It gave me the following results.
MSFT US Equity
HistoricalDataResponse (choice) = {
securityData = {
security = MSFT US Equity
sequenceNumber = 0
}
}
YAS_BOND_YLD
HistoricalDataResponse (choice) = {
securityData = {
security = YAS_BOND_YLD
sequenceNumber = 0
securityError = {
source = 500::bbdbh5
code = 15
category = BAD_SEC
message = Unknown/Invalid securityInvalid Security [nid:500]
subcategory = INVALID_SECURITY
}
}
}
As per #assylias comment, I used YAS_BOND_YLD as a field. And blpapi returned the following as a response.
My input to the request:
Ticker: XXX XX Equity Start/End Date: 20160818 Fields: CUR_MKT_CAP YAS_BOND_YLD PX_LAST EQY_SH_OUT
BLPAPI's response is,
HistoricalDataResponse (choice) = {
securityData = {
security = XXX XX Equity
sequenceNumber = 0
fieldData[] = {
fieldData = {
date = 2016-08-18
CUR_MKT_CAP = 117.7144
PX_LAST = 1.06
EQY_SH_OUT = 111.051
}
}
}
}
Note: I changed the ticker to XXX XX on purpose. =D