Как получить данные из API и показать их в моем приложении? - PullRequest
0 голосов
/ 13 февраля 2020

Я новичок в Android development и kotlin и в настоящее время работаю над приложением для викторин. Я решил использовать Open Trivia Database . Сейчас я пытаюсь получить данные json и отобразить их. Вот как выглядит мой код:

class TriviaRequest (

    val results: List<TriviaResult>
)

class TriviaResult(

    val category: String,
    val type: String,
    val question: String,
    val correct_answer: String,
    val incorrect_answer: List<String>
)

class AnswerActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_answer)

    fetch()


}

private fun fetch(){

    Log.d("fetch", "fetching")
    val url = "https://opentdb.com/api.php?amount=1&type=multiple"
    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()
            val gson = GsonBuilder().create()
            val triviaRequest = gson.fromJson(body, TriviaRequest::class.java)

            val result = triviaRequest.results[0]
            val question = result.question.toSpanned()
            val questionCategory = result.category.toSpanned()
            val correctAnswer = result.correct_answer.toSpanned()
            val incorrectAnswer1 = result.incorrect_answer[0].toSpanned()
            val incorrectAnswer2 = result.incorrect_answer[1].toSpanned()
            val incorrectAnswer3 = result.incorrect_answer[2].toSpanned()

            val questions = listOf(
                correctAnswer,
                incorrectAnswer1,
                incorrectAnswer2,
                incorrectAnswer3
            )

            Collections.shuffle(questions)

            runOnUiThread {

                questionText.text = question
                themeText.text =  questionCategory

                alternative1.text = questions[0]
                alternative1.isEnabled = true

                alternative2.text = questions[1]
                alternative2.isEnabled = true

                alternative3.text = questions[2]
                alternative3.isEnabled = true

                alternative4.text = questions[3]
                alternative4.isEnabled = true

                alternative1.setOnClickListener {
                    alternative1.isClickable = false
                    if (alternative1.text == correctAnswer) {
                        fetch()
                    } else {
                        alternative1.text = "---"
                    }
                }

                alternative2.setOnClickListener {
                    alternative2.isClickable = false
                    if (alternative2.text == correctAnswer) {
                        fetch()
                    } else {
                        alternative2.text = "---"
                    }
                }

                alternative3.setOnClickListener {
                    alternative3.isClickable = false
                    if (alternative3.text == correctAnswer) {
                        fetch()
                    } else {
                        alternative3.text = "---"
                    }
                }

                alternative4.setOnClickListener {
                    alternative4.isClickable = false
                    if (alternative4.text == correctAnswer) {
                        fetch()
                    } else {
                        alternative4.text = "---"
                    }
                }
            }
        }

        override fun onFailure(call: Call, e: IOException) {
            Log.d("Failure", "Failure fetching")
        }
    })
  }
}

Когда я вхожу в это действие, оно просто падает с этой трассировкой стека:

2020-02-13 15:18:53.940 1266-1353/? E/AndroidRuntime: FATAL EXCEPTION: OkHttp 
Dispatcher
Process: com.example.quizzo, PID: 1266
java.lang.SecurityException: Permission denied (missing INTERNET permission?)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:150)
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
    at java.net.InetAddress.getAllByName(InetAddress.java:1152)
    at okhttp3.Dns$Companion$SYSTEM$1.lookup(Dns.kt:48)
    at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.kt:160)
    at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.kt:125)
    at okhttp3.internal.connection.RouteSelector.next(RouteSelector.kt:71)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:199)
    at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:109)
    at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:77)
    at okhttp3.internal.connection.Transmitter.newExchange$okhttp(Transmitter.kt:162)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:35)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:84)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:71)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
    at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
 Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    at libcore.io.Linux.android_getaddrinfo(Native Method)
    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
    at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
    at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
    at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
    Caused by: android.system.ErrnoException: android_getaddrinfo failed: EPERM (Operation not permitted)

РЕДАКТИРОВАТЬ: Я сузился до этого кода:

val неверный1 = result.incorrect_answer [0] .toSpanned ()

Это моя функция toSpanned:

fun String.toSpanned() : Spanned {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
    } else {
        @Suppress("DEPRECATION")
        return Html.fromHtml(this)
    }
}

Я не знаю, почему там происходит сбой, но я был бы очень признателен, если бы кто-нибудь обнаружил проблему с этим, спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...