The data I get from Firebase does not enter the if else control - android

val energy = enerjiText.text.toString()
if (energy < 50 .toString()){
progressBar.max = 1000
val currentProgress = 900
ObjectAnimator.ofInt(progressBar,"progress",currentProgress)
.setDuration(2000)
.start()
progressBar2.max = 1000
val currentProgress2 = 700
ObjectAnimator.ofInt(progressBar2,"progress",currentProgress2)
.setDuration(2000)
.start()
}
else{
progressBar.max = 1000
val currentProgress = 600
ObjectAnimator.ofInt(progressBar,"progress",currentProgress)
.setDuration(2000)
.start()
progressBar2.max = 1000
val currentProgress2 = 300
ObjectAnimator.ofInt(progressBar2,"progress",currentProgress2)
.setDuration(2000)
.start()
}
The id of the textView circled in black is enerjiText. In this textView I am printing the data that I have saved in firestore. But without checking the values ​​in the if-else loop you see in the code, the progress bars inside the if push the screen. I gave the value of energy < 50 in the if, the answer is 227, but it shows the progress bar values ​​in the if without going into the else loop. If I don't convert the enerjiText and the energy < 50 control to string I get the error "java lang numberformatexception For input string"
val panelC = binding.panelCount3.text.toString()
val landSl = binding.landSlope.text.toString()
val landS = binding.landSize3.text.toString()
val billT = binding.bill.text.toString()
if (panelC.isEmpty() || landSl.isEmpty() || landS.isEmpty() || billT.isEmpty()){
Toast.makeText(requireContext(),"Alanları Doldurun",Toast.LENGTH_LONG).show()
}
else{
val pco = panelC.toInt()
val lsl = landSl.toInt()
val ls = landS.toInt()
val b = billT.toInt()
val enerji = Math.round((((ls * pco) + (lsl * b)) / 100).toDouble())
val postMap = hashMapOf<String,Any>()
postMap.put("Panel Sayisi",binding.panelCount3.text.toString())
postMap.put("Arazi Eğimi",binding.landSlope.text.toString())
postMap.put("Arazi Boyutu",binding.panelCount3.text.toString())
postMap.put("Fatura",binding.bill.text.toString())
postMap.put("Enerji",enerji.toDouble())
postMap.put("date",com.google.firebase.Timestamp.now())
firestore.collection("Enerji").add(postMap).addOnSuccessListener {
}.addOnFailureListener {
Toast.makeText(requireContext(),it.localizedMessage,Toast.LENGTH_LONG).show()
}
These codes are the codes where the calculations of the number that should be written in enerjiText are made and saved in firestore.
private fun getData(){
db.collection("Enerji").addSnapshotListener { value, error ->
if (error!=null){
Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_LONG).show()
}else{
if (value !=null){
if (!value.isEmpty){
val documents = value.documents
for (document in documents){
val panelSayisi = document.get("Panel Sayisi") as String
val araziEgimi = document.get("Arazi Eğimi") as String
val araziBoyutu = document.get("Arazi Boyutu") as String
val faturaDegeri = document.get("Fatura") as String
val enerji = Enerji(panelSayisi, araziEgimi, araziBoyutu, faturaDegeri)
postArrayList.add(enerji)
}
}
}
}
val db = FirebaseFirestore.getInstance()
db.collection("Enerji").orderBy("date", Query.Direction.DESCENDING).limit(1)
.get()
.addOnCompleteListener {
val result : StringBuffer = StringBuffer()
if (it.isSuccessful){
for (document in it.result){
result.append(document.data.getValue("Enerji"))
}
enerjiText.setText(result)
}
}
}
These are the codes that I get the data I saved in firebase above and wrote into EnerjiText.
data class Enerji (val panelSayisi : String, val araziEgimi : String, val araziBoyutu : String, val faturaDegeri : String)
Finally, the Enerji class defined inside the postArrayList, which I think might be the source of the error.

Related

How to return a List field as an empty list "[]" in Android Studio?

So I have been tackling this issue for a couple of days now. I have a Data class that is used to send information back into the API. In this instance, I have this x amount of fields. In these fields, there are three List fields with different types, as such.
The Data Classes
data class ApiSurveySiteUpdateBody(
#SerializedName("UserId") val userId: Int,
#SerializedName("SStatusId") val sStatusId: Int,
#SerializedName("SSId") val sSId: Int,
#SerializedName("SPONum") val sPoNum: Int,
#SerializedName("WorkPerformanceTypeId") val workPerformTypeId: Int,
#SerializedName("SSAddressId") val sSAddressId: Int,
#SerializedName("WorktoPerformDate") val workToBePerformedDate: String,
#SerializedName("CableRun") val cableRun: String,
#SerializedName("Entrance") val entranceInfo: String,
#SerializedName("DoorLockHardware") val doorLockHardware: String,
#SerializedName("HandicapOperator") val handicapOperator: String,
#SerializedName("DeviceComplete") val completedPrimaryDeviceList: List<Int>,
#SerializedName("TemplateId") val templateId: Int,
#SerializedName("NewDeviceList") val newDeviceList: List<ApiNewDeviceList> = emptyList(),
#SerializedName("UpdateDeviceList") val updateDeviceList: List<ApiUpdateDeviceList> = emptyList(),
#SerializedName("RemoveDeviceList") val removedDeviceList: List<ApiRemovedDeviceList> = emptyList()
)
The Converter function
private fun getSomeRequestBody(
dbInfo: DbFormWithEList,
apiSurveySiteMedias: List<ApiSSMediaInfo>
)
: ApiSSUpdateBody {
val updateRequestApi = ApiSSUpdateBody(
userId = dbInfo.sSDbInfo.userId,
sSId = dbInfo.sSDbInfo.sSId,
sStatusId = dbInfo.sStatusDbInfo.sSId,
sPoNum = dbInfo.sSDbInfo.sPoNumber,
workPerformTypeId = dbInfo.sSDbInfo.workPerformTypeId,
sSAddressId = dbInfo.sSDbInfo.sSAddressId,
workToBePerformedDate = dbInfo.sSDbInfo.workToBePerformedDate,
cableRun = dbInfo.sSDbInfo.cableRun,
entranceInfo = dbInfo.sSDbInfo.entranceInfo,
doorLockHardware = dbInfo.sSDbInfo.doorLockHardware,
handicapOperator = dbInfo.sSDbInfo.handicapOperator,
completedPrimaryDeviceList = dbInfo.sSDbInfo.completedPrimaryDeviceList.toIntList(),
templateId = dbInfo.sSDbInfo.templateId,
newDeviceList = List(dbInfo.equipmentList.size) { i -> // “NewDeviceList”
val dbEquipmentInfo = dbInfo.equipmentList[i].sSEquipmentDbInfo
Log.d(TAG, "NewDeviceListDB $dbEquipmentInfo")
val secondaryDeviceCheckedStatus = dbEquipmentInfo.secondaryDeviceCheckedStatus
val isDuplicateDeviceInUpdatePhase = dbEquipmentInfo.isDeviceUpdateMode
if (sDeviceCheckedS == CHECKED_YES && !isDuplicateDUP){
val newDeviceListRequestBody = ApiNewDeviceList(
secondaryDeviceId = dbEquipmentInfo.secondaryDeviceId,
deviceInstanceId = dbEquipmentInfo.deviceInstanceId.toString(),
mediaNameList = dbEquipmentInfo.mediaNames,
deviceSerialNumber = dbEquipmentInfo.deviceSerialNumber,
devicePartNumber = dbEquipmentInfo.devicePartNumber,
deviceManufacturerName = dbEquipmentInfo.deviceManufacturer,
deviceInstallationDate = DateUtil.dateToStringUTCSS(dbEquipmentInfo.deviceInstallationDate),
deviceLocation = dbEquipmentInfo.locationInfo,
deviceTechnicianNotes = dbEquipmentInfo.deviceTechnicianNotes
)
Log.d(TAG, "newDeviceListRequestBodyAPI $newDeviceListRequestBody")
newDeviceListRequestBody
}
else if (sDeviceCheckedS == CHECKED_NO){
apiDeviceListMapperUpdateSS.sendDeviceNotExistsInNewDeviceList(dbEquipmentInfo)
}
else {
apiDeviceListMapperUpdateSS.sendEmptyNewDeviceList()
}
},
updateDeviceList = (List(dbInfo.equipmentList.size) { i ->
val dbEquipmentInfo = dbInfo.equipmentList[i].sSEquipmentDbInfo
Log.d("UpdatingSiteSurvey", "UpdateDeviceListDB $dbEquipmentInfo")
val secondaryDeviceCheckedStatus = dbEquipmentInfo.secondaryDeviceCheckedStatus
val isDuplicateDeviceInUpdatePhase = dbEquipmentInfo.isDeviceUpdateMode
if (secondaryDeviceCheckedStatus == CHECKED_YES && isDuplicateDeviceInUpdatePhase){
val updateDeviceListRequestBody = ApiUpdateDeviceList(
deviceEquipmentId = dbEquipmentInfo.deviceEquipmentId,
secondaryDeviceId = dbEquipmentInfo.secondaryDeviceId,
deviceInstanceId = dbEquipmentInfo.deviceInstanceId.toString(),
deviceSerialNumber = dbEquipmentInfo.deviceSerialNumber,
devicePartNumber = dbEquipmentInfo.devicePartNumber,
deviceManufacturerName = dbEquipmentInfo.deviceManufacturer,
deviceInstallationDate = DateUtil.dateToStringUTCSiteSurvey(dbEquipmentInfo.deviceInstallationDate),
deviceLocation = dbEquipmentInfo.locationInfo,
deviceTechnicianNotes = dbEquipmentInfo.deviceTechnicianNotes
)
Log.d(TAG, "updateDeviceListRequestBodyAPI $updateDeviceListRequestBody")
updateDeviceListRequestBody
} else Unit.apply { } //<- the issue is here
}) as List<ApiUpdateDeviceList>,
removedDeviceList = List(dbInfo.sSDbInfo.removedDeviceList.size) { i ->
val dbRemovedMediaItem = dbInfo.sSDbInfo.removedDeviceList[i]
Log.d(TAG, "RemovedListDB $dbRemovedMediaItem")
if (dbRemovedMediaItem.removedDeviceEquipmentId == null && dbRemovedMediaItem.removedMediaName.isNullOrEmpty()){
val removeDevice = apiDeviceListMapperUpdateSiteSurvey.removeDevice(dbRemovedMediaItem)
Log.d(TAG, "removeDevice $removeDevice")
removeDevice
}else{
val removeMediaForExistingDevice = apiDeviceListMapperUpdateSS.removeMediaForExistingDevice(dbRemovedMediaItem)
Log.d(TAG, "removeMediaForExistingDevice $removeMediaForExistingDevice")
removeMediaForExistingDevice
}
}
)
Log.d(TAG, "MainUpdateRequestAPI $updateRequestApi")
return updateRequestApi
}
The goal is to have the else statement that is highlighted to return an emptyList "[]" to that updateDeviceList field. I have tried a few ways but never was able to return that exact empty list "[]". Any help will be appreciated. Thank you.
I can't tell if you want (1) the whole list to be invalidated and become empty if any item in the iteration fails the if check, or if you just want (2) to filter out items that fail the if check. But here's how I would approach each of those tasks.
I am breaking out the conversion between DbEquipmentInfo and ApiUpdateDeviceList into a separate extension function (fun DbEquipmentInfo.toApiUpdateDeviceList(): ApiUpdateDeviceList). Not just to avoid code repetition, but also to keep the logic code easy to read, and make the project's code more maintainable in general.
1.
val isValid = dbInfo.equipmentList.all { dbEquipmentInfo ->
val secondaryDeviceCheckedStatus = dbEquipmentInfo.secondaryDeviceCheckedStatus
val isDuplicateDeviceInUpdatePhase = dbEquipmentInfo.isDeviceUpdateMode
secondaryDeviceCheckedStatus == CHECKED_YES && isDuplicateDeviceInUpdatePhase
}
updateDeviceList =
if (isValid) dbInfo.equipmentList.map { it.toApiUpdateDeviceList() }
else emptyList()
updateDeviceList = dbInfo.equipmentList.filter { dbEquipmentInfo ->
val secondaryDeviceCheckedStatus = dbEquipmentInfo.secondaryDeviceCheckedStatus
val isDuplicateDeviceInUpdatePhase = dbEquipmentInfo.isDeviceUpdateMode
secondaryDeviceCheckedStatus == CHECKED_YES && isDuplicateDeviceInUpdatePhase
}.map { it.toApiUpdateDeviceList() }

I want to show a data whose values I have determined myself in text

calculateButton.setOnClickListener {
val panelC = binding.panelCount.text.toString()
val panelS = binding.panelSize.text.toString()
val landS = binding.landSlope.text.toString()
val landSi = binding.landSize.text.toString()
val cit = binding.city.text.toString()
val sun = (1000).toInt()
val air = (1.25).toFloat()
val cel = (25).toInt()
val verim = ((sun * air)/ cel).toString().toDouble()
if (panelC.equals("") || panelS.equals("")|| landS.equals("")|| landSi.equals("")||cit.equals("")){
Toast.makeText(requireContext(),"Alanları Doldurunuz.", Toast.LENGTH_SHORT).show()
}
else{
val action = SignUpCalculateFragmentDirections.actionSignUpCalculateFragmentToDataFragment()
Navigation.findNavController(view).navigate(action)
}
val postMap = hashMapOf<String, Any>()
postMap.put("Panel Sayisi",binding.panelCount.text.toString())
postMap.put("Panel Boyutu",binding.panelSize.text.toString())
postMap.put("Arazi Eğimi",binding.landSlope.text.toString())
postMap.put("Arazi Boyutu",binding.landSize.text.toString())
postMap.put("Şehir",binding.city.text.toString())
postMap.put("date", Timestamp.now())
postMap.put("verim",verim.toString().toDouble())
firestore.collection("Posts").add(postMap).addOnFailureListener {
}.addOnFailureListener {
Toast.makeText(requireContext(),it.localizedMessage,Toast.LENGTH_SHORT).show()
}
There is a calculatePage Fragment Codes. On this page, I am trying to make a yield calculation based on the data I receive from the user. However, I need to add the values that are kept constant in the efficiency calculation, such as "sun", "cel", "air" that I defined in the code. I wrote a random operation there as an example. To see if I can write inside the text I'm trying to print without getting any errors. But the app crashed.
private fun getData(){
firestore.collection("Posts").addSnapshotListener { value, error ->
if (error!=null){
Toast.makeText(requireContext(),error.localizedMessage,Toast.LENGTH_SHORT).show()
}else{
if (value !=null){
if (!value.isEmpty){
val documents = value.documents
for (document in documents){
val pc = document.get("Panel Sayisi") as String
val ps = document.get("Panel Boyutu") as String
val ls = document.get("Arazi Eğimi") as String
val lsi = document.get("Arazi Boyutu") as String
val c = document.get("Şehir") as String
val v = document.get("verim") as Double
val post = Post(pc,ps,ls,lsi,c,v)
postArrayList.add(post)
}
}
}
}
val db = FirebaseFirestore.getInstance()
db.collection("Posts").orderBy("date",Query.Direction.DESCENDING).limit(1)
.get()
.addOnCompleteListener {
val result : StringBuffer = StringBuffer()
if (it.isSuccessful){
for (document in it.result){
result.append(document.data.getValue("verim"))
}
verimText.setText(result)
}
}
On this page, I added the values I defined in my class named 'post' to the postList and added them to Firestore.
data class Post(val pc: String, val ps: String, val ls: String, val lsi: String, val c: String, val v : Double)
#ServerTimestamp
var date: Date? = null
This is my post class
The error is like this: java.lang.NullPointerException: null cannot be cast to non-null
type kotlin.Double
As I explained at the beginning of my question, what I am trying to do is using both the data such as "panelCount", "panelSize" that I get from the user and the "sun", "cel", "air" values that are defined as constants, using the "verimText.setText(result)" in the DataFragment page. I need to show this calculation to the user.
The user enters values such as 'Panel Sayisi', 'Panel Boyutu' that should be used while calculating on the calculation page. I need to show this to the user in verimText using both this data and the 'cel', 'sun', 'air' constants that I wrote in the first code.
PS: verim: 20000 value is the result of hypothetical values that I wrote in the first code. In this part, I need to make a calculation using the other data entered by the user and these constant values and show it in the verimText.

sending a value outside a thread

I am trying to collect values from sqlite saved data and html value queried by jsoup inside a thread,the sqlite data was brought good,but the values inside thread that bring data from an html page didn't print anything.
why?
is this because i can't send a value outside a thread?,i made a global variable outside thread (stringbuilder) to catch data inside thread and send outside thread,but also this didn't work although i tested this thread in another page (outside database file) and works fine
what's wrong with this code?
DatabaseHandler.kt
fun allInvestments():List<InvestModelClass>{
val invList:ArrayList<InvestModelClass> = ArrayList<InvestModelClass>()
val selectQuery = "SELECT * FROM $TABLE_CONTACTS order by id desc"
val db = this.readableDatabase
var cursor: Cursor?
try{
cursor = db.rawQuery(selectQuery, null)
}catch (e: SQLiteException) {
db.execSQL(selectQuery)
return ArrayList()
}
// var invest_id: Int
var start_date: String
var amount:String
var currency: String
var karat:String
var enter_price:String
var percent:String
//moveToFirst will bring all ids
//moveToLast will bring the last inserted id
if (cursor.moveToFirst()) {
do {
// invest_id = cursor.getInt(cursor.getColumnIndex("id"))
start_date = cursor.getString(cursor.getColumnIndex("dt"))
amount = cursor.getString(cursor.getColumnIndex("amount"))
currency = cursor.getString(cursor.getColumnIndex("currency"))
karat = cursor.getString(cursor.getColumnIndex("karat"))
enter_price = cursor.getString(cursor.getColumnIndex("enter_price"))
if(enter_price.contains("إلى")){
var splitterx="إلى"
val split_strx=enter_price.split(splitterx)
enter_price=split_strx[0]
}else {
var splitterx=" "
val split_strx=enter_price.split(splitterx)
enter_price=split_strx[0]
}
//set percent,new amount
//calculate percent/profit and advice
if(currency=="الجنيه المصرى"){
url_link = "http://egypt.gold-price-today.com/"
}
if(currency=="الريال السعودي"){
url_link = "http://saudi-arabia.gold-price-today.com/"
}
if(currency=="الدرهم الإماراتى"){
url_link = "http://united-arab-emirates.gold-price-today.com/"
}
if(currency=="الدينار الكويتى"){
url_link = "http://kuwait.gold-price-today.com/"
}
//start thread to get current price
var catch_new_amount=StringBuilder()
var catch_percent=StringBuilder()
Thread(Runnable {
var init_recent_price=StringBuilder()
try{
val doc = Jsoup.connect(url_link).get()
val table = doc.select("table")[0]
val tbody = table.select("tbody")
val rows = tbody.select("tr")
for (i in rows.indices) {
val row = rows[i]//
val cols = row.select("td")
//karat 21
if (i == 2 ) {
karat_recent_price = cols[0].text()
if(karat_recent_price.contains("إلى")){
var splitter="إلى"
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}else {
var splitter=" "
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}
}
//karat 18
if (i == 3 ) {
karat_recent_price = cols[0].text()
if(karat_recent_price.contains("إلى")){
var splitter="إلى"
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}else {
var splitter=" "
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}
}
//karat 24
if (i == 0 ) {
karat_recent_price = cols[0].text()
if(karat_recent_price.contains("إلى")){
var splitter="إلى"
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}else {
var splitter=" "
val split_str=karat_recent_price.split(splitter)
karat_recent_price=split_str[0]
init_recent_price.append(karat_recent_price) //show karat price text
}
}
//inv_amount[index] , inv_enter_price[index] , karat_recent_price
var int_amount=amount
// new_amount=(int_amount * int_recent_price_string / int_enter_price).toString()
new_amount= karat_recent_price
catch_new_amount.append(new_amount)
if(new_amount > int_amount){
var inc=new_amount.toFloat() - int_amount.toFloat()
var percent_inc=(inc/int_amount.toFloat())* 100
percent=percent_inc.toString()
init_percent_string=percent
catch_percent.append(percent)
}else {
var dec=int_amount.toFloat() - new_amount.toFloat()
var percent_dec=(dec/int_amount.toFloat()) * 100
percent=percent_dec.toString()
init_percent_string=percent
catch_percent.append(percent)
}
}//end for
}
catch(e: IOException){
e.printStackTrace()
}
// runOnUiThread{}
}).start()
//id,start_date,enter_price,amount,currency,karat,percent,profit
val emp= InvestModelClass(
start_date = start_date,
enter_price = enter_price,
amount = amount,
currency = currency,
karat = karat,
new_amount = catch_new_amount.toString(),
percent = catch_percent.toString()
)
invList.add(emp)
} while (cursor.moveToNext())
}
return invList
}
ListInvests.kt
package com.example.parsehtml
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.list_invests.*
import kotlinx.android.synthetic.main.startinvest_main.*
class ListInvests : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.startinvest_main)
button.setOnClickListener(){
intent = Intent(this,MainActivity::class.java)
startActivity(intent)
}
//creating the instance of DatabaseHandler class
val databaseHandler: DatabaseHandler= DatabaseHandler(this)
//calling the viewEmployee method of DatabaseHandler class to read the records
//id,start_date,enter_price,amount,currency,karat,percent,profit
val inv: List<InvestModelClass> = databaseHandler.allInvestments()
val inv_startdate = Array<String>(inv.size){"0"}
val inv_enter_price = Array<String>(inv.size){"null"}
val inv_amount = Array<String>(inv.size){"null"}
val inv_currency = Array<String>(inv.size){"null"}
val inv_karat = Array<String>(inv.size){"null"}
val inv_new_amount=Array(inv.size){"null"}
val inv_percent=Array(inv.size){"null"}
var index = 0
for(e in inv){
inv_startdate[index] = e.start_date.toString()
inv_enter_price[index] = e.enter_price.toString()
inv_amount[index] = e.amount.toString()
inv_currency[index] = e.currency.toString()
inv_karat[index] = e.karat.toString()
inv_new_amount[index]=e.new_amount.toString()
inv_percent[index]=e.percent.toString()
index++
}
//creating custom ArrayAdapter
//id,start_date,enter_price,amount,currency,karat,percent,profit
val myListAdapter = InvestListAdapter(this,inv_startdate,inv_enter_price,inv_amount,inv_currency,inv_karat,inv_new_amount,inv_percent)
listView.adapter = myListAdapter
}//end oncreate
}
InvestModelClass.kt
package com.example.parsehtml
//id,start_date,enter_price,amount,currency,karat,percent,profit
class InvestModelClass ( val start_date:String ,val enter_price:String, val amount: String,val currency:String,val karat:String,val new_amount:String,val percent:String)

Accessing local variable in lambda in Kotlin

I want to save data acquired from Volley, But lambda used in VolleyRequest function(which gets json data from server) blocks it.
How should I change local variable that is in outside of lambda?
Thanks in advance.
class ConDataforReturn( val title:String , val imgDataList: ArrayList<ConImgData>)
fun getConData(context: Context, idx : String):ConDataforReturn{
val params = HashMap<String,String>()
var cd = arrayListOf<ConImgData>()
var title =""
params.put("package_idx",idx)
Log.e("idx size",idx.length.toString())
VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
val answer = JSONObject(response)
var json = answer.getJSONArray("detail")
title = answer.getJSONObject("info").getString("title")
Log.d("title",title)//Prints right data
for (i in 0..(json.length() - 1)) {
val v = json.getJSONObject(i)
cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
}
}
return ConDataforReturn(title,cd)//returns ConDataforReturn("",arrayListOf<ConImgData>())
}
Here the the code from were you are calling this method
getConData(this, "id") { condata ->
}
Now, your method look like this,
fun getConData(context: Context, idx : String, returnConData : (condata : ConDataforReturn) -> Unit){
val params = HashMap<String,String>()
var cd = arrayListOf<ConImgData>()
var title =""
params.put("package_idx",idx)
Log.e("idx size",idx.length.toString())
VolleyRequest(context,params,"https://dccon.dcinside.com/index/package_detail") { response ->
val answer = JSONObject(response)
var json = answer.getJSONArray("detail")
title = answer.getJSONObject("info").getString("title")
Log.d("title",title)//Prints right data
for (i in 0..(json.length() - 1)) {
val v = json.getJSONObject(i)
cd.add(ConImgData(v.getString("title"), v.getString("ext"), v.getString("path")))
}
returnConData(ConDataforReturn(title,cd)) //returns ConDataforReturn("",arrayListOf<ConImgData>())
}
}

