Skip to content

Commit

Permalink
Complete places API integration
Browse files Browse the repository at this point in the history
  • Loading branch information
Protino committed Nov 27, 2016
1 parent dac6e8a commit 2095766
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 12 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,10 @@ This is an android application which shows real-time weather data by using <a hr

`MyOpenWeatherMapApiKey = "[YOUR_API_KEY_HERE]"`
You can get an API_KEY from <a href="http://openweathermap.org" target="_blank">Open Weather</a>
5. Also, add the places API key in the AndroidManifest.xml file

`<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ENTER_YOU_API_KEY_HERE"/>`

Please report issues by attaching log errors, if possible else screenshots will do.
5 changes: 4 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
<uses-permission
android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>

<!-- Permissions required to access location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
Expand All @@ -26,7 +29,7 @@
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API-KEY"/>
android:value="ENTER_YOU_API_KEY_HERE"/>
<activity
android:name=".activity.MainActivity"
android:label="@string/app_name"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.calgen.prodek.sunshine_v2.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
Expand All @@ -9,19 +10,27 @@
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.calgen.prodek.sunshine_v2.R;
import com.calgen.prodek.sunshine_v2.Utility;
import com.calgen.prodek.sunshine_v2.data.WeatherContract;
import com.calgen.prodek.sunshine_v2.sync.SunshineSyncAdapter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;

/**
* Created by Gurupad on 15-Jun-16.
*/
public class SettingsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener, SharedPreferences.OnSharedPreferenceChangeListener {

public final static int PLACE_PICKER_REQUEST = 9090;
private static final String TAG = SettingsActivity.class.getSimpleName();
private ImageView attribution;

@Override
public void onCreate(Bundle savedInstanceState) {
Expand All @@ -34,6 +43,16 @@ public void onCreate(Bundle savedInstanceState) {
bindPreferenceSummaryToValue(findPreference(getResources().getString(R.string.pref_location_key)));
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_icon_pack_key)));
bindPreferenceSummaryToValue(findPreference(getResources().getString(R.string.pref_temperature_key)));

attribution = new ImageView(this);
attribution.setPadding(16,16,16,16);
attribution.setImageResource(R.drawable.powered_by_google_light);
if (!Utility.isLocationLatLonAvailable(this)) {
attribution.setVisibility(View.GONE);
}
setListFooter(attribution);


