聚合天气预报

聚合天气预报_第1张图片

1.使用 http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json 新浪 IP API 进行城市定位。

2.添加 ProgressDialog ,获取数据时显示“请稍后”。
报错:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
UI组件不能写在进程中,要写在handle中,通过进程发消息控制其显隐。
3.TextView添加点击刷新:
设置TextView的XML的属性 android:onClick="click",
代码中写:
    public void click(View v) {
        Toast.makeText(getApplicationContext(), "刷新", Toast.LENGTH_LONG).show();
        new Thread(t).start();
    }
点击没反应?布局XML文件中要设置TextView的clickable属性值为true, 或者对TextView实例调用setClickable方法,参数设为true。

已知问题:刷新后界面乱了:
聚合天气预报_第2张图片
package com.hy.weatherjhm;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    int iweather[];
    String city, url, jsons, tempnow, scity, supdatetime, stempnow, sweather1,
            stemp1, swind1, shumidity, stoday, sdate[], sweek[], sweather[],
            stemp[], swind[];
    JSONObject jsono, info;
    private final Handler handler = new Handler();
    ProgressDialog PD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(t).start();
    }

    final Runnable mUpdateResults = new Runnable() {
        @Override
        public void run() {
            TextView tvcity = (TextView) findViewById(R.id.city);
            tvcity.setText(scity);
            TextView updatetime = (TextView) findViewById(R.id.updatetime);
            updatetime.setText(supdatetime);
            TextView tempnow = (TextView) findViewById(R.id.tempnow);
            tempnow.setText(stempnow);
            TextView weather0 = (TextView) findViewById(R.id.weather);
            weather0.setText(sweather[0]);
            ImageView bg = (ImageView) findViewById(R.id.bg);
            bg.setImageDrawable(MainActivity.this.getResources().getDrawable(
                    getBgImage(sweather[0])));
            TextView temp0 = (TextView) findViewById(R.id.temp);
            temp0.setText(stemp[0]);
            TextView wind0 = (TextView) findViewById(R.id.wind);
            wind0.setText(swind[0]);
            TextView humidity = (TextView) findViewById(R.id.humidity);
            humidity.setText(shumidity);
            TextView today = (TextView) findViewById(R.id.today);
            today.setText(stoday);
            LinearLayout future = (LinearLayout) findViewById(R.id.future);
            for (int i = 1; i < 7; i++) {
                LinearLayout f = new LinearLayout(MainActivity.this);
                f.setOrientation(LinearLayout.VERTICAL);
                f.setGravity(Gravity.CENTER);
                int p = 0;
                f.setPadding(p, p, p, p);
                future.addView(f, new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                TextView date = new TextView(MainActivity.this);
                date.setText(sdate[i]);
                f.addView(date);
                date.setGravity(Gravity.CENTER);
                TextView week = new TextView(MainActivity.this);
                week.setText(sweek[i]);
                f.addView(week);
                week.setGravity(Gravity.CENTER);
                ImageView wi = new ImageView(MainActivity.this);
                wi.setImageDrawable(MainActivity.this.getResources()
                        .getDrawable(iweather[i]));
                f.addView(wi);
                LayoutParams params = wi.getLayoutParams();
                params.width = 90;
                params.height = 90;
                wi.setLayoutParams(params);
                TextView weather = new TextView(MainActivity.this);
                weather.setText(sweather[i]);
                f.addView(weather);
                weather.setGravity(Gravity.CENTER);
                TextView temp = new TextView(MainActivity.this);
                temp.setText(stemp[i]);
                // temp.setLayoutParams(new LayoutParams(
                // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                temp.setGravity(Gravity.CENTER);
                f.addView(temp);
                TextView wind = new TextView(MainActivity.this);
                wind.setText(swind[i]);
                // wind.setLayoutParams(new LayoutParams(
                // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                wind.setGravity(Gravity.CENTER);
                f.addView(wind);
            }
            PDD.sendEmptyMessage(0);
        }
    };

    Thread t = new Thread() {
        @Override
        public void run() {
            PDS.sendEmptyMessage(0);
            url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
            jsons = HttpUtils.getURLResponse(url);
            try {
                jsono = new JSONObject(jsons);
                city = jsono.getString("city");
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                city = java.net.URLEncoder.encode(city, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            url = "http://v.juhe.cn/weather/index?cityname=" + city
                    + "&key=e73ad3113b4e8dc2b7e8d8298a40d8e3";
            jsons = HttpUtils.getURLResponse(url);
            try {
                jsono = new JSONObject(jsons);
                JSONObject sk = jsono.getJSONObject("result").getJSONObject(
                        "sk");
                scity = jsono.getJSONObject("result").getJSONObject("today")
                        .getString("city");
                supdatetime = sk.getString("time") + "更新";
                stempnow = sk.getString("temp") + "℃";
                shumidity = sk.getString("humidity");
                stoday = jsono.getJSONObject("result").getJSONObject("today")
                        .getString("date_y")
                        + " "
                        + jsono.getJSONObject("result").getJSONObject("today")
                                .getString("week");
                Calendar c = Calendar.getInstance();
                String day[] = new String[7];
                sdate = new String[7];
                sweek = new String[7];
                iweather = new int[7];
                sweather = new String[7];
                stemp = new String[7];
                swind = new String[7];
                for (int i = 0; i < 7; i++) {
                    int y = c.get(Calendar.YEAR);
                    int m = c.get(Calendar.MONTH) + 1;
                    int d = c.get(Calendar.DAY_OF_MONTH);
                    day[i] = new String("day_" + y + m1(m) + d1(d));
                    JSONObject day_ = jsono.getJSONObject("result")
                            .getJSONObject("future").getJSONObject(day[i]);
                    sdate[i] = day_.getString("date").substring(4, 8);
                    sweek[i] = day_.getString("week");
                    iweather[i] = getWeatherImage(day_.getString("weather"));
                    sweather[i] = day_.getString("weather");
                    stemp[i] = day_.getString("temperature");
                    swind[i] = day_.getString("wind");
                    c.add(Calendar.DAY_OF_MONTH, 1);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            handler.post(mUpdateResults);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "退出");
        menu.add(0, 1, 1, "关于");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
        case 0:
            MainActivity.this.finish();
            break;
        case 1:
            new AlertDialog.Builder(this)
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("聚合天气  V3.0")
                    .setMessage(
                            "聚合天气API预报,\n桌面动态图标,\n图形天气预报界面。\n作者:黄颖\nQQ:84429027")
                    .setPositiveButton("确定", null).show();
            break;
        }
        return true;
    }

    String m1(int i) {
        return i < 10 ? "0" + i : "" + i;
    }

    String d1(int i) {
        return i < 10 ? "0" + i : "" + i;
    }

    private int getWeatherImage(String weather) {
        if (weather.indexOf("晴") != -1)
            return R.drawable.qing;
        if (weather.indexOf("阴") != -1)
            return R.drawable.yin;
        if (weather.indexOf("多云") != -1)
            return R.drawable.duoyun;
        if (weather.indexOf("阵雨") != -1)
            return R.drawable.zhenyu;
        if (weather.indexOf("中雨") != -1)
            return R.drawable.zhongyu;
        return R.drawable.ic_launcher;
    }

    private int getBgImage(String weather) {
        if (weather.indexOf("晴") != -1)
            return R.drawable.bgqing;
        if (weather.indexOf("阴") != -1)
            return R.drawable.bgyin;
        if (weather.indexOf("多云") != -1)
            return R.drawable.bgduoyun;
        if (weather.indexOf("雨") != -1)
            return R.drawable.bgrain;
        if (weather.indexOf("雪") != -1)
            return R.drawable.bgsnow;
        return R.drawable.ic_launcher;
    }

    public void click(View v) {
        Toast.makeText(getApplicationContext(), "刷新", Toast.LENGTH_LONG).show();
        new Thread(t).start();
    }

    private final Handler PDD = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PD.dismiss();
        }
    };

    private final Handler PDS = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PD = ProgressDialog.show(MainActivity.this, null, "加载数据中,请稍等");
        }
    };
}

你可能感兴趣的:(android)