当前位置:   article > 正文

天气预报_android studio 天气预报app csdn定位摇一摇和风

android studio 天气预报app csdn定位摇一摇和风

一、运行效果图





二、核心代码

  1. package com.example.weather;
  2. import com.example.weather.R;
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.view.Menu;
  6. public class MainActivity extends Activity {
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. }
  12. @Override
  13. public boolean onCreateOptionsMenu(Menu menu) {
  14. // Inflate the menu; this adds items to the action bar if it is present.
  15. getMenuInflater().inflate(R.menu.main, menu);
  16. return true;
  17. }
  18. }

  1. package com.example.weather;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import com.example.weather.R;
  7. import com.example.weather.adapter.WeatherAdapter;
  8. import com.example.weather.moder.Weather;
  9. import com.example.weather.util.HttpCallbackListener;
  10. import com.example.weather.util.HttpUtil;
  11. import com.google.gson.JsonArray;
  12. import com.google.gson.JsonObject;
  13. import com.google.gson.JsonParser;
  14. import android.app.Activity;
  15. import android.os.Bundle;
  16. import android.os.Handler;
  17. import android.os.Message;
  18. import android.view.View;
  19. import android.view.View.OnClickListener;
  20. import android.view.animation.LayoutAnimationController;
  21. import android.view.animation.ScaleAnimation;
  22. import android.widget.EditText;
  23. import android.widget.ImageButton;
  24. import android.widget.ListView;
  25. import android.widget.Toast;
  26. public class WeatherActivity extends Activity {
  27. private EditText ecCity;
  28. private ImageButton btnQuery;
  29. private ListView lvFutureWeather;
  30. public static final int SHOW_RESPONSE = 1;
  31. private List<Weather> data;
  32. private Handler handler = new Handler() {
  33. public void handleMessage(Message msg) {
  34. switch (msg.what) {
  35. case SHOW_RESPONSE:
  36. String response = (String) msg.obj;
  37. if (response != null) {
  38. parseWithJSON(response);
  39. WeatherAdapter weatherAdapter = new WeatherAdapter(
  40. WeatherActivity.this,
  41. R.layout.activity_weather_listitem, data);
  42. lvFutureWeather.setAdapter(weatherAdapter);
  43. ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0,
  44. 1);
  45. scaleAnimation.setDuration(1000);
  46. LayoutAnimationController animationController = new LayoutAnimationController(
  47. scaleAnimation, 0.6f);
  48. lvFutureWeather.setLayoutAnimation(animationController);
  49. }
  50. break;
  51. default:
  52. break;
  53. }
  54. }
  55. private void parseWithJSON(String response) {
  56. // TODO Auto-generated method stub
  57. data = new ArrayList<Weather>();
  58. JsonParser parser = new JsonParser();// json解析器
  59. JsonObject obj = (JsonObject) parser.parse(response);
  60. // 获取返回状态吗
  61. String resultcode = obj.get("resultcode").getAsString();
  62. // 状态码如果是200说明数据返回成功
  63. if (resultcode != null && resultcode.equals("200")) {
  64. JsonObject resultObj = obj.get("result").getAsJsonObject();
  65. JsonArray futureWeatherArray = resultObj.get("future")
  66. .getAsJsonArray();
  67. for (int i = 0; i < futureWeatherArray.size(); i++) {
  68. Weather weather = new Weather();
  69. JsonObject weatherObject = futureWeatherArray.get(i)
  70. .getAsJsonObject();
  71. weather.setDayOfWeek(weatherObject.get("week")
  72. .getAsString());
  73. weather.setDate(weatherObject.get("date").getAsString());
  74. weather.setTemperature(weatherObject.get("temperature")
  75. .getAsString());
  76. weather.setWeather(weatherObject.get("weather")
  77. .getAsString());
  78. data.add(weather);
  79. }
  80. }
  81. }
  82. };
  83. @Override
  84. protected void onCreate(Bundle savedInstanceState) {
  85. super.onCreate(savedInstanceState);
  86. setContentView(R.layout.activity_weather);
  87. initViews();
  88. setListeners();
  89. }
  90. public void initViews() {
  91. ecCity = (EditText) findViewById(R.id.etCity);
  92. btnQuery = (ImageButton) findViewById(R.id.btnQuery);
  93. lvFutureWeather = (ListView) findViewById(R.id.lvFutureWeather);
  94. data = new ArrayList<Weather>();
  95. }
  96. private void setListeners() {
  97. btnQuery.setOnClickListener(new OnClickListener() {
  98. public void onClick(View v) {
  99. // TODO Auto-generated method stub
  100. String cityName = ecCity.getText().toString();
  101. try {
  102. cityName = URLEncoder.encode(cityName, "utf-8");
  103. } catch (UnsupportedEncodingException e1) {
  104. e1.printStackTrace();
  105. }
  106. System.out.println("lvFutureWeather=" + lvFutureWeather);
  107. Toast.makeText(WeatherActivity.this, "success",
  108. Toast.LENGTH_LONG).show();
  109. String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="
  110. + cityName + "&key=b6683508adf0adc07aa24e5cc0811487";
  111. Toast.makeText(WeatherActivity.this, "success" + weatherUrl,
  112. Toast.LENGTH_LONG).show();
  113. HttpUtil.sendHttpRequest(weatherUrl,
  114. new HttpCallbackListener() {
  115. public void onFinish(String response) {
  116. // TODO Auto-generated method stub
  117. Message message = new Message();
  118. message.what = SHOW_RESPONSE;
  119. // 将服务器返回的结果存放到Message中
  120. message.obj = response.toString();
  121. handler.sendMessage(message);
  122. }
  123. public void onError(Exception e) {
  124. // TODO Auto-generated method stub
  125. System.out.println("访问失败");
  126. }
  127. });
  128. }
  129. });
  130. }
  131. }

  1. package com.example.weather.adapter;
  2. import java.util.List;
  3. import android.content.Context;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.ArrayAdapter;
  8. import android.widget.TextView;
  9. import com.example.weather.R;
  10. import com.example.weather.moder.Weather;
  11. public class WeatherAdapter extends ArrayAdapter<Weather> {
  12. private int resourceId;
  13. public WeatherAdapter(Context context, int textViewResourceId,
  14. List<Weather> objects) {
  15. super(context, textViewResourceId, objects);
  16. resourceId = textViewResourceId;
  17. }
  18. @Override
  19. public View getView(int position, View convertView, ViewGroup viewgroup) {
  20. Weather weather = getItem(position);
  21. ViewHolder viewHolder = null;
  22. if (convertView == null) {
  23. viewHolder = new ViewHolder();
  24. convertView = LayoutInflater.from(getContext()).inflate(resourceId,
  25. null);
  26. viewHolder.tvDayOfWeek = (TextView) convertView
  27. .findViewById(R.id.tvDayofWeek);
  28. viewHolder.tvDate = (TextView) convertView
  29. .findViewById(R.id.tvDate);
  30. viewHolder.tvTemperature = (TextView) convertView
  31. .findViewById(R.id.tvTemperature);
  32. viewHolder.tvWeather = (TextView) convertView
  33. .findViewById(R.id.tvWeather);
  34. convertView.setTag(viewHolder);
  35. } else {
  36. viewHolder = (ViewHolder) convertView.getTag();
  37. }
  38. viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());
  39. viewHolder.tvDate.setText(weather.getDate());
  40. viewHolder.tvTemperature.setText(weather.getTemperature());
  41. viewHolder.tvWeather.setText(weather.getWeather());
  42. return convertView;
  43. }
  44. private class ViewHolder {
  45. TextView tvDayOfWeek;
  46. TextView tvDate;
  47. TextView tvTemperature;
  48. TextView tvWeather;
  49. }
  50. }

  1. package com.example.weather.moder;
  2. public class Weather {
  3. private String dayOfWeek;// 星期几
  4. private String date;// 日期
  5. private String temperature;// 温度
  6. private String weather;// 天气
  7. public Weather() {
  8. }
  9. public Weather(String dayOfWeek, String date, String temperature,
  10. String weather) {
  11. super();
  12. this.dayOfWeek = dayOfWeek;
  13. this.date = date;
  14. this.temperature = temperature;
  15. this.weather = weather;
  16. }
  17. public String getDayOfWeek() {
  18. return dayOfWeek;
  19. }
  20. public void setDayOfWeek(String dayOfWeek) {
  21. this.dayOfWeek = dayOfWeek;
  22. }
  23. public String getDate() {
  24. return date;
  25. }
  26. public void setDate(String date) {
  27. this.date = date;
  28. }
  29. public String getTemperature() {
  30. return temperature;
  31. }
  32. public void setTemperature(String temperature) {
  33. this.temperature = temperature;
  34. }
  35. public String getWeather() {
  36. return weather;
  37. }
  38. public void setWeather(String weather) {
  39. this.weather = weather;
  40. }
  41. @Override
  42. public String toString() {
  43. return "Weather [dayOfWeek=" + dayOfWeek + ", date=" + date
  44. + ", temperature=" + temperature + ", weather=" + weather + "]";
  45. }
  46. }

  1. package com.example.weather.test;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URLEncoder;
  4. import com.example.weather.util.HttpCallbackListener;
  5. import com.example.weather.util.HttpUtil;
  6. import android.test.AndroidTestCase;
  7. public class WeatherGetTest extends AndroidTestCase {
  8. public void testGetData() {
  9. String cityName = null;
  10. try {
  11. cityName = URLEncoder.encode(cityName, "utf-8");
  12. String weatherUrl = "http://v.juhe.cn/weather/index?format=2&cityname="
  13. + cityName + "&key=b6683508adf0adc07aa24e5cc0811487";
  14. HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
  15. public void onFinish(String response) {
  16. // TODO Auto-generated method stub
  17. System.out.println(response);
  18. }
  19. public void onError(Exception e) {
  20. // TODO Auto-generated method stub
  21. }
  22. });
  23. } catch (Exception e) {
  24. // TODO: handle exception
  25. }
  26. }
  27. }

  1. package com.example.weather.util;
  2. public interface HttpCallbackListener {
  3. void onFinish(String response);
  4. void onError(Exception e);
  5. }

  1. package com.example.weather.util;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import android.util.Log;
  8. public class HttpUtil {
  9. public static void sendHttpRequest(final String address,
  10. final HttpCallbackListener listener) {
  11. new Thread(new Runnable() {
  12. public void run() {
  13. HttpURLConnection connection = null;
  14. try {
  15. URL url = new URL(address);
  16. connection = (HttpURLConnection) url.openConnection();
  17. connection.setRequestMethod("GET");
  18. connection.setConnectTimeout(8000);
  19. connection.setReadTimeout(8000);
  20. connection.setDoInput(true);
  21. connection.setDoOutput(true);
  22. InputStream in = connection.getInputStream();
  23. BufferedReader reader = new BufferedReader(
  24. new InputStreamReader(in));
  25. StringBuilder response = new StringBuilder();
  26. String line;
  27. while ((line = reader.readLine()) != null) {
  28. response.append(line);
  29. }
  30. if (listener != null) {
  31. // 回调 onFinish()方法
  32. listener.onFinish(response.toString());
  33. }
  34. } catch (Exception e) {
  35. if (listener != null) {
  36. // 回调 onError()方法
  37. listener.onError(e);
  38. }
  39. } finally {
  40. if (connection != null) {
  41. connection.disconnect();
  42. }
  43. }
  44. }
  45. }).start();
  46. }
  47. }

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:layout_margin="10dp"
  6. android:background="@drawable/list_item_shape"
  7. android:padding="10dp" >
  8. <TextView
  9. android:id="@+id/tvDayofWeek"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_alignParentLeft="true"
  13. android:layout_alignParentTop="true"
  14. android:layout_marginLeft="15dp"
  15. android:text="星期日" />
  16. <TextView
  17. android:id="@+id/tvDate"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:layout_alignBaseline="@+id/tvDayofWeek"
  21. android:layout_alignBottom="@+id/tvDayofWeek"
  22. android:layout_alignParentRight="true"
  23. android:text="20160207" />
  24. <TextView
  25. android:id="@+id/tvTemperature"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:layout_alignLeft="@+id/tvDayofWeek"
  29. android:layout_below="@+id/tvDayofWeek"
  30. android:layout_marginTop="15dp"
  31. android:text="temperature" />
  32. <TextView
  33. android:id="@+id/tvWeather"
  34. android:layout_width="wrap_content"
  35. android:layout_height="wrap_content"
  36. android:layout_alignLeft="@+id/tvTemperature"
  37. android:layout_below="@+id/tvTemperature"
  38. android:layout_marginTop="15dp"
  39. android:text="weather" />
  40. </RelativeLayout>

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:background="@drawable/city"
  6. tools:context=".WeatherActivity" >
  7. <LinearLayout
  8. android:id="@+id/linearLayout1"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:orientation="horizontal" >
  12. <EditText
  13. android:id="@+id/etCity"
  14. android:layout_width="0dp"
  15. android:layout_height="wrap_content"
  16. android:layout_marginLeft="10dp"
  17. android:layout_marginTop="20dp"
  18. android:layout_weight="1"
  19. android:background="@android:drawable/edit_text"
  20. android:drawableLeft="@drawable/etcity"
  21. android:drawablePadding="5dp"
  22. android:ems="10"
  23. android:hint="@string/etCity" >
  24. <requestFocus />
  25. </EditText>
  26. <ImageButton
  27. android:id="@+id/btnQuery"
  28. android:layout_width="50dp"
  29. android:layout_height="50dp"
  30. android:layout_marginTop="20dp"
  31. android:background="@null"
  32. android:src="@drawable/serch" />
  33. </LinearLayout>
  34. <ListView
  35. android:id="@+id/lvFutureWeather"
  36. android:layout_width="match_parent"
  37. android:layout_height="wrap_content"
  38. android:layout_below="@+id/linearLayout1"
  39. android:layout_centerHorizontal="true"
  40. android:layout_marginLeft="10dp"
  41. android:layout_marginRight="10dp"
  42. android:dividerHeight="10dp"
  43. android:layoutAnimation="@anim/weather_list_layout_animation" >
  44. </ListView>
  45. </RelativeLayout>

三、运行中遇到的问题

刚开始运行的时候显示成功但是不出来天气预报,后来询问过同学之后,修改了代码解决了。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/590051
推荐阅读
相关标签
  

闽ICP备14008679号