【实战】android获取天气情况(Json来返回数据)

本文介绍了一个简单的Android应用程序,用于查询城市的天气状况。通过输入城市名称,应用会显示该城市的天气预报。实现过程中涉及网络请求、JSON解析及UI更新等关键技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在输入框输入查询的城市,即可输出天气情况

一、android工程结构:


MainActivity.java:

package com.lcz.research;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;


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


import com.lcz.research.utils.StreamTool;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements View.OnClickListener {


	private Button btn;
	private EditText ed_city;
	private TextView city_result1;
	private TextView city_result2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);
        
        ed_city=(EditText) findViewById(R.id.ed_city);
        city_result1=(TextView) findViewById(R.id.city_result1);
        city_result2=(TextView) findViewById(R.id.city_result2);
    }




    


    private final static String PATH="http://wthrcdn.etouch.cn/weather_mini?city=";
	protected static final int SUCCESS = 0;
	protected static final int INVALID_CITY = 1;
	protected static final int ERROR = 2;
	
    private String city;
    String ul;
    
    
    private Handler mhandler=new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		dialog.dismiss();
    		switch (msg.what) {
			case SUCCESS:
				
					JSONArray data=(JSONArray) msg.obj;
				try {
					String day01= data.getString(0);
					String day02= data.getString(1);
					city_result1.setText(day01);
					city_result2.setText(day02);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					break;
		
					
				
			case INVALID_CITY:
				Toast.makeText(MainActivity.this, "城市无效", 0).show();
				break;
			case ERROR:
				Toast.makeText(MainActivity.this, "网络无效", 0).show();
				break;
			default:
				break;
			}
    	};
    };
    ProgressDialog dialog=null;
    
	public void onClick(View v) {
		// TODO Auto-generated method stub
		city=ed_city.getText().toString().trim();
		if(TextUtils.isEmpty(city)){
			Toast.makeText(this, "路径错误", 0).show();
			return ;
		}
		dialog=new ProgressDialog(this);
		dialog.setMessage("正在玩命加载中");
		dialog.show();
		//发起请求给那个网站
		new Thread(){
			public void run() {
				try {
				    ul=PATH+URLEncoder.encode(city,"UTF-8");
					
					URL url=new URL(ul);
					
					//设置必要的参数信息
					HttpURLConnection conn=(HttpURLConnection) url.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");
					
					//判断响应码
					int code = conn.getResponseCode();
					if(code==200){
						//连接网络成功
						InputStream in = conn.getInputStream();
						String data = StreamTool.decodeStream(in);
						
						
						//解析json格式的数据
						JSONObject jsonObj=new JSONObject(data);
						//获得desc的值
						String result = jsonObj.getString("desc");
						if("OK".equals(result)){
							//城市有效,返回了需要的数据
							JSONObject dataObj = jsonObj.getJSONObject("data");
							
							JSONArray jsonArray = dataObj.getJSONArray("forecast");
							//通知更新ui
							Message msg = Message.obtain();
							msg.obj=jsonArray;
							msg.what=SUCCESS;
							mhandler.sendMessage(msg);
						}else{
							//城市无效
							Message msg=Message.obtain();
							msg.what=INVALID_CITY;
							mhandler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.what=ERROR;
					mhandler.sendMessage(msg);
				}
			};
		}.start();
	}
    
}

StreamTool.java:

package com.lcz.research.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTool {

	public static String decodeStream(InputStream in) throws IOException {
		
		// 底层流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int len =0;
		byte[] buf = new byte[1024];
		
		while((len=in.read(buf))>0){
			baos.write(buf, 0, len);
		}
		
		String data = baos.toString();
		
		return data;
	}

}

2.activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  	android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="请输入你要查询的城市" />
	 <EditText
	   
	    android:id="@+id/ed_city"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
	 <Button
	    android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查询" />
	  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/city_result1" />
	  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/city_result2" />
</LinearLayout>

3.AndroidMainfest.xml
    <uses-permission android:name="android.permission.INTERNET"/>

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mind_programmonkey

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值