天气解析

<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>


好,搞点,继续下一个!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值