Отредактируйте переменные и используйте другой класс (Kotlin) - PullRequest
0 голосов
/ 05 августа 2020

Помогите, пожалуйста, программа не работает. Я хочу изменить переменные a и b и поместить их в имена Спасибо .................................. .................................................. ..........

class Asd(){
        lateinit var a: String
        lateinit var b: String
        var database = FirebaseDatabase.getInstance().getReference("RedCars")
            .child("20-8-2020 18:0")
            .addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {

                }

                override fun onDataChange(p0: DataSnapshot) {
                    var map = p0.value as Map<String, Any>

                a = map["price"].toString()
                 b = map["pickup"].toString()
            }

        })
}


public class MyCustomAdapter(context: Context): BaseAdapter(){

    private val mContext: Context

    val d = Asd().a
    val h = Asd().b
    var names = arrayListOf<String>(
        d, h
    )

Я пробую это: .............

 public class MyCustomAdapter(context: Context): BaseAdapter(){

    lateinit var a: String
    lateinit var b: String
    var database = FirebaseDatabase.getInstance().getReference("RedCars")
        .child("20-8-2020 18:0")
        .addValueEventListener(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
                var map = p0.value as Map<String, Any>
                
                a = map["price"].toString()
                b = map["pickup"].toString()
            }

        })

    private val mContext: Context

    var names = arrayListOf<String>(
        a, b
    )

Ошибка Logcat: .. ..................................................

2020-08-05 22:03:16.024 9227-9227/com.example.redcars E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.redcars, PID: 9227
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.redcars/com.example.redcars.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3895)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
    at android.os.Handler.dispatchMessage(Handler.java:110)
    at android.os.Looper.loop(Looper.java:219)
    at android.app.ActivityThread.main(ActivityThread.java:8347)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
 Caused by: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
    at com.example.redcars.MainActivity$MyCustomAdapter.<init>(MainActivity.kt:133)
    at com.example.redcars.MainActivity.onCreate(MainActivity.kt:47)
    at android.app.Activity.performCreate(Activity.java:8085)
    at android.app.Activity.performCreate(Activity.java:8073)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3868)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473) 
    at android.os.Handler.dispatchMessage(Handler.java:110) 
    at android.os.Looper.loop(Looper.java:219) 
    at android.app.ActivityThread.main(ActivityThread.java:8347) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055) 

И это в MainActivity:

listView.adapter = MyCustomAdapter(this)

1 Ответ

1 голос
/ 06 августа 2020

Вы должны использовать свойства lateinit только после их инициализации. Поэтому я предлагаю перенести инициализацию массива names на ValueEventListener:

public class MyCustomAdapter(context: Context): BaseAdapter(){

    lateinit var a: String
    lateinit var b: String
    lateinit var names: ArrayList<String>

    // or you can use MutableList
    // var namesMutable: MutableList<String> = mutableListOf()


    var database = FirebaseDatabase.getInstance().getReference("RedCars")
        .child("20-8-2020 18:0")
        .addValueEventListener(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError) {

            }

            override fun onDataChange(p0: DataSnapshot) {
                var map = p0.value as Map<String, Any>
                
                a = map["price"].toString()
                b = map["pickup"].toString()

                // INITIALIZE THE ARRAY HERE

                names = arrayListOf<String>(a, b)
                // namesMutable.add(a)
                // namesMutable.add(b)
                // notifyDatasetChanged()
            }

        })

    // ...
}
...