如何使用If Else Statement为这个android天气应用程序

时间:2016-11-16 20:18:35

标签: android location weather

当下面的代码运行时,它以度为单位显示温度。

公共类MainActivity扩展AppCompatActivity实现了GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {

private static final String APP_ID = "80e4eede56844462ef3cdc721208c31f";

private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
private GoogleApiClient googleApiClient;

private TextView textView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                PERMISSION_ACCESS_COARSE_LOCATION);
    }

    googleApiClient = new GoogleApiClient.Builder(this, this, this).addApi(LocationServices.API).build();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_ACCESS_COARSE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // All good!
            } else {
                Toast.makeText(this, "Need your location!", Toast.LENGTH_SHORT).show();
            }

            break;
    }
}

@Override
protected void onStart() {
    super.onStart();
    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}

@Override
protected void onStop() {
    googleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(MainActivity.class.getSimpleName(), "Connected to Google Play Services!");

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

        double lat = lastLocation.getLatitude(), lon = lastLocation.getLongitude();
        String units = "imperial";
        String url = String.format("http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s",
                lat, lon, units, APP_ID);
        new GetWeatherTask(textView).execute(url);
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}

private class GetWeatherTask extends AsyncTask<String, Void, String> {
    private TextView textView;

    public GetWeatherTask(TextView textView) {
        this.textView = textView;
    }

    @Override
    protected String doInBackground(String... strings) {
        String weather = "UNDEFINED";
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder builder = new StringBuilder();

            String inputString;
            while ((inputString = bufferedReader.readLine()) != null) {
                builder.append(inputString);
            }

            JSONObject topLevel = new JSONObject(builder.toString());
            JSONObject main = topLevel.getJSONObject("main");
            weather = String.valueOf(main.getDouble("temp"));


            urlConnection.disconnect();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return weather;
    }


    @Override
    public void onPostExecute(String temp) {
        textView.setText("Weather temperature is: " + temp + "°");


    }
}

}

有人可以帮助我如何使用if和else语句来使它如果温度低于一定程度,用户界面将显示一些文本,如果它高于某种程度,它会显示不同的文字吗?

2 个答案:

答案 0 :(得分:1)

@Override
public void onPostExecute(String temp) {
    textView.setText("Weather temperature is: " + temp + "°");

    if (temp < someValue)
          //doSomething
    else
        //doSomethingElse
}

这应该足够直观。

答案 1 :(得分:0)

首先,您将获得temp作为double值 不要将其转换为字符串,替换此

 weather = String.valueOf(main.getDouble("temp"));

 double weather = main.getDouble("temp");

并执行此操作

 @Override
public void onPostExecute() {
 if (weather < yourValue)
      //yourCode 
 else
    //anthorCode
}

如果您想将临时值转换为字符串,只需添加此

即可
 @Override
public void onPostExecute() {
 if (weather.equals("yourValue"))
      //yourCode 
 else
    //anthorCode
}

我不建议这样做。