-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainActivity.java
More file actions
160 lines (135 loc) · 5.69 KB
/
MainActivity.java
File metadata and controls
160 lines (135 loc) · 5.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package com.example.ramesh.camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private EditText cityInput;
private Button fetchWeatherButton;
private ProgressBar loadingIndicator;
private TextView weatherResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityInput = (EditText) findViewById(R.id.cityInput);
fetchWeatherButton = (Button) findViewById(R.id.fetchWeatherButton);
loadingIndicator = (ProgressBar) findViewById(R.id.loadingIndicator);
weatherResult = (TextView) findViewById(R.id.weatherResult);
fetchWeatherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String cityName = cityInput.getText().toString().trim();
if (TextUtils.isEmpty(cityName)) {
Toast.makeText(MainActivity.this, "Please enter a city name", Toast.LENGTH_SHORT).show();
return;
}
new WeatherTask().execute(cityName);
}
});
}
private class WeatherTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingIndicator.setVisibility(View.VISIBLE);
fetchWeatherButton.setEnabled(false);
weatherResult.setText("");
}
@Override
protected String doInBackground(String... params) {
String cityName = params[0];
try {
return fetchWeather(cityName);
} catch (IOException e) {
return "Network error: " + e.getMessage();
} catch (JSONException e) {
return "Unable to read weather data right now.";
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
loadingIndicator.setVisibility(View.GONE);
fetchWeatherButton.setEnabled(true);
weatherResult.setText(result);
}
}
private String fetchWeather(String cityName) throws IOException, JSONException {
String encodedCity = URLEncoder.encode(cityName, "UTF-8");
String geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search?name=" + encodedCity + "&count=1&language=en";
JSONObject geocodeResponse = new JSONObject(readFromUrl(geocodeUrl));
JSONArray results = geocodeResponse.optJSONArray("results");
if (results == null || results.length() == 0) {
return "No results found for \"" + cityName + "\".";
}
JSONObject location = results.getJSONObject(0);
double latitude = location.getDouble("latitude");
double longitude = location.getDouble("longitude");
String resolvedName = location.optString("name");
String country = location.optString("country");
String weatherUrl = "https://api.open-meteo.com/v1/forecast?current_weather=true&latitude="
+ latitude + "&longitude=" + longitude + "&timezone=auto";
JSONObject weatherResponse = new JSONObject(readFromUrl(weatherUrl));
JSONObject currentWeather = weatherResponse.optJSONObject("current_weather");
if (currentWeather == null) {
return "Weather details are unavailable right now.";
}
double temperature = currentWeather.optDouble("temperature");
double windSpeed = currentWeather.optDouble("windspeed");
String time = currentWeather.optString("time");
StringBuilder builder = new StringBuilder();
builder.append("Current weather in ").append(resolvedName);
if (!TextUtils.isEmpty(country)) {
builder.append(", ").append(country);
}
builder.append(":\n\n");
builder.append("Temperature: ").append(temperature).append("°C\n");
builder.append("Wind speed: ").append(windSpeed).append(" km/h\n");
if (!TextUtils.isEmpty(time)) {
builder.append("Updated at: ").append(time);
}
return builder.toString();
}
private String readFromUrl(String urlString) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
}
}