1

I am creating an application to find the users current location. I referred this link What is the simplest and most robust way to get the user's current location on Android?

to create my app. My problem i have tried with both the providers, but it didn't detect any providers and the result is always location=null returns. Why this problem and how can i get the location in my phone.? Thanks in advance...

My code goes here This is MyLocation.java class

package com.example.locationupadates;

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Log.v("Ansar",""+"Network Enabled");}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Log.v("Ansar",""+"Network Enabled");}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled){
             Log.v("Ansar",""+"Not anything Enabled");
            return false;
        }
        if(gps_enabled){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
            Log.v("Ansar",""+"Location Listener Gps");
        } if(network_enabled){
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
            Log.v("Ansar",""+"Location Listener Network");
        }  timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
            Log.v("Ansar",""+location.getLongitude());
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

MainActivity.java

package com.example.locationupadates;

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.example.locationupadates.MyLocation.LocationResult;

public class MainActivity extends Activity {
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         tv=(TextView) findViewById(R.id.tv);
         Log.d("Ansar",""+"oncreate");
        LocationResult locationResult = new LocationResult(){
            @Override
            public void gotLocation(Location location){
                Log.v("Ansar",""+location.getLongitude());
               tv.setText("location:"+location+"latitude: "+location.getLatitude()+"longitude "+location.getLongitude()); 
            }
        };
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(this, locationResult);

    }

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

}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationupadates"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />
    <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.example.locationupadates.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>

Exception

02-21 11:39:05.963: W/dalvikvm(18909): threadid=11: thread exiting with uncaught exception (group=0x410e4390)
02-21 11:39:05.963: E/AndroidRuntime(18909): FATAL EXCEPTION: Timer-0
02-21 11:39:05.963: E/AndroidRuntime(18909): java.lang.NullPointerException
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MainActivity$1.gotLocation(MainActivity.java:23)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MyLocation$GetLastLocation.run(MyLocation.java:102)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at java.util.Timer$TimerImpl.run(Timer.java:284)
02-21 11:39:05.963: W/dalvikvm(18909): threadid=11: thread exiting with uncaught exception (group=0x410e4390)
02-21 11:39:05.963: E/AndroidRuntime(18909): FATAL EXCEPTION: Timer-0
02-21 11:39:05.963: E/AndroidRuntime(18909): java.lang.NullPointerException
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MainActivity$1.gotLocation(MainActivity.java:23)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at com.example.locationupadates.MyLocation$GetLastLocation.run(MyLocation.java:102)
02-21 11:39:05.963: E/AndroidRuntime(18909):    at java.util.Timer$TimerImpl.run(Timer.java:284)
Community
  • 1
  • 1
Ansar
  • 364
  • 3
  • 16
  • 2
    Can you paste your code with manifest.xml and error log if any. – Lucifer Feb 21 '14 at 05:42
  • Question edited with code – Ansar Feb 21 '14 at 05:48
  • try adding these permissions ` ` – Lucifer Feb 21 '14 at 05:52
  • I think you forgot to read [comment](http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-a/3145655#comment32977978_3145655) on that answer link. – Lucifer Feb 21 '14 at 05:56
  • Now it shows this exception – Ansar Feb 21 '14 at 06:10
  • Error indicates that you are trying something. Lets solve this error. – Lucifer Feb 21 '14 at 06:12
  • 1
    When I ran your code in my device Samsung then it is perfectly giving me desired result. I tried with both provider and result is positive, not error. – Lucifer Feb 21 '14 at 06:23
  • Sorry for the delay 02-21 12:13:34.241: E/AndroidRuntime(22258): FATAL EXCEPTION: Timer-0 02-21 12:13:34.241: E/AndroidRuntime(22258): java.lang.NullPointerException – Ansar Feb 21 '14 at 06:46
  • Ithink this exception caught when getLastKnownLocation() returns a null value.It doesn't call onLocationChanged().Therefore it doen't update the new location. – Ansar Feb 21 '14 at 06:49
  • I dnt knw how to overcome this – Ansar Feb 21 '14 at 06:50
  • which device you are trying ? – Lucifer Feb 21 '14 at 06:50
  • HTC one S is my device – Ansar Feb 21 '14 at 06:52
  • I suggest you to try this code in some other device as well. – Lucifer Feb 21 '14 at 06:56
  • yes i got the result in htc icredebile using android 4.0 ,but why this problem in android 4.1.1.Whic is your android version?Thank you for your valuable comment – Ansar Feb 21 '14 at 07:11
  • mine is Android 4.0.4 I havent check code in 4.1 or 4.2 my be after lunch i will check it. – Lucifer Feb 21 '14 at 07:12
  • I got the same exception along with that result in htc incredible device – Ansar Feb 21 '14 at 07:15
  • what is Android version in HTC ? – Lucifer Feb 21 '14 at 07:16
  • 02-21 12:43:51.755: E/AndroidRuntime(654): FATAL EXCEPTION: Timer-0 02-21 12:43:51.755: E/AndroidRuntime(654): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 02-21 12:43:51.755: E/AndroidRuntime(654): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4132) \ – Ansar Feb 21 '14 at 07:16
  • 1
    `Only the original thread that created a view hierarchy can touch its views` Normally this error occurs when you try to access any view from thread. Check in your code. You get this error as you are setting Text into Textview , Am I right ? – Lucifer Feb 21 '14 at 07:17
  • This is the exception caught in htc incredible android version 4.0.4 – Ansar Feb 21 '14 at 07:18
  • 1
    I have seen these kinds of exceptions with HTC device most. – Lucifer Feb 21 '14 at 07:20
  • yes it is not working in Android Jellybean – Ansar Feb 21 '14 at 10:12
  • is there any solution for that – Ansar Feb 21 '14 at 10:12
  • 1
    I run your code in my Samsung S2 , Android 4.1.2 and it is working fine :) – Lucifer Feb 21 '14 at 10:28
  • then do you know why this prob in htcone s – Ansar Feb 21 '14 at 10:48
  • I do not know any solid reason since I am not having HTC device with me, but yes I do know that on HTC sometimes this happens. – Lucifer Feb 21 '14 at 10:49

0 Answers0