Я работаю над проектом, который состоит из функций, которые извлекают и записывают в переменную html_data, и таймера, который вызывает их каждую минуту.
Я сохраняю предыдущие html_data в переменную prev_html_data, а затем, когда они отличаются, я отправляю уведомление.
Проблема в том, что переменная всегда представляет собой пустую строку (способ Я его инициализировал), то есть он никогда не будет переопределен. html_data работает нормально и инициализируется точно так же. Я теряю из-за этого рассудок. Пожалуйста, помогите мне...
Я даже выделил все в функцию, чтобы можно было вызывать ее из основного класса, но она все равно ни черта не работает.
Переменная всегда представляет собой пустую строку, что бы я ни делал... Каждый раз, когда я ее печатаю...
А еще я забыл упомянуть html_data, которые я print в timerRun() по какой-то причине никогда не анализировался html_parse(), даже хотя я вызываю эту функцию в fetchdata().
class MainActivity : AppCompatActivity() {
var unique_id = 1000
var html_data = ""
var prev_html_data = ""
lateinit var notificationManager: NotificationManager
lateinit var notificationChannel: NotificationChannel
lateinit var builder: Notification.Builder
private val channelId = "hallomotto"
private val description = "***** alert"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
fetchdata()
this.prev_html_data = html_data
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.GREEN
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this, channelId)
.setContentTitle("Floria alert!!")
.setContentText("A new message has been posted (Floria is here!!!)")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))
} else {
builder = Notification.Builder(this)
.setContentTitle("Floria alert!!")
.setContentText("A new message has been posted (Floria is here!!!)")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))
}
val timer = Timer(true)
timer.schedule(object : TimerTask() {
override fun run() {
timerRun()
}
}, 60000, 60000)
}
private fun fetchdata() {
val volleyQueue = Volley.newRequestQueue(this)
val url = "*****"
val jsonRequest = JSONObject()
jsonRequest.put("key", "*****")
val jsonObjectRequest = JsonObjectRequest(
Request.Method.POST,
url,
jsonRequest,
{ response ->
val html_message = response.get("html_data")
html_data = html_message.toString()
display_html()
},
{ error ->
Toast.makeText(this, "Error has occurred when making the request", Toast.LENGTH_LONG).show()
Log.e("MainActivity", "load_error: ${error.localizedMessage}")
}
)
volleyQueue.add(jsonObjectRequest)
Log.v("JSON request", jsonRequest.toString())
}
private fun html_parse() {
html_data = """
""".trimIndent() + html_data
html_data += """
""".trimIndent()
}
private fun display_html() {
html_parse()
Log.v("Output", html_data)
val encoded_data = Base64.encodeToString(html_data.toByteArray(), Base64.NO_PADDING)
val webview = findViewById(R.id.webview)
webview.loadData(encoded_data, "text/html", "base64")
}
private fun timerRun(){
fetchdata()
if(html_data != this.prev_html_data){
notificationManager.notify(unique_id, builder.build())
unique_id += 1
Log.e("Match 1", html_data);
Log.e("Match 2", this.prev_html_data)
}
this.prev_html_data = html_data
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... -in-kotlin
Как сделать переменную доступной из функции запуска TimerTask() в Kotlin (Android)? ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение