Android Location Services not working - android

Here goes: I've spent all night scouring the internet, especially StackOverflow, trying to figure out why I can't get basic Location Services working in Android. I have tried in a variety of emulated environments, from Android 1.6 up to Android 4, all with GPS services emulated, as well as on an actual Android 2.2.2 Device. Location is always returned as null, I've tried at least seven different downloadable sample projects, using them verbatim, and getting the same results.
Obviously, I'm missing something key. If anyone could point out what I'm doing wrong, it would be greatly appreciated.
com.mytestproject.android:
package com.mytestproject.android;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.mytestproject.android.R;
public class MyTestProject extends Activity {
private TextView mytext;
private LocationManager locmgr = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mytext = (TextView) findViewById(R.b.mytext);
//grab the location manager service
locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mytext.setText("waiting for location");
}
//Start a location listener
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location loc) {
//sets and displays the lat/long when a location is provided
String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();
mytext.setText(latlong);
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// required for interface, not used
}
};
//pauses listener while app is inactive
#Override
public void onPause() {
super.onPause();
locmgr.removeUpdates(onLocationChange);
}
//reactivates listener when app is resumed
#Override
public void onResume() {
super.onResume();
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,10000.0f,onLocationChange);
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/mytext"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.johnandbrian.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MyTestProject"
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>

add this to onCreate() function,
locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,10000.0f,onLocationChange);

If onLocationChanged() isn't even being called, even with sample projects, then I don't think "location is always null" is an accurate description of the problem. onLocationChanged() is only called when the location changes. So it sounds like you are (a) not injecting mock locations or otherwise driving the location engine when using the emulator, and (b) not moving around enough on the real device. I suggest loading a sample project onto the real device, going outside, and moving around some (several 10s of meters). Put some breadcrumbs in the onLocationChanged() method (in the sample project) to verify that it's being called.

Related

onLocationChanged method doesn't call

I search a lot and also see a lot of post inside stackoverflow but no answered or it was not clear and complicated. it's simple i want to onLocationChanged() method called when i send Longitude and Latitude from emulator control so i wrote this code inside main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.mrg.findlocation.Main$PlaceholderFragment" >
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
And put this code inside Main.java file:
package com.mrg.findlocation;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView text = (TextView)findViewById(R.id.textview);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListner = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
double latti = location.getLatitude();
double longi = location.getLongitude();
Log.d("MRG","It worked");
text.setText("latti :"+latti+"\n"+"longi :"+longi);
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
}
}
And inside manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mrg.findlocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mrg.findlocation.Main"
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>
Then i send two value from emulator control nothing happened:
Are there anyone to solve this problem one time for ever? the code i pasted here it's very simple to reproduce and it doesn't contain google map or anotherthing
Edit:
This code is suitable for real device
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
This code works on emulator
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListner);
I think the problem is that you're requesting updates from the Network Provider and the emulator uses GPS provider.
Try changing:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListner);
with:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListner);
Try to implements LocationListener on your activity class
public class Main extends Activity implements LocationListener {
#Override
public void onLocationChange(Location location){
// do something
}
}

current location is not loading at Startup

