天气解析

原创 2016年06月02日 09:53:31

<span style="font-family: 'Microsoft Yahei', Simsun; background-color: rgb(255, 255, 255);">前段时间做了一个天气类的解析,防止自己忘记了,特整理以下笔记。</span>

​首先,接口用的是http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101200105&weatherType=0  这个,需要更多的接口看这个http://www.eoeandroid.com/thread-333874-1-1.html,里面整理了几个Json数据的接口,很好用。是我百度得到的...。

其次,开始实施:

先看结构:


我这个​解析是在我的一个应用里做的,解析的数据展示在fragment里面,所以用的是fragment。

继续:下面是贴代码

​1、回调接口,好拿数据

package http;

public interface HttpCallbackListener {
	void onFinish(String response);

	void onError(Exception e);
}

2、网络请求类,返回json数据

package http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class HttpUtils {

	public static void sendHttpRequest(final String address,
			final HttpCallbackListener listener) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				Looper.prepare();
				HttpURLConnection connection = null;
				try {
					URL url = new URL(address);

					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					if (listener != null) {
						// 回调onFinish()方法
						listener.onFinish(response.toString());
						Log.i("HttpUtils", "-----"+response.toString());
					}
				} catch (Exception e) {
					if (listener != null) {
						// 回调onError()方法
						listener.onError(e);
					}
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
				Looper.loop();
			}
		}).start();

	}

}

3、天气的实体类

package http;

public class Weather {

	public String city;
	public String tem;
	public String wea;
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getTem() {
		return tem;
	}
	public void setTem(String tem) {
		this.tem = tem;
	}
	public String getWea() {
		return wea;
	}
	public void setWea(String wea) {
		this.wea = wea;
	}
	@Override
	public String toString() {
		return "Weather [city=" + city + ", tem=" + tem + ", wea=" + wea + "]";
	}
	
	
	
}


4、json数据解析类,本次实现的的方式是把获取到的数据存入到本地,采用sharedpreference的存储方式。

package http;

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


