prosidha

DownloadTask

Mar 17th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. /**
  2. * Created by Prosidha on 3/17/2017.
  3. */
  4.  
  5. package tech.prasidha.elegantweather;
  6.  
  7.  
  8. import android.os.AsyncTask;
  9. import android.util.Log;
  10. import android.widget.Toast;
  11.  
  12. import org.json.JSONArray;
  13. import org.json.JSONException;
  14. import org.json.JSONObject;
  15.  
  16. import java.io.InputStream;
  17. import java.io.InputStreamReader;
  18. import java.net.HttpURLConnection;
  19. import java.net.MalformedURLException;
  20. import java.net.URL;
  21.  
  22.  
  23. public class DownloadTask extends AsyncTask<String, Void, String> {
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30. @Override
  31. protected String doInBackground(String... urls) {
  32.  
  33. String result = "";
  34. URL url;
  35. HttpURLConnection urlConnection = null;
  36.  
  37. try {
  38. url = new URL(urls[0]);
  39. urlConnection = (HttpURLConnection) url.openConnection();
  40. InputStream in = urlConnection.getInputStream();
  41. InputStreamReader reader = new InputStreamReader(in);
  42.  
  43. int data = reader.read();
  44.  
  45. while (data != -1){
  46. char current = (char) data;
  47. result += current;
  48. data = reader.read();
  49. }
  50.  
  51. return result;
  52.  
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. return null;
  57. }
  58.  
  59. @Override
  60. protected void onPostExecute(String result){
  61. super.onPostExecute(result);
  62. try {
  63. JSONObject jsonObject = new JSONObject(result);
  64. JSONObject weatherDatas = new JSONObject(jsonObject.getString("main"));
  65.  
  66.  
  67.  
  68. double temperature = Double.parseDouble(weatherDatas.getString("temp"));
  69.  
  70. int tempIn = (int) (temperature*1.8-459.67);
  71.  
  72. String placeName = (String) jsonObject.get("name");
  73.  
  74.  
  75. MainActivity.tempeartureTextView.setText("" + tempIn);
  76. MainActivity.placeTextView.setText(placeName);
  77. Log.i("it made it", "to end of DownloadTask");
  78.  
  79.  
  80. } catch (Exception e) {
  81. e.printStackTrace();
  82. }
  83.  
  84. }
  85.  
  86. }
Add Comment
Please, Sign In to add comment