【问题标题】:How to use If Else Statement for this android weather application如何为这个 android 天气应用程序使用 If Else 语句
【发布时间】:2016-11-16 20:18:35
【问题描述】:

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

公共类 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 语句来制作它,以便如果温度低于一定程度,用户界面将显示一些文本,如果高于一定程度,它将显示不同的文字?

【问题讨论】:

  • 拜托,去 google Java if elseJava Android Toast 就可以了

标签: android location weather


【解决方案1】:
@Override
public void onPostExecute(String temp) {
    textView.setText("Weather temperature is: " + temp + "°");

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

这应该足够直观。

【讨论】:

  • 这取决于您的布局。如果您有 TextView,则使用 setText。
【解决方案2】:

首先你会收到双倍值的温度 不要将其转换为字符串,替换它

 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
}

我不推荐这个。

【讨论】:

  • 嗨,当我添加你的建议时:double weather = main.getDouble("temp");意思是“天气”已经在范围中定义了。我能做什么?
  • removeString 天气;
  • 我删除了 String weather = UNDEFINED 现在它说它无法解析“返回天气”处的天气符号。我该如何解决这个问题?
  • 请提供更多解释.. @JohnDoe
  • 是的,在我替换了“weather = String.valueOf(main.getDouble("temp"));”之后与“双天气 = main.getDouble("temp");"并删除了“字符串天气;”。该程序告诉我代码底部“返回天气”上的天气符号无法解析。 “double weather = main.getDouble..”中的变量“weather”也没有使用。另外,我不能使用 if else 语句,因为运算符不能应用于字符串和 int 。我试图完成的主要目标是让 if else 语句工作,但我没有尝试过任何工作。有什么想法..?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2022-08-10
  • 1970-01-01
相关资源
最近更新 更多