Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package teamtreehouse.com.stromy;
- import android.content.Context;
- import android.graphics.drawable.Drawable;
- import android.location.Address;
- import android.location.Geocoder;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.Bundle;
- import android.support.v7.app.ActionBarActivity;
- import android.util.Log;
- import android.view.View;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.squareup.okhttp.Call;
- import com.squareup.okhttp.Callback;
- import com.squareup.okhttp.OkHttpClient;
- import com.squareup.okhttp.Request;
- import com.squareup.okhttp.Response;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.IOException;
- import java.util.List;
- import java.util.Locale;
- import butterknife.ButterKnife;
- import butterknife.InjectView;
- public class MainActivity extends ActionBarActivity {
- public static final String TAG = MainActivity.class.getSimpleName();
- public String address;
- private CurrentWeather mCurrentWeather;
- double latitude;
- double longitude;
- @InjectView(R.id.timeLabel) TextView mTimeLabel;
- @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
- @InjectView(R.id.humidityValue) TextView mHumidityValue;
- @InjectView(R.id.precipValue) TextView mPrecipValue;
- @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
- @InjectView(R.id.iconImageView) ImageView mIconImageView;
- @InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
- @InjectView(R.id.progressBar) ProgressBar mProgressBar;
- @InjectView(R.id.locationLabel) TextView mLocation;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.inject(this);
- mProgressBar.setVisibility(View.INVISIBLE);
- GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
- if (gpsTracker.canGetLocation()) {
- latitude = gpsTracker.latitude;
- longitude = gpsTracker.longitude;
- }
- // final double latitude = 37.8267;
- // final double longitude = -122.423;
- mRefreshImageView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- getForecast(latitude, longitude);
- }
- });
- getForecast(latitude, longitude);
- Log.d(TAG, "Main UI code is running!");
- }
- private void getForecast(final double latitude, final double longitude) {
- String apiKey = "e42a81c6e6fcdbb89f4e91e091b88682";
- String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
- "/" + latitude + "," + longitude;
- if (isNetworkAvailable()) {
- toggleRefresh();
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder()
- .url(forecastUrl)
- .build();
- Call call = client.newCall(request);
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Request request, IOException e) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- toggleRefresh();
- }
- });
- alertUserAboutError();
- }
- @Override
- public void onResponse(Response response) throws IOException {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- toggleRefresh();
- }
- });
- try {
- String jsonData = response.body().string();
- Log.v(TAG, jsonData);
- if (response.isSuccessful()) {
- mCurrentWeather = getCurrentDetails(jsonData);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- updateDisplay();
- }
- });
- } else {
- alertUserAboutError();
- }
- }
- catch (IOException e) {
- Log.e(TAG, "Exception caught: ", e);
- }
- catch (JSONException e) {
- Log.e(TAG, "Exception caught: ", e);
- }
- }
- });
- }
- else {
- Toast.makeText(this, getString(R.string.network_unavailable_message),
- Toast.LENGTH_LONG).show();
- }
- }
- private void toggleRefresh() {
- if (mProgressBar.getVisibility() == View.INVISIBLE) {
- mProgressBar.setVisibility(View.VISIBLE);
- mRefreshImageView.setVisibility(View.INVISIBLE);
- }
- else {
- mProgressBar.setVisibility(View.INVISIBLE);
- mRefreshImageView.setVisibility(View.VISIBLE);
- }
- }
- private String getCompleteAddressString() {
- Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
- // String info = "";
- List<Address> addresses = null;
- Address addr = null;
- String info ="";
- try {
- Log.v(TAG, "lattis" + latitude);
- Log.v(TAG, "longs" +longitude);
- addresses = gcd.getFromLocation(latitude,longitude, 1);
- Log.v(TAG,"Address"+addresses);
- if (addresses != null && addresses.size() > 0) {
- addr = addresses.get(0);
- Log.d(TAG,"addr" + addr);
- info = "Address is: ";
- info += addr.getMaxAddressLineIndex() > 0 ? addr
- .getAddressLine(0) : "";
- info = info + ", " + addr.getLocality() + ", "
- + addr.getCountryName();
- Log.v(TAG,"Infoooo" + info);
- Toast.makeText(getApplicationContext(), info,
- Toast.LENGTH_LONG).show();
- } else
- Toast.makeText(getApplicationContext(),
- "Address not found", Toast.LENGTH_LONG).show();
- } catch (Exception e) {
- Toast.makeText(getApplicationContext(), "Address not found",
- Toast.LENGTH_LONG).show();
- }
- return info;
- }
- public void updateDisplay() {
- mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
- mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
- mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
- mPrecipValue.setText(mCurrentWeather.getPercipChance() + "%");
- mSummaryLabel.setText(mCurrentWeather.getSummary());
- mLocation.setText(getCompleteAddressString());
- Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
- mIconImageView.setImageDrawable(drawable);
- }
- private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
- JSONObject forecast = new JSONObject(jsonData);
- String timezone = forecast.getString("timezone");
- Log.i(TAG, "From JSON: " + timezone);
- JSONObject currently = forecast.getJSONObject("currently");
- CurrentWeather currentWeather = new CurrentWeather();
- currentWeather.setHumidity(currently.getDouble("humidity"));
- currentWeather.setTime(currently.getLong("time"));
- currentWeather.setIcon(currently.getString("icon"));
- currentWeather.setPercipChance(currently.getDouble("precipProbability"));
- currentWeather.setSummary(currently.getString("summary"));
- currentWeather.setTemperature(currently.getDouble("temperature"));
- currentWeather.setTimeZone(timezone);
- Log.d(TAG, currentWeather.getFormattedTime());
- return currentWeather;
- }
- private boolean isNetworkAvailable() {
- ConnectivityManager manager = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = manager.getActiveNetworkInfo();
- boolean isAvailable = false;
- if (networkInfo != null && networkInfo.isConnected()) {
- isAvailable = true;
- }
- return isAvailable;
- }
- private void alertUserAboutError() {
- AlertDialogFragment dialog = new AlertDialogFragment();
- dialog.show(getFragmentManager(), "error_dialog");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement