####前言
写了上一篇文章,讲了下这个实现天气预报的使用内容,现在又到了看代码的时候,主要还是贴代码,然后添加足够的注释。
####聚合数据SDK配置
- 将juhe_sdk_v_X_X.jar以及armeabi文件夹(内包含libJuheSDK_v_X_X.so)添加到工程中libs文件夹下
- 打开Moudle setting -> app -> Dependencies,添加juhe_sdk_v_X_X.jar,
- 在AndroidManifest.xml中,加入所需权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- 添加所申请的openid(这个是在Juhe官网上申请的).在继承Application类之后, 在AndroidManifest.xml中,加入android:name属性,值为继承Application的类的路径.
- 初始化聚合数据SDK
import android.app.Application;
public class MyApplication extends Application {
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
JuheSDKInitializer.initialize(getApplicationContext());
}
}
####工程代码
MyApplication.java
package com.onlyloveyd.weather;
import android.app.Application;
import com.thinkland.sdk.android.JuheSDKInitializer;
public class MyApplication extends Application {
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
JuheSDKInitializer.initialize(getApplicationContext());//初始化Juhe数据SDK
}
}
城市选择界面
ChooseCityActivity.java
package com.onlyloveyd.weather;
import ......;
public class ChooseCityActivity extends Activity {
public static final String TAG = "ChooseCityActivity";
@Bind(R.id.tv_choose_city_title)
TextView tvChooseCityTitle;
@Bind(R.id.et_search_city)
EditText etSearchCity;
@Bind(R.id.tv_hotcity)
TextView tvHotcity;
@Bind(R.id.gv_hotcity)
GridView gvHotcity;
private ArrayList<CityItem> mSupportCityList;//所有城市List
private ArrayList<CityItem> mSearchCityList;//城市查询结果List
private CityAdapter mCityAdapter;//城市GridView的Adapter
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.citylist);//城市选择界面
ButterKnife.bind(this);//依赖注入
mSupportCityList = new ArrayList<CityItem>();
mSearchCityList = new ArrayList<CityItem>();
//设置带shape模式的编辑框的背景颜色
//GradientDrawable myGrad = (GradientDrawable)mSearchEditView.getBackground();
//myGrad.setColor(getResources().getColor(R.color.choosecitysearchbackground));
//给城市名编译框添加文本变化的观察者
etSearchCity.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mSearchCityList.clear();//城市查询结果list清空
String searchkey = charSequence.toString();
Log.e(TAG, " city size " + mSupportCityList.size());
for (int j = 0; j < mSupportCityList.size(); j++) {
CityItem item = mSupportCityList.get(j);
if (searchkey.contains(item.getDistrict()) || item.getDistrict().contains(searchkey)) {//遍历查询
mSearchCityList.add(item);
}
}
mCityAdapter.setCityList(mSearchCityList);
mCityAdapter.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
mCityAdapter = new CityAdapter(this, mSupportCityList);
gvHotcity.setAdapter(mCityAdapter);
getSupportCity(this);
}
private void getSupportCity(Context context) {
/**Juhe SDK 封装的方法
* 请求的方法 参数: 第一个参数 当前请求的context 第二个参数 接口id 第三二个参数 接口请求的url 第 四个参数 接口请求的方式
* 第五个参数 接口请求的参数,键值对com.thinkland.sdk.android.Parameters类型; 第六个参数
* 请求的回调方法,com.thinkland.sdk.android.DataCallBack;
*
*/
JuheData.executeWithAPI(context, 39, "http://v.juhe.cn/weather/citys", JuheData.GET, null, new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
try {
//解析JSON数据
JSONObject jsonObject = new JSONObject(responseString);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject object = (JSONObject) result.get(i);
CityItem item = new CityItem(object.getString("id"), object.getString("province"), object.getString("city"), object.getString("district"));
mSupportCityList.add(item);//查询结果添加
mCityAdapter.notifyDataSetChanged();//notify数据变化
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
}
@Override
public void onFailure(int statusCode, String responseString, Throwable throwable) {
Log.e(TAG, responseString);
}
});
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
etSearchCity.setText(null);//避免onBackPress的时候编辑框中还有数据
super.onPause();
}
}
聚合数据针对支持的城市返回的JSON数据格式为
{
“resultcode”:“200”,
“reason”:“successed”,
“result”:[
{
“id”:“1”, /城市ID/
“province”:“北京”,/省份名称/
“city”:“北京”, /城市/
“district”:“北京” /城市/区名称/
},
{
“id”:“2”,
“province”:“北京”,
“city”:“北京”,
“district”:“海淀”
},
}
}
按照这种格式解析出JSON数据
//天气显示界面
WeatherActivity.java
package com.onlyloveyd.weather;
import XXXX;
public class WeatherActivity extends Activity {
private static final String TAG = "MainActivity";
@Bind(R.id.imageview)
ImageView imageview;
@Bind(R.id.tv_cityname)
TextView tvCityname;
@Bind(R.id.tv_date)
TextView tvDate;
@Bind(R.id.iv_zhengfu)
ImageView ivZhengfu;
@Bind(R.id.iv_tenth)
ImageView ivTenth;
@Bind(R.id.iv_geth)
ImageView ivGeth;
@Bind(R.id.iv_du)
ImageView ivDu;
@Bind(R.id.iv_weather_fa)
ImageView ivWeatherFa;
@Bind(R.id.tv_weather)
TextView tvWeather;
@Bind(R.id.iv_weather_fb)
ImageView ivWeatherFb;
@Bind(R.id.tv_temp)
TextView tvTemp;
@Bind(R.id.tv_humidity)
TextView tvHumidity;
@Bind(R.id.tv_wind)
TextView tvWind;
@Bind(R.id.tv_refreshtime)
TextView tvRefreshtime;
@Bind(R.id.gv_future)
GridView gvFuture;
WeatherInfo.ResultBean.SkBean mSk;
WeatherInfo.ResultBean.TodayBean mToday;
FutureAdapter mFutureAdapter;
ArrayList<WeatherInfo.ResultBean.FutureBean> mFutureList;
private Context mContext;
private String mCityName = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.weather);
ButterKnife.bind(this);//依赖注入
Intent intent = getIntent();
mCityName = intent.getStringExtra("cityname");//从选择城市界面选择城市传递到这个Activity
mFutureList = new ArrayList<WeatherInfo.ResultBean.FutureBean>();//未来7天预报的List
mFutureAdapter = new FutureAdapter(this, mFutureList);//未来天气预报的GridView的Adapter
gvFuture.setAdapter(mFutureAdapter);
}
@Override
protected void onResume() {
super.onResume();
mFutureList.clear();
getWeatherInfoByCity(this, mCityName);//查询天气信息,包含的内容比较多,速度还算快,没有单独使用线程
tvCityname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void getWeatherInfoByCity(Context context, String city) {
Log.e(TAG, "getWeatherInfoByCity");
Parameters param = new Parameters();
param.add("cityname", city);
param.add("format", 2);
JuheData.executeWithAPI(context, 39, "http://v.juhe.cn/weather/index", JuheData.GET, param, new DataCallBack() {
@Override
public void onSuccess(int statusCode, String responseString) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject(responseString);
JSONObject resultjson = jsonObject.getJSONObject("result");
JSONObject skjson = resultjson.getJSONObject("sk");
JSONObject todayjson = resultjson.getJSONObject("today");
JSONArray futurejson = resultjson.getJSONArray("future");
mSk = gson.fromJson(skjson.toString(), WeatherInfo.ResultBean.SkBean.class);
mToday = gson.fromJson(todayjson.toString(), WeatherInfo.ResultBean.TodayBean.class);
Log.e(TAG, futurejson.get(2).toString());
for (int i = 0; i < futurejson.length(); i++) {
WeatherInfo.ResultBean.FutureBean futureBean = gson.fromJson(futurejson.get(i).toString(), WeatherInfo.ResultBean.FutureBean.class);
Log.e(TAG, futureBean.toString());
mFutureList.add(futureBean);
}
mFutureAdapter.setmFutureList(mFutureList);
gvFuture.setAdapter(mFutureAdapter);
mFutureAdapter.notifyDataSetChanged();
tvCityname.setText(mCityName);
tvDate.setText(mToday.getDate_y() + " " + mToday.getWeek());
tvWeather.setText(mToday.getWeather());
tvTemp.setText(mToday.getTemperature());
tvHumidity.setText(mSk.getHumidity());
tvWind.setText(mSk.getWind_direction() + " " + mSk.getWind_strength());
tvRefreshtime.setText(getString(R.string.refreshtimesuffix) + mSk.getTime());
String fa = mToday.getWeather_id().getFa();
String fb = mToday.getWeather_id().getFb();
if (fa.equals(fb)) {
ivWeatherFa.setImageResource(getWeatherDrawableByWeatherId("w_", fa));
ivWeatherFb.setImageDrawable(null);
} else {
ivWeatherFa.setImageResource(getWeatherDrawableByWeatherId("w_", fa));
ivWeatherFb.setImageResource(getWeatherDrawableByWeatherId("w_", fb));
}
int tmp = Integer.valueOf(mSk.getTemp());
if (tmp < 0) {
ivZhengfu.setImageResource(R.drawable.fuhao);
int tenth = (0 - tmp) / 10;
int geth = (0 - tmp) % 10;
ivTenth.setImageResource(getWeatherDrawableByWeatherId("org4_widget_nw", String.valueOf(tenth)));
ivGeth.setImageResource(getWeatherDrawableByWeatherId("org4_widget_nw", String.valueOf(geth)));
} else {
ivZhengfu.setImageDrawable(null);
int tenth = tmp / 10;
int geth = tmp % 10;
ivTenth.setImageResource(getWeatherDrawableByWeatherId("org4_widget_nw", String.valueOf(tenth)));
ivGeth.setImageResource(getWeatherDrawableByWeatherId("org4_widget_nw", String.valueOf(geth)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, String responseString, Throwable throwable) {
// TODO Auto-generated method stub
Log.e(TAG, responseString);
}
});
}
private int getWeatherDrawableByWeatherId(String suffix, String fa) {
String res = suffix + fa;
int resid = getResources().getIdentifier(res, "drawable", getPackageName());
return resid;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
float startX = 0;
switch (action) {
case MotionEvent.ACTION_DOWN:
startX = event.getRawX();
break;
case MotionEvent.ACTION_UP:
float endX = event.getRawX();
if ((int) (endX - startX) > 10) {
onBackPressed();
}
break;
default:
break;
}
return true;
}
}
介绍一个Intellij插件 ----- Gson Format, 通过Json格式快速生成Java Bean类,提高开发效率
其实有很多很好用的插件可供选择,不仅可以提高效率,还可以增加自己对开发的兴趣,可以去多了解一下。
谢谢。