Android 天气预报

绝地灬酷狼 2022-07-28 04:06 385阅读 0赞

从开始到完成基本功能差不多一个星期 因为不知道怎么入手和很多导包的问题
在这个项目里我第一次用了线程 网络请求 json解析
所以觉得还是挺有意义的
我在写的时候没有找到讲解特别详细的源码
导致其实理解起来不知道干什么的时候是很没方向和步骤的 所以用写博客的形式把整个思路和流程梳理一遍
写一个界面显示天气接收地点button查询 界面就这个三大部分
关键部分就在从网上得到json键值对 然后解析 显示这三大步骤
界面后面我会贴出代码虽然很丑但是有些控件id还是可以体现出来的
先看一下从网上得到json键值对
从网上得到键值对用了类 一个getURLConnection的函数这个函数在thread类中调用作用是从给定的接口地址(也就是代码中的path)获取对应的信息

  1. public static String getURLConnection(String path) {
  2. String xml = "";
  3. System.out.println("sept5");
  4. try{
  5. System.out.println("sept6");
  6. HttpClient client = new DefaultHttpClient();//创建一个httpclient对象
  7. System.out.println("sept7");
  8. HttpGet get = new HttpGet(path);
  9. System.out.println("sept8");
  10. HttpResponse response = client.execute(get);
  11. System.out.println("sept9");
  12. int code = response.getStatusLine().getStatusCode();
  13. Log.d("http", "code");
  14. if (code == 200) {
  15. //如果返回200才算成功才可以继续执行
  16. System.out.println("sept3");
  17. InputStream reader = response.getEntity().getContent();
  18. BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
  19. String list = buffer.readLine();//读一行
  20. while (list != null) {
  21. xml += list;
  22. list = buffer.readLine();
  23. }
  24. }
  25. }catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. System.out.println("2222"+xml);
  29. return xml;
  30. }
  31. private class thread implements Runnable {
  32. @Override
  33. public void run() {
  34. String todayFirst = "http://api.k780.com:88/?app=weather.today&weaid=";
  35. String todayCity = ed_city.getText().toString();
  36. System.out.println(todayCity+"sept2");
  37. String todayLast ="&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
  38. System.out.println("sept1"+todayFirst+todayCity+todayLast);
  39. String todayWeather = getURLConnection(todayFirst+todayCity+todayLast);
  40. System.out.println("1111"+todayWeather);
  41. Message msg = new Message();
  42. Bundle bundle = new Bundle();
  43. bundle.putString("todayWeather", todayWeather);
  44. msg.setData(bundle);
  45. handler.sendMessage(msg);
  46. }
  47. }