when i run the application it load the map but not my current location.when i clicked on gps after then it zoom in to my current location. i also want to update the location as the user moves from one location to another. this location update code is not working properly. And when i change the orientation of device it reload the map again.Same things happens again.
Xml file
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
class file
package com.design.googlemap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
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;
public class MainActivity extends FragmentActivity{
private GoogleMap googlemap;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetMapIfNeeded();
}
private void SetMapIfNeeded() {
// TODO Auto-generated method stub
if(googlemap==null){
//try to obtain google map form SupportMapFragment;
googlemap=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
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) 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_NORMAL);
//Get Latitude object of current location
double latitude=myLocation.getLatitude();
//Get Latitude object of current location
double longitude=myLocation.getLatitude();
//Create a LatLng object for current location
LatLng latLng = new LatLng(latitude,longitude);
//show the current location of Google Map
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
LocationListener listner = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManager =(LocationManager) getSystemService(LOCATION_SERVICE);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) listner);
}
#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;
}
}
ManifestFile
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.design.googlemap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<permission
android:name="com.design.googlemap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<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 following two 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" />
<uses-permission android:name="com.design.googlemap.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.design.googlemap.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>
<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="XXXXXXXXXXXXXXXXXXXXXXXXXXXX" />
</application>
</manifest>
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria,false);
Even if Gps if Off. Your approx location will be pointed.
And for locationUpdates on your GoogleMaps go through this link
Also for zooming to a particular position add this code:
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(YOUR_LATLNG).zoom(ZOOM_LEVEL).build(); // int ZOOM_LEVEL=12
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
go through this link for more on zooming.
To hide the WebView call the Visibility functions in your Activity[OnClick of your Button]
WebView wv=(WebView)findViewById(R.id.YOUR_WEB_VIEW);
wv.setVisibility(View.GONE);// when you want to hide[shrink]
wv.setVisibility(View.VISIBLE);// when you want to Show[Zoom]
1. If you only want to show your own location, than a MyLocationOverlay is probably easiest.
Quick information here (rest of that article might be helpful too):
http://www.vogella.com/articles/AndroidLocationAPI/article.html#maps_mylocation
Use MyLocationOverlay, as that is what it is there for. Here is a sample application that uses MyLocationOverlay and a custom overlay; you can always get rid of the custom one if you do not need it.
2. To avoid the common behavior of reloading, you have to handle configuration change for your app .
Add this line to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
android:configChanges="keyboardHidden|orientation|screenSize"

Android: Crash start application using api google maps

I'm following this https://developers.google.com/maps/documentation/android/start#installing_the_google_maps_android_v2_api to learn to use Google Map API.
This is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dude.uniplaces"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.dude.uniplaces.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.dude.uniplaces.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<permission
android:name="com.dude.uniplaces.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.dude.uniplaces.permission.MAPS_RECEIVE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.dude.uniplaces" />
</intent-filter>
</receiver>
<service android:name="com.dude.uniplaces.GCMIntentService" />
<activity
android:name="com.dude.uniplaces.Index"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.dude.uniplaces.Dude"
android:label="dude" >
</activity>
<activity
android:name="com.dude.uniplaces.SendMess"
android:label="sendmess" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBUO0v3_pHsRXfnGyJ68AeZkCUtHINw6OA"/>
</application>
</manifest>
This is my xml file of main activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Index" >
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Invia Messaggio"
android:onClick="sendMex" />
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</RelativeLayout>
This is my main activity :
package com.dude.uniplaces;
import static com.dude.uniplaces.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.dude.uniplaces.CommonUtilities.EXTRA_MESSAGE;
import static com.dude.uniplaces.CommonUtilities.SENDER_ID;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
public class Index extends Activity {
ProgressDialog progressBar;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.index);
// Phone is ready
GCMRegistrar.checkDevice(this);
// Checking Manifest
GCMRegistrar.checkManifest(this);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
// Ottieni il Registration ID
final String regId = GCMRegistrar.getRegistrationId(this);
// Controllo se sono registrato
if (regId.equals("")) {
// Mi registro
GCMRegistrar.register(this, SENDER_ID);
} else {
// Sono registrato
if (!GCMRegistrar.isRegisteredOnServer(this)) {
// Provo a registrarmi ancora
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
/* Here I should be registred */
/* Now is time to take gps coordinates */
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Map<String, String> params = new HashMap<String, String>();
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
String message="x";
String Id = GCMRegistrar.getRegistrationId(this);
if( location != null)
message = String.format("%1$s \n%2$s \n%3$s",Id,
location.getLongitude(), location.getLatitude()
);
if(location == null )
params.put("one", "BONAA");
else
params.put("one", message);
ServerUtilities su = new ServerUtilities();
su.go("http://unipiapp.altervista.org/cord.php",params);
}
/**
* Ricevo notifica push
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Sveglia il telefono se รจ in stand-by
WakeLocker.acquire(getApplicationContext());
// Visualizza il messaggio
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Rilascia il wavelocker
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
}
super.onDestroy();
}
/* Function call clickin on button */
public void sendMex(View w)
{
Intent intent = new Intent(Index.this, SendMess.class);
startActivity(intent);
}
} /* END CLASS */
I Downloaded google play service and add it to my workspace, but When I try to start application in my phone, it crashes:
05-04 20:11:24.441: E/AndroidRuntime(11190): FATAL EXCEPTION: main
05-04 20:11:24.441: E/AndroidRuntime(11190):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.dude.uniplaces/com.dude.uniplaces.Index}:
android.view.InflateException: Binary XML file line #19: Error
inflating class fragment
EDIT:
I modified my index.xml as you saw me, then I added (think) in right way google libs, but i still take crash!
Solution:
I solved adding import android.support.v4.app.FragmentActivity;
and chancing extends Activity with FragmentActivity
Right click on the project and select Android Tools -> Add Support Library ...
and change this
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
to this
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and just to confirm that you have included the google play services correctly right click on project and select Properties. In left tab select Android. In the botton of the right pane you shoud see a frame with label library. If google play is added correctly it will appear as green check mark. Also make sure that the google play project is open in the workspace.
It look like you have some kind of problem with the way you are referencing the google-play-services library. take a look at the first three step of this blog post I wrote on Google Maps API V2 to get an idea of how to do it correctly:
Google Maps API V2
Your min sdk in 8
Note : If you wish to run the app on api 11 and lower You will need to add support library as well.
http://developer.android.com/tools/extras/support-library.html
Use this
android:name="com.google.android.gms.maps.SupportMapFragment"
Also make sure you have followed all the steps from the below link
https://developers.google.com/maps/documentation/android/start
Edit
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
MapFragment for api 12 and higher support fragment for api 11 and lower
Also make sure you map project references google play services library project.
Refer your google play services in your map project
To check if its a library project. right click on your project goto properties. choose android. check if Is Library is ticked.
To refer the library project in your map project.
right click on your project goto properties. choose android. Click add, browse the library project click add and ok. Notice the green tick below.
For more information check the below link
https://developer.android.com/tools/projects/projects-eclipse.html.
You also need to add Support library since you are using SupportFragment. Check the below link
https://developer.android.com/tools/extras/support-library.html

