简体   繁体   中英

Please help me find errors in this small piece of code

I am into Android Development. I don't know Kotlin just Java but had to submit a project in Kotlin so I wrote the code in Java and Used the inbuilt "Convert Java code to Kotlin Code" feature of Android Studio. But the converted code has some errors, I don't know how to solve them. Heres the code:

package com.varunsen.newcards

import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import java.util.*

class MainActivity : AppCompatActivity() {
    var listView: ListView? = null
    var refreshLayout: SwipeRefreshLayout? = null
    var list: MutableList<*> = ArrayList<Int>()
    var adapter: ArrayAdapter<*>? = null
    var cardCount: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Toast.makeText(this, "Try Refreshing by swiping down.", Toast.LENGTH_LONG).show()
        listView = findViewById<View>(R.id.listView) as ListView
        refreshLayout = findViewById(R.id.refreshLayout)
        cardCount = findViewById(R.id.card_count)
        list.add("1")
        list.add("2")
        list.add("3")
        list.add("4")
        cardCount.setText("Total Cards : " + list.size)
        adapter = ArrayAdapter(this@MainActivity, R.layout.card, list)
        listView!!.adapter = adapter
        refreshLayout.setOnRefreshListener(OnRefreshListener {
            list.add(list.size + 1)
            adapter.notifyDataSetChanged()
            cardCount.setText("Total Cards : " + list.size)
            refreshLayout.setRefreshing(false)
        })
    }
}

Android studio is showing red underlines under all .add() functions, then the cardCount below it, refreshLayout, adapter all red.

It is showing 2 errors:

  1. Out-projected type 'MutableList<*>' prohibits the use of 'public abstract fun add(element: E): Boolean defined in kotlin.collections.MutableList

  2. Smart cast to 'TextView!' is impossible, because 'cardCount' is a mutable property that could have been changed by this time

You can replace MutableList<*> by MutableList<Int> for case 1. For case 2, you need to use cardCount? because this var is nullable. I recommend you to study the kotlin basics before coding in kotlin.

Hope to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM