Android Google Maps API - cannot resolve "location.setLatitude()" - java

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).

Related

How mapbox navigation draw(Polyline) user location changed coordinates on Map?

private static class LocationChangeListeningActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MapMatchingActivity> activityWeakReference;
LocationChangeListeningActivityLocationCallback(MapMatchingActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
Feature feature = Feature.fromGeometry(Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude()));
if (location == null) {
return;
}
Log.e("Coords", String.valueOf(result.getLastLocation().getLatitude() +" " + result.getLastLocation().getLongitude()));
String[] latlong = (result.getLastLocation().getLatitude() +"," + result.getLastLocation().getLongitude()).split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
latLngList.add(new LatLng(longitude,latitude));
// activity.drawMarker();
}
}
#Override
public void onFailure(#NonNull Exception exception) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The above code where I am getting user location coordinates, I got to know that MapBox updated SDK, and PolylineOptions is now Deprecated, I have drawn lines using LineOptions but still have No idea how to update based on user location Please check below code.
private void getDirection(List<LatLng> coordinates,LatLng latLng){
List<LatLng> latLngs = new ArrayList<>();
latLngs.add(new LatLng(21.23504447 ,72.81109308));
latLngs.add(new LatLng( 21.23471482921968, 72.81101793050766));
latLngs.add(new LatLng(21.23425981047001, 72.81080335378647));
LineOptions lineOptions = new LineOptions()
.withLatLngs(latLngs)
.withLineColor(ColorUtils.colorToRgbaString(Color.BLACK))
.withLineWidth(5.0f);
lineManager.create(lineOptions);
}

Instantiating a class return null values

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));
}
}

My App is failing to log in with no possible explanation whatsoever

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.

Map route between your current location and a fixed marker can't make polylines

