Advertisement
sshuvro58

Geocoder

Apr 6th, 2015
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.91 KB | None | 0 0
  1. package teamtreehouse.com.stromy;
  2.  
  3.  
  4. import android.content.Context;
  5. import android.graphics.drawable.Drawable;
  6. import android.location.Address;
  7. import android.location.Geocoder;
  8. import android.net.ConnectivityManager;
  9. import android.net.NetworkInfo;
  10. import android.os.Bundle;
  11. import android.support.v7.app.ActionBarActivity;
  12. import android.util.Log;
  13. import android.view.View;
  14. import android.widget.ImageView;
  15. import android.widget.ProgressBar;
  16. import android.widget.TextView;
  17. import android.widget.Toast;
  18.  
  19. import com.squareup.okhttp.Call;
  20. import com.squareup.okhttp.Callback;
  21. import com.squareup.okhttp.OkHttpClient;
  22. import com.squareup.okhttp.Request;
  23. import com.squareup.okhttp.Response;
  24.  
  25. import org.json.JSONException;
  26. import org.json.JSONObject;
  27.  
  28. import java.io.IOException;
  29. import java.util.List;
  30. import java.util.Locale;
  31.  
  32. import butterknife.ButterKnife;
  33. import butterknife.InjectView;
  34.  
  35. public class MainActivity extends ActionBarActivity {
  36.  
  37. public static final String TAG = MainActivity.class.getSimpleName();
  38. public String address;
  39.  
  40. private CurrentWeather mCurrentWeather;
  41. double latitude;
  42. double longitude;
  43. @InjectView(R.id.timeLabel) TextView mTimeLabel;
  44. @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
  45. @InjectView(R.id.humidityValue) TextView mHumidityValue;
  46. @InjectView(R.id.precipValue) TextView mPrecipValue;
  47. @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
  48. @InjectView(R.id.iconImageView) ImageView mIconImageView;
  49. @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
  50. @InjectView(R.id.progressBar) ProgressBar mProgressBar;
  51. @InjectView(R.id.locationLabel) TextView mLocation;
  52.  
  53. @Override
  54. protected void onCreate(Bundle savedInstanceState) {
  55. super.onCreate(savedInstanceState);
  56. setContentView(R.layout.activity_main);
  57. ButterKnife.inject(this);
  58.  
  59. mProgressBar.setVisibility(View.INVISIBLE);
  60. GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
  61.  
  62. if (gpsTracker.canGetLocation()) {
  63. latitude = gpsTracker.latitude;
  64. longitude = gpsTracker.longitude;
  65.  
  66.  
  67. }
  68.  
  69. // final double latitude = 37.8267;
  70. // final double longitude = -122.423;
  71.  
  72. mRefreshImageView.setOnClickListener(new View.OnClickListener() {
  73. @Override
  74. public void onClick(View v) {
  75. getForecast(latitude, longitude);
  76. }
  77. });
  78.  
  79. getForecast(latitude, longitude);
  80.  
  81. Log.d(TAG, "Main UI code is running!");
  82. }
  83.  
  84. private void getForecast(final double latitude, final double longitude) {
  85. String apiKey = "e42a81c6e6fcdbb89f4e91e091b88682";
  86. String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
  87. "/" + latitude + "," + longitude;
  88.  
  89. if (isNetworkAvailable()) {
  90. toggleRefresh();
  91.  
  92. OkHttpClient client = new OkHttpClient();
  93. Request request = new Request.Builder()
  94. .url(forecastUrl)
  95. .build();
  96.  
  97. Call call = client.newCall(request);
  98. call.enqueue(new Callback() {
  99. @Override
  100. public void onFailure(Request request, IOException e) {
  101. runOnUiThread(new Runnable() {
  102. @Override
  103. public void run() {
  104. toggleRefresh();
  105. }
  106. });
  107. alertUserAboutError();
  108. }
  109.  
  110. @Override
  111. public void onResponse(Response response) throws IOException {
  112. runOnUiThread(new Runnable() {
  113. @Override
  114. public void run() {
  115. toggleRefresh();
  116. }
  117. });
  118.  
  119. try {
  120. String jsonData = response.body().string();
  121. Log.v(TAG, jsonData);
  122. if (response.isSuccessful()) {
  123. mCurrentWeather = getCurrentDetails(jsonData);
  124. runOnUiThread(new Runnable() {
  125. @Override
  126. public void run() {
  127.  
  128. updateDisplay();
  129. }
  130. });
  131. } else {
  132. alertUserAboutError();
  133. }
  134. }
  135. catch (IOException e) {
  136. Log.e(TAG, "Exception caught: ", e);
  137. }
  138. catch (JSONException e) {
  139. Log.e(TAG, "Exception caught: ", e);
  140. }
  141. }
  142. });
  143. }
  144. else {
  145. Toast.makeText(this, getString(R.string.network_unavailable_message),
  146. Toast.LENGTH_LONG).show();
  147. }
  148. }
  149.  
  150. private void toggleRefresh() {
  151. if (mProgressBar.getVisibility() == View.INVISIBLE) {
  152. mProgressBar.setVisibility(View.VISIBLE);
  153. mRefreshImageView.setVisibility(View.INVISIBLE);
  154. }
  155. else {
  156. mProgressBar.setVisibility(View.INVISIBLE);
  157. mRefreshImageView.setVisibility(View.VISIBLE);
  158. }
  159. }
  160.  
  161. private String getCompleteAddressString() {
  162. Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
  163. // String info = "";
  164. List<Address> addresses = null;
  165. Address addr = null;
  166. String info ="";
  167. try {
  168.  
  169. Log.v(TAG, "lattis" + latitude);
  170. Log.v(TAG, "longs" +longitude);
  171. addresses = gcd.getFromLocation(latitude,longitude, 1);
  172. Log.v(TAG,"Address"+addresses);
  173. if (addresses != null && addresses.size() > 0) {
  174. addr = addresses.get(0);
  175. Log.d(TAG,"addr" + addr);
  176. info = "Address is: ";
  177. info += addr.getMaxAddressLineIndex() > 0 ? addr
  178. .getAddressLine(0) : "";
  179. info = info + ", " + addr.getLocality() + ", "
  180. + addr.getCountryName();
  181.  
  182. Log.v(TAG,"Infoooo" + info);
  183. Toast.makeText(getApplicationContext(), info,
  184. Toast.LENGTH_LONG).show();
  185. } else
  186. Toast.makeText(getApplicationContext(),
  187. "Address not found", Toast.LENGTH_LONG).show();
  188. } catch (Exception e) {
  189. Toast.makeText(getApplicationContext(), "Address not found",
  190. Toast.LENGTH_LONG).show();
  191. }
  192. return info;
  193. }
  194.  
  195.  
  196. public void updateDisplay() {
  197.  
  198. mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
  199. mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
  200. mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
  201. mPrecipValue.setText(mCurrentWeather.getPercipChance() + "%");
  202. mSummaryLabel.setText(mCurrentWeather.getSummary());
  203.  
  204. mLocation.setText(getCompleteAddressString());
  205.  
  206. Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
  207. mIconImageView.setImageDrawable(drawable);
  208. }
  209.  
  210. private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
  211. JSONObject forecast = new JSONObject(jsonData);
  212. String timezone = forecast.getString("timezone");
  213. Log.i(TAG, "From JSON: " + timezone);
  214.  
  215. JSONObject currently = forecast.getJSONObject("currently");
  216.  
  217. CurrentWeather currentWeather = new CurrentWeather();
  218. currentWeather.setHumidity(currently.getDouble("humidity"));
  219. currentWeather.setTime(currently.getLong("time"));
  220. currentWeather.setIcon(currently.getString("icon"));
  221. currentWeather.setPercipChance(currently.getDouble("precipProbability"));
  222. currentWeather.setSummary(currently.getString("summary"));
  223. currentWeather.setTemperature(currently.getDouble("temperature"));
  224. currentWeather.setTimeZone(timezone);
  225.  
  226. Log.d(TAG, currentWeather.getFormattedTime());
  227.  
  228. return currentWeather;
  229. }
  230.  
  231.  
  232.  
  233. private boolean isNetworkAvailable() {
  234. ConnectivityManager manager = (ConnectivityManager)
  235. getSystemService(Context.CONNECTIVITY_SERVICE);
  236. NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  237. boolean isAvailable = false;
  238. if (networkInfo != null && networkInfo.isConnected()) {
  239. isAvailable = true;
  240. }
  241.  
  242. return isAvailable;
  243. }
  244.  
  245. private void alertUserAboutError() {
  246. AlertDialogFragment dialog = new AlertDialogFragment();
  247. dialog.show(getFragmentManager(), "error_dialog");
  248. }
  249. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement