Places of Interest not showing in Android Google Maps - java

So I am following a tutorial to find places of interest: LINK. I turn my Places API & Google Maps V2 ON in Google Console. I have my API Key and everything set correctly, because my map does comes up and my current location. But the places never show. I see no error in the logcat as well.
Heres my code:
MapsActivity.java
package indabutt.com.indabuttalpha;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationManager;
import android.content.Context;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locMan;
private Marker userMarker;
private Marker[] placeMarkers;
private final int MAX_PLACES = 10;
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
private void updatePlaces(){
//Update Location
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
LatLng lastLatLng = new LatLng(lat,lng);
if(userMarker!=null) userMarker.remove();
userMarker = mMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here!")
.snippet("I am here BITCH!!!"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastLatLng,10));
String latVal=String.valueOf(lat);
String lngVal=String.valueOf(lng);
String url;
try {
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+URLEncoder.encode(latVal, "UTF-8")
+","
+URLEncoder.encode(lngVal, "UTF-8")
+"&radius="
+URLEncoder.encode("5000", "UTF-8")
+"&sensor="
+URLEncoder.encode("true", "UTF-8")
+"&types="
+URLEncoder.encode("food|bar|church|museum|art_gallery", "UTF-8")
+"&key="
+ URLEncoder.encode("AIzaSyBOY3eUzIL_Pz8NB9pSdRJcABiCw_kQ0M8", "UTF-8");
new GetPlaces().execute(url);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
//mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
placeMarkers = new Marker[MAX_PLACES];
updatePlaces();
}
private class GetPlaces extends AsyncTask<String, Void, String>{
//fetch and parse place data
protected String doInBackground(String... placesURL){
//fetch places
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL){
//execute Search
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
protected void onPostExecute(String result){
//parse place data returned from Google Places
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try{
//parse JSON
JSONObject resultObject = new JSONObject(result);
JSONArray placesArray = resultObject.getJSONArray("results");
places = new MarkerOptions[placesArray.length()];
//loop through places
for(int p=0; p<placesArray.length();p++){
//parse each place
boolean missingValue = false;
LatLng placeLL = null;
String placeName = "";
String vicinity = "";
// int currIcon = othericon;
try{
//attempt to retrieve place data values
missingValue=false;
JSONObject placeObject = placesArray.getJSONObject(p);
JSONObject loc = placeObject.getJSONObject("geometry").getJSONObject("location");
placeLL = new LatLng(
Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng"))
);
JSONArray types = placeObject.getJSONArray("types");
for(int t=0; t<types.length();t++){
//what type is it
String thisType = types.get(t).toString();
if(thisType.contains("food")){
// currIcon = foodIcon;
System.out.println("HELLO JAMAL THIS IS FOOD");
break;
}
else if(thisType.contains("bar")){
// currIcon = drinkIcon;
System.out.println("HELLO JAMAL THIS IS BAR");
break;
}
else if(thisType.contains("store")){
System.out.println("HELLO JAMAL THIS IS store");
// currIcon = shopIcon;
break;
}
}
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
}
catch (JSONException jse){
missingValue=true;
jse.printStackTrace();
}
if(missingValue) {
places[p] = null;
Log.e("<Jamal>", "Places is missing!");
}
else{
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
// .icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
Log.e("<Jamal>", "Places is HERE BITCH!");
}
}
}
catch (Exception e){
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length;p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=mMap.addMarker(places[p]);
}
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="indabutt.com.indabuttalpha" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please message back with any potential solution!
Thank you

Thank you bjiang, but I made a mistake when setting up my API Key, in order to use Places API, you need a Browser Key to get an accepted JSON response. I was using my API Key which give me a denial response.
I capture some logs regarding the JSON Response by putting this line of code in:
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
Log.e("<Five>", lineIn);
}
Everything works great now :)

Related

This APK works when I runon Android Studio, but does not work when APK is build and installed on my Phone. What changes should be made?

This code does exactly what it's supposed to do when run on Sample device in Android Studio. But when I Build APK and install it in my phone it does not work.
MapsActivity.java
package com.example.coordinatetracker;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
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.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationListener locationListener;
private LocationManager locationManager;
private final long MIN_DIST = 1;
private final long MIN_TIME = 100;
private LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
}
/**
* 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;
//googleMap.getUiSettings().setZoomGesturesEnabled(false);
mMap.getUiSettings().setTiltGesturesEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(false);
// Add a marker in Sydney and move the camera
/*LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
locationListener = new LocationListener() {
Marker marker = null;
#Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
//Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
if (marker!=null) {
marker.remove();
marker=null;
}
String lat = String.format("%.4f",location.getLatitude());
String lng = String.format("%.4f",location.getLongitude());
String coordinates = lat + "," + lng;
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(coordinates));
mMap.setMinZoomPreference(15.0f);
mMap.setMaxZoomPreference(18.0f);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).tilt(60).zoom(18).bearing(0).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
catch(SecurityException e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME,MIN_DIST,locationListener);
}
catch(SecurityException e){
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coordinatetracker">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have attached the JAVA and XML files. Where and what changes should be made to make this program work?
PS: I read somewhere about Instant Run, but there is no such option in my Android Studio.

Geocoder IntentService is not being called

I understand this questions has been asked many times, for each question that has already been asked, the implementation is different from mine. The method I used create and call the intentService for a geocoder, was used from the android dev tutorial site.
https://developer.android.com/training/location/display-address.html.
I have gone over the the tutorial 3 times over to make sure I wasn't missing anything, but it is clear that I am.
Here is my manifest file, I have added the location and internet permissions.
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".selectRouteAndTransportMethod">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<service
android:name=".FetchAddressIntentService"
android:exported="false"/>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name="user.com.commuterapp.MapsActivity"
android:label="#string/title_activity_maps"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
Here is my main activity: All I am doing here is using a buttonClick to create the intent and to start the intent.
package user.com.commuterapp;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import user.com.commuterapp.R;
import static java.lang.Boolean.TRUE;
public class selectRouteAndTransportMethod extends AppCompatActivity {
Intent mIntent;
PendingIntent mPendingIntent;
myLocation mCurrentLocation;
private AddressResultReceiver mResultReceiver;
public static final String TAG = selectRouteAndTransportMethod.class.getSimpleName();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_route_and_transport_method);
mIntent = new Intent(this, selectRouteAndTransportMethod.class);
mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);
mCurrentLocation = new myLocation(this, this, mPendingIntent);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "On Start");
mCurrentLocation.connect();
boolean connecting = mCurrentLocation.mGoogleApiClient.isConnecting();
boolean registered = mCurrentLocation.mGoogleApiClient.isConnectionCallbacksRegistered(mCurrentLocation);
//ConnectionResult connectionResult = mCurrentLocation.mGoogleApiClient.getConnectionResult(LocationServices.API);
if (connecting == TRUE) {
Log.d(TAG, "Connecting");
}
if (registered == TRUE) {
Log.d(TAG, "registered");
}
}
#Override
protected void onResume() {
super.onResume();
mCurrentLocation.connect();
}
#Override
protected void onPause() {
super.onPause();
// mCurrentLocation.disconnect();
}
protected void buttonOriginClick(View view)
{
Log.d(TAG,"retrieving address");
retrieveAddress();
}
protected void retrieveAddress() {
Intent geoCoderIntent = new Intent(this, FetchAddressIntentService.class);
geoCoderIntent.putExtra(FetchAddressIntentService.Constants.RECIEVER, mResultReceiver);
geoCoderIntent.putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA, mCurrentLocation.mCurrentLocation);
startService(geoCoderIntent);
}
}
And lastly here is the intentService class. This was straight out of the android dev tutorial site, nothing original here.
package user.com.commuterapp;
import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.os.ResultReceiver;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static android.content.ContentValues.TAG;
/**
* Created by User on 1/21/2017.
*/
public class FetchAddressIntentService extends IntentService {
public final class Constants{
public static final int SUCCESS_RESULT = 0;
public static final int FAILURE_RESULT = 1;
public static final String PACKAGE_NAME =
"user.com.commuterapp";
public static final String RECIEVER = PACKAGE_NAME +
".RECIEVER";
public static final String RESULT_DATA_KEY = PACKAGE_NAME + ".RESULT_DATA_KEY";
public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
".LOCATION_DATA_EXTRA";
}
protected ResultReceiver mReceiver;
public FetchAddressIntentService()
{
super("FetchAddressIntentService");
}
private void deliverResultToReceiver(int resultCode, String message){
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
mReceiver.send(resultCode,bundle);
}
#Override
protected void onHandleIntent (Intent intent) {
Log.d(TAG, "GeoCoder Service Started");
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String errorMessage = "";
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
location.getLongitude(),
location.getLatitude(),
1);
}catch (IOException ioException) {
//catch network or other I/O Problems
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage);
} catch (IllegalArgumentException illegalArgumentException){
//catch invalid latitude or longitude values
errorMessage = getString(R.string.invalid_lat_long_used);
Log.e(TAG, errorMessage + "." + "Latitude =" + location.getLatitude()
+ ", Longitude = " + location.getLongitude(),
illegalArgumentException);
}
//handle cases where no addresses was foudn
if (addresses == null || addresses.size() == 0)
{
if(errorMessage.isEmpty()){
errorMessage = getString(R.string.no_address_found);
Log.e(TAG,errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
}else
{
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
//Fetch the address lines using getAddressLine
//join them and send them to the thread
for(int i = 0; i < address.getMaxAddressLineIndex(); i++){
addressFragments.add(address.getAddressLine(i));
}
Log.i(TAG, getString(R.string.address_found));
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.seperator"), addressFragments));
}
}
}
EDIT: I have tried rewriting the geocoder following the instructions from the android dev site again, but no success.
EDIT2: I noticed in the manifest I declared the service, within the application declaration, instead of outside, I made the change but to no avail, any insights will be appreciated

