Créez une application pour obtenir des informations météorologiques à l'aide de l'API tout en consultant le livre technique.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!--Voir la liste des villes-->
    <ListView
        android:id="@+id/lvCityList"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5" />
    <!--Disposition de la moitié inférieure de l'écran affichant les informations météorologiques-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:layout_weight="0.5"
        android:orientation="vertical">
        <!--Afficher "Détails météo"-->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:gravity="center"
            android:text="@string/tv_winfo_title"
            android:textSize="25dp"
            />
        <!--Disposition pour organiser les noms de villes et la météo côte à côte-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:orientation="horizontal">
            <!--Affichage du nom de la ville-->
            <TextView
                android:id="@+id/tvCityName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"/>
            <!--Afficher la météo-->
            <TextView
                android:id="@+id/tvWeatherTelop"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textSize="20sp"/>
        </LinearLayout>
        <!--Parties de l'écran qui permettent de faire défiler la partie des informations détaillées de la météo-->
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <!--Afficher les informations météorologiques détaillées-->
            <TextView
                android:id="@+id/tvWeatherDesc"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textSize="15dp"/>
        </ScrollView>
    </LinearLayout>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.asyncsample">
    <uses-permission
        android:name="android.permission.INTERNET"/>
    <uses-permission
        android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
strings.xml
<resources>
    <string name="app_name">Information météo</string>
    <string name="tv_winfo_title">Détails météo</string>
</resources>
MainActivity.java
package com.example.asyncsample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//Obtenir la partie d'écran ListView
        ListView lvCityList = findViewById(R.id.lvCityList);
//Préparer un objet List à utiliser avec SimpleAdapter
        List<Map<String, String>> cityList = new ArrayList<>();
//Préparation de l'objet Map pour stocker les données de la ville et l'enregistrement des données dans cityList
        Map<String, String> city = new HashMap<>();
        city.put("name", "Osaka");
        city.put("id", "270000");
        cityList.add(city);
        city = new HashMap<>();
        city.put("name", "Kobe");
        city.put("id", "280010");
        cityList.add(city);
//Utilisé avec SimpleAdapter de-Préparation des variables pour à
        String[] from = {"name"};
        int[] to = {android.R.id.text1};
//Définir SimpleAdapter
        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, cityList, android.R.layout.simple_expandable_list_item_1, from, to);
//Définir SimpleAdapter dans ListView
        lvCityList.setAdapter(adapter);
//Définir l'auditeur sur ListView
        lvCityList.setOnItemClickListener(new ListItemClickListener());
    }
//Une classe de membre qui décrit le traitement lorsqu'une liste est sélectionnée
    private class ListItemClickListener implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//Obtenez le nom de la ville et l'ID de ville de la ligne tapée dans ListView
            Map<String, String> item = (Map<String, String>) parent.getItemAtPosition(position);
            String cityName = item.get("name");
            String cityId = item.get("id");
//Définissez le nom de la ville acquis sur tvCityName
            TextView tvCityName = findViewById(R.id.tvCityName);
            tvCityName.setText(cityName + "La météo:");
//Obtenez TextView pour afficher les informations météorologiques
            TextView tvWeatherTelop = findViewById(R.id.tvWeatherTelop);
//Obtenez TextView pour afficher des informations météorologiques détaillées
            TextView tvWeatherDesc = findViewById(R.id.tvWeatherDesc);
//WeatherInfoReceiver nouveau. Passez le TextView obtenu ci-dessus comme argument.
            WeatherInfoReceiver receiver = new WeatherInfoReceiver(tvWeatherTelop, tvWeatherDesc);
//Exécuter WeatherInfoReceiver
            receiver.execute(cityId);
        }
    }
    private class WeatherInfoReceiver extends AsyncTask<String, String, String> {
//Champ de partie de l'écran pour afficher la météo actuelle
        private TextView _tvWeatherTelop;
//Champ de partie de l'écran pour afficher les détails météorologiques
        private TextView _tvWeatherDesc;
//constructeur
//Les parties de l'écran qui affichent les informations météorologiques sont acquises à l'avance et stockées sur le terrain.
        public WeatherInfoReceiver(TextView tvWeatherTelop, TextView tvWeatherDesc){
            _tvWeatherTelop = tvWeatherTelop;
            _tvWeatherDesc = tvWeatherDesc;
        }
        @Override
        public String doInBackground(String... params){
//Récupère le premier argument de longueur variable (index 0). Il s'agit de l'ID de la ville.
            String id = params[0];
//Créez une chaîne d'URL de connexion à l'aide de l'ID de la ville
            String urlStr = "http://weather.livedoor.com/forecast/webservice/json/v1?city=" + id;
//Chaîne JSON obtenue du service d'informations météorologiques. Les informations météorologiques sont stockées.
            String result = "";
//Décrivez le processus de connexion à l'URL ci-dessus et obtenez la chaîne de caractères JSON ici
//Renvoie une chaîne JSON
            HttpURLConnection con = null;
            InputStream is = null;
            try{
                URL url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.connect();
                is = con.getInputStream();
                result = is2String(is);
            }
            catch(MalformedURLException ex){
            }
            catch(IOException ex){
            }
            finally{
                if(con != null){
                    con.disconnect();
                }
                if(is != null){
                    try{
                        is.close();
                    }
                    catch(IOException ex){
                    }
                }
            }
            return result;
        }
        @Override
        public void onPostExecute(String result){
//Préparer des variables de chaîne de caractères pour les informations météorologiques
            String telop = "";
            String desc = "";
            try{
                JSONObject rootJSON = new JSONObject(result);
                JSONObject descriptionJSON = rootJSON.getJSONObject("description");
                desc = descriptionJSON.getString("text");
                JSONArray forecasts = rootJSON.getJSONArray("forecasts");
                JSONObject forecastNow = ((JSONArray) forecasts).getJSONObject(0);
                telop = forecastNow.getString("telop");
            }
            catch(JSONException ex){
            }
//Décrivez ici le processus d'analyse de la chaîne de caractères JSON des informations météorologiques.
//Définir la chaîne d'informations météorologiques dans TextView
            _tvWeatherTelop.setText(telop);
            _tvWeatherDesc.setText(desc);
        }
    }
    private String is2String(InputStream is) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuffer sb = new StringBuffer();
        char[] b = new char[1024];
        int line;
        while(0 <= (line = reader.read(b))){
            sb.append(b, 0, line);
        }
        return sb.toString();
    }
}
        Recommended Posts