CheckBoxPreference notificationPreference = (CheckBoxPreference) findPreference(getResources().getString(R.string.pref_notification_key));
notificationPreference.setOnPreferenceChangeListener(this);
}
Expand Down Expand Up @@ -119,10 +138,64 @@ protected void onPause() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.pref_location_key))) {
// we've changed the location
// Wipe out any potential PlacePicker latlng values so that we can use this text entry.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(getString(R.string.pref_location_latitude));
editor.remove(getString(R.string.pref_location_longitude));
editor.commit();

if (attribution != null) attribution.setVisibility(View.GONE);

Utility.resetLocationStatus(this);
SunshineSyncAdapter.syncImmediately(this);
} else if (key.equals(getString(R.string.pref_temperature_key))) {
// units have changed. update lists of weather entries accordingly
getContentResolver().notifyChange(WeatherContract.WeatherEntry.CONTENT_URI, null);
} else if (key.equals(getString(R.string.pref_location_status_key))) {
// our location status has changed. Update the summary accordingly
Preference locationPreference = findPreference(getString(R.string.pref_location_key));
bindPreferenceSummaryToValue(locationPreference);
} else if (key.equals(getString(R.string.pref_icon_pack_key))) {
// art pack have changed. update lists of weather entries accordingly
getContentResolver().notifyChange(WeatherContract.WeatherEntry.CONTENT_URI, null);
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check to see if the result is from our Place Picker intent
if (requestCode == PLACE_PICKER_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String address = place.getAddress().toString();
LatLng latLong = place.getLatLng();

if (TextUtils.isEmpty(address)) {
address = String.format("(%.2f, %.2f)", latLong.latitude, latLong.longitude);
}

SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getString(R.string.pref_location_key), address);
editor.putFloat(getString(R.string.pref_location_latitude), (float) latLong.latitude);
editor.putFloat(getString(R.string.pref_location_longitude), (float) latLong.longitude);
editor.commit();

Preference locationPreference = findPreference(getString(R.string.pref_location_key));
locationPreference.setSummary(address);

if (attribution!=null){
attribution.setVisibility(View.VISIBLE);
}

Utility.resetLocationStatus(this);
SunshineSyncAdapter.syncImmediately(this);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
24 changes: 24 additions & 0 deletions app/src/main/java/com/calgen/prodek/sunshine_v2/Utility.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,30 @@ public class Utility {
public static final String DATE_FORMAT = "yyyyMMdd";
private static final String TAG = Utility.class.getSimpleName();

// We'll default our latlong to 0. Yay, "Earth!"
public static float DEFAULT_LATLONG = 0F;

public static boolean isLocationLatLonAvailable(Context context) {
SharedPreferences prefs
= PreferenceManager.getDefaultSharedPreferences(context);
return prefs.contains(context.getString(R.string.pref_location_latitude))
&& prefs.contains(context.getString(R.string.pref_location_longitude));
}

public static float getLocationLatitude(Context context) {
SharedPreferences prefs
= PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getFloat(context.getString(R.string.pref_location_latitude),
DEFAULT_LATLONG);
}

public static float getLocationLongitude(Context context) {
SharedPreferences prefs
= PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getFloat(context.getString(R.string.pref_location_longitude),
DEFAULT_LATLONG);
}

public static String getPreferredLocation(Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString(context.getResources().getString(R.string.pref_location_key)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.calgen.prodek.sunshine_v2.customView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
Expand All @@ -13,11 +14,14 @@
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.calgen.prodek.sunshine_v2.R;
import com.calgen.prodek.sunshine_v2.activity.SettingsActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.ui.PlacePicker;

/**
* Created by Gurupad Mamadapur on 11/8/2016.
Expand Down Expand Up @@ -61,8 +65,16 @@ protected View onCreateView(ViewGroup parent) {
currentLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// We'll use a toast for now so that we can test our new preference widget.
Toast.makeText(getContext(), "Woo!", Toast.LENGTH_LONG).show();
Context context = getContext();

PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder();

Activity settingsActivity = (SettingsActivity) context;
try {
settingsActivity.startActivityForResult(intentBuilder.build(settingsActivity), SettingsActivity.PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesNotAvailableException
| GooglePlayServicesRepairableException ignore) {
}
}
});

Expand All @@ -86,7 +98,7 @@ public void onTextChanged(CharSequence s, int start, int before, int count) {

@Override
public void afterTextChanged(Editable s) {
Dialog dialog= getDialog();
Dialog dialog = getDialog();
if (dialog instanceof AlertDialog) {
AlertDialog alertDialog = (AlertDialog) dialog;
Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,10 @@ static private void setLocationStatus(Context c, @LocationStatus int locationSta
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.d(LOG_TAG, "Starting sync");
String locationQuery = Utility.getPreferredLocation(getContext());
Context context = getContext();
String locationQuery = Utility.getPreferredLocation(context);
String locationLatitude = String.valueOf(Utility.getLocationLatitude(context));
String locationLongitude = String.valueOf(Utility.getLocationLongitude(context));

// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
Expand All @@ -217,17 +220,27 @@ public void onPerformSync(Account account, Bundle extras, String authority, Cont
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String LAT_PARAM = "lat";
final String LON_PARAM = "lon";
final String API_KEY = "APPID";

Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, locationQuery)
.appendQueryParameter(FORMAT_PARAM, format)

Uri.Builder builder = Uri.parse(FORECAST_BASE_URL).buildUpon();

if (Utility.isLocationLatLonAvailable(context)) {
builder.appendQueryParameter(LAT_PARAM, locationLatitude)
.appendQueryParameter(LON_PARAM, locationLongitude);
} else {
builder.appendQueryParameter(QUERY_PARAM, locationQuery);
}

builder.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(API_KEY, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();

URL url = new URL(builtUri.toString());
URL url = new URL(builder.toString());

// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
Expand Down
10 changes: 8 additions & 2 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
<string name="pref_location_label">Location</string>


<string name="pref_location_key" translatable="false">location</string>
<string name="pref_location_default" translatable="false">Bagalkot</string>
<string name="pref_location_key" translatable="false">loc-status</string>
<string name="pref_location_default" translatable="false">Badami</string>
<string name="pref_location_status_key">LOCATION_STATUS_KEY</string>

<string name="pref_location_latitude" translatable="false">loc-latitude</string>
<string name="pref_location_longitude" translatable="false">loc-longitude</string>


<!-- Temperature Settings -->
<string name="pref_temperature_label">Temperature</string>
Expand Down Expand Up @@ -171,4 +174,7 @@

<string name="pref_current_location_desc">Use my location</string>

<!--Related to attributions-->
<string name="attribution_text">Powered by Google</string>

</resources>

0 comments on commit 2095766

Please sign in to comment.