Android fetch data from mySql

I have to get some data from a MySQL database on server. I have the following code.but the app crashes when I run it. I also get the Permission denied (missing INTERNET permission?) in my Logcat even though I specified the internet permission in my Android Manifest.
Any idea what might be wrong here?
Java file
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://xxxxx/data.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String desc=obj.getString("description");
// String lat=obj.getString("lat");
Log.e("STRING", name);
r.add(name);
r.add(desc);
// r.add(lat);
list.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.diana.menu" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
data.php
<?php
$conn=mysql_connect('localhost', 'xxxx', 'xxxxx','u199776286_pois');
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, description FROM pois';
mysql_select_db('u199776286_pois');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "NAME : {$row['name']} <br> ".
"DESCRIPTION : {$row['description']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
my logcat
This happens because you're connecting to your MySQL server from the main UI thread. create a secondary thread (or async task) to connect and to get the results.
Use Async Task to get the data from your database..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Writing the above code is not at all a better way to get rid from NetworkOnMainThreadException . You have to use any background thread for doing network operation in android above api 11 such as Asynch Task , Intent Service etc.
How to fix android.os.NetworkOnMainThreadException?
You can also use Executors for network task's
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
//You can performed your task here.
}
});
Add Internet Permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Use Asynck Task like
List<String> r = new ArrayList<String>();
Need to declare out of connect();
with Oncreate
new LongOperation().execute("");
now create
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
connect();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
// need to remove Ui control from connect(); and that require value
bind it on onPostExecute
use Async. For more help check this

