为什么视图不会使用JSON解析信息进行更新

时间:2015-07-22 14:40:55

标签: android

我在视图中更新JSON解析信息时遇到问题。从互联网获取JSON文本没有任何问题,它工作正常。我希望解析过程看起来也不错。我在视图中显示内容时遇到问题。

package rev.app.revlearningdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class JsonFromInternet extends Activity {

    String jsonText, name, weather_main, description, lon, lat, temp, pressure,
            humidity, temp_min, temp_max, speed, deg;
    long dt, sunrise, sunset;
    TextView area, info, main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather);
        area = (TextView) findViewById(R.id.weatherAreaName);
        info = (TextView) findViewById(R.id.weatherInfo);
        main = (TextView) findViewById(R.id.weatherMain);
        Thread net = new Thread() {
            public void run() {
                URL url;
                BufferedReader buff = null;
                StringBuilder build = new StringBuilder();
                try {
                    url = new URL(
                            "http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
                    buff = new BufferedReader(new InputStreamReader(
                            url.openStream(), "UTF-8"));
                    for (String l; (l = buff.readLine()) != null;)
                        build.append(l.trim());
                } catch (IOException e1) {
                    Log.e("REV DEMO", "ERROR");
                } finally {
                    if (buff != null)
                        try {
                            buff.close();
                        } catch (IOException e) {
                            Log.e("REV DEMO", "ERROR");
                        }
                    jsonText = build.toString();
                    interrupt();
                }
            };
        };
        net.start();
        if (net.getState()==Thread.State.TERMINATED) {
            parseJsonText(jsonText);
            area.setText(name);
            info.setText(description + "\n" + "Longitude, Lattitude " + lon
                    + ", " + lat + "\nTemperature " + temp + "\n(Min:"
                    + temp_min + ", Max:" + temp_max + ")\nPressure "
                    + pressure + "\nHumidity " + humidity + "\nWind Speed "
                    + speed + ", direction " + deg);
            main.setText(weather_main);
        }
    }

    private void parseJsonText(String jsonFromInternet) {
        JSONObject root, coord, main, wind, sys, weather;

        try {
            root = new JSONObject(jsonFromInternet);

            coord = root.getJSONObject("coord");
            lon = coord.optString("lon");
            lat = coord.optString("lat");

            main = root.getJSONObject("main");
            temp = main.optString("temp");
            pressure = main.optString("pressure");
            humidity = main.optString("humidity");
            temp_min = main.optString("temp_min");
            temp_max = main.optString("temp_max");

            wind = root.getJSONObject("wind");
            speed = wind.optString("speed");
            deg = wind.optString("deg");

            sys = root.getJSONObject("sys");
            sunrise = sys.optLong("sunrise");
            sunset = sys.optLong("sunset");

            dt = root.optLong("dt");
            name = root.optString("name");

            weather = root.optJSONArray("weather").getJSONObject(0);
            weather_main = weather.optString("main");
            description = weather.optString("description");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

启动异步Thread以下载JSON,这意味着您的视图会立即更新(当您的jsonText尚未初始化时)。

将您的视图更新到run()方法的结尾,并在完成解析数据时更新您的视图,而不是更早。警告:要从线程调用setText,您必须使用runOnUiThread方法。

    Thread net = new Thread() {
        public void run() {
            URL url;
            BufferedReader buff = null;
            StringBuilder build = new StringBuilder();
            try {
                url = new URL(
                        "http://api.openweathermap.org/data/2.5/weather?q=Madurai,in");
                buff = new BufferedReader(new InputStreamReader(
                        url.openStream(), "UTF-8"));
                for (String l; (l = buff.readLine()) != null;)
                    build.append(l.trim());                    

                // parse and update views now:
                jsonText = build.toString();
                parseJsonText(jsonText);
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        area.setText(name);
                        info.setText(description + "\n" + "Longitude, Lattitude " + lon
                                + ", " + lat + "\nTemperature " + temp + "\n(Min:"
                                + temp_min + ", Max:" + temp_max + ")\nPressure "
                                + pressure + "\nHumidity " + humidity + "\nWind Speed "
                                + speed + ", direction " + deg);
                        main.setText(weather_main);
                    }
                });


            } catch (IOException e1) {
                Log.e("REV DEMO", "ERROR");
            } finally {
                if (buff != null)
                    try {
                        buff.close();
                    } catch (IOException e) {
                        Log.e("REV DEMO", "ERROR");
                    }
                interrupt();
            }
        };
    };