天气应用 (JSON) 数据未显示在文本视图中

Posted

技术标签:

【中文标题】天气应用 (JSON) 数据未显示在文本视图中【英文标题】:Weather app (JSON) data is not showing in the textview 【发布时间】:2019-04-19 15:42:04 【问题描述】:

我在 android studio 上用 Java 和 XML 完成了我的天气应用程序,但是当我运行该应用程序时,数据没有显示。我正在为我的 JSON 数据使用开放天气,并且我已经在 XML 宣言中授予了访问位置和互联网的权限。我只用 3 个变量测试代码

Weatherapp.ctemp.setText(String.valueOf(ctempreture));
Weatherapp.ftemp.setText(String.valueOf(ftempreture));
Weatherapp.ktemp.setText(String.valueOf(ktempreture));

我需要让 JSON 的结果以某种方式出现在我的应用中。

下面是主要活动(weatherapp)。

public class Weatherapp extends AppCompatActivity 
static TextView ctemp;
static TextView ftemp;
static TextView ktemp;
static TextView location;
static TextView pressure;
static TextView humidity;
static TextView mintempc;
static TextView mintempf;
static TextView mintempk;
static TextView maxtempc;
static TextView maxtempf;
static TextView maxtempk;
static TextView sealevel;
static TextView groundlevel;
static TextView windspeed;
static Button refresh;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weatherapp);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Dowlode task = new Dowlode();
    String provider = locationManager.getBestProvider(new Criteria(), false);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    
    Location locationn = locationManager.getLastKnownLocation(provider);
    Double lat = locationn.getLatitude();
    Double lng = locationn.getLongitude();
    task.execute("https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=4ba583d5302c8723764443f9d6f08116");
    ctemp = findViewById(R.id.ctemp);
    ftemp = findViewById(R.id.ftemp);
    ktemp = findViewById(R.id.ktemp);
    location = findViewById(R.id.location);
    pressure = findViewById(R.id.pressure);
    humidity = findViewById(R.id.humidity);
    mintempc = findViewById(R.id.mintempc);
    mintempf = findViewById(R.id.mintempf);
    mintempk = findViewById(R.id.mintempk);
    maxtempc = findViewById(R.id.maxtempc);
    maxtempf = findViewById(R.id.maxtempf);
    maxtempk = findViewById(R.id.maxtempk);
    sealevel = findViewById(R.id.sealevel);
    groundlevel = findViewById(R.id.groundlevel);
    windspeed = findViewById(R.id.windspeed);
    refresh = findViewById(R.id.refresh);

下面是我的下载活动代码

public class Dowlode extends AsyncTask<String,Void,String > 

@Override
protected String doInBackground(String... urls) 
    String result="";
    URL url;
    HttpURLConnection urlConnection =null;

    try 
        url=new URL(urls[0]);
        urlConnection=(HttpURLConnection) url.openConnection();
        InputStream in =urlConnection.getInputStream() ;
        InputStreamReader reader=new InputStreamReader(in);
        int data = reader.read();
        while (data!=-1)
            char current = (char) data;
            result += current;
            data = reader.read();

        
        return result;
     catch (MalformedURLException e) 
        e.printStackTrace();
     catch (IOException e) 
        e.printStackTrace();
    

    return null;


@Override
protected void onPostExecute(String s) 
    super.onPostExecute(s);

    try 
    JSONObject jsonObject = new JSONObject();

    JSONObject weather = new JSONObject(jsonObject.getString("main"));

    double tempreture = Double.parseDouble(weather.getString("temp"));
    int ctempreture = (int) (tempreture- 273.15 );
    int ftempreture = (int) (tempreture * 1.8-459.67);
    int ktempreture = (int) (tempreture);

    Weatherapp.ctemp.setText(String.valueOf(ctempreture));
    Weatherapp.ftemp.setText(String.valueOf(ftempreture));
    Weatherapp.ktemp.setText(String.valueOf(ktempreture));

    String location = jsonObject.getString("name");

    double pressure = Double.parseDouble(weather.getString("pressure"));
    String pressuree = pressure+ "pascal";

    double humidity = Double.parseDouble(weather.getString("humidity"));
    String humidityy= humidity+"";

    double temp_min = Double.parseDouble(weather.getString("temp_min"));
        int cmintemp = (int) (temp_min- 273.15 );
        int fmintemp = (int) (temp_min * 1.8-459.67);
        int kmintemp = (int) (temp_min);

    double temp_max = Double.parseDouble((weather.getString("temp_max")));
        int cmaxtemp = (int) (temp_max- 273.15 );
        int fmaxtemp = (int) (temp_max * 1.8-459.67);
        int kmaxtemp = (int) (temp_max);

    double sea_level = Double.parseDouble(weather.getString("sea_level"));
        int sealevel  = (int) (sea_level);

   double grnd_level = Double.parseDouble((weather.getString("grnd_level")));
        int groundlevel= (int) (grnd_level);

     JSONObject wind = new JSONObject(jsonObject.getString("wind"));

     double speed = Double.parseDouble((wind.getString("speed")));
     int speedd   = (int) (speed);

     catch (Exception e) 
        e.printStackTrace();
    


【问题讨论】:

您是否尝试过调试应用程序? 我试过了,但似乎没有任何错误 【参考方案1】:

在执行 findViewById 之前,您正在执行异步任务,因此当您尝试在 onPostExecute() 方法中设置文本时,文本视图的变量可能尚未设置。

此外,您最好不要在活动中使用静态变量。为避免这种情况,您可以将 Dowlode 类放在活动类中,也可以通过构造函数将活动(或相关视图)传递给 Dowlode 类。

【讨论】:

以上是关于天气应用 (JSON) 数据未显示在文本视图中的主要内容,如果未能解决你的问题,请参考以下文章

图像未显示在表格视图中

在搜索城市之前使显示数据文本视图不可见

简单的安卓天气应用

我的表格视图已创建,但数组未显示在表格视图中,控制台中的所有数据都来了。请帮我解决 json 解析

渲染 json 未显示在 rails 4 的视图中

AFNetworking 2.0 解析的数据未显示在表格视图中