I want to make a route between my current location and marker not sure how to follow. I added a marker on the map but it doesn't show the polylines. For example when the user starts the app, they should get a route from their location to the marker.I am really stack on this.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
ArrayList < LatLng > MarkerPoints;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Initializing
MarkerPoints = new ArrayList < > ();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#
Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions().position(new LatLng(34.701466, 33.029269)).title("UMAR"));
// Already two locations
if (MarkerPoints.size() > 1) {
MarkerPoints.clear();
mMap.clear();
}
}
// Setting onclick event listener for the map
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#
Override
public void onMapClick(LatLng point) {
// Adding new item to the ArrayList
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if (MarkerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Checks, whether start and end locations are captured
if (MarkerPoints.size() >= 2) {
LatLng origin = MarkerPoints.get(0);
LatLng dest = MarkerPoints.get(1);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
});
}
private String getUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask < String, Void, String > {
#
Override
protected String doInBackground(String...url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
Log.d("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#
Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask < String, Integer, List < List < HashMap < String, String >>> > {
// Parsing the data in non-ui thread
#
Override
protected List < List < HashMap < String, String >>> doInBackground(String...jsonData) {
JSONObject jObject;
List < List < HashMap < String, String >>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("ParserTask", jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask", "Executing routes");
Log.d("ParserTask", routes.toString());
} catch (Exception e) {
Log.d("ParserTask", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#
Override
protected void onPostExecute(List < List < HashMap < String, String >>> result) {
ArrayList < LatLng > points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList < > ();
lineOptions = new PolylineOptions();
// Fetching i-th route
List < HashMap < String, String >> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap < String, String > point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(10);
lineOptions.color(Color.RED);
Log.d("onPostExecute", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
mMap.addPolyline(lineOptions);
} else {
Log.d("onPostExecute", "without Polylines drawn");
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#
Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#
Override
public void onConnectionSuspended(int i) {
}
#
Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#
Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#
Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}

Failed to Exit or finish my app android (Activity) correctly

The following app upload video to Dropbox when it is start, I added finish() in the end of onCreate to exit the app when its completed the uploading, but I got "Unfortunately, DBRoulette has stopped.".
In the Eclipse LogCat:
Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
android.view.WindowLeaked: Activity com.dropbox.android.sample.DBRoulette has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#42a7ee38 that was originally added here
I have Progress viewer which may cause the problem but I don't know how to solve it!
What I want to do is closing the app automatically when the uploading completed.
DBRoulette.java
#SuppressLint("SimpleDateFormat")
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";
final static private String APP_KEY = "<My APP_KEY>";
final static private String APP_SECRET = "<My APP_SECRET>";
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private static final boolean USE_OAUTH1 = false;
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
// Android widgets
private Button mSubmit;
private RelativeLayout mDisplay;
private Button mGallery;
private ImageView mImage;
private final String PHOTO_DIR = "/Motion/";
#SuppressWarnings("unused")
final static private int NEW_PICTURE = 50;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button) findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
if (USE_OAUTH1) {
mApi.getSession().startAuthentication(DBRoulette.this);
} else {
mApi.getSession().startOAuth2Authentication(
DBRoulette.this);
}
}
}
});
mDisplay = (RelativeLayout) findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView) findViewById(R.id.image_view);
File outFile = new File("/mnt/sdcard/ipwebcam_videos/video.mov");
mCameraFileName = outFile.toString();
UploadPicture upload = new UploadPicture(DBRoulette.this, mApi, PHOTO_DIR,outFile);
upload.execute();
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
storeAuth(session);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri)
{
String[] proj = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Logout from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Login with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") || APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its manifest properly.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's "
+ "manifest is not set up correctly. You should have a "
+ "com.dropbox.client2.android.AuthActivity with the "
+ "scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void loadAuth(AndroidAuthSession session) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key == null || secret == null || key.length() == 0
|| secret.length() == 0)
return;
if (key.equals("oauth2:")) {
// If the key is set to "oauth2:", then we can assume the token is
// for OAuth 2.
session.setOAuth2AccessToken(secret);
} else {
// Still support using old OAuth 1 tokens.
session.setAccessTokenPair(new AccessTokenPair(key, secret));
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a
* local store, rather than storing user name & password, and
* re-authenticating each time (which is not to be done, ever).
*/
private void storeAuth(AndroidAuthSession session) {
// Store the OAuth 2 access token, if there is one.
String oauth2AccessToken = session.getOAuth2AccessToken();
if (oauth2AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, "oauth2:");
edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
edit.commit();
return;
}
// Store the OAuth 1 access token, if there is one. This is only
// necessary if
// you're still using OAuth 1.
AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
if (oauth1AccessToken != null) {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME,
0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
edit.commit();
return;
}
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
loadAuth(session);
return session;
}
}
UploadPicture.java
public class UploadPicture extends AsyncTask<Void, Long, Boolean> {
private DropboxAPI<?> mApi;
private String mPath;
private File mFile;
private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;
private String mErrorMsg;
private File outFiles;
public UploadPicture(Context context, DropboxAPI<?> api, String dropboxPath,
File file) {
// We set the context this way so we don't accidentally leak activities
mContext = context.getApplicationContext();
mFileLen = file.length();
mApi = api;
mPath = dropboxPath;
mFile = file;
Date dates = new Date();
DateFormat dfs = new SimpleDateFormat("yyyyMMdd-kkmmss");
String newPicFiles = dfs.format(dates) + ".mov";
String outPaths = new File(Environment
.getExternalStorageDirectory(), newPicFiles).getPath();
outFiles = new File(outPaths);
mDialog = new ProgressDialog(context);
mDialog.setMax(100);
mDialog.setMessage("Uploading " + outFiles.getName());
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setProgress(0);
mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// This will cancel the putFile operation
mRequest.abort();
}
});
mDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// By creating a request, we get a handle to the putFile operation,
// so we can cancel it later if we want to
FileInputStream fis = new FileInputStream(mFile);
String path = mPath + outFiles.getName();
mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
new ProgressListener() {
#Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
#Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
if (mRequest != null) {
mRequest.upload();
return true;
}
} catch (DropboxUnlinkedException e) {
// This session wasn't authenticated properly or user unlinked
mErrorMsg = "This app wasn't authenticated properly.";
} catch (DropboxFileSizeException e) {
// File size too big to upload via the API
mErrorMsg = "This file is too big to upload";
} catch (DropboxPartialFileException e) {
// We canceled the operation
mErrorMsg = "Upload canceled";
} catch (DropboxServerException e) {
// Server-side exception. These are examples of what could happen,
// but we don't do anything special with them here.
if (e.error == DropboxServerException._401_UNAUTHORIZED) {
// Unauthorized, so we should unlink them. You may want to
// automatically log the user out in this case.
} else if (e.error == DropboxServerException._403_FORBIDDEN) {
// Not allowed to access this
} else if (e.error == DropboxServerException._404_NOT_FOUND) {
// path not found (or if it was the thumbnail, can't be
// thumbnailed)
} else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
// user is over quota
} else {
// Something else
}
// This gets the Dropbox error, translated into the user's language
mErrorMsg = e.body.userError;
if (mErrorMsg == null) {
mErrorMsg = e.body.error;
}
} catch (DropboxIOException e) {
// Happens all the time, probably want to retry automatically.
mErrorMsg = "Network error. Try again.";
} catch (DropboxParseException e) {
// Probably due to Dropbox server restarting, should retry
mErrorMsg = "Dropbox error. Try again.";
} catch (DropboxException e) {
// Unknown error
mErrorMsg = "Unknown error. Try again.";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Long... progress) {
int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
mDialog.setProgress(percent);
}
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
error.show();
}
}
Your problem is that you are trying to update an Activity's UI after the activity has finished.
First, you kick of an AsyncTask which posts progress updates to the UI thread. Then, before the task completes, you call finish(). Any updates to the Activity's UI after finish() is called are liable to throw exceptions, cause window leak issues, etc.
If you want to have any UI behavior as you perform your AsyncTask, you do not want to finish() the Activity until it the task is completed.
To achieve this, you could include a callback in the onPostExecute which tells the activity it is OK to finish once the AsyncTask completes.
This is how I would do it:
Change the signature of UploadPicture:
final Activity callingActivity;
public UploadPicture(final Activity callingActivity, DropboxAPI api, String dropboxPath, File file) {
Context mContext = callingActivity.getApplicationContext();
this.callingActivity = callingActivity;
Add the finish call to onPostExecute:
#Override
protected void onPostExecute(Boolean result) {
mDialog.dismiss();
if (result) {
showToast("Image successfully uploaded");
} else {
showToast(mErrorMsg);
}
callingActivity.finish(); //Finish activity only once you are done
}

Categories

Resources