Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to display openweather map data separately in Android?

    • 0
    • 0
    • 0
    • 2
    • 0
    • 0
    • 0
    • 524
    Answer it

    I am using openweathermap.org API for displaying current weather for a place user type. My application displayed it However, it is not flexible as it is displaying all different details such as weather description, latitude, longitude, Wind Speed , current temperature.. all in a single string so it is not reusable which we should make. Suppose if i want to display the place on google map with current temperature with a map marker, I should be able to get only what i want in this case current temperature and latitude and longitude.

    I want these details to display on separete textfields. I am beginner in Android. Please look into my code and suggest me with a solution and guidance.


    Here is my main activity code
     

     

    1. Public class MainActivity extends Activity {
    2. Button btnSubmitCity, btnMap;
    3. EditText editCityText;
    4. TextView weather_description, current_temp, wind_speed, textViewResult;
    5.  
    6.  
    7. @Override
    8. protected void onCreate(Bundle savedInstanceState) {
    9. super.onCreate(savedInstanceState);
    10. setContentView(R.layout.activity_main);
    11. editCityText = (EditText) findViewById(R.id.editCity);
    12. btnMap =(Button) findViewById(R.id.mapButton);
    13. btnSubmitCity = (Button) findViewById(R.id.submitCity);
    14. weather_description = (TextView) findViewById(R.id.weatherDescription);
    15. current_temp = (TextView) findViewById(R.id.currentTemp);
    16. wind_speed = (TextView) findViewById(R.id.windSpeed);
    17. //textViewResult = (TextView)findViewById(R.id.result);
    18. textViewResult = (TextView)findViewById(R.id.result);
    19. btnMap.setVisibility(View.INVISIBLE);
    20.  
    21. btnMap.setOnClickListener(new View.OnClickListener() {
    22. @Override
    23. public void onClick(View v) {
    24.  
    25. }
    26. });
    27. btnSubmitCity.setOnClickListener(new View.OnClickListener() {
    28. @Override
    29. public void onClick(View v) {
    30. //editCityText.getText().toString();
    31. //HttpGetTask
    32. String cityString = editCityText.getText().toString();
    33. if(TextUtils.isEmpty(cityString)) {
    34. Toast.makeText(MainActivity.this, "Enter a place", Toast.LENGTH_LONG).show();
    35. return;
    36. } else{
    37. new HttpGetTask(cityString, weather_description).execute(cityString);
    38.  
    39. btnMap.setVisibility(View.VISIBLE);
    40.  
    41. }
    42.  
    43.  
    44. //String cityString = city.getText().toString();
    45. //new HttpGetTask().execute();
    46. /*
    47. new HttpGetTask(
    48. editCityText.getText().toString(),
    49. textViewResult).execute();
    50. */
    51.  
    52. }
    53. });
    54.  
    55. }
    56. private class HttpGetTask extends AsyncTask<String, Void, String> {
    57. final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/weather?";
    58. private static final String TAG = "HttpGetTask";
    59. String cityName;
    60. TextView tvResult;
    61.  
    62. HttpGetTask(String cityName, TextView tvResult){
    63. this.cityName = cityName;
    64. this.tvResult = tvResult;
    65. }
    66.  
    67.  
    68. @Override
    69. protected String doInBackground(String... params){
    70. InputStream in = null;
    71. HttpURLConnection httpUrlConnection = null;
    72. String result = "";
    73. try {
    74. Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
    75. .appendQueryParameter("q", cityName+",us") // city
    76. .appendQueryParameter("mode", "json") // json format as result
    77. .appendQueryParameter("units", "imperial") // metric unit
    78. .appendQueryParameter("APPID", "e1004b4321dde3f04591ac3386fa3a41")
    79. .build();
    80. URL url = new URL(builtUri.toString());
    81. httpUrlConnection = (HttpURLConnection) url.openConnection();
    82. in = new BufferedInputStream(
    83. httpUrlConnection.getInputStream());
    84. String data = readStream(in);
    85. result = edu.uco.rawal.p6rabina.JSONWeatherData.getData(data);
    86.  
    87. } catch (MalformedURLException exception) {
    88. Log.e(TAG, "MalformedURLException");
    89. } catch (IOException exception) {
    90. Log.e(TAG, "IOException");
    91. } catch (JSONException e) {
    92. Log.e(TAG, e.getMessage(), e);
    93. e.printStackTrace();
    94. } finally {
    95. if (null != httpUrlConnection) {
    96. httpUrlConnection.disconnect();
    97. }
    98. if (in != null) {
    99. try {
    100. in.close();
    101. } catch (final IOException e) {
    102. Log.e(TAG, "Error closing stream", e);
    103. }
    104. }
    105. }
    106.  
    107. return result;
    108. }
    109. @Override
    110. protected void onPostExecute(String result) {
    111. if (result == null || result == "") {
    112. Toast.makeText(MainActivity.this,
    113. "Invalid weather data. Possibly a wrong query",
    114. Toast.LENGTH_SHORT).show();
    115. return;
    116. } else {
    117. //btnMap.setVisibility(View.VISIBLE);
    118. tvResult.setText(result);
    119.  
    120. }
    121. }
    122.  
    123. private String readStream(InputStream in) {
    124. BufferedReader reader = null;
    125. StringBuffer data = new StringBuffer("");
    126. try {
    127. reader = new BufferedReader(new InputStreamReader(in));
    128. String line ;
    129. while ((line = reader.readLine()) != null) {
    130. data.append(line);
    131. }
    132. } catch (IOException e) {
    133. Log.e(TAG, "IOException");
    134. } finally {
    135. if (reader != null) {
    136. try {
    137. reader.close();
    138. } catch (IOException e) {
    139. e.printStackTrace();
    140. }
    141. }
    142. }
    143. return data.toString();
    144. }
    145. }
    146. }
    147.  
    148. Here is my JSONWeatherData.java
    149.  
    150. > public class JSONWeatherData {
    151.  
    152. public static String getData(String weatherJson) throws JSONException {
    153. String jsonResult = "";
    154.  
    155. try {
    156. JSONObject JsonObject = new JSONObject(weatherJson);
    157. String cod = jsonHelperGetString(JsonObject, "cod");
    158. if(cod != null) {
    159. if (cod.equals("200")) {
    160.  
    161. jsonResult += jsonHelperGetString(JsonObject, "name") + "\n";
    162. JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys");
    163. if (sys != null) {
    164. jsonResult += jsonHelperGetString(sys, "country") + "\n";
    165. }
    166. jsonResult += "\n";
    167. JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord");
    168. if(coord != null){
    169. String lon = jsonHelperGetString(coord, "lon");
    170. String lat = jsonHelperGetString(coord, "lat");
    171. jsonResult += "Lon: " + lon + "\n";
    172. jsonResult += "Lat: " + lat + "\n";
    173. }
    174. jsonResult += "\n";
    175. JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather");
    176. if(weather != null){
    177. for(int i=0; i<weather.length(); i++){
    178. JSONObject thisWeather = weather.getJSONObject(i);
    179. jsonResult += "Weather " + i + ":\n";
    180.  
    181. jsonResult += jsonHelperGetString(thisWeather, "main") + "\n";
    182. jsonResult += jsonHelperGetString(thisWeather, "description") + "\n";
    183. jsonResult += "\n";
    184. }
    185. }
    186. JSONObject main = jsonHelperGetJSONObject(JsonObject, "main");
    187. if(main != null){
    188. jsonResult += "temp: " + jsonHelperGetString(main, "temp") + "\n";
    189.  
    190. jsonResult += "\n";
    191. }
    192. JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind");
    193. if(wind != null){
    194.  
    195. jsonResult += "Wind Speed: " + jsonHelperGetString(wind, "speed") + "\n";
    196.  
    197. jsonResult += "\n";
    198. }
    199.  
    200. }
    201. else if(cod.equals("404")){
    202. String message = jsonHelperGetString(JsonObject, "message");
    203. jsonResult += "cod 404: " + message;
    204.  
    205. }
    206. } else{
    207. jsonResult += "cod == null\n";
    208. }
    209.  
    210.  
    211. } catch (JSONException e) {
    212. e.printStackTrace();
    213. Log.e(TAG, e.getMessage(), e);
    214. jsonResult += e.getMessage();
    215.  
    216. }
    217. return jsonResult;
    218.  
    219. }
    220.  
    221. private static String jsonHelperGetString(JSONObject obj, String k){
    222. String v = null;
    223. try {
    224. v = obj.getString(k);
    225. } catch (JSONException e) {
    226. e.printStackTrace();
    227. }
    228.  
    229. return v;
    230. }
    231. private static JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){
    232. JSONObject o = null;
    233.  
    234. try {
    235. o = obj.getJSONObject(k);
    236. } catch (JSONException e) {
    237. e.printStackTrace();
    238. }
    239.  
    240. return o;
    241. }
    242. private static JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){
    243. JSONArray a = null;
    244.  
    245. try {
    246. a = obj.getJSONArray(k);
    247. } catch (JSONException e) {
    248. e.printStackTrace();
    249. }
    250.  
    251. return a;
    252. }
    253. }
    254.  

     

 2 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: