我正在尝试从功能和截击方面进行反击, 我正在对Web服务中的某些数据进行for循环,当数据与我拥有的某些数据相同时,我希望计数器加1,这很容易,但是当函数结束并返回到onCreate函数时,计数器变为0,这是我的代码:
class MainActivity : AppCompatActivity() {
var n1 = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("counter0", n1.toString())
selectType()
Log.d("counter2", n1.toString())
carCount1.text= "$n1 cars "
}
}
fun selectType() {
val url= "http://mydomen/getallcars.php"
val pd= ProgressDialog(this)
pd.setMessage("Please Wait...")
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER)
pd.show()
val rq= Volley.newRequestQueue(this)
val sr= StringRequest(
Request.Method.GET, url,
Response.Listener { response ->
pd.hide()
//converting the string to json array object
val array = JSONArray(response)
list.clear()
//traversing through all the object
for (i in 0 until array.length()) {
//getting item object from json array
val product = array.getJSONObject(i)
Log.d("testing123", product.toString())
//adding the product to item list
if(product.getString("type") == fandvtext.text.toString()) {
n1=+1
Log.d("counter1", n1.toString())
}
list.add(
Cars(
product.getString("type")
)
)
}
},
Response.ErrorListener { error ->
pd.hide()
Toast.makeText(this, error.message.toString(), Toast.LENGTH_LONG).show()
})
Toast.makeText(this, n1.toString(), Toast.LENGTH_LONG).show()
rq.add(sr)
}
}
class Cars(types: String) {
var types:String = types
}
然后当我运行它时,Logcat 中会显示此内容
D/counter0: 0
D/counter1: 1
D/counter2: 0
counter0 应该是 0,它是 counter2 必须为 1,但事实并非如此! 那么,现在我该怎么办!?
最佳答案
来 self 的模板:How to get data from any asynchronous operation in android
这是你可以做的事情
像这样改变你的函数:
fun selectType(callback:(Int) -> Unit){
....
将此代码更改为:
fun selectType(callback:(Int) -> Unit) {
val url= "http://mydomen/getallcars.php"
val pd= ProgressDialog(this)
pd.setMessage("Please Wait...")
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER)
pd.show()
val rq= Volley.newRequestQueue(this)
val sr= StringRequest(
Request.Method.GET, url,
Response.Listener { response ->
pd.hide()
//converting the string to json array object
val array = JSONArray(response)
list.clear()
//traversing through all the object
var n1 = 0
for (i in 0 until array.length()) {
//getting item object from json array
val product = array.getJSONObject(i)
Log.d("testing123", product.toString())
//adding the product to item list
if(product.getString("type") == fandvtext.text.toString()) {
n1=+1
Log.d("counter1", n1.toString())
}
list.add(
Cars(
product.getString("type")
)
)
}
callback.invoke(n1)
},
然后,在 onCreate 中调用它:
selectType(){ result ->
//here, the result is the value of your count
}
关于java - 如何使用android中的函数进行异步计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57451508/