import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class Utility {

	/**
	 * 解析服务器返回的json数据
	 * @param context
	 * @param response
	 */
	public static void handleWeatherResponse(Context context,String response){
		Log.i("Utility", "-------handleWeatherResponse+运行到这里");
		try {
			JSONObject jsonObject =new JSONObject(response);
			JSONObject weatherInfo =jsonObject.getJSONObject("weatherInfo");
			String city =weatherInfo.getString("city");
			String tem =weatherInfo.getString("temp1");
			String weather =weatherInfo.getString("weather");
			Log.i("Utility", "--------"+city+tem+weather);
			SharedPreferences.Editor edit =PreferenceManager.getDefaultSharedPreferences(context).edit();
//			SharedPreferences.Editor edit = getSharedPreferences("data",context.MODE_PRIVATE).edit();
			edit.putString("city", city);
			edit.putString("tem",tem);
			edit.putString("weather", weather);
			
			SharedPreferences pres =PreferenceManager.getDefaultSharedPreferences(context);
			String city2 =pres.getString("city", "");
			Log.i("MainActivity","-----------写入数据===此时获取到的city数据是:"+city);
			edit.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
5、最后就是fragment里给各个控件利用handler机制给定值啦。

package http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;


import com.example.snxx.R;
import com.example.snxx.R.layout;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Fragment_top extends Fragment{
	
	private TextView txt_city,txt_tem,txt_wea;
	private String address2 ="http://weather.51wnl.com/weatherinfo/GetMoreWeather?cityCode=101200105&weatherType=0";
	
	private Handler handler =new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what ==0x11){
				SharedPreferences pres =(SharedPreferences) msg.obj;
				String city =pres.getString("city", "");
				String tem =pres.getString("tem", "");
				String weather =pres.getString("weather", "");
				txt_city.setText(city);
				txt_tem.setText(tem);
				txt_wea.setText(weather);
			}
		};
	};
	
	
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view =inflater.inflate(R.layout.fragment_title_wether, container, false);
		txt_city =(TextView)view.findViewById(R.id.fragmentweather_city);
		txt_tem=(TextView)view.findViewById(R.id.fragmentweather_tem);
		txt_wea =(TextView)view.findViewById(R.id.fragmentweather_wea);

		Toast.makeText(getActivity(), "tooo", Toast.LENGTH_SHORT).show();
		
		showWeather();
		
		Toast.makeText(getActivity(), "this", Toast.LENGTH_SHORT).show();
		
		return view;
	}

	public Fragment_top() {
		super();
	}
	
	public void showWeather(){

		HttpUtils.sendHttpRequest(address2, new HttpCallbackListener() {
			
			@Override
			public void onFinish(String response) {
				Log.i("Utility", "-------onFinish+运行到这里  response="+response);
				handleWeatherResponse(response);
				Log.i("Utility", "---------Utility.handleWeatherResponse+运行到这里");
//				SharedPreferences pres =PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
				
				SharedPreferences pres =PreferenceManager.getDefaultSharedPreferences(getActivity());
				String city =pres.getString("city", "");
				String tem =pres.getString("tem", "");
				String weather =pres.getString("weather", "");
				String str1 =city;
				String str2 =tem;
				String str3 =weather;
				Log.i("MainActivity","-----------即将发送消息===此时获取到的city数据是:"+city);
				Message msg =new Message();
				msg.obj =pres;
				msg.what =0x11;
				handler.sendMessage(msg);
				
			}
			
			@Override
			public void onError(Exception e) {
				Toast.makeText(getActivity(), "网络获取数据失败", Toast.LENGTH_SHORT).show();
			}
		});
	}
	public  void sendHttpRequest(final String address,
			final HttpCallbackListener listener) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				Looper.prepare();
				HttpURLConnection connection = null;
				try {
					URL url = new URL(address);

					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					if (listener != null) {
						// 回调onFinish()方法
						listener.onFinish(response.toString());
						Log.i("HttpUtils", "-----"+response.toString());
					}
				} catch (Exception e) {
					if (listener != null) {
						// 回调onError()方法
						listener.onError(e);
					}
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
				Looper.loop();
			}
		}).start();

	}
	public void handleWeatherResponse(String response){
		Log.i("Utility", "-------handleWeatherResponse+运行到这里");
		try {
			JSONObject jsonObject =new JSONObject(response);
			JSONObject weatherInfo =jsonObject.getJSONObject("weatherinfo");
			String city =weatherInfo.getString("city");
			String tem =weatherInfo.getString("temp1");
			String weather =weatherInfo.getString("weather1");
			Log.i("Utility", "--------=====1=1=1=1=1=1="+city+tem+weather);
//			SharedPreferences.Editor edit =PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
			SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
			edit.putString("city", city);
			edit.putString("tem",tem);
			edit.putString("weather", weather);
			
			SharedPreferences pres =PreferenceManager.getDefaultSharedPreferences(getActivity());
			String city2 =pres.getString("city", "");
			Log.i("MainActivity","-----------写入数据===此时获取到的city数据是:"+city);
			edit.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
6、最后想了下,还是把布局文件贴上去,坑谁读别坑自己啊

fragment_title_wether.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="horizontal" >

    <TextView
        android:id="@+id/fragmentweather_city"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center" 
        android:textSize="@dimen/x50"/>

    <LinearLayout 
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
        android:id="@+id/fragmentweather_wea"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="0dp" 
        android:gravity="center"
        android:textSize="@dimen/x40"/>
        <TextView
        android:id="@+id/fragmentweather_tem"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="0dp" 
        android:gravity="center"
        android:textSize="@dimen/x40"/>
    </LinearLayout>

</LinearLayout>

list_item.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="horizontal" >
    <TextView 
        android:id="@+id/list_item_city"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="武汉"
        android:gravity="center"
        android:textColor="@color/orange"
        android:textSize="@dimen/x40"/>
    <LinearLayout 
        android:layout_width="0dp"
        android:layout_weight="3"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView 
            android:id="@+id/list_item_weather"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="晴"
            android:textSize="@dimen/x35"/>
        <TextView 
            android:id="@+id/list_item_tem"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="26~30"
            android:textSize="@dimen/x35"/>
    </LinearLayout>

</LinearLayout>


好,搞点,继续下一个!


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

天气预报json解析

  • 2014-09-22 10:27
  • 2.83MB
  • 下载

利用dom4j解析xml--天气预报

解析xml之前我们先获取下xml文件,这里以天气预报接口为例, 在浏览器里输入http://wthrcdn.etouch.cn/WeatherApi?city=杭州就可以获取到杭州的当天天气. 将获取...

13pull解析xml天气信息

  • 2015-10-13 11:50
  • 855KB
  • 下载

国家气象局天气预报接口JSON完全解析

最近由于谷歌天气预报接口出现了一些小问题,没办法,只能重新写一下国家气象局天气预报接口JSON完全解析,程序包括了所有的地点,所以有些复杂 1.首先准备好要解析的json数据,方便以后写程序解析的时...

Android使用XmlPullParser解析XML以及天气预报信息api使用

最近学校组织做实训,分到的任务是做Android的天气预报软件,我分到的任务是制作生活小贴士的部分。主要是关于空气质量、洗车指数一类的信息的显示,我使用的API是新浪天气的API,新浪天气的API提供...

JSON亲测解析 实现北京的天气预报信息

经过俩天的学习与实践  本次通过一个天气预报小小数据虽说仅仅只接了一组数据但大体还是了解JSON的解析的基本过程。下面就是先关解析的过程:先把解析封装成一个类: 上面是一个仅仅解析一个北京市的天...

Android小程序-Walker解析天气(七)

目标效果:   输入城市名称点击按钮,会在下边的ListView中显示未来几天的天气情况。 1.程序素材:http://pan.baidu.com/s/1qYCHHhi 2.将素材中的图片文...

个人小程序智能对话查询工具完整代码分享--快递、身份证、词典、诗词等

这篇文章的原文地址:http://blog.csdn.net/huangmeimao/article/details/76418753 转载请标明出处,谢谢。 这个小程序旨在通过自然语言对话查询快...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)