Android 天气预报
从开始到完成基本功能差不多一个星期 因为不知道怎么入手和很多导包的问题
在这个项目里我第一次用了线程 网络请求 json解析
所以觉得还是挺有意义的
我在写的时候没有找到讲解特别详细的源码
导致其实理解起来不知道干什么的时候是很没方向和步骤的 所以用写博客的形式把整个思路和流程梳理一遍
写一个界面显示天气接收地点button查询 界面就这个三大部分
关键部分就在从网上得到json键值对 然后解析 显示这三大步骤
界面后面我会贴出代码虽然很丑但是有些控件id还是可以体现出来的
先看一下从网上得到json键值对
从网上得到键值对用了类 一个getURLConnection的函数这个函数在thread类中调用作用是从给定的接口地址(也就是代码中的path)获取对应的信息
public static String getURLConnection(String path) {
String xml = "";
System.out.println("sept5");
try{
System.out.println("sept6");
HttpClient client = new DefaultHttpClient();//创建一个httpclient对象
System.out.println("sept7");
HttpGet get = new HttpGet(path);
System.out.println("sept8");
HttpResponse response = client.execute(get);
System.out.println("sept9");
int code = response.getStatusLine().getStatusCode();
Log.d("http", "code");
if (code == 200) {
//如果返回200才算成功才可以继续执行
System.out.println("sept3");
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String list = buffer.readLine();//读一行
while (list != null) {
xml += list;
list = buffer.readLine();
}
}
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("2222"+xml);
return xml;
}
private class thread implements Runnable {
@Override
public void run() {
String todayFirst = "http://api.k780.com:88/?app=weather.today&weaid=";
String todayCity = ed_city.getText().toString();
System.out.println(todayCity+"sept2");
String todayLast ="&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
System.out.println("sept1"+todayFirst+todayCity+todayLast);
String todayWeather = getURLConnection(todayFirst+todayCity+todayLast);
System.out.println("1111"+todayWeather);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("todayWeather", todayWeather);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
解析键值对和改变UI信息在下面这个handle中实现
public class Myhandler extends Handler{
public void handleMessage(Message msg){
String todayWeather = msg.getData().getString("todayWeather");
if (!todayWeather.equals("")){
try{
todayWeather = String.valueOf(new JSONObject(todayWeather).getJSONObject("result"));
JSONObject json = new JSONObject(todayWeather);
tv_city.setText(json.getString("citynm"));
tv_jintian.setText(json.getString("weather"));
tv_wendu.setText(json.getString("temp_curr")+"°");
tv_fanwei.setText(json.getString("temperature"));
tv_priview.setText(todayWeather);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
以上就可以写实现天气预报的功能了 并没有别的东西 对就只是功能啦!!
以下是源码
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ddf0ed"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="70dp"
android:id="@+id/ed_city"
android:text="西安"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_toStartOf="@+id/bt_serch" />
<Button
android:layout_width="70dp"
android:layout_height="70dp"
android:text="天气"
android:id="@+id/bt_serch"
android:background="@drawable/se_button"
android:layout_alignBottom="@+id/ed_city"
android:layout_alignParentEnd="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="@+id/ed_city"
android:weightSum="1"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="地区"
android:textSize="40dp"
android:gravity="center"
android:id="@+id/tv_city"
android:layout_weight="0.18" />
<TextView
android:layout_width="fill_parent"
android:layout_height="30dp"
android:textSize="25dp"
android:text="今日天气"
android:gravity="center"
android:id="@+id/tv_weather"
android:layout_weight="0.10" />
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="今天温度"
android:gravity="center"
android:textSize="40dp"
android:id="@+id/tv_wendu"
android:layout_weight="0.27" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="温度范围"
android:textSize="25dp"
android:gravity="center"
android:id="@+id/tv_fanwei"
android:layout_weight="0.12" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="建议"
android:id="@+id/tv_advices"
android:layout_weight="0.29" />
</LinearLayout>
</RelativeLayout>
mainactivity
package com.example.katherine_qj.weatherday;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private EditText ed_city;
private Button bt_serch;
private TextView tv_priview;
private TextView tv_city;
private TextView tv_jintian;
private TextView tv_wendu;
private TextView tv_fanwei;
public static Handler handler;
private Thread t;
int i = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Init();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
bt_serch.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
thread gt = new thread();
t = new Thread(gt, "Refresh");
t.start();
handler = new Myhandler();
}
} );
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
thread gt = new thread();
t = new Thread(gt, "Refresh");
t.start();
handler = new Myhandler();
}
});
// Init();
// thread gt = new thread();
// t = new Thread(gt, "Refresh");
// t.start();
// handler = new Myhandler();
}
public void Init (){
ed_city = (EditText)findViewById(R.id.ed_city);
bt_serch = (Button)findViewById(R.id.bt_serch);
tv_priview =(TextView)findViewById(R.id.tv_advices);
tv_city = (TextView)findViewById(R.id.tv_city);
tv_jintian = (TextView)findViewById(R.id.tv_weather);
tv_wendu = (TextView)findViewById(R.id.tv_wendu);
tv_fanwei = (TextView)findViewById(R.id.tv_fanwei);
}
public static String getURLConnection(String path) {
String xml = "";
System.out.println("sept5");
try{
System.out.println("sept6");
HttpClient client = new DefaultHttpClient();//创建一个httpclient对象
System.out.println("sept7");
HttpGet get = new HttpGet(path);
System.out.println("sept8");
HttpResponse response = client.execute(get);
System.out.println("sept9");
int code = response.getStatusLine().getStatusCode();
Log.d("http", "code");
if (code == 200) {
//如果返回200才算成功才可以继续执行
System.out.println("sept3");
InputStream reader = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(reader));
String list = buffer.readLine();//读一行
while (list != null) {
xml += list;
list = buffer.readLine();
}
}
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("2222"+xml);
return xml;
}
private class thread implements Runnable {
@Override
public void run() {
String todayFirst = "http://api.k780.com:88/?app=weather.today&weaid=";
String todayCity = ed_city.getText().toString();
System.out.println(todayCity+"sept2");
String todayLast ="&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
System.out.println("sept1"+todayFirst+todayCity+todayLast);
String todayWeather = getURLConnection(todayFirst+todayCity+todayLast);
System.out.println("1111"+todayWeather);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("todayWeather", todayWeather);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
public class Myhandler extends Handler{
public void handleMessage(Message msg){
String todayWeather = msg.getData().getString("todayWeather");
if (!todayWeather.equals("")){
try{
todayWeather = String.valueOf(new JSONObject(todayWeather).getJSONObject("result"));
JSONObject json = new JSONObject(todayWeather);
tv_city.setText(json.getString("citynm"));
tv_jintian.setText(json.getString("weather"));
tv_wendu.setText(json.getString("temp_curr")+"°");
tv_fanwei.setText(json.getString("temperature"));
tv_priview.setText(todayWeather);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
还有在实现过程中遇到的问题 使用网络的时候必须要导入这两个包
compile files(‘libs/httpclient-4.4.1.jar’)
compile files(‘libs/httpcore-4.4.1.jar’)
然后必须加上这段代码
packagingOptions {//导入http包的时候必须要加的以下这段话
exclude ‘META-INF/DEPENDENCIES.txt’
exclude ‘META-INF/LICENSE.txt’
exclude ‘META-INF/NOTICE.txt’
exclude ‘META-INF/NOTICE’
exclude ‘META-INF/LICENSE’
exclude ‘META-INF/DEPENDENCIES’
exclude ‘META-INF/notice.txt’
exclude ‘META-INF/license.txt’
exclude ‘META-INF/dependencies.txt’
exclude ‘META-INF/LGPL2.1’
}
还要在androidmanifest文件中加入网络请求
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
over!!!!!
还没有评论,来说两句吧...