android studio天气预报代码
时间: 2023-07-17 13:56:41 浏览: 164
android天气预报代码
5星 · 资源好评率100%
以下是一个简单的 Android Studio 天气预报应用的代码示例:
```java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText cityEditText;
private Button getWeatherButton;
private TextView weatherTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityEditText = findViewById(R.id.cityEditText);
getWeatherButton = findViewById(R.id.getWeatherButton);
weatherTextView = findViewById(R.id.weatherTextView);
getWeatherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String city = cityEditText.getText().toString();
if (!city.isEmpty()) {
String url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=YOUR_API_KEY";
new GetWeatherTask().execute(url);
}
}
});
}
private class GetWeatherTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
result = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject main = jsonObject.getJSONObject("main");
double temp = main.getDouble("temp");
int humidity = main.getInt("humidity");
weatherTextView.setText("Temperature: " + temp + "°C\nHumidity: " + humidity + "%");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
```
请注意替换代码中的 `YOUR_API_KEY` 为你自己的 OpenWeatherMap API 密钥。此代码使用 OpenWeatherMap 的 API 来获取天气数据,并在界面上显示温度和湿度信息。
这只是一个简单的示例,你可以根据需要进行修改和扩展。希望对你有所帮助!
阅读全文