GPS coordinates not being retrieved

HI i have been trying to run this code from an example in a book but all i get is is the null value being passed to the variable and so i only get the message as "Your Current Position is : no location found"
The manifest file is as below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.snooze.android.geopositioning"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_INTERNET" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<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>
The main.xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/myLocationText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
Lastly is the MainActivity.java
package com.snooze.android.geopositioning;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
public void updateWithNewLocation(Location location)
{
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + String.valueOf(lat) + "\nLong:" + String.valueOf(lng);
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" + latLongString);
}
}
This is my first project so i am unfamiliar with a few of the workings but i copied everything as the book said but it does not work. Have tried various things on many sites, as well as answers from this forum....but to no avail.
I am using Eclipse and have added tried to run it on and AVD with Android 2.2 as well as for Google APIs.
What i think is that the co-ordinates are not being passed to the variables.
I had posted as a new user but was not able to comment on it so i have asked it again.
Lukas Kunth, chaitanya and wareninja thanks for your answers.
Apologies for the duplication.
Please help
You are missing the LocationListener without which your application cannot receive location updates.
Here is an excellent blog on GPS Location fetching..
http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/

Android google maps showing greed lines

I have one google maps application it does not show the maps it only shows the lines
It does not show the mapview,and i also have the internet Connection
And it also genrate the following error
09-30 12:01:12.934: WARN/Resources(587): Converting to string:
TypedValue{t=0x12/d=0x0 a=2 r=0x7f050002}
09-30 12:01:13.094: WARN/GpsLocationProvider(59): Duplicate add listener for uid
10042
09-30 12:01:13.334: INFO/MapActivity(587): Handling network change
notification:CONNECTED
09-30 12:01:13.334: ERROR/MapActivity(587): Couldn't get connection factory client
Showmap.java
package de.vogella.android.locationapi.maps;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.RelativeLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class ShowMap extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// create a map view
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 13,
14, new GeoUpdateHandler());
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
This is My mainfest
?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".ShowMap"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>
And main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainlayout"
android:orientation="vertical"
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="0cHF-o_cvW1DEz3ocWAyybGqUsg8aUlwKMoyr4A"
/>
Do you have the required permissions in place in the AndroidManifest.xml? In an Android app that I've made for GPS + Maps I have the following:
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
This is a problem with an API-Key.
Here you can do it.
You need to generate different one for each emulator, device etc. and for final release, and you need to merge them with an keystore you're using, what sux, but there is no different way :/.
Good luck!

Categories

Resources