Advertisement
Guest User

Untitled

a guest
Oct 21st, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.17 KB | None | 0 0
  1. private LocationManager locationManager;
  2. private LocationListener listener;
  3.  
  4. static float lat;
  5. static float lon;
  6.  
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11.  
  12. if (savedInstanceState == null) {
  13. getSupportFragmentManager().beginTransaction().add(R.id.container, new WeatherFragment()).commit();
  14. }
  15.  
  16.  
  17. locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  18.  
  19.  
  20. listener = new LocationListener() {
  21. @Override
  22. public void onLocationChanged(Location location) {
  23. lat = (float)location.getLatitude();
  24. lon = (float)location.getLongitude();
  25.  
  26. //t.setText("n " + lat + "n" + lon);
  27. }
  28.  
  29. @Override
  30. public void onStatusChanged(String s, int i, Bundle bundle) {
  31.  
  32. }
  33.  
  34. @Override
  35. public void onProviderEnabled(String s) {
  36.  
  37. }
  38.  
  39. @Override
  40. public void onProviderDisabled(String s) {
  41.  
  42. Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  43. startActivity(i);
  44. }
  45. };
  46.  
  47. configure_button();
  48.  
  49.  
  50. }
  51.  
  52. @Override
  53. public boolean onCreateOptionsMenu(Menu menu) {
  54. getMenuInflater().inflate(R.menu.weather, menu);
  55. return true;
  56. }
  57.  
  58. @Override
  59. public boolean onOptionsItemSelected(MenuItem item) {
  60. if(item.getItemId() == R.id.change_city){
  61. showInputDialog();
  62. }
  63. return false;
  64. }
  65.  
  66. private void showInputDialog(){
  67. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  68. builder.setTitle("Escolher a Cidade:");
  69. final EditText input = new EditText(this);
  70. input.setInputType(InputType.TYPE_CLASS_TEXT);
  71. builder.setView(input);
  72. builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
  73. @Override
  74. public void onClick(DialogInterface dialog, int which) {
  75. changeCity(input.getText().toString());
  76. }
  77. });
  78. builder.show();
  79. }
  80.  
  81. public void changeCity(String city){
  82. WeatherFragment wf = (WeatherFragment)getSupportFragmentManager()
  83. .findFragmentById(R.id.container);
  84. wf.changeCity(city);
  85. new CityPreference(this).setCity(city);
  86. }
  87.  
  88.  
  89. @Override
  90. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  91. switch (requestCode){
  92. case 10:
  93. configure_button();
  94. break;
  95. default:
  96. break;
  97. }
  98. }
  99.  
  100. void configure_button(){
  101. // first check for permissions
  102. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  103. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  104. requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
  105. ,10);
  106. }
  107. return;
  108. }
  109. // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
  110.  
  111. //noinspection MissingPermission
  112. locationManager.requestLocationUpdates("gps", 5000, 0, listener);
  113. }
  114.  
  115. //private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
  116.  
  117.  
  118. //private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&units=metric";
  119.  
  120. private static final String OPEN_WEATHER_MAP_API = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=metric";
  121.  
  122.  
  123.  
  124. public static JSONObject getJSON(Context context, String city){
  125. try {
  126. URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
  127. HttpURLConnection connection =
  128. (HttpURLConnection)url.openConnection();
  129.  
  130. connection.addRequestProperty("x-api-key", context.getString(R.string.open_weather_maps_app_id));
  131.  
  132. BufferedReader reader = new BufferedReader(
  133. new InputStreamReader(connection.getInputStream()));
  134.  
  135. StringBuffer json = new StringBuffer(1024);
  136. String tmp="";
  137. while((tmp=reader.readLine())!=null)
  138. json.append(tmp).append("n");
  139. reader.close();
  140.  
  141. JSONObject data = new JSONObject(json.toString());
  142.  
  143. if(data.getInt("cod") != 200){
  144. return null;
  145. }
  146.  
  147. return data;
  148. }catch(Exception e){
  149. return null;
  150. }
  151. }
  152.  
  153. Typeface weatherFont;
  154.  
  155. TextView cityField;
  156. TextView updatedField;
  157. TextView detailsField;
  158. TextView currentTemperatureField;
  159. TextView weatherIcon;
  160.  
  161. TextView windField;
  162.  
  163. Handler handler;
  164.  
  165. public WeatherFragment(){
  166. handler = new Handler();
  167. }
  168.  
  169. @Override
  170. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  171. Bundle savedInstanceState) {
  172. View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
  173. cityField = (TextView)rootView.findViewById(R.id.city_field);
  174. updatedField = (TextView)rootView.findViewById(R.id.updated_field);
  175. detailsField = (TextView)rootView.findViewById(R.id.details_field);
  176. currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field);
  177. weatherIcon = (TextView)rootView.findViewById(R.id.weather_icon);
  178.  
  179. windField = (TextView)rootView.findViewById(R.id.wind_detail);
  180.  
  181. weatherIcon.setTypeface(weatherFont);
  182. return rootView;
  183. }
  184.  
  185. @Override
  186. public void onCreate(Bundle savedInstanceState) {
  187. super.onCreate(savedInstanceState);
  188. weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "weather.ttf");
  189. updateWeatherData(new CityPreference(getActivity()).getCity());
  190. }
  191.  
  192. private void updateWeatherData(final String city){
  193. new Thread(){
  194. public void run(){
  195. final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
  196. if(json == null){
  197. handler.post(new Runnable(){
  198. public void run(){
  199. Toast.makeText(getActivity(),
  200. getActivity().getString(R.string.place_not_found),
  201. Toast.LENGTH_LONG).show();
  202. }
  203. });
  204. } else {
  205. handler.post(new Runnable(){
  206. public void run(){
  207. renderWeather(json);
  208. }
  209. });
  210. }
  211. }
  212. }.start();
  213. }
  214.  
  215. private void renderWeather(JSONObject json){
  216. try {
  217. cityField.setText(json.getString("name").toUpperCase(Locale.US) +
  218. ", " +
  219. json.getJSONObject("sys").getString("country"));
  220.  
  221. JSONObject details = json.getJSONArray("weather").getJSONObject(0);
  222. JSONObject main = json.getJSONObject("main");
  223. detailsField.setText(
  224. details.getString("description").toUpperCase(Locale.US) +
  225. "n" + "Humidity: " + main.getString("humidity") + "%" +
  226. "n" + "Pressure: " + main.getString("pressure") + " hPa");
  227.  
  228. JSONObject wind = json.getJSONObject("wind");
  229.  
  230. //converter para km/h
  231. double wind_ms = Double.parseDouble(wind.getString("speed").toUpperCase(Locale.getDefault()));
  232. double wind_km = wind_ms * 3.6;
  233. //DecimalFormat decimal = new DecimalFormat("#.##");
  234. //wind_km = Double.valueOf(decimal.format(wind_km));
  235. windField.setText("Wind: " + wind_km + " Km/h ");
  236.  
  237.  
  238. currentTemperatureField.setText(
  239. String.format("%.2f", main.getDouble("temp"))+ " ℃");
  240.  
  241. DateFormat df = DateFormat.getDateTimeInstance();
  242. String updatedOn = df.format(new Date(json.getLong("dt")*1000));
  243. updatedField.setText("Last update: " + updatedOn);
  244.  
  245. setWeatherIcon(details.getInt("id"),
  246. json.getJSONObject("sys").getLong("sunrise") * 1000,
  247. json.getJSONObject("sys").getLong("sunset") * 1000);
  248.  
  249. }catch(Exception e){
  250. Log.e("SimpleWeather", "One or more fields not found in the JSON data");
  251. }
  252. }
  253.  
  254. private void setWeatherIcon(int actualId, long sunrise, long sunset){
  255. int id = actualId / 100;
  256. String icon = "";
  257. if(actualId == 800){
  258. long currentTime = new Date().getTime();
  259. if(currentTime>=sunrise && currentTime<sunset) {
  260. icon = getActivity().getString(R.string.weather_sunny);
  261. } else {
  262. icon = getActivity().getString(R.string.weather_clear_night);
  263. }
  264. } else {
  265. switch(id) {
  266. case 2 : icon = getActivity().getString(R.string.weather_thunder);
  267. break;
  268. case 3 : icon = getActivity().getString(R.string.weather_drizzle);
  269. break;
  270. case 7 : icon = getActivity().getString(R.string.weather_foggy);
  271. break;
  272. case 8 : icon = getActivity().getString(R.string.weather_cloudy);
  273. break;
  274. case 6 : icon = getActivity().getString(R.string.weather_snowy);
  275. break;
  276. case 5 : icon = getActivity().getString(R.string.weather_rainy);
  277. break;
  278. }
  279. }
  280. weatherIcon.setText(icon);
  281. }
  282.  
  283. public void changeCity(String city){
  284. updateWeatherData(city);
  285. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement