前段时间做了一个天气类的解析,防止自己忘记了,特整理以下笔记。
首先,接口用的是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);
}
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 + "]";
}
}
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