The app just would not move past the log in page and the error pointing me to an inbuilt documentation
04-14 22:10:48.482 4206-4206/com.onyebuchboss.bossweatherbitcoinapp E/StorageHelpers: No value for version
org.json.JSONException: No value for version
at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getString(JSONObject.java:550)
at com.google.firebase.auth.internal.zzz.zzc(Unknown Source)
at com.google.firebase.auth.internal.zzz.zzbi(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.(Unknown Source)
at com.google.firebase.auth.internal.zzj.(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.zza(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
at java.lang.reflect.Method.invoke(Native Method)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.zzc(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
at android.app.ActivityThread.-wrap1(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
my code
public class WeatherActivity extends AppCompatActivity {
final int REQUEST_CODE = 123;
//the openweather url to be used
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
//the API key
final String APP_ID = "c9e6cb73daaf09d1bf0d1502d964bf60";
//time between location update (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
//Distance between location in metres
final float MIN_DISTANCE = 1000;
final String TAG = "WeatherApp";
//For the app to detect the user's location,
//we set the LOCATION_PROVIDER
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
//declare the variables to be linked to the layout
TextView mTemperature;
TextView mCity;
ImageView mWeatherImage;
//declare the LocationListener and LocationManager
LocationManager mLocationManager;
LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_layout);
//Link the elements in the Layout here
mCity = (TextView) findViewById(R.id.locationFetching);
mTemperature = (TextView) findViewById(R.id.tempereatureView);
mWeatherImage = (ImageView) findViewById(R.id.weatherImage);
ImageButton ChangeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
//The Intent method used below is mostly used for switching between Activities
ChangeCityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent changeCityIntent = new Intent(WeatherActivity.this, ChangeCityController.class);
// finish();
startActivity(changeCityIntent);
}
});
}
//the onResume method is one of android lifecycle method
//that starts/execute after the onCreate method
#Override
protected void onResume() {
super.onResume();
//retrieving the city name passed in the
//ChangecityController
//City was used in the PutExtra method in changeCity
Intent myIntent = getIntent();
String city =myIntent.getStringExtra("City");
//if the user does not enter a particular city
//retrieve user current city
if(city != null) {
getWeatherForNewLocation(city);
} else {
getWeatherForCurrentLocation();
}
}
//The method to retrieve any city entered by the user
private void getWeatherForNewLocation(String city) {
//the request params passes in the required parameters to retrieve data using the API
//The openWeatherMap API being used in this project, "q" and acity's name
//is to be assigned to iy
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
networkingCalls(params);
}
// get weather situation for current city -getWeatherForCurrentCityHere()
private void getWeatherForCurrentLocation() {
//create an instance of LocationManager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//the Location listener does the checking of the location for update
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: callback received");
//get the longitude and latitude of current locaion
//stored as a string
String Longitude = String.valueOf(location.getLongitude());
String Latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "onLocation Latitude is: " + Latitude);
Log.d(TAG, "onLocationChanged: longitude " + Longitude);
RequestParams params = new RequestParams();
params.put("lat", Latitude);
params.put("lon", Longitude);
params.put("appid", APP_ID);
networkingCalls(params);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: callback");
}
};
//REQUEST A LOCATION UPDATE PASSING THE LOCATION PROVIDER TO BE USED, MIN TIME,
// MIN DISTANCE AND mLISTENER as the receiver
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//request permissions to use the user's device GPS
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
}
//the override method below gives the result of the
// permission request to use the user's GPS
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//check to see if the request code matches the Request Code we gave
//during the request
if(requestCode == REQUEST_CODE){
if(grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult(): Granted!");
getWeatherForCurrentLocation();
}else{
Log.d(TAG, "onRequestPermissionsResult: Permission Denied");
}
}
}
//create the networkingCalls method here
//this method, we implement an HttpRequest, using it to make a Get request
private void networkingCalls(RequestParams params){
AsyncHttpClient client = new AsyncHttpClient();
//the Json object handler is used to notify whether the Getrequest failed or was successful
//the json response hanler receive 2 messages - onSucess and onFailure
//both methods are declared below
client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
Log.d(TAG, "onSuccess: " + response.toString());
// call the json from the WeatherDataModel
WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
updateUI(weatherData);
}
#Override
public void onFailure(int statuscode, Header[] headers, Throwable e, JSONObject response){
Log.e(TAG, "onFailure: "+ e.toString());
Log.d(TAG, "Status code: " + statuscode);
Toast.makeText(WeatherActivity.this, "Request failed", Toast.LENGTH_SHORT).show();
}
});
}
private void updateUI(WeatherDataModel weather){
mTemperature.setText(weather.getTemperature());
mCity.setText(weather.getCity());
int resourceID = getResources().getIdentifier(weather.getIconname(), "drawable", getPackageCodePath());
mWeatherImage.setImageResource(resourceID);
}
//This code below frees up memory
//when mListener is not in use and it is automatically generated
#Override
protected void onPause() {
super.onPause();
if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
}
}
public class WeatherDataModel {
private String mTemperature;
private String mCity;
private String mIconname;
private int mCondition;
//create a weatherdatamodel fromJson:
public static WeatherDataModel fromJson(JSONObject jsonObject) {
WeatherDataModel weatherData = new WeatherDataModel();
//we surround the json parsing code with a try-catch statement
//to handle errors like nan and empty values
try {
//get json object called -id, that is nested oin an object "0", thats also nested in an array called weather
weatherData.mCondition = jsonObject.getJSONArray("weather").getJSONObject(0).getInt("id");
weatherData.mCity = jsonObject.getString("name");
weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);
double temp = jsonObject.getJSONObject("main").getDouble("temp") - 273.15;
int rdValue = (int) Math.rint(temp);
weatherData.mTemperature= Integer.toString(rdValue);
return weatherData;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
private static String updateWeatherIcon(int condition) {
if (condition >= 0 && condition < 300) {
return "tstorm1";
} else if (condition >= 300 && condition < 500) {
return "light_rain";
} else if (condition >= 500 && condition < 600) {
return "shower3";
} else if (condition >= 600 && condition <= 700) {
return "snow4";
} else if (condition >= 701 && condition <= 771) {
return "fog";
} else if (condition >= 772 && condition < 800) {
return "tstorm3";
} else if (condition == 800) {
return "sunny";
} else if (condition >= 801 && condition <= 804) {
return "cloudy2";
} else if (condition >= 900 && condition <= 902) {
return "tstorm3";
} else if (condition == 903) {
return "snow5";
} else if (condition == 904) {
return "sunny";
} else if (condition >= 905 && condition <= 1000) {
return "tstorm3";
}
return "dunno";
}
//create a Get() for the variable created, so it can be retrieved in the weatherActivity
public String getTemperature() {
return mTemperature + "°";
}
public String getCity() {
return mCity;
}
public String getIconname() {
return mIconname;
}
}
Try checking if the JSON object exists first:
if (jsonObjectjsonObject.getJSONArray("weather").getJSONObject(0).has("id")) {
weatherData.mCity = jsonObject.getString("name");
weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);
}
I'm seeing the same stacktrace with slightly different message after building with Firebase SDK 15.0.0 (released April 10):
org.json.JSONException: No value for userMetadata
For me, the exception is non-fatal and only occurs the first time the new build is run on a device. I think it can be ignored.
If you are seeing the error repeatedly, or it is causing problems, downgrade to Firebase 12.0.1.
Related
I'm making an app that needs to get the results in my MainActivity, when I call getData() I get the data from my instantiation, but when i try to calculate the position it returns null.
This is my Location.class
public class Location implements GoogleApiClient.OnConnectionFailedListener {
private List<Integer> mTypeList;
private ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
LatLng mLatLang;
private PlaceLikelihood pl;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
public Location(Context context) {
this.listItems = new ArrayList<>();
this.mTypeList = new ArrayList<>();
mContext = context;
buildGoogleApiClient();
connect();
getData();
}
public void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient
.Builder(mContext)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
public void connect() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
public void getData() {
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
pl = placeLikelihoods.get(0);
Log.e("singleplacetype", "onResult: "+pl.getPlace().getPlaceTypes());
Log.e("singleliketype2", "onResult: "+pl.getLikelihood());
Log.e("singleliketype3", "onResult: "+pl.getPlace().getName());
mTypeList = pl.getPlace().getPlaceTypes();
//Latitude and longitude
mLatLang = pl.getPlace().getLatLng();
String latlongshrink = mLatLang.toString();
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(latlongshrink);
while (m.find()) {
Log.e("Test", "" + m.group(1));
latlongshrink = m.group(1);
}
for (int i = 0; i < mTypeList.size(); i++) {
try {
nearestPlaces(latlongshrink, getPlaceTypeForValue(mTypeList.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
try {
listItems.add(pl.getPlace().getName() + " " + pl.getLikelihood() + " " + mTypeList + " " + getPlaceTypeForValue(mTipoList.get(i)));
Log.e("singleList", "onResult: "+listItems );
} catch (Exception e) {
e.printStackTrace();
}
}
placeLikelihoods.release();
}
});
}
public Integer getTypes(int posicion) {
Log.e("listType", "getTypes: "+mTypeList);
int type;
if(mTypeList.size()>0){
type = mTypeList.get(posicion);
}else{
return null;
}
return type;
}
Now, that's my Location.class, I call that class in my MainActivity like this
Location loc = new Location(getApplicationContext());
I have another class that calculates some values with the first class, so after I instantiate the Location.class I can succefull see that getData() is executed as it returns to me some places.
json.class
private Integer getPosition(Location loc) {
return loc.getTypes(0);
}
so, now again into my MainActivity i'm trying to fetch te values from Location.class but from json.class, since getPosition does something else before it is beign executed
MainActivity.class
Json json = new Json(getApplicationContext());
Log.e("jsonClassData", "onCreate: "+json.getPosition(loc));
now, this line is returning null , but I dont know why since getData() have been created but getTypes have inside mTypeList that is returning 0 as size and returning null since mTypeList.size is 0
Also if in MainActivity.class I call this line it returns null too
Location loc = new Location(getApplicationContext());
loc.getType(0);
it seems getData() is not saving the values inside mTypeList
Why is this happening ?
thanks
Location loc = new Location(getApplicationContext());
You are not supposed to create an activity with the new operator.
You should use an intent for that.
And so do away with all those public member functions.
The problem was that getData() is an asynchronous operation that is waiting for the results. Now, if I don't wait for that data to be done, getTypes does not have any value on it. Now, thanks to Mike M. I just solved the problem using a simple interface.
I created an interface called PlaceSuccessListener
public interface PlaceSuccessListener {
void onPlaceFound(int placeFound);
}
called it at the last of my pendingResult
private PlaceSuccessListener mPlaceSuccessListener;
getData();
.....
placeLikelihoods.release();
mPlaceSuccessListener.onPlaceFound(200);
}
And then in my MainActivity I just waited for the result to be done in order to access my data. I implemented PlaceSuccessListener and attached the setInterface(this)
#Override
public void onPlaceFound(int placeFound) {
if(placeFound==200){
Log.e("jsonClassData", "onCreate: "+json.getPosition(loc));
}
}
I'm trying to create a location and set latitude and longitude, but when I write
location.setLatitude
I'm getting
cannot resolve symbol
error. Anyone can help?
Location location = new Location("");
location.setLatitude(0.0d);
If I change code like this:
Location location = new Location("")
.setLatitude(0.0d)
I'm getting error
Incopatible types. ;
Required: android.location.Location ;
Found: void
Edit: Here's the class. It's literally code from Google tutorial. I deleted some unnecessary parts, and added few i needed.
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback {
private static final String TAG = MapsActivity.class.getSimpleName();
private GoogleMap mMap;
private CameraPosition mCameraPosition;
// The entry points to the Places API.
private GeoDataClient mGeoDataClient;
private PlaceDetectionClient mPlaceDetectionClient;
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient mFusedLocationProviderClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng mDefaultLocation = new LatLng(49.656639, 19.636917);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
// Keys for storing activity state.
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// Used for selecting the current place.
private static final int M_MAX_ENTRIES = 5;
private String[] mLikelyPlaceNames;
private String[] mLikelyPlaceAddresses;
private String[] mLikelyPlaceAttributions;
private LatLng[] mLikelyPlaceLatLngs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
}
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// Construct a GeoDataClient.
mGeoDataClient = Places.getGeoDataClient(this, null);
// Construct a PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
// Build the map.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Saves the state of the map when the activity is paused.
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
if (mMap != null) {
outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
super.onSaveInstanceState(outState);
}
}
LatLng centPoint = new LatLng(49.656639, 19.636917);
int kolStrefa = Color.argb(40, 255, 0, 0);
Location location = new Location("");
location.setLatitude(0.0d); //Cannot resolve symbol
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
// Prompt the user for permission.
getLocationPermission();
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
CircleOptions strefa = new CircleOptions()
.center(centPoint)
.radius(200)
.strokeColor(Color.RED)
.fillColor(kolStrefa);
Circle circle = mMap.addCircle(strefa);
}
double distance = mLastKnownLocation.distanceTo(krzCent);
/**
* Gets the current location of the device, and positions the map's camera.
*/
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = task.getResult();
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
/**
* Prompts the user for permission to use the device location.
*/
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
/**
* Handles the result of the request for location permissions.
*/
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
private void showCurrentPlace() {
if (mMap == null) {
return;
}
if (mLocationPermissionGranted) {
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
#SuppressWarnings("MissingPermission") final
Task<PlaceLikelihoodBufferResponse> placeResult =
mPlaceDetectionClient.getCurrentPlace(null);
placeResult.addOnCompleteListener
(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceLikelihoodBufferResponse> task) {
if (task.isSuccessful() && task.getResult() != null) {
PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
// Set the count, handling cases where less than 5 entries are returned.
int count;
if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
count = likelyPlaces.getCount();
} else {
count = M_MAX_ENTRIES;
}
int i = 0;
mLikelyPlaceNames = new String[count];
mLikelyPlaceAddresses = new String[count];
mLikelyPlaceAttributions = new String[count];
mLikelyPlaceLatLngs = new LatLng[count];
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
// Build a list of likely places to show the user.
mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
.getAddress();
mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
.getAttributions();
mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (count - 1)) {
break;
}
}
// Release the place likelihood buffer, to avoid memory leaks.
likelyPlaces.release();
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
openPlacesDialog();
} else {
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
} else {
// The user has not granted permission.
Log.i(TAG, "The user did not grant location permission.");
// Add a default marker, because the user hasn't selected a place.
mMap.addMarker(new MarkerOptions()
.title("DEF")
.position(mDefaultLocation)
.snippet("DEFfd"));
// Prompt the user for permission.
getLocationPermission();
}
}
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = mLikelyPlaceLatLngs[which];
String markerSnippet = mLikelyPlaceAddresses[which];
if (mLikelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
mMap.addMarker(new MarkerOptions()
.title(mLikelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
// Position the map's camera at the location of the marker.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
// Display the dialog.
}
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mLastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
}
First, you should try to create a completely new class and create this Location there to see if the error lies within the rest of the code.
And finally,
Location location = new Location("").setLatitude(0.0d); will not work because you first create your Location and then instantly set the latitude. Java thinks that you want to assign the return value of #setLatitude to the variable (which of course is not possible since it returns void).
It's my first time using stackoverflow so sorry for my question. I have been learning java and swift for only 4-5 month, so I'm just a beginner.
I'm writing a simple app with google Map and some other features like Weather Activity.
Map Activity running perfectly, Weather Activity also, but only with static latitude and longitude:
asyncTask.execute("28.125696","-15.440090" );
How to implement get currentLocation.getLatitude(), currentLocation.getLongitude() from MainActivityWeather in asyncTask.execute(...); ?
Am I thinking right? Is it a good way to build a weather app with a current location data? Map Activity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
public static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136)
);
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutoCompleteAdapter mPlaceAutoCompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
getLocationPermission();
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
BottomNavigationViewHelper.removeShiftMode(bottomNav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_menu:
Intent intent0 = new Intent(MapActivity.this, MainActivity.class);
startActivity(intent0);
break;
case R.id.nav_note:
Intent intent1 = new Intent(MapActivity.this, MainListActivity.class);
startActivity(intent1);
break;
case R.id.nav_map:
break;
case R.id.nav_attraction:
Intent intent3 = new Intent(MapActivity.this, MainActivityGrid.class);
startActivity(intent3);
break;
}
return false;
}
});
}
private void init(){
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener );
mPlaceAutoCompleteAdapter = new PlaceAutoCompleteAdapter(this, mGoogleApiClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutoCompleteAdapter);
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
geoLocate();
}
return false;
}
});
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
hideSoftKeyboard();
}
private void geoLocate(){
Log.d(TAG, "geoLocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapActivity.this);
List<Address> list = new ArrayList<>();
try{
list = geocoder.getFromLocationName(searchString,1);
}catch (IOException e) {
Log.d(TAG, "geoLocate: IOException " +e.getMessage());
}
if(list.size() > 0 ){
Address address = list.get(0);
Log.d(TAG, "geoLocate: found a location "+ address.toString());
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM, address.getAddressLine(0));
}
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()&& task.getResult() != null){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "My location");
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom, String title){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if(!title.equals("My location")){
MarkerOptions options = new MarkerOptions().position(latLng).title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutoCompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.d(TAG, "onResult: Place query did not mplete successfully" + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
mPlace.setAttributions(place.getAttributions().toString());
Log.d(TAG, "onResult: attributions: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id:" + place.getId());
mPlace.setLatlng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: phone number: " + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: website uri: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch (NullPointerException e){
Log.e(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace.getName());
places.release();
}
};}
Wheather Activities:
public class MainActivityWeather extends AppCompatActivity {
private static final String TAG = "WeatherActivity";
TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_weather);
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute( ); // asyncTask.execute("Latitude", "Longitude")
}}
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "fdbf72863aba44b6fc7ce9e3324a689f";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}}
So I have implemented so far asking for the user to give me permission to their google account. I need to then take that token and add it to the following URL https://api.comma.ai/v1/auth/?access_token= to get a token from them and store that token so that I can use it. However, as the title I get {"success": false, "error": "oauth failed"} which is better than the 401 that I was getting...I think? This is my first time diving into this. I am not sure where I am going wrong on this. Any help is greatly appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this;
private AccountManager mAccountManager;
private AuthPreferences authPreferences;
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "";
static final String API_URL = "https://api.comma.ai/v1/auth/?access_token=";
static final String ClientId = "45471411055-m902j8c6jo4v6mndd2jiuqkanjsvcv6j.apps.googleusercontent.com";
static final String ClientSecret = "";
static final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
mAccountManager = AccountManager.get(this);
authPreferences = new AuthPreferences(this);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
doCoolAuthenticatedStuff();
new RetrieveFeedTask().execute();
} else{
chooseAccount();
}
}
});
// Button queryButton = (Button) findViewById(R.id.queryButton);
//
// queryButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (isNetworkAvailable() == true) {
// new RetrieveFeedTask().execute();
// Intent intent = new Intent(context, NavDrawerActivity.class);
// startActivity(intent);
// } else {
// Toast.makeText(MainActivity.this, "No Network Service, please check your WiFi or Mobile Data Connection", Toast.LENGTH_SHORT).show();
// }
// }
// });
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "WiFi");
myDiag.setCancelable(false);
}
}
private void doCoolAuthenticatedStuff() {
Log.e("AuthApp", authPreferences.getToken());
}
private void chooseAccount() {
Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
private void requestToken() {
Account userAccount = null;
String user = authPreferences.getUser();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
for (Account account : mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(user)) {
userAccount = account;
break;
}
}
mAccountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, new OnTokenAcquired(), null);
}
private void invalidateToken()
{
AccountManager mAccountManager = AccountManager.get(this);
mAccountManager.invalidateAuthToken("com.google", authPreferences.getToken());
authPreferences.setToken(null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == AUTHORIZATION_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
authPreferences.setUser(accountName);
// invalidate old tokens which might be cached. we want a fresh
// one, which is guaranteed to work
invalidateToken();
requestToken();
}
}
}
public class OnTokenAcquired implements AccountManagerCallback<Bundle>
{
#Override
public void run(AccountManagerFuture<Bundle> result)
{
try {
Bundle bundle = result.getResult();
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if(launch != null)
{
startActivityForResult(launch, AUTHORIZATION_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
authPreferences.setToken(token);
doCoolAuthenticatedStuff();
}
} catch (Exception e){
Log.e("ERROR", e.getMessage(), e);
}
}
}
public boolean isNetworkAvailable()
{
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected())
{
Log.e("Network Testing", "Available");
return true;
}
Log.e("Network Testing", "Not Available");
return false;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL(API_URL + authPreferences);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("client_id", ClientId);
urlConnection.addRequestProperty("client_secret", ClientSecret);
urlConnection.setRequestProperty("Authorization", "OAuth " + authPreferences);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
//
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}
}
And here is the AuthPreferences.java if anyone needs to look at it.
public class AuthPreferences {
private static final String KEY_USER = "user";
private static final String KEY_TOKEN = "token";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context
.getSharedPreferences("auth", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.commit();
}
public void setToken(String password) {
Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, null);
}
public String getToken() {
return preferences.getString(KEY_TOKEN, null);
}
}
I did never use Android for OAuth2 but as far as I understand your code I think there are a few errors.
Fix the RetrieveFeedTask (OAuth2 Token is typically Bearer Token for all I know), use the access token like this:
URL url = new URL(API_URL + authPreferences.getToken());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("client_id", ClientId);
urlConnection.addRequestProperty("client_secret", ClientSecret);
urlConnection.setRequestProperty("Authorization", "OAuth " + authPreferences.getToken());
Furthermore I am not sure if your approach is correct (can you post a link where this snippet is from?). As far as I understand OAuth2 I would expect that at this time you can simply authorize by using a Bearer token und do no longer have to supply the access token in the URL / the client id and secrets. Or you may be missing a step (e.g. splitting the upper codes in two requests). Make sure you are explicitely following the OAuth2 standard and be sure what grant type you are using. Then debug your application to find out where the error is returned.
I'm able to grant or deny permissions in my fragment but I'm trying to call a method when permission has been granted but it doesn't seem to get called.
public final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 1;
In onCreateView(): (This works)
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
retrieveGyms();
} else {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_COARSE_LOCATION);
}
retrieveGyms() is not called when permission is granted from dialog, but permission does get granted.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_COARSE_LOCATION: {
if (permissions.length == 1 && permissions[0] == Manifest.permission.ACCESS_COARSE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
retrieveGyms();
} else {
// Location permission denied.
}
}
}
}
Showing retrieveGyms() just to show what it does and what I'm expecting
public void retrieveGyms() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://gyminyapp.azurewebsites.net/api/Gym", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
gymsArray = response;
// HashMap<String, Object> returnedGyms = new HashMap<String, Object>();
for (int i = 0; i < gymsArray.length(); i++) {
try {
// TODO: check distance from current user location and remove if not within search radius
String latitude = gymsArray.getJSONObject(i).getString("latitude");
String longitude = gymsArray.getJSONObject(i).getString("longitude");
Double doubleLat = Double.parseDouble(latitude);
Double doubleLong = Double.parseDouble(longitude);
LatLng gymCoord = new LatLng(doubleLat, doubleLong);
String name = gymsArray.getJSONObject(i).getString("name");
Object gymAddress = gymsArray.getJSONObject(i).get("address");
JSONObject gymAddressJSONObj = (JSONObject)gymAddress;
String streetAddress = gymAddressJSONObj.getString("streetAddress");
String city = gymAddressJSONObj.getString("city");
String state = gymAddressJSONObj.getString("state");
int zipCode = gymAddressJSONObj.getInt("zipCode");
String zipCodeString = Integer.toString(zipCode);
String addressString = streetAddress + " " + city + ", " + state + " " + zipCodeString;
Marker marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
.flat(false)
.title(name)
.snippet(addressString)
.position(gymCoord));
// Add marker to markers array
markers.add(marker);
} catch (JSONException e) {
e.printStackTrace();
}
// Zoom map to fit all markers
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = 75;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cameraUpdate);
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable e) {
}
});
}