Getting GoogleApiClient to work with Activity Recognition

I am currently working with ActivityRecognitionClient , but unfortunately that Google has announced that the class had been deprecated and to use GoogleApiClient instead.
Not sure if I am doing it wrong or not, I am getting confused with the new API file. I have imported the Google Play Libraries, setup the API v2 key. I followed an online source on coding up the ActivityRecognitionClient version.
Below are the codes of the different files, whenever I switch tab to the actRecog it crashes and points the error to this line with a null pointer exception.
mActivityRecognitionPendingIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Full source code below : (API v2 keys are intentionally hidden for privacy purposes.)
MainActivity.java
package com.example.healthgps;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
TabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = getTabHost();
TabSpec firstSpec = mTabHost.newTabSpec("Stats");
firstSpec.setIndicator("Stats");
Intent firstIntent = new Intent(this, FirstActivity.class);
firstSpec.setContent(firstIntent);
TabSpec thirdSpec = mTabHost.newTabSpec("ActRecog");
thirdSpec.setIndicator("ActRecog");
Intent thirdIntent = new Intent(this, activityrecignition.class);
thirdSpec.setContent(thirdIntent);
mTabHost.addTab(firstSpec);
mTabHost.addTab(thirdSpec);
}
}
Manifest XML File :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.healthgps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<permission
android:name="com.example.healthgps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="com.example.healthgps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" />
<activity
android:name="com.example.healthgps.MainActivity"
android:label="Health Kit"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FirstActivity"
android:label="Health Kit" >
</activity>
<activity
android:name=".activityrecignition"
android:label="Health Kit" >
</activity>
<service
android:name="com.example.healthgps.ActivityRecognitionIntentService"
android:label="#string/app_name"
android:exported="false">
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
activityrecignition.java (purposely typo for the name)
package com.example.healthgps;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.ActivityRecognitionResult;
import com.google.android.gms.location.DetectedActivity;
public class activityrecignition extends FragmentActivity implements ConnectionCallbacks,OnConnectionFailedListener {
public static final int MILLISECONDS_PER_SECOND = 1000;
public static final int DETECTION_INTERVAL_SECONDS = 20;
public static final int DETECTION_INTERVAL_MILLISECONDS =
MILLISECONDS_PER_SECOND * DETECTION_INTERVAL_SECONDS;
private final static int
CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private PendingIntent mActivityRecognitionPendingIntent;
// Store the current activity recognition client
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private Intent intent;
TextView tv;
ActivityRecognitionIntentService ar;
private boolean mInProgress;
public enum REQUEST_TYPE {START, STOP}
private REQUEST_TYPE mRequestType;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
mActivityRecognitionPendingIntent = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
tv=(TextView) findViewById(R.id.activityname);
mInProgress=false;
ar.onHandleIntent(i);
}
#SuppressLint("NewApi") public static class ErrorDialogFragment extends DialogFragment {
private Dialog mDialog;
#SuppressLint("NewApi") public ErrorDialogFragment() {
super();
mDialog = null;
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
public void show(FragmentManager supportFragmentManager, String tag) {
}
}
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch (resultCode) {
case Activity.RESULT_OK :
break;
}
}
}
private boolean servicesConnected() {
int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("Activity Recognition", "Google Play services is available.");
return true;
} else {
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(
getSupportFragmentManager(),
"Activity Recognition");
}
return false;
}
}
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
private String getNameFromType(int activityType) {
switch(activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
#Override
protected void onHandleIntent(Intent intent) {
// If the incoming intent contains an update
if (ActivityRecognitionResult.hasResult(intent)) {
// Get the update
ActivityRecognitionResult result =
ActivityRecognitionResult.extractResult(intent);
// Get the most probable activity
DetectedActivity mostProbableActivity =
result.getMostProbableActivity();
/*
* Get the probability that this activity is the
* the user's actual activity
*/
int confidence = mostProbableActivity.getConfidence();
/*
* Get an integer describing the type of activity
*/
int activityType = mostProbableActivity.getType();
String activityName = getNameFromType(activityType);
tv.setText(activityName);
/*
* At this point, you have retrieved all the information
* for the current update. You can display this
* information to the user in a notification, or
* send it to an Activity or Service in a broadcast
* Intent.
*/
} else {
/*
* This implementation ignores intents that don't contain
* an activity update. If you wish, you can report them as
* errors.
*/
tv.setText("There are no updates!!!");
}
}
}
public void onClick(View v){
if(v.getId()==R.id.Start){
startUpdates();
}
if(v.getId()==R.id.Stop){
stopUpdates();
}
}
public void startUpdates() {
// Check for Google Play services
mRequestType = REQUEST_TYPE.START;
if (!servicesConnected()) {
return;
}
// If a request is not already underway
if (!mInProgress) {
// Indicate that a request is in progress
mInProgress = true;
// Request a connection to Location Services
mGoogleApiClient.connect();
//
} else {
/*
* A request is already underway. You can handle
* this situation by disconnecting the client,
* re-setting the flag, and then re-trying the
* request.
*/
mInProgress = true;
mGoogleApiClient.disconnect();
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, DETECTION_INTERVAL_MILLISECONDS, mActivityRecognitionPendingIntent);
}
}
#Override
public void onConnected(Bundle dataBundle) {
// TODO Auto-generated method stub
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, DETECTION_INTERVAL_MILLISECONDS, mActivityRecognitionPendingIntent);
/*
* Since the preceding call is synchronous, turn off the
* in progress flag and disconnect the client
*/
mInProgress = false;
mGoogleApiClient.disconnect();
switch (mRequestType) {
case START :
/*
* Request activity recognition updates using the
* preset detection interval and PendingIntent.
* This call is synchronous.
*/
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, DETECTION_INTERVAL_MILLISECONDS, mActivityRecognitionPendingIntent);
break;
case STOP :
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(mGoogleApiClient, mActivityRecognitionPendingIntent);
/*
* An enum was added to the definition of REQUEST_TYPE,
* but it doesn't match a known case. Throw an exception.
*/
default :
try {
throw new Exception("Unknown request type in onConnected().");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
mInProgress = false;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Turn off the request flag
mInProgress = false;
/*
* If the error has a resolution, start a Google Play services
* activity to resolve it.
*/
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (SendIntentException e) {
// Log the error
e.printStackTrace();
}
// If no resolution is available, display an error dialog
} else {
// Get the error code
int errorCode = connectionResult.getErrorCode();
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
errorCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment =
new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(
getSupportFragmentManager(),
"Activity Recognition");
}
}
}
public void stopUpdates() {
// Set the request type to STOP
mRequestType = REQUEST_TYPE.STOP;
/*
* Test for Google Play services after setting the request type.
* If Google Play services isn't present, the request can be
* restarted.
*/
if (!servicesConnected()) {
return;
}
// If a request is not already underway
if (!mInProgress) {
// Indicate that a request is in progress
mInProgress = true;
// Request a connection to Location Services
mGoogleApiClient.connect();
//
} else {
/*
* A request is already underway. You can handle
* this situation by disconnecting the client,
* re-setting the flag, and then re-trying the
* request.
*/
}
}
}
In the old code, it contains a part where the ActivityRecognitionClient requires an instantiation, but GoogleApiClient doesn't have.
Is there anyone who manage to switch over to the new API already ? I need some guide to get it there.
Thanks.
you must use GoogleApiClient.Builder in the following way
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(<context>)
.addApi(<some api, i.e LocationServices.API>)
.addConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnectionSuspended(int arg) {}
#Override
public void onConnected(Bundle arg0) {
Intent intent = new Intent(getApplicationContext(), ActivityRecognitionService.class); // your custom ARS class
mPendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi
.requestActivityUpdates(mGoogleApiClient, ACTIVITY_RECOGNITION_INTERVAL, mPendingIntent);}
}
.addOnConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
});
mGoogleApiClient = builder.build();
mGoogleApiClient.connect();

