Android parses the weather forecast of aggregated data

Time:2022-9-21

Free Weather Forecast API:https://www.juhe.cn/docs/api/id/73

Android parses the weather forecast of aggregated data

MainActivity.java

<span style="font-size:14px;">package com.example.networktest;  

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.net.URLEncoder;  

import org.json.JSONArray;  
import org.json.JSONException;  
import org.json.JSONObject;  

import android.app.Activity;  
import android.os.Bundle;  
import android.os.Handler;  
import android.os.Message;  
import android.util.Log;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.TextView;  

public class MainActivity extends Activity {  
    private Button sendRequest;  
    private TextView responseText;  
    public static final int SHOW_RESPONSE = 0;  
    private Handler handler = new Handler() {  

        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case SHOW_RESPONSE:  
                String response = (String) msg.obj;  
                // Perform UI operations here and display the results on the interface  
                responseText.setText(response);  
            }  
        }  

    };  

    @Override 
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        sendRequest = (Button) findViewById(R.id.send_request);  
        responseText = (TextView) findViewById(R.id.response);  
        sendRequest.setOnClickListener(new OnClickListener() {  
            @Override 
            public void onClick(View arg0) {  
                sendRequestWithHttpURLConnection();  
            }  
        });  
    }  

    protected void sendRequestWithHttpURLConnection() {  
        new Thread() {  
            @Override 
            public void run() {  
                URL url;  
                HttpURLConnection connection = null;  
                try {  
                    // url = new  
                    // URL("https://10.2.5.119:8080/Server/getData.json");  
                    String cityName = URLEncoder.encode(&quot;Binzhou&quot;, &quot;utf-8&quot;);  
                    url = new URL(  
                            "http://v.juhe.cn/weather/index?format=2&cityname=" 
                                    + cityName  
                                    + "&key=ab9d7e2007472d723baf71fcdc4ba094");  
                    connection = (HttpURLConnection) url.openConnection();  
                    connection.setRequestMethod("GET");  
                    connection.setConnectTimeout(8000);  
                    connection.setReadTimeout(8000);  
                    InputStream in = connection.getInputStream();  
                    // Next, read the obtained input stream  
                    BufferedReader reader = new BufferedReader(  
                            new InputStreamReader(in));  
                    StringBuilder response = new StringBuilder();  
                    String line;  
                    while ((line = reader.readLine()) != null) {  
                        response.append(line);  
                    }  
                    System.out.println("response=" + response.toString());  
                    //parseWithJSON(response.toString());  
                    parseWeatherWithJSON(response.toString());  
                    Message message = new Message();  
                    message.what = SHOW_RESPONSE;  
                    // Store the result returned by the server in the Message  
                    message.obj = response.toString();  
                    handler.sendMessage(message);  
                } catch (MalformedURLException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                } finally {  
                    if (connection != null) {  
                        connection.disconnect();  
                    }  
                }  
            }  
        }.start();  

    }  

    protected void parseWeatherWithJSON(String response) {  
        try {  
            JSONObject jsonObject=new JSONObject(response);  
            String resultcode=jsonObject.getString("resultcode");  
            if(resultcode.equals("200")){  
                JSONObject resultObject=jsonObject.getJSONObject("result");  
                JSONObject todayObject=resultObject.getJSONObject("today");  
                String date_y=todayObject.getString("date_y");  
                String week=todayObject.getString("week");  
                String temperature=todayObject.getString("temperature");  
                Log.d("MainActivity", "date_y="+date_y+"week="+week+"temp="+temperature);  
            }  

        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
    }  

    protected void parseWithJSON(String response) {  
        try {  
            JSONArray jsonArray = new JSONArray(response);  
            for (int i = 0; i < jsonArray.length(); i++) {  
                JSONObject jsonObject = jsonArray.getJSONObject(i);  
                String id = jsonObject.getString("id");  
                String name = jsonObject.getString("name");  
                String version = jsonObject.getString("version");  
                Log.d("MainActivity", "id=" + id + "name=" + name + "version=" 
                        + version);  
            }  
        } catch (JSONException e) {  
            e.printStackTrace();  
        }  
    }  

}</span>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>

Original link:https://blog.csdn.net/nysi_i/…

Recommended Today

Getting started with MapStruct

Article directory In actual project development, POJOs are widely used as data carriers, usually as follows: entity name entity meaning illustrate DO Data Object One-to-one correspondence with the database table structure, and the data source object is transmitted upward through the DAO layer DTO Data Transfer Object The data transfer object, the object that the […]