Issue with trying to access Android Location Data - android

So I am trying to a simple Lat Long for my phone.
I am testing using my own phone which is on FirmWare Level 2.3.6.
This is the main code:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class MainActivity extends FragmentActivity {
private LocationManager locationManager = null;
private LocationListener locationListener = null;
// private LocationListener onLocationChange=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
System.out.println("I got here");
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
/*
* System.out.println("This happened"); String message =
* "Longitude:" + loc.getLongitude() + " Latitude: " +
* loc.getLongitude(); Toast.makeText( getBaseContext(),
* "Location changed: Lat: " + loc.getLatitude() + " Lng: " +
* loc.getLongitude(), Toast.LENGTH_SHORT).show();
*/
System.out.println("IN ON LO
CATION CHANGE, lat="
+ loc.getLatitude() + ", lon=" + loc.getLongitude());
}
#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
}
}
}
This is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cloud.pushpin"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.cloud.pushpin.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.maps.v2.API_KEY"
android:value="AIzaSyArmkmqy3i-wNsVH0f8RH15OsaR4lv4Sp8" />
</application>
<permission
android:name="com.cloud.pushpin.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.cloud.pushpin.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
</manifest>
So basically what I Am seeing is that nothing happens when I start up the app. When I shake the phone, I get the message "I got here" a bunch of times, but never the latitude and longitude displaying. I don't understand why the callback is not occurring. The other permissions are for later when I implement the google maps api. GPS is enabled on the phone as well as mobile data.

Related

longitude and latitude acquiring (Android) + reverse geocoding