How to access a TextView from a non-parent file [Android]

I want to access and change the text of a TextView from a non parent file.
This is the class I would like to make the edits from
class BarcodeProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) :
FrameProcessorBase<List<FirebaseVisionBarcode>>() {
In this class there is no onCreat()
Do I need to have AppCompatActivity() in order to gain access to the xml layout files?
Inside this file is where the barcode is processed and I can display the results along with a SQL query to the console, but I want to update the interface to reflect those values. Can I pass them through the companion oject to the parent class?
Is there any way I can make the layout updates from the BarcodeProcessor file?
I've tried including imports
import kotlinx.android.synthetic.main.barcode_field.*
#MainThread
override fun onSuccess(
image: FirebaseVisionImage,
results: List<FirebaseVisionBarcode>,
graphicOverlay: GraphicOverlay
) {
var z = ""
var isSuccess: Boolean? = false
//Variables used in the SQL query
var strData = ""
var strData2 = ""
try {
con = dbConn() // Connect to database
if (con == null) {
z = "Check Your Internet Access!"
} else {
val query = "select [ValueOne], [ValueTwo] from [TableName] where [ValueOne] = '$barcodeValue'"
val stmt = con!!.createStatement()
val cursor = stmt.executeQuery(query)
barcodeValue = results[0].getRawValue()!!
println(barcodeValue)
if (cursor.next()) {
//Selects the values from the columns in the table where the query is taking place
strData = cursor.getString("[ValueOne]")
strData2 = cursor.getString("[ValueTwo]")
var finalDispositionID = strData
var moduleSizeID = strData2
println(finalDispositionID)
println(moduleSizeID)
//barcode_field_value3 is the name of the textview
//barcode_field_value2 is the name of the other textview
//barcode_field_value3.text = strData
z = "Login successful"
isSuccess = true
con!!.close()
} else {
z = "Invalid Credentials!"
isSuccess = false
}
}
} catch (ex: java.lang.Exception) {
isSuccess = false
z = ex.message!!
}
The query happens in the function onSuccess(). I included the entire file for reference though.
LiveBarcodeScanningActivity
private fun setUpWorkflowModel() {
workflowModel = ViewModelProviders.of(this).get(WorkflowModel::class.java)
// Observes the workflow state changes, if happens, update the overlay view indicators and
// camera preview state.
workflowModel!!.workflowState.observe(this, Observer { workflowState ->
if (workflowState == null || Objects.equal(currentWorkflowState, workflowState)) {
return#Observer
}
currentWorkflowState = workflowState
Log.d(TAG, "Current workflow state: ${currentWorkflowState!!.name}")
val wasPromptChipGone = promptChip?.visibility == View.GONE
when (workflowState) {
WorkflowState.DETECTING -> {
promptChip?.visibility = View.VISIBLE
promptChip?.setText(R.string.prompt_point_at_a_barcode)
startCameraPreview()
}
WorkflowState.CONFIRMING -> {
promptChip?.visibility = View.VISIBLE
promptChip?.setText(R.string.prompt_move_camera_closer)
startCameraPreview()
}
WorkflowState.SEARCHING -> {
promptChip?.visibility = View.VISIBLE
promptChip?.setText(R.string.prompt_searching)
stopCameraPreview()
}
WorkflowState.DETECTED, WorkflowState.SEARCHED -> {
promptChip?.visibility = View.GONE
stopCameraPreview()
}
else -> promptChip?.visibility = View.GONE
}
val shouldPlayPromptChipEnteringAnimation = wasPromptChipGone && promptChip?.visibility == View.VISIBLE
promptChipAnimator?.let {
if (shouldPlayPromptChipEnteringAnimation && !it.isRunning) it.start()
}
})
workflowModel?.detectedBarcode?.observe(this, Observer { barcode ->
if (barcode != null) {
val barcodeFieldList = ArrayList<BarcodeField>()
barcodeFieldList.add(BarcodeField("Module Serial Number", barcode.rawValue ?: ""))
BarcodeResultFragment.show(supportFragmentManager, barcodeFieldList)
}
})
}```
You are setting workflowModel.detectedBarcode live data in BarcodeProcessor. So you can find where you are passing this workflowModel to BarcodeProcessor constructor and add such a code to observe this live data in your activtiy:
workflowModel.detectedBarcode.observe(this, Observer {
myTextView.text = it
})
This answer pertains directly to displaying results in the Google ML-Kit Showcase sample project. So if your working on that with barcode scanning this is related.
In order to display the results on successful scan you need to add the fields into the
BarcodeFieldAdapter file
internal class BarcodeFieldViewHolder private constructor(view: View) : RecyclerView.ViewHolder(view) {
private val labelView: TextView = view.findViewById(R.id.barcode_field_label)
private val valueView: TextView = view.findViewById(R.id.barcode_field_value)
private val moduleSize: TextView = view.findViewById(R.id.textViewModuleSize)
private val finalDisposition: TextView = view.findViewById(R.id.textViewFinalDisp)
private val NCRNotes: TextView = view.findViewById(R.id.textViewNCR)
private val OverlapLengthText: TextView = view.findViewById((R.id.textViewOverlapLength))
fun bindBarcodeField(barcodeField: BarcodeField) {
//These are the original values that display in the Barcode_field.xml
labelView.text = barcodeField.label
valueView.text = barcodeField.value
//These are the new values I passed in
moduleSize.text = BarcodeProcessor.data.moduleSize
finalDisposition.text = BarcodeProcessor.data.finalDisposition
NCRNotes.text = BarcodeProcessor.data.NCRNotes
OverlapLengthText.text = BarcodeProcessor.data.OverlapLength
}
Inside
BarcodeProcessor
declare a data object
object data {
var finalDisposition = "init"
var moduleSize = "init"
var barcodeValue: String = ""
var NCRNotes = ""
var OverlapLength = ""
}
These variables will be passed into the BarcodeFieldAdapter file above then displayed in the barcode_field.xml on success.
Inside the query function - That is in the BarcodeProcessor file
//Selects the values from the columns in the table where the query is taking place
strData = cursor.getString("Column Name 1")
strData2 = cursor.getString("Column Name 2")
strData4 = cursor.getString("Column Name 3")
//Assigns the values to the variables inside the object data
data.finalDisposition = strData
data.moduleSize = strData2
data.OverlapLength = strData4
data.NCRNotes = ""
Finally, inside the barcode_field.xml file, create TextViews with the (R.id.TextViewNAMES) that are shown above in the BarcodeFieldAdapter file. Now on successful scanning the new values from the query will be displayed.

Categories

Resources