Kotlin | Запрос API с охттп - PullRequest
       16

Kotlin | Запрос API с охттп

0 голосов
/ 07 марта 2020

Решение:

class MainActivity : AppCompatActivity() {
    lateinit var playerStats: PlayerStats

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Picasso.get().load("https://...../....../example.png").into(Viewer)
        var PlayerName: String = ""

        fun fetchJson() {
            val url = "https://my.api.site/example/"
            val request = Request.Builder().url(url).build()
            val client = OkHttpClient()
            client.newCall(request).enqueue(object : Callback {
                var mainHandler = Handler(this@MainActivity.getMainLooper())
                override fun onResponse(call: Call, response: Response) {
                    mainHandler.post {
                        val body = response.body()?.string()
                        if (body == null) return@post
                        println(body)

                        val gson = GsonBuilder().create()
                        playerStats = gson.fromJson(body, PlayerStats::class.java)
                        println(playerStats)

                        // TODO Now you can access to your view and set every thing to textView
                        textView.text = playerStats.username
                    }
                }

                override fun onFailure(call: Call, e: IOException) {
                    println("API execute failed")
                }
            })
        }

        buttonGO.setOnClickListener {
            PlayerName = editText.text.toString()
            fetchJson()
            if (PlayerName == null || PlayerName.trim() == "") {
                println("please input data, input cannot be blank")
            } else {
                Picasso.get().load("https://...../...../" + PlayerName + ".png")
                    .into(Viewer)
                textView.setText(PlayerName).toString()
            }
        }
    }
} ```

У меня есть этот код для моего запроса API, и он работает, когда я использую отладчик .

Я вижу результаты в PlayerStats класс но сейчас у меня проблема.

Но на MainActivity.class это function не работает:

val url = "https://api.example.com/..../"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()

client.newCall(request).enqueue(object: Callback {
    override fun onResponse(call: Call, response: Response) {
        val body = response?.body?.string()
        println(body)
        val gson = GsonBuilder().create()
        val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
        println(PlayerStats)
    }

    override fun onFailure(call: Call, e: IOException) {
        println("API execute failed")
    }
})

Stats.class :

class PlayerStats(val username: String  , val level: Double )

Мне нужен способ получить доступ к val username / val level из MainActivity

class MainActivity(val mystats: PlayerStats) : AppCompatActivity(){

Не работает, из-за нулевых аргументов.

Если я попытаюсь исправить:

class MyActivity: AppCompatActivity() {
    var myStats: Stats? = null
//..
}

В среде IDE говорят, что ей требуется вызов с подтверждением safe call или non-null, но если я попытаюсь сделать это с заявленным вызовом non-null, приложение cra sh и я получаю эту ошибку:

2020-03-05 18: 58: 02.803 23276-23276 / my.example.package E / AndroidRuntime: FATAL EXCEPTION: main Process: my. example.package, PID: 23276 kotlin .KotlinNullPointerException в my.example.package.MainActivity $ onCreate $ 1.invoke (MainActivity.kt: 31) в my.example.package.MainActivity $ onCreate $ 3.onClick (MainActivity.kt: 68) в android .view.View.performClick (View. java: 7125) в android .view.View.performClickInternal (View. java: 7102) в android .view.View.access 3500 долларов (просмотр. java: 801) при android .view.View $ PerformClick.run (Vi ew. java: 27336) в android .os.Handler.handleCallback (обработчик. java: 883) в android .os.Handler.dispatchMessage (обработчик. java: 100) в android .os.Looper.l oop (Looper. java: 214) в android .app.ActivityThread.main (ActivityThread. java: 7356) в java .lang.reflect.Method.invoke ( Собственный метод) в com. android .internal.os.RuntimeInit $ MethodAndArgsCaller.run (RuntimeInit. java: 492) в com. android .internal.os.ZygoteInit.main (ZygoteInit. java: 930 )

С safe call я получаю null в качестве вывода


Полный код:

MainActivity.class:

package my.example.package

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.GsonBuilder
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.*
import java.io.IOException

class MainActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Picasso.get().load("https://...../....../example.png").into(Viewer)
        var PlayerName: String = ""
        fun fetchJson() {
            val url = "https://my.api.site/example/"
            val request = Request.Builder().url(url).build()
            val client = OkHttpClient()
            client.newCall(request).enqueue(object: Callback {
                override fun onResponse(call: Call, response: Response) {
                    val body = response?.body?.string()
                    println(body)
                    val gson = GsonBuilder().create()
                    val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
                    println(PlayerStats)
                }
                override fun onFailure(call: Call, e: IOException) {
                    println("API execute failed")
                }
            })
        }

        buttonGO.setOnClickListener {
            PlayerName = editText.text.toString()
            fetchJson()
            if (PlayerName == null || PlayerName.trim() == "") {
                println("please input data, input cannot be blank")
            } else {
                Picasso.get().load("https://...../...../" + PlayerName + ".png")
                    .into(Viewer)
                textView.setText(PlayerName).toString()
            }
        }
    }
}

PlayerStats.class:

package my.example.package
class PlayerStats(val username: String  , val level: Double )

1 Ответ

0 голосов
/ 07 марта 2020

Замените это на ваш код:

class MainActivity : AppCompatActivity() {
    lateinit var playerStats: PlayerStats

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Picasso.get().load("https://...../....../example.png").into(Viewer)
        var PlayerName: String = ""

        fun fetchJson() {
            val url = "https://my.api.site/example/"
            val request = Request.Builder().url(url).build()
            val client = OkHttpClient()
            client.newCall(request).enqueue(object : Callback {
                var mainHandler = Handler(this@MainActivity.getMainLooper())
                override fun onResponse(call: Call, response: Response) {
                    mainHandler.post {
                        val body = response.body()?.string()
                        if (body == null) return@post
                        println(body)

                        val gson = GsonBuilder().create()
                        playerStats = gson.fromJson(body, PlayerStats::class.java)
                        println(playerStats)

                        // TODO Now you can access to your view and set every thing to textView
                        textView.text = playerStats.username
                    }
                }

                override fun onFailure(call: Call, e: IOException) {
                    println("API execute failed")
                }
            })
        }

        buttonGO.setOnClickListener {
            PlayerName = editText.text.toString()
            fetchJson()
            if (PlayerName == null || PlayerName.trim() == "") {
                println("please input data, input cannot be blank")
            } else {
                Picasso.get().load("https://...../...../" + PlayerName + ".png")
                    .into(Viewer)
                textView.setText(PlayerName).toString()
            }
        }
    }
} ```

...