So i put together a few snippets that i found here and there; aiming to make a more complex app, however, at one point i was able to obtain the the longitude and latitude number, but once I've tried supply those number to the reverse GeoCoding mechanism, i have not been able to get the Long and Lat numbers and the app crashes after i click the button (which does the reverse geocoding)
package com.example.com.example;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
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.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button myLocation;
TextView myAddress;
TextView textLat;
TextView textLong;
double latHolder = 0.0;
double longHolder = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocation= (Button) findViewById(R.id.location);
myAddress = (TextView)findViewById(R.id.address);
textLat = (TextView)findViewById(R.id.textLat); ///COORDINATION VARIABLES1
textLong = (TextView)findViewById(R.id.textLong);///2
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //gets it from the Operating system
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); //LOCATION UPDATED LINKED
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
textLat.setText("GPS ONLINE (PLEASE WAIT)");
textLong.setText("GPS ONLINE (PLEASE WAIT)");
}
else
{
textLat.setText("GPS OFFLINE");
textLong.setText("GPS OFFLINE");
}
myLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getMyLocationAddress();
}
});
}
///////////COORDIATION ACQUIRING DOWN HERE
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
latHolder = pLat;
longHolder = pLong;
}
}
#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
}
}
public void getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latHolder,longHolder, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText("I am at: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
Here is my Manafist with all permissions which should be enough
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<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=".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>
and last but not lease my xml layout
<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=".MainActivity" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LATITUDE" />
<Button
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/address"
android:layout_below="#+id/address"
android:layout_marginTop="79dp"
android:text="get_location" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="135dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="44dp"
android:text="LONGITUD" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title" />
</RelativeLayout>
DO PLEASE NOTE! i have added two global variables called LongHolder and LatHolder to pass the values of the GPS straight to the reverse geocoding. I believe they failed their purpose but if you need to test random selected Coordinates yourself, remember to remove them. THANK YOU

my application stops working as soon as launched

(ANDROID GPS)
i made this application to send gps coordinates via sms but the app crashes(as soon as i open it) can somebody help me
logcat images
logcal image1
log cat image 2
MainActivity.java
package com.adzz.gps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager manager= (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =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) {
}
#Override
public void onLocationChanged(Location location) {
final String phoneNumber="9453603045";
double lat1=location.getLatitude();
Double d1= new Double(lat1);
double longi1=location.getLongitude();
Double d2=new Double(longi1);
m="latitude = "+ d1.toString() + "and latitude = "+ d2.toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, m, null, null);
TextView lat= (TextView) findViewById(R.id.lat);
TextView longi=(TextView) findViewById(R.id.longi);
lat.setText("latitude = "+lat1);
longi.setText("longitude ="+longi1);
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 25,
listener);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast=Toast.makeText(Main.this, m, 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
#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;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="#+id/button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adzz.gps001"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.adzz.gps001.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>
In your manifest file you must include
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
Read the documentation under "Requesting User Permissions" for more details.
http://developer.android.com/guide/topics/location/strategies.html
Your app is failing because you need to add the android.permisssion.ACCESS_FINE_LOCATION permission to your manifest file.

google map blank screen, programmatic added

I have put the google map service on by console, and generate a debug key.
I've debug it, the mMap and mLocation both are not null. I can get latitude and longitude successfully.
But the map is still blank.
Please help.
sam
here is the layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f2f5fa"
tools:context=".LocFm" >
<!-- top bar component -->
<ImageView
android:id="#+id/loc_topbar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="#drawable/topbar" />
<TextView
android:id="#+id/loc_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/loc_backBtn"
android:layout_centerHorizontal="true"
android:text="#string/loc_title"
android:textColor="#171717"
android:textSize="#dimen/title_font" />
<ImageView
android:id="#+id/loc_backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/backbtn" />
<!-- BODY -->
<FrameLayout android:id="#+id/map_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/loc_topbar"
android:layout_above="#+id/loc_bottombar"
>
<!-- Put fragments dynamically -->
</FrameLayout>
<!-- bottom bar component -->
<ImageView
android:id="#+id/loc_bottombar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#drawable/bottombar" />
<Button
android:id="#+id/locBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentLeft="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Loc"
android:textSize="#dimen/button_font"/>
<Button
android:id="#+id/loc_nextBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Continue"
android:textSize="#dimen/button_font"/>
<ImageView
android:id="#+id/nextImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/loc_nextBtn"
android:layout_alignTop="#+id/loc_nextBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/next" />
<ImageView
android:id="#+id/locImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/locBtn"
android:layout_alignTop="#+id/locBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/location" />
</RelativeLayout>
Here is the manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.map.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/logo_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my api key" />
<activity
android:name="com.example.map.LocFm"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Java code:
package com.example.map;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
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.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocFm extends FragmentActivity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
Timer positionTimer;
private GoogleMap mMap;
private Location mLocation;
private UiSettings mUiSettings;
private LocationClient mLocationClient;
private static SupportMapFragment mMapView;
private static final String MAP_FRAGMENT_TAG = "map";
public FragmentManager fManager;
double latitude, longitude, radius;
String sLat,sLong,sRange;
boolean bMaploaded=false;
int index =0;
int positionCount=0;
final int POSITION_COUNT_MAX=5;
final int POSITION_MIN=100;
final int PSSITION_MAX_TIMES=10;
OnlineHistoryInfo onLineHistory;
ProgressDialog dialog;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLocFm();
}
#Override
public void onLocationChanged(Location location) {
if (mLocationClient != null && mLocationClient.isConnected())
{
mLocation=mLocationClient.getLastLocation();
}
if (mLocation!=null)
{
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
radius=mLocation.getAccuracy();
sLat=Double.toString(latitude);
sLong=Double.toString(longitude);
sRange=Double.toString(radius);
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.addMarker(new MarkerOptions().position(latLng).title(getString(R.string.map_msg)));
}
positionCount++;
if(mLocationClient==null || radius<=POSITION_MIN)
{
mLocationClient.disconnect();
positionCount=0;
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setOnClickListener(this);
loc_nextBtn.setVisibility(View.VISIBLE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.VISIBLE);
showDialog(false,null);
}
if(positionCount>=POSITION_COUNT_MAX)
{
mLocationClient.disconnect();
positionCount=0;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
setUpMapIfNeeded();
position();
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private void mapDestroy()
{
if (mLocationClient != null)
mLocationClient.disconnect();
if(mMapView!=null){
FragmentTransaction ft = mMapView.getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(mMapView);
ft.commit();
}
if(mMap!=null)
{
mMap=null;
}
bMaploaded=false;
}
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 MapFragment.
mMap = mMapView.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
this,
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loc_backBtn:
mapDestroy();
LocFm.this.finish();
break;
case R.id.loc_nextBtn:
positionCount=0;
mapDestroy();
break;
case R.id.locBtn:
relocate();
break;
}
}
public void setLocFm(){
setContentView(R.layout.loc_fm);
loadMapFragment();
ImageView loc_backBtn=(ImageView)findViewById(R.id.loc_backBtn);
loc_backBtn.setOnClickListener(this);
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setVisibility(View.GONE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.GONE);
Button locBtn=(Button)findViewById(R.id.locBtn);
locBtn.setOnClickListener(this);
bMaploaded=true;
}
private void loadMapFragment() {
showDialog(true,getString(R.string.alert_postion));
// It isn't possible to set a fragment's id programmatically so we set a tag instead and
// search for it using that.
mMapView = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapView == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapView = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map_fragment, mMapView, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected()) mLocationClient.connect();
}
private void position()
{
showDialog(true,getString(R.string.alert_postion));
if (mMap != null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
mLocation = locationManager.getLastKnownLocation(provider);
mUiSettings = mMap.getUiSettings();
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
// Check if we were successful in obtaining the map.
mLocationClient.requestLocationUpdates(REQUEST,this); // LocationListener
}
}
public void relocate()
{
if (!mLocationClient.isConnected()) mLocationClient.connect();
WSWLog.i("relocate()");
}
/**
* #param dialgShow
*/
public void showDialog(boolean dialgShow,final String message)
{
WSWLog.i(" showDialog ("+dialgShow+","+message+")");
if(dialgShow)
{
if(dialog==null)
{
dialog = new ProgressDialog(this);
dialog.setCancelable(false);//false
{
dialog.setMessage(message);
}
}
else
{
dialog.setMessage(message);
}
dialog.show();
//
if(null != positionTimer)
{
positionTimer.cancel();
}
positionTimer= new Timer(true);
TimerTask task = new TimerTask(){
public void run() {
handler.sendEmptyMessage(1);
}
};
positionTimer.schedule(task,PSSITION_MAX_TIMES*1000, PSSITION_MAX_TIMES*1000);
}
else
{
if(null != positionTimer)
{
positionTimer.cancel();
}
if(dialog!=null)
{
dialog.dismiss();
}
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(null != positionTimer)
{
positionTimer.cancel();
}
showDialog(false,null);
//
alertNoPosition();
super.handleMessage(msg);
}
};
/**
*/
private void alertNoPosition()
{
AlertDialog.Builder builder = new Builder(this);
builder.setMessage(getString(R.string.loc_alert_realloc)); builder.setTitle(getString(R.string.button_Loc));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LocFm.this.finish();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
relocate();
}
});
builder.create().show();
}
}
First check your debug key whether you are using right one? second use following permission. Remove repeated permission from manifest.xml.
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:required="false" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
android:required="false" />
Use supportmap fragment instead of simple fragment
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView)).getMap();
follow this simple tutorial you may find it usefull http://mobisys.in/blog/2012/12/google-rolls-out-android-maps-api-v2/
your code is not clear...
try this when you are showing lat-long on your map. i could not find this in your code
mCurrentLattitude = mGPSListener.GetLatitudeRaw();
mCurrentLongitude = mGPSListener.GetLongitudeRaw();
LatLng coordinates = new LatLng(mCurrentLattitude, mCurrentLongitude);
Log.d("MAP"," setCurrentLocation lat-lang values: "+mCurrentLattitude +" : "+mCurrentLongitude);
CameraUpdate center= CameraUpdateFactory.newLatLng(coordinates);
String lPreviousZoomLevelString = Config.getSetting(getApplicationContext(), "MAPZOOMLEVEL");
mPreviousZoomLevel = Float.parseFloat(lPreviousZoomLevelString);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(mPreviousZoomLevel);
mMap.animateCamera(zoom);
CameraPosition i = mMap.getCameraPosition();
Log.d("MAP"," after setting zoom 2 :"+i.zoom);
mMap.moveCamera(center);
I still don't know what's happened. However, here is the step I took:
I took the advice by Gaurav Sharma, make the permission required="false"
This caused the onConnected() can't be triggered.
Then I changed the permission required="true". The map magically displayed! what a amazing google map!
Anyway, the map is shown. Don't know what's wrong. Thanks #GauravSharma

