Weather app #1

Разрешение в AndroidManifest

<uses-permission android:name="android.permission.INTERNET"/>

Зависимость Volley для build.gradle

implementation 'com.android.volley:volley:1.2.1'

MainActivity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.meter_alc_rgb.wetherapp2.databinding.ActivityMainBinding
import org.json.JSONObject

const val API_KEY = "297ffc1c3e944aefaaf93152221705"
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.bGet.setOnClickListener {
getResult("London")
}
}
private fun getResult(name: String){
val url = "https://api.weatherapi.com/v1/current.json" +
"?key=$API_KEY&q=$name&aqi=no"
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.GET,
url,
{
response->
val obj = JSONObject(response)
val temp = obj.getJSONObject("current")
Log.d("MyLog","Response: ${temp.getString("temp_c")}")
},
{
Log.d("MyLog","Volley error: $it")
}
)
queue.add(stringRequest)
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvTemp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toTopOf="@+id/bGet"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.47"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.16" />

<Button
android:id="@+id/bGet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="16dp"
android:text="get"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

1 комментарий для “Weather app #1”

  1. Буду писать по этим уроком. Если заработает, куплю курс. Работать буду с завтрашнего дня, часов по 6 или 8. Надеюсь получится. Как то вопросы можно задавать?

Добавить комментарий

Ваш адрес email не будет опубликован.