I have made a class that have a method and a locaton listener. The locationListener will be executed every 2 seconds , gets the lat longs and will pass it to the Async Task. The Async Task class will pass the lat longs to Google Road Api to get snapped lat longs and will pass the lat longs to postExecute()
The PostExecute() should draw the polylines But it does not..
Please See the below code.:
MapsActivity.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
final String URL = "https://roads.googleapis.com/v1/snapToRoads?path=";
final String KEY = "API KEY HERE";
int i = 0;
AsyncTask<Void, Void, LatLng> latLng1 = null;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
BackgroundTask backgroundTask = new BackgroundTask(MapsActivity.this, latLng, URL, KEY, activity, mMap);
backgroundTask.execute();
/*mMap.addMarker(new MarkerOptions().position(latLng1));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
BackgroundTask.java
package com.example.akshay.roadsapi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by Akshay on 9/8/2015.
*/
public class BackgroundTask extends AsyncTask<Void, Void, LatLng> {
Context CONTEXT;
LatLng LATLNGS;
String URL;
String KEY;
Double LAT = null;
Double LONG = null;
GoogleMap map;
Activity ACTIVITY;
myInt myInt = null;
int flag = 0;
LatLng prev;
LatLng latlng;
public BackgroundTask(Context context, LatLng LATLNGS, String URL, String KEY, Activity ACTIVITY, GoogleMap map) {
this.CONTEXT = context;
this.LATLNGS = LATLNGS;
this.URL = URL;
this.KEY = KEY;
this.ACTIVITY = ACTIVITY;
this.map = map;
}
#Override
protected LatLng doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet();
HttpResponse response = null;
HttpEntity entity = null;
InputStream inputStreamReader = null;
BufferedReader bufferedReader = null;
String line = null;
StringBuilder strin = new StringBuilder();
try {
get.setURI(new URI(URL + LATLNGS.latitude + "," + LATLNGS.longitude + "&interpolate=false&key=" + KEY));
response = client.execute(get);
entity = response.getEntity();
inputStreamReader = entity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStreamReader));
while ((line = bufferedReader.readLine()) != null) {
strin.append(line + "\n");
}
Log.e("============", strin.toString());
JSONObject ob = new JSONObject(strin.toString());
JSONArray array = ob.getJSONArray("snappedPoints");
for (int i = 0; i <= array.length(); i++) {
JSONObject object = array.getJSONObject(i).getJSONObject("location");
LAT = object.getDouble("latitude");
LONG = object.getDouble("longitude");
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
latlng= new LatLng(LAT, LONG);
return latlng;
}
#Override
protected void onPostExecute(LatLng latLng) {
super.onPostExecute(latLng);
/* MarkerOptions markerOptions = new MarkerOptions().position(latLng);
map.addMarker(markerOptions);*/
if (flag == 0) {
prev = latLng;
flag = 1;
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
/* Marker marker = map.addMarker(new MarkerOptions().position(latLng));*/
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.add(prev, latLng).color(Color.BLUE).width(50).visible(true);
map.addPolyline(polylineOptions);
map.animateCamera(cameraUpdate);
prev = latLng;
latLng = null;
}
}
I am getting the Json Array From GOOGLE API and getting the lats long values successfully but polyline is not Drawn..
Please Help
Thanks
Related
I've been working on this for the past few days and have tried different codes, but none of them have worked so far. I'm trying to make an activity that takes the user's current location and displays nearby hospitals to them.
Here's the code I'm using (it's the 1 I found online that doesn't crash android studio):
activity_hospitals.java (The draw() function is where I place markers):
package com.example.mobileproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.CancellationTokenSource;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.maps.model.PlacesSearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class activity_hospitals extends FragmentActivity implements OnMapReadyCallback {
Toolbar mytoolbar;
GoogleMap Gmap;
FusedLocationProviderClient flsc;
public LatLng here;
public double longo, lato;
Button Test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospitals);
Test=findViewById(R.id.btnGet);
Test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (here == null)
Toast.makeText(activity_hospitals.this, "Success!", Toast.LENGTH_SHORT).show();
else{
Toast.makeText(activity_hospitals.this, "Error", Toast.LENGTH_SHORT).show();
draw();
}
}
catch(Exception e){
}
}
});
mytoolbar = (Toolbar) findViewById(R.id.hospitalToolbar);
mytoolbar.setTitle("Hospitals Near You");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
flsc = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Gmap = googleMap;
}
public void draw(){
here = new LatLng(33.71456158807447, 35.48425016137045);
Gmap.addMarker(new MarkerOptions().position(here).title("Your Location").snippet("Your last recorded location"));
float zoomLevel = 11.0f; //This goes up to 21
Gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(here, zoomLevel));
double lat = here.latitude;
double lng = here.longitude;
StringBuilder sb = new StringBuilder("http://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+ 33.71456158807447 + "," + 35.48425016137045);
sb.append("&radius=1000");
sb.append("&types=hospital|health");
sb.append("&sensor=true");
sb.append("&key=" +getResources().getString(R.string.map_key));
String url=sb.toString();
Object dataFetch[] = new Object[2];
dataFetch[0] = Gmap;
dataFetch[1] = url;
FetchData fetchData = new FetchData();
fetchData.execute(dataFetch);
}
public void getLastLocation(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
flsc.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null) {
longo = location.getLatitude();
lato = location.getLongitude();
here = new LatLng(lato, longo);
}
});
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 100){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getLastLocation();
}
else{
Toast.makeText(this, "Required Permission", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
DownloadURL.java:
package com.example.mobileproject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadURL {
public String retrieveUrl(String url) throws IOException {
String urlData="";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
URL getUrl = new URL(url);
httpURLConnection = (HttpURLConnection) getUrl.openConnection();
httpURLConnection.connect();
inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb = new StringBuffer();
String line ="";
while((line = bufferedReader.readLine())!=null){
sb.append(line);
}
urlData = sb.toString();
bufferedReader.close();//////
}catch(Exception e){
Log.d("Exception", e.toString());
}finally{
inputStream.close();
httpURLConnection.disconnect();
}
return urlData;
}
}
FetchData.java:
package com.example.mobileproject;
import android.os.AsyncTask;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
public class FetchData extends AsyncTask<Object, String, String> {
String googleNearByPlacesData;
GoogleMap googleMap;
String url;
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsOnObject = jsonArray.getJSONObject(i);
JSONObject getLocation=jsOnObject.getJSONObject("geometry").getJSONObject("location");
String lat = getLocation.getString("lat");
String lng = getLocation.getString("lng");
JSONObject getName = jsonArray.getJSONObject(i);
String name = getName.getString("name");
LatLng latlng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(name);
markerOptions.position(latlng);
googleMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Object... objects) {
try{
googleMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadURL downloadURL = new DownloadURL();
googleNearByPlacesData = downloadURL.retrieveUrl(url);
} catch (IOException e) {
e.printStackTrace();
}
return googleNearByPlacesData;
}
}
I've also tried a different way using PlacesSearchResponse request = new PlacesSearchResponse(); that I found in a stackoverflow post. It also didn't crash the application, but it didn't work.
I just got the permissions handled through the library Let, but I still can't get a longitude and latitude in my android app. I'm using a service called GPS_Service.java. Also I'm not 100% sure my permissions aren't the issue. The call to the google API in GPS_Service still is underlined with the warning that it requires permissions which might be rejected. Is that supposed to go away even with third party libraries? Would this still be an issue because on my device the app has location permissions enabled?
here is my main activity:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.google.android.gms.maps.model.LatLng;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements RuntimePermissionListener {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private Context mContext;
#BindView(R.id.timeLabel)
TextView mTimeLabel;
#BindView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#BindView(R.id.humidityValue)
TextView mHumidityValue;
#BindView(R.id.precipValue)
TextView mPrecipValue;
#BindView(R.id.summaryLabel)
TextView mSummaryLabel;
#BindView(R.id.iconImageView)
ImageView mIconImageView;
#BindView(R.id.refreshImageView)
ImageView mRefreshImageView;
#BindView(R.id.progressBar)
ProgressBar mProgressBar;
#BindView(R.id.locationLabel)
TextView mLocationlabel;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Let.handle(this, requestCode, permissions, grantResults);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
#AskPermission({Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION})
private void checkGPS() {
GPS_Service gps_service = new GPS_Service(this);
gps_service.getLocation();
mLatitude = gps_service.getLatitude();
mLongitude = gps_service.getLongitude();
}
#Override
public void onShowPermissionRationale(List<String> permissionList, RuntimePermissionRequest permissionRequest) {
}
#Override
public void onPermissionDenied(List<DeniedPermission> deniedPermissionList) {
}
}
And here is my GPS_Service.java:
package com.example.paxie.stormy;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.canelmas.let.AskPermission;
import com.canelmas.let.DeniedPermission;
import com.canelmas.let.Let;
import com.canelmas.let.RuntimePermissionListener;
import com.canelmas.let.RuntimePermissionRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import java.util.ArrayList;
import java.util.List;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
private static final int RC_GPS_PERMS = 124;
public String[] perm = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
public GPS_Service(Context c) {
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void getLocation() {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In that case enable your GPS and go to google maps and hit the location button, wait until google maps locate u and then go back and test in ur app. This should work because if u are using the first time ur phone without never been conected to GPS it gives u that problem
It is looking for specifically "LastKnownLocation", I had this issue as well. Move about 3 meters and try again. If there is no 'last known location' then it sends a null value.
What I did was set a few if statements for my application. If the GPS Provider was spitting out null values, then use the Network Provider location coordinates, and if that was spitting out null values then I just displayed a message saying "To Wait" or "Try again later". Eventually your GPS Provider will pick up location values after it has been activated for a while.
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationProvider = LocationManager.NetworkProvider;
newLoc = _locationManager.GetLastKnownLocation(_locationProvider);
if (newLoc != null)
{
_latitudeUser = newLoc.Latitude;
_longitudeUser = newLoc.Longitude;
_locationText.Text = string.Format("{0:f6},{1:f6}", newLoc.Latitude, newLoc.Longitude);
}
else
{
_locationText.Text = string.Format("We currently cannot determine your location, please try again later.");
}
google map is loading on emulator givin error that application is stopped unfortunately following is my code package com.ayesha.MIT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Spot_Location_Screen extends FragmentActivity implements
LocationListener {
Database_Table_Operations database;
ArrayList<String> locations = new ArrayList<String>();
ArrayList<String> latitude = new ArrayList<String>();
ArrayList<String> longitude = new ArrayList<String>();
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
Intent intent;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
double mLatitude = 0;
double mLongitude = 0;
Button btnFind;
Button doneButton;
boolean isFound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spot_location_screen);
mPlaceType = getResources().getStringArray(R.array.place_type);
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
mSprPlaceType.setAdapter(adapter);
btnFind = (Button) findViewById(R.id.btn_find);
doneButton = (Button) findViewById(R.id.doneButton);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
database = new Database_Table_Operations(getApplicationContext());
if (getIntent().getStringExtra("Update") != null) {
if (getIntent().getStringExtra("Update").equals("true")) {
addMarker(getIntent().getStringExtra("Date"));
}
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
if (location != null) {
onLocationChanged(location);
}
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkInternetConnection(getApplicationContext())) { // browser
// key
mGoogleMap.clear();
locations.clear();
latitude.clear();
longitude.clear();
int selectedPosition = mSprPlaceType
.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + 33.6000 + "," + 73.0333);
sb.append("&radius=20000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyAVhTyd9GXAkJ9VJ1S7OD9ldrBsQgOH69c");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
}
}
});
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkInternetConnection(getApplicationContext())) {
if (getIntent().getStringExtra("Update").equals("true")) {
database.open();
String myDate = getIntent().getStringExtra("Date");
locations.add(database.getLocation(myDate));
latitude.add(database.getLatitude(myDate));
longitude.add(database.getLongitude(myDate));
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude", latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date",
getIntent().getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
database.close();
startActivity(intent);
finish();
} else {
if (locations.size() != 0) {
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude",
latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date", getIntent()
.getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
startActivity(intent);
finish();
}
}
}
}
});
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
latitude.add(String.valueOf(lat));
double lng = Double.parseDouble(hmPlace.get("lng"));
longitude.add(String.valueOf(lng));
String name = hmPlace.get("place_name");
String vicinity = hmPlace.get("vicinity");
locations.add(name + ", " + vicinity);
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
mGoogleMap.addMarker(markerOptions);
}
if (locations.size() > 1) {
int median = locations.size();
median = median / 2;
LatLng myLatLng = new LatLng(Double.parseDouble(latitude
.get(median)),
Double.parseDouble(longitude.get(median)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
} else if (locations.size() == 1) {
LatLng myLatLng = new LatLng(
Double.parseDouble(latitude.get(0)),
Double.parseDouble(longitude.get(0)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
}
}
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
intent = new Intent(Spot_Location_Screen.this,
SetMeetup_Screen.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
public void addMarker(String date) {
database.open();
MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(Double.parseDouble(database
.getLatitude(date)), Double.parseDouble(database
.getLongitude(date)));
markerOptions.position(latLng);
markerOptions.title("Your saved location:\n"
+ database.getLocation(date));
mGoogleMap.addMarker(markerOptions);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
database.close();
}
}, 2500);
}
public boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
isFound = true;
} else {
isFound = false;
}
return isFound;
}
}
Google Android Map API is not able to run Google Maps on the Android emulator. You must use an Real Android device for testing your app.
Refer this link to run Google Map on emulator.
hey ma problem is solved but the emulator is not working with Google maps I think its about the device problem but before it was also not working with the blue stacks for that I've changed the package name
right click the package from
src folder->refactor->rename
and
change the package name then change the package name in the manifest then click the on the project
ctrl+shiftz+o
it will change the package name throughout your project..
then again create the browser key and android key with new package name and it will load the map.....
and don forget to turn on the API's in Google console... and also check the minimum SDK version if its 9 then go to SSDK manager and install API 9 by clicking the obsolete option there...
I have a problem about uploading images from android to a server, the problem is about the android version, my application can run on android version 2.3 but can not run on version > 2.3. these is my code
function TambahLokasi()
{
$base = $_REQUEST["gambar"];
if (isset($base)){
$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";
$binary = base64_decode($base);
header("Content-Type: bitmap; charset=utf-8");
$file = fopen("gambar/" . $image_name, "wb");
fwrite($file, $binary);
fclose($file);
$username = $_POST['USERNAME'];
$loc_name = $_POST['LOCATION_NAME'];
$category = $_POST['CATEGORY'];
$address = $_POST['ADDRESS'];
$city = $_POST['CITY'];
$descript = $_POST['DESCRIPTION'];
$own = $_POST['OWNER'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$query = "insert into location (USERNAME,LOCATION_NAME,CATEGORY,ADDRESS,CITY,DESCRIPTION,OWNER,lat,lng,gambar)values ('$username', '$loc_name', '$category', '$address','$city','$descript','$own','$lat','$lng','$image_name')";
//$query = "insert into pasien values ('','n', 'n', 'n', 'n','bar','','','n','n','n')";
$hasil = mysql_query($query);
if($hasil)
{
$respon["success"] = "1";
$respon["pesan"] = "Data berhasil diinput";
echo json_encode($respon);
}
else
{
$respon["success"] = "0";
$respon["pesan"] = "Data gagal diinput. Mohon cek kembali.";
echo json_encode($respon);
die($image_name);
}
}else {
die("No POST");
}
}
function createRandomID() {
$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);
$i = 0;
$pass = "";
while ($i <= 5) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and this is java code
package com.adi.lib;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.adi.peta.AddLocation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
public class HttpUploader extends AsyncTask<String, Void, String>
{
String ba1;
Base64 base;
ProgressDialog pDialog;
Intent intent;
AddLocation add;
#SuppressWarnings("static-access")
protected String doInBackground(String... path)
{
String output = null;
for(String sdPath : path)
{
Bitmap bmp = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
double width = bmp.getWidth();
double height = bmp.getHeight();
double ratio = 400/width;
int newHeight = (int)(ratio*height);
bmp = Bitmap.createScaledBitmap(bmp, 400, newHeight, true);
bmp.compress(CompressFormat.JPEG, 90, bao);
byte[] ba= bao.toByteArray();
ba1 = base.encodeToString(ba, 0);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USERNAME", add.strUsername));
params.add(new BasicNameValuePair("LOCATION_NAME", add.strLocName));
params.add(new BasicNameValuePair("CATEGORY", add.strCategory));
params.add(new BasicNameValuePair("ADDRESS", add.strAddress));
params.add(new BasicNameValuePair("CITY", add.strCity));
params.add(new BasicNameValuePair("DESCRIPTION", add.strDesc));
params.add(new BasicNameValuePair("OWNER", add.strowner));
params.add(new BasicNameValuePair("lat", add.strlat));
params.add(new BasicNameValuePair("lng", add.strLng));
params.add(new BasicNameValuePair("gambar", ba1));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://batiktour.adi-hidayat.com/Android/AddLocation.php");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity);
Log.i("GET RESPONSE--",output);
Log.e("log_tag ******", "good connection");
bmp.recycle();
}
catch (Exception e)
{
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
}
return output;
}
}
AddLocation.java
package com.adi.peta;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.ErrorManager;
import android.widget.AdapterView.OnItemSelectedListener;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Text;
import com.adi.lib.HttpUploader;
import com.adi.lib.JSONParser;
import com.adi.lib.SessionManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.R.string;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.AdapterView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddLocation extends FragmentActivity implements LocationListener
{
Uri currImageURI;
GoogleMap googlemap;
ProgressDialog pDialog;
SessionManager session;
JSONParser jsonParser = new JSONParser();
EditText loc_name, address, city, desc, owner, latitude, longitude;
Spinner category;
Button submit, browse, gps;
String[] items = { "Tulis", "Cap", "Campuran" };
String id_user, tempcate, email, name, phone;
TextView path,status;
String image_name;
private static String url = "http://batiktour.adi-hidayat.com/Android/AddLocation.php";
public static String strUsername;
public static String strLocName;
public static String strCategory;
public static String strAddress;
public static String strCity;
public static String strDesc;
public static String strowner;
public static String strlat;
public static String strLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_location);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
.show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_USER);
// phone = user.get(SessionManager.KEY_PHONE);
TextView status = (TextView) findViewById(R.id.status);
status.setText(Html.fromHtml(email));
loc_name = (EditText) findViewById(R.id.locName);
address = (EditText) findViewById(R.id.address);
city = (EditText) findViewById(R.id.city);
desc = (EditText) findViewById(R.id.desc);
owner = (EditText) findViewById(R.id.owner);
latitude = (EditText) findViewById(R.id.tvLAT);
longitude = (EditText) findViewById(R.id.tvLNG);
category = (Spinner) findViewById(R.id.category);
submit = (Button) findViewById(R.id.submit);
browse = (Button) findViewById(R.id.browse);
gps = (Button) findViewById(R.id.ubahGPS);
path = (TextView) findViewById(R.id.path);
category = (Spinner)findViewById(R.id.category);
ArrayAdapter aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(aa);
category.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
strCategory = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapTambah);
googlemap = fm.getMap();
googlemap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
ImageView img = new ImageView(this);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 1);
}
});
gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
double chgLat;
double chgLng;
chgLat = Double.parseDouble(latitude.getText().toString());
chgLng = Double.parseDouble(longitude.getText().toString());
LatLng latlng = new LatLng(chgLat, chgLng);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions()
.position(latlng)
.title("POSISI")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
});
googlemap.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng latlong)
{
double lat = latlong.latitude;
double lng = latlong.longitude;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lng));
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latlong);
googlemap.clear();
// Animating to the touched position
googlemap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
// Placing a marker on the touched position
googlemap.addMarker(markerOptions);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(loc_name.getText().toString().trim().length()>0 &&
address.getText().toString().trim().length()>0 &&
city.getText().toString().trim().length()>0 &&
owner.getText().toString().trim().length()>0 &&
desc.getText().toString().trim().length()>0 &&
latitude.getText().toString().trim().length()>0 &&
longitude.getText().toString().trim().length()>0
){
if (path.getText().equals("")) {
Toast.makeText(getApplicationContext(),
"Belum Pilih Gambar", Toast.LENGTH_LONG).show();
} else {
String idUser;
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
idUser = user.get(SessionManager.KEY_USER);
strUsername = idUser;
strLocName = loc_name.getText().toString();
strAddress = address.getText().toString();
strCity = city.getText().toString();
strDesc = desc.getText().toString();
strowner = owner.getText().toString();
strlat = latitude.getText().toString();
strLng = longitude.getText().toString();
new AddLoc().execute();
}
}
else
{
Toast.makeText(getApplicationContext(), "Isilah yang kosong", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onLocationChanged(Location location) {
EditText tvLAT = (EditText) findViewById(R.id.tvLAT);
EditText tvLNG = (EditText) findViewById(R.id.tvLNG);
Button gps = (Button) findViewById(R.id.ubahGPS);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions().position(latLng)
.title("You're Here"));
tvLAT.setText(String.valueOf(latitude));
tvLNG.setText(String.valueOf(longitude));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the
// content:
currImageURI = data.getData();
path.setText(getRealPathFromURI(currImageURI));
}
}
}
// Convert the image URI to the direct file system path of the image file
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
android.database.Cursor cursor = managedQuery(contentUri, proj,
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
class AddLoc extends AsyncTask<String, String, String> {
String hasil,success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddLocation.this);
pDialog.setMessage("Menyimpan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpUploader uploader = new HttpUploader();
try {
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
} catch (InterruptedException e) {
Log.e("note1", "upload");
hasil="Interupasi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
} catch (ExecutionException e) {
Log.e("note1", "upload2");
hasil="Eksekusi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
}
return image_name;
}
protected void onPostExecute(String notifikasi) {
pDialog.dismiss();
Intent dash = new Intent(AddLocation.this,Dashboard.class);
startActivity(dash);
}
}
}
The culprit is most likely related to this line:
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
You're firing an AsyncTask from inside another AsyncTask, and the first one blocks until the second is completed. But, from the documentation:
Starting with HONEYCOMB, tasks are executed on a single thread to
avoid common application errors caused by parallel execution.
Since the second task never gets to start (in Android >= 3.0), the first one never gets to finish.
You could fix this by using executeOnExecutor(THREAD_POOL_EXECUTOR)...
... but I would suggest changing your code. Since the first task does nothing (i/o, networking) that would need a background thread, that code can just run in the UI thread. Provide the second (now, only) task with a callback to call in onPostExecute() when it has the result. See android asynctask sending callbacks to ui for a good example of this pattern.
Using get() on AsyncTasks is rarely a good idea.
I was wondering if anyone can help me with this. I am trying to add auto-completion to my app with the Google Places API. I am following a tutorial and the following code is what I am having a problem with:
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(args[0], "UTF-8") +
"&types=geocode&language=en&sensor=true&key=" +
getResources().getString(R.string.googleAPIKey));
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
The line "getResources()" is coming back with a "cannot resolve to a type" error because of the "R.string.googleAPIKey". I will put in my whole code down below:
package com.multinav;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null){
// Try to obtain the map from the SupportMapFragment.
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null){
setUpMap();
}
}
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// Set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("BAAMMMM!"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Main extends Activity {
/** Called when the activity is first created. */
public ArrayAdapter<String> adapter;
public AutoCompleteTextView textview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_list);
final AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(args[0], "UTF-8") +
"&types=geocode&language=en&sensor=true&key= +
getResources().getString(R.string.googleAPIKey));
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
}
catch (IOException e)
{
Log.e("MultiNAV", "GetPlaces : doInBackground", e);
}
catch (JSONException e)
{
Log.e("MultiNAV", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result){
Log.d("MultiNAV", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
textview.setAdapter(adapter);
for (String string : result){
Log.d("MultiNAV", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("MultiNAV", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
}
}