How to Latitude and Longitude in android

I have developed simple application to display the latitude and longitude in android... but it is showing the null pointer exception... please let me know what is the error..
My Activity class
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.widget.Toast;
public class SignalStrengthActivity extends Activity implements LocationListener{
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
super.onResume();
}
#Override
protected void onPause() {
locationManager.removeUpdates(this);
super.onPause();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Toast.makeText(this, "Latitude and Longitude " + location.getLatitude() + " " +
location.getLongitude(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Latitude and Longitude Offline ", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
My Manifest file :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.latitudelongitude"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.latitudelongitude.SignalStrengthActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
when i execute the application it does not display anything.. indicating that the location object is null... please let me know how to fix the problem
Go through the link below:
Link 1

Showing Grid view instead of Map

I'm very new to android. I'm developing an app which shows the current location using Google Map.
I've generated key for this application. But It doesn't show the map instead, it shows Grid View.
The following is the code..!
//MActivity
package velu.ndot.hosp;
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 android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class HospitalActivity extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private TextView myLongitude, myLatitude;
private MapView myMapView;
private SeekBar myZoomBar;
private MapController myMapController;
private void CenterLocation(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);
myLongitude.setText("Longitude: "+
String.valueOf((float)centerGeoPoint.getLongitudeE6()/1000000)
);
myLatitude.setText("Latitude: "+
String.valueOf((float)centerGeoPoint.getLatitudeE6()/1000000)
);
};
private void SetZoomLevel()
{
int myZoomLevel = myZoomBar.getProgress()+1;
myMapController.setZoom(myZoomLevel);
Toast.makeText(this,
"Zoom Level : " + String.valueOf(myZoomLevel),
Toast.LENGTH_LONG).show();
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtab);
myMapView = (MapView)findViewById(R.id.mapview);
myLongitude = (TextView)findViewById(R.id.longitude);
myLatitude = (TextView)findViewById(R.id.latitude);
myZoomBar = (SeekBar)findViewById(R.id.zoombar);
myMapView.setSatellite(true); //Set satellite view
myMapController = myMapView.getController();
SetZoomLevel();
myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);
//Get the current location in start-up
//check LastKnownLocation, if not valid, skip it.
Location initLocation=
myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(initLocation != null)
{
GeoPoint initGeoPoint = new GeoPoint(
(int)(initLocation.getLatitude()*1000000),
(int)(initLocation.getLongitude()*1000000));
CenterLocation(initGeoPoint);
}
myZoomBar.setOnSeekBarChangeListener(myZoomBarOnSeekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener myZoomBarOnSeekBarChangeListener =
new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
SetZoomLevel();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
CenterLocation(myGeoPoint);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
//Manifest file
This is my manifest.xml File and I have got permission with the internet
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="velu.ndot.hosp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:theme="#android:style/Theme.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".HospitalActivity"
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>
</application>
</manifest>
//Layout
My layout design..!
<?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"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
/>
<TextView
android:id="#+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:"
/>
<SeekBar
android:id="#+id/zoombar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="0"/>
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="false"
android:apiKey="key**********************"
/>
</LinearLayout>
This looking all right in your code. Please try to take another map key and then check may be this will solve your problem .
As your code is similar to:
http://www.mubasheralam.com/tutorials/android/how-use-google-maps-android-application

Categories

Resources