getLastKnownLocation() always returning null, all providers are DummyLocationProvider

I have seen many posts regarding this problem, but none of them offered a solution for me.
I am trying to get the user position through the GPS (or, ultimately, any other valid provider). But I am always getting null locations. I do get a map, and can set an arbitrary location, is the providers that don't work.
I have my MAPS key properly set (also checked that it was the right one), all necessary permissions set (android.permission.INTERNET, android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_FINE_LOCATION) and in fact, all seemed to be working just fine yesterday!
I tried getting all possible providers with this code:
List<String> providers = locManager.getAllProviders();
for (String provider : providers) {
printProvider(provider);
}
Which shows all providers (4, in my case) are DummyLocationProviders.
I am trying to run my app on the phone, not the emulator (although I also tried with the emulator, with GPS enabled, to no avail).
This is the code I am using to fetch the location (which, again, worked just fine yesterday):
//Get criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get best provider
String bestProvider = locManager.getBestProvider(criteria, false);
printProvider(bestProvider);
//get the current location (last known location) from the location manager
Location location = locManager.getLastKnownLocation(bestProvider);
//if location found display as a toast the current latitude and longitude
if (location != null) {
Toast.makeText(this, "Current location:\nLatitude: " + location.getLatitude() + "\n" + "Longitude: " + location.getLongitude(), Toast.LENGTH_LONG).show();
point = new GeoPoint((int) (location.getLatitude()*1E6),(int)(location.getLongitude() *1E6));
controller.animateTo(point);
} else {
Toast.makeText(this, "Cannot fetch current location!", Toast.LENGTH_LONG).show();
}
My manifest file:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activities.MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".activities.GoogleMapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".activities.MyMapsActivity"
android:label="#string/title_activity_maps" >
</activity>
</application>
</manifest>
Try this code :
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.Canvas;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class MyMapsActivity extends MapActivity
{
MapView mapView;
MapController mapController;
LocationManager locationManager;
LocationListener locationListener;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(5);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Touchy t = new Touchy();
List<Overlay> overlayList = mapView.getOverlays();
overlayList.add(t);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay
{
public boolean onTap(GeoPoint point, MapView mapView)
{
Context contexto = mapView.getContext();
String msg = "Latitude : " + point.getLatitudeE6()/1E6 + " - " + "Longitude : " + point.getLongitudeE6()/1E6;
Toast toast = Toast.makeText(contexto, msg, Toast.LENGTH_SHORT);
toast.show();
return true;
}
}
private class GPSLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
if (location != null)
{
GeoPoint point = new GeoPoint((int) (location.getLatitude() * 1E6),(int) (location.getLongitude() * 1E6));
Toast.makeText(getBaseContext(),"Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();
mapController.animateTo(point);
mapController.setZoom(5);
mapView.invalidate();
}
if (location != null)
{
GeoPoint point=null;
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0;
index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
}
Layout Coding :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="Your MAP API Key"/>
<LinearLayout android:id="#+id/zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Link for getting own API key process :
http://sanathnandasiri.blogspot.in/2011/04/obtaining-google-maps-api-key-for.html
//get the current location (last known location) from the location manager
Location location = locManager.getLastKnownLocation(bestProvider);
use this instead of above line
location = locManager.getLastKnownLocation(bestProvider);
locManager.requestLocationUpdates(bestProvider,0, 0, locationListener);
location = locManager.getLastKnownLocation(bestProvider);
locManager.requestLocationUpdates(bestProvider,0, 0, locationListener);
First time location is null , so set your current location is last location .

Categories

Resources