简体   繁体   English

天气应用(JSON)数据未显示在textview中

[英]Weather app (JSON) data is not showing in the textview

I finished my weather app on android studio in Java and XML but when I run the app the data isn't showing. 我在Android Studio上用Java和XML完成了我的weather app,但是当我运行该应用程序时,数据没有显示。 I'm using open weather for my JSON data and I already gave the permissions in the XML manifesto to access location and internet. 我将开放天气用于JSON数据,并且已经在XML清单中授予访问位置和Internet的权限。 I am only testing the code with 3 variables 我只用3个变量测试代码

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

I need to have those results from the JSON appear in my app somehow. 我需要使JSON的结果以某种方式出现在我的应用程序中。

below is the main activity (weatherapp). 以下是主要活动(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);
}

below is my download activity code 以下是我的下载活动代码

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();
    }
}
}

You are performing your async task before you do the findViewById stuff, so when you try to set the texts in the onPostExecute() method, the variables for the textviews are probably not set yet. 在执行findViewById之前,您正在执行异步任务,因此,当您尝试在onPostExecute()方法中设置文本时,可能尚未设置textview的变量。

Also, you should better not use static variables in your activity. 另外,最好不要在活动中使用静态变量。 To avoid this, you can either put the Dowlode class inside your activity class, or you can pass the activity (or the relevant views) to the Dowlode class via a constructor. 为避免这种情况,您可以将Dowlode类放入活动类中,也可以通过构造函数将活动(或相关视图)传递给Dowlode类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM