Android 天气预报(使用okHttp、AsyncTask访问和风天气并Gosn解析数据)

版权声明:没事随便转 https://blog.csdn.net/qq_41816123/article/details/84993968

第一步老规矩导架包,都是开源哦

在项目的配置文件中添加
在这里插入图片描述
在这里插入图片描述

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okio:okio:1.9.0'
compile 'com.google.code.gson:gson:2.8.0'

第二步添加权限

在清单文件AndroidManifest.xml中添加

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

第三步布局(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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/et_cityname"
            android:hint="请输入城市名字"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/btn_select_weather"
            android:text="查询"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_werther_conten"
            android:textSize="20sp"
            android:text="测试"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

第四步活动内访问(MainActivity.class)

package com.example.myapplication2;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private final String KEY = "e1984444a03d4a52a1f6cc545cce9245";
    private TextView tv_werther_conten;
    private EditText et_cityname;
    private Button btn_select_weather;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Werther werther= (Werther) msg.obj;
            switch(msg.what){
                case 1:
                    tv_werther_conten.setText("时间:" + String.valueOf(werther.getHeWeather6().get(0).getUpdate().getLoc()) +
                            "、地点:" + werther.getHeWeather6().get(0).getBasic().getLocation() +
                            "、天气:" + werther.getHeWeather6().get(0).getNow().getCond_txt() +
                            "、风向:" + werther.getHeWeather6().get(0).getNow().getWind_dir() +
                            "、气温:" + werther.getHeWeather6().get(0).getNow().getTmp());
                    break;
            }
            Log.d(TAG, "onResponse: " + String.valueOf(werther.getHeWeather6().get(0).getUpdate().getLoc()));

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDate();
        btn_select_weather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityname = String.valueOf(et_cityname.getText());
                if (cityname.equals("")) {
                    Toast.makeText(MainActivity.this, "城市名不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    String url = "https://free-api.heweather.com/s6/weather/now?key=e1984444a03d4a52a1f6cc545cce9245&location=" + cityname;
                    new MyAsyncTask().execute(url);

                }
            }
        });
    }

    private void initDate() {

    }

    private void initView() {
        tv_werther_conten = (TextView) this.findViewById(R.id.tv_werther_conten);
        et_cityname = (EditText) this.findViewById(R.id.et_cityname);
        btn_select_weather = (Button) this.findViewById(R.id.btn_select_weather);
    }

    private void getWerther(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Log.d(TAG, "url: " + url);
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.d(TAG, "onFailure: ");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                Log.d(TAG, "onResponse: " + responseData);
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
                Werther werther = gson.fromJson(responseData, Werther.class);
                Message message=new Message();
                message.what=1;
                message.obj=werther;
                handler.sendMessage(message);
            }
        });

    }

    class MyAsyncTask extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... strings) {
            String url = strings[0];
            getWerther(url);
            return null;
        }
    }
}

讲一下这其中的注意点:

1.String responseData = response.body().string();访问成功之后拿到的数据
在这里插入图片描述
你可以复制上面的地址给个城市中文拼音都可以
拿到这个数据之后
Json自动创建module网站
进这个网站
在项目中创建这些类
在这里插入图片描述
用上自己的包名和第一个类名
在这里插入图片描述
在解析过程中如果内容不多可以不用这种方式。毕竟还是有点小麻烦的。
可以直接原生态

String json = "{\n" +
                "  \"rst\": 0,\n" +
                "  \"msg\": \"ok\",\n" +
                "  \"data\": {\n" +
                "    \"cookie\": \"JSESSIONID=abcntKeuJhop56LGykfdw\"\n" +
                "  }\n" +
                "}";
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(json);
        System.out.println("rst:" + jsonObject.get("rst").getAsInt());
        System.out.println("msg:" + jsonObject.get("msg").getAsString());
        System.out.println("data:" + jsonObject.get("data").getAsJsonObject().get("cookie").getAsString());

2.附上和服天气的接口地址,你可以从中拿你所需要的数据并放到界面中显示,key我也给你了,不同的接口地址不一样,自己注意哦。
和风天气接口地址
3.更改UI要在主线程中进行,不然会报错。所以我用到了Handler
大概意思和你说一下:

你在访问网络过程中是开了一个子线程,而你的主线程会继续运行下去,当你访问并获取数据的时候再更新UI,你的主线程已经跑完了。

总结:

1.在开发的过程中不能急,虽然说拿别人的代码会改就行,但是还是要自己理解和看懂。
2.没事像小白一样多写写,就记住了。不能每天都学习新知识。好像是拿了玉米丢了桃子,消化了在拿不是美滋滋。

猜你喜欢

转载自blog.csdn.net/qq_41816123/article/details/84993968