解析键值对和改变UI信息在下面这个handle中实现

  1. public class Myhandler extends Handler{
  2. public void handleMessage(Message msg){
  3. String todayWeather = msg.getData().getString("todayWeather");
  4. if (!todayWeather.equals("")){
  5. try{
  6. todayWeather = String.valueOf(new JSONObject(todayWeather).getJSONObject("result"));
  7. JSONObject json = new JSONObject(todayWeather);
  8. tv_city.setText(json.getString("citynm"));
  9. tv_jintian.setText(json.getString("weather"));
  10. tv_wendu.setText(json.getString("temp_curr")+"°");
  11. tv_fanwei.setText(json.getString("temperature"));
  12. tv_priview.setText(todayWeather);
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }
  18. }

以上就可以写实现天气预报的功能了 并没有别的东西 对就只是功能啦!!
以下是源码
xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent"
  5. android:layout_height="fill_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  6. android:paddingRight="@dimen/activity_horizontal_margin"
  7. android:paddingTop="@dimen/activity_vertical_margin"
  8. android:paddingBottom="@dimen/activity_vertical_margin"
  9. android:background="#ddf0ed"
  10. app:layout_behavior="@string/appbar_scrolling_view_behavior"
  11. tools:showIn="@layout/activity_main" tools:context=".MainActivity">
  12. <EditText
  13. android:layout_width="wrap_content"
  14. android:layout_height="70dp"
  15. android:id="@+id/ed_city"
  16. android:text="西安"
  17. android:layout_alignParentTop="true"
  18. android:layout_alignParentStart="true"
  19. android:layout_toStartOf="@+id/bt_serch" />
  20. <Button
  21. android:layout_width="70dp"
  22. android:layout_height="70dp"
  23. android:text="天气"
  24. android:id="@+id/bt_serch"
  25. android:background="@drawable/se_button"
  26. android:layout_alignBottom="@+id/ed_city"
  27. android:layout_alignParentEnd="true" />
  28. <LinearLayout
  29. android:orientation="vertical"
  30. android:layout_width="fill_parent"
  31. android:layout_height="match_parent"
  32. android:layout_below="@+id/ed_city"
  33. android:weightSum="1"
  34. android:layout_alignParentStart="true"
  35. android:layout_alignParentEnd="true">
  36. <TextView
  37. android:layout_width="fill_parent"
  38. android:layout_height="50dp"
  39. android:text="地区"
  40. android:textSize="40dp"
  41. android:gravity="center"
  42. android:id="@+id/tv_city"
  43. android:layout_weight="0.18" />
  44. <TextView
  45. android:layout_width="fill_parent"
  46. android:layout_height="30dp"
  47. android:textSize="25dp"
  48. android:text="今日天气"
  49. android:gravity="center"
  50. android:id="@+id/tv_weather"
  51. android:layout_weight="0.10" />
  52. <TextView
  53. android:layout_width="fill_parent"
  54. android:layout_height="40dp"
  55. android:text="今天温度"
  56. android:gravity="center"
  57. android:textSize="40dp"
  58. android:id="@+id/tv_wendu"
  59. android:layout_weight="0.27" />
  60. <TextView
  61. android:layout_width="fill_parent"
  62. android:layout_height="wrap_content"
  63. android:text="温度范围"
  64. android:textSize="25dp"
  65. android:gravity="center"
  66. android:id="@+id/tv_fanwei"
  67. android:layout_weight="0.12" />
  68. <TextView
  69. android:layout_width="fill_parent"
  70. android:layout_height="wrap_content"
  71. android:text="建议"
  72. android:id="@+id/tv_advices"
  73. android:layout_weight="0.29" />
  74. </LinearLayout>
  75. </RelativeLayout>

mainactivity

  1. package com.example.katherine_qj.weatherday;
  2. import android.os.Bundle;
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.support.design.widget.FloatingActionButton;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.support.v7.widget.Toolbar;
  8. import android.util.Log;
  9. import android.view.View;
  10. import android.view.Menu;
  11. import android.view.MenuItem;
  12. import android.view.Window;
  13. import android.widget.Button;
  14. import android.widget.EditText;
  15. import android.widget.TextView;
  16. import org.apache.http.HttpResponse;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.impl.client.DefaultHttpClient;
  20. import org.json.JSONObject;
  21. import java.io.BufferedReader;
  22. import java.io.InputStream;
  23. import java.io.InputStreamReader;
  24. public class MainActivity extends AppCompatActivity {
  25. private EditText ed_city;
  26. private Button bt_serch;
  27. private TextView tv_priview;
  28. private TextView tv_city;
  29. private TextView tv_jintian;
  30. private TextView tv_wendu;
  31. private TextView tv_fanwei;
  32. public static Handler handler;
  33. private Thread t;
  34. int i = 1;
  35. @Override
  36. protected void onCreate(Bundle savedInstanceState) {
  37. super.onCreate(savedInstanceState);
  38. requestWindowFeature(Window.FEATURE_NO_TITLE);
  39. setContentView(R.layout.activity_main);
  40. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  41. setSupportActionBar(toolbar);
  42. Init();
  43. FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
  44. bt_serch.setOnClickListener(new View.OnClickListener(){
  45. @Override
  46. public void onClick(View v) {
  47. thread gt = new thread();
  48. t = new Thread(gt, "Refresh");
  49. t.start();
  50. handler = new Myhandler();
  51. }
  52. } );
  53. fab.setOnClickListener(new View.OnClickListener() {
  54. @Override
  55. public void onClick(View v) {
  56. thread gt = new thread();
  57. t = new Thread(gt, "Refresh");
  58. t.start();
  59. handler = new Myhandler();
  60. }
  61. });
  62. // Init();
  63. // thread gt = new thread();
  64. // t = new Thread(gt, "Refresh");
  65. // t.start();
  66. // handler = new Myhandler();
  67. }
  68. public void Init (){
  69. ed_city = (EditText)findViewById(R.id.ed_city);
  70. bt_serch = (Button)findViewById(R.id.bt_serch);
  71. tv_priview =(TextView)findViewById(R.id.tv_advices);
  72. tv_city = (TextView)findViewById(R.id.tv_city);
  73. tv_jintian = (TextView)findViewById(R.id.tv_weather);
  74. tv_wendu = (TextView)findViewById(R.id.tv_wendu);
  75. tv_fanwei = (TextView)findViewById(R.id.tv_fanwei);
  76. }
  77. public static String getURLConnection(String path) {
  78. String xml = "";
  79. System.out.println("sept5");
  80. try{
  81. System.out.println("sept6");
  82. HttpClient client = new DefaultHttpClient();//创建一个httpclient对象
  83. System.out.println("sept7");
  84. HttpGet get = new HttpGet(path);
  85. System.out.println("sept8");
  86. HttpResponse response = client.execute(get);
  87. System.out.println("sept9");
  88. int code = response.getStatusLine().getStatusCode();
  89. Log.d("http", "code");
  90. if (code == 200) {
  91. //如果返回200才算成功才可以继续执行
  92. System.out.println("sept3");
  93. InputStream reader = response.getEntity().getContent();
  94. BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
  95. String list = buffer.readLine();//读一行
  96. while (list != null) {
  97. xml += list;
  98. list = buffer.readLine();
  99. }
  100. }
  101. }catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. System.out.println("2222"+xml);
  105. return xml;
  106. }
  107. private class thread implements Runnable {
  108. @Override
  109. public void run() {
  110. String todayFirst = "http://api.k780.com:88/?app=weather.today&weaid=";
  111. String todayCity = ed_city.getText().toString();
  112. System.out.println(todayCity+"sept2");
  113. String todayLast ="&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
  114. System.out.println("sept1"+todayFirst+todayCity+todayLast);
  115. String todayWeather = getURLConnection(todayFirst+todayCity+todayLast);
  116. System.out.println("1111"+todayWeather);
  117. Message msg = new Message();
  118. Bundle bundle = new Bundle();
  119. bundle.putString("todayWeather", todayWeather);
  120. msg.setData(bundle);
  121. handler.sendMessage(msg);
  122. }
  123. }
  124. public class Myhandler extends Handler{
  125. public void handleMessage(Message msg){
  126. String todayWeather = msg.getData().getString("todayWeather");
  127. if (!todayWeather.equals("")){
  128. try{
  129. todayWeather = String.valueOf(new JSONObject(todayWeather).getJSONObject("result"));
  130. JSONObject json = new JSONObject(todayWeather);
  131. tv_city.setText(json.getString("citynm"));
  132. tv_jintian.setText(json.getString("weather"));
  133. tv_wendu.setText(json.getString("temp_curr")+"°");
  134. tv_fanwei.setText(json.getString("temperature"));
  135. tv_priview.setText(todayWeather);
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. }
  141. }
  142. @Override
  143. public boolean onCreateOptionsMenu(Menu menu) {
  144. // Inflate the menu; this adds items to the action bar if it is present.
  145. getMenuInflater().inflate(R.menu.menu_main, menu);
  146. return true;
  147. }
  148. @Override
  149. public boolean onOptionsItemSelected(MenuItem item) {
  150. // Handle action bar item clicks here. The action bar will
  151. // automatically handle clicks on the Home/Up button, so long
  152. // as you specify a parent activity in AndroidManifest.xml.
  153. int id = item.getItemId();
  154. //noinspection SimplifiableIfStatement
  155. if (id == R.id.action_settings) {
  156. return true;
  157. }
  158. return super.onOptionsItemSelected(item);
  159. }
  160. }

还有在实现过程中遇到的问题 使用网络的时候必须要导入这两个包
compile files(‘libs/httpclient-4.4.1.jar’)
compile files(‘libs/httpcore-4.4.1.jar’)
然后必须加上这段代码
packagingOptions {//导入http包的时候必须要加的以下这段话
exclude ‘META-INF/DEPENDENCIES.txt’
exclude ‘META-INF/LICENSE.txt’
exclude ‘META-INF/NOTICE.txt’
exclude ‘META-INF/NOTICE’
exclude ‘META-INF/LICENSE’
exclude ‘META-INF/DEPENDENCIES’
exclude ‘META-INF/notice.txt’
exclude ‘META-INF/license.txt’
exclude ‘META-INF/dependencies.txt’
exclude ‘META-INF/LGPL2.1’
}
还要在androidmanifest文件中加入网络请求

  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  2. over!!!!!

发表评论

表情:
评论列表 (有 0 条评论,385人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android 天气预报(2)

    之前实现过了天气预报的功能 但是真的好丑 真的只是实现功能 所以上一篇博客也没有贴出图片 这次 相对于第一个 首先是界面做了调整 其次就是 之前那个只能查看实时天气 这个天气预

    相关 Android 天气预报

    从开始到完成基本功能差不多一个星期 因为不知道怎么入手和很多导包的问题 在这个项目里我第一次用了线程 网络请求 json解析 所以觉得还是挺有意义的 我在写的时候没