Android-приложение с фактами о Чаке Норрисе на Kotlin – Devcolibri

  • Автор темы Lucania
  • 21
  • Обновлено
  • 05, May 2023
  • #1
Привет! Вот пример приложения с фактами о Чаке Норрисе на языке Kotlin:
  • Создайте новый проект в Android Studio с пустой активностью.
  • Откройте файл
     activity_main.xml
    и добавьте в него
     TextView
    для отображения фактов:


phpCopy code
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.example.chucknorrisfacts.MainActivity">

<TextView

android:id="@+id/fact_textview"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="24sp"

android:layout_centerInParent="true"/>

</RelativeLayout>


  • Создайте класс
     FactFetcher
    для получения фактов о Чаке Норрисе:


kotlinCopy code
 import org.json.JSONObject
import java.net.URL

class FactFetcher {

fun fetchFact(): String? {

val url = URL("https://api.chucknorris.io/jokes/random")

val jsonString = url.readText()

val json = JSONObject(jsonString)

return json.getString("value")

}
}

  • В классе
     MainActivity
    получите факт и отобразите его в
     TextView
    :


kotlinCopy code
 import android.os.Bundle

import android.os.AsyncTask

import androidx.appcompat.app.AppCompatActivity

import kotlinx.android.synthetic.main.activity_main.*

import java.lang.Exception

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

FetchFactTask().execute()

}

inner class FetchFactTask : AsyncTask<Void, Void, String>() {

override fun doInBackground(vararg params: Void?): String? {

val factFetcher = FactFetcher()

return try {

factFetcher.fetchFact()

} catch (e: Exception) {

null

}

}

override fun onPostExecute(result: String?) {

fact_textview.text = result ?: "Failed to fetch a fact"

}

}

}

Теперь запустите приложение, и оно будет показывать случайные факты о Чаке Норрисе при каждом запуске.

Lucania


Рег
02 Feb, 2023

Тем
27158

Постов
27328

Баллов
298908
Тем
49554
Комментарии
57426
Опыт
552966

Интересно