0

Im trying to get the current location using async task this code works fine without async task but when i tried it with async task its showing NO Location Found and Sorry No Address Found.here is my code plz help me thanks in advance

public class MainActivity extends Activity {
/** Called when the activity is first created. */
String addressString;    
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        new Getlocation().execute();    

}

// STARTING OF ASYNC TASK

class Getlocation extends AsyncTask<String, String, String> {


    ProgressDialog p;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

       p = new ProgressDialog(MainActivity.this);                   
         p.setMessage("Please Wait Retrieving data..");     
         p.setTitle(" ");                                       
         p.setIcon(R.drawable.settings2);                       
         p.show();                                               
    }
    @Override
    protected String doInBackground(String... params) {
        Looper.prepare();

          LocationManager locationManager; 

            String context = Context.LOCATION_SERVICE; 
            locationManager = (LocationManager)getSystemService(context); 

            Criteria crta = new Criteria(); 
            crta.setAccuracy(Criteria.ACCURACY_FINE); 
            crta.setAltitudeRequired(false); 
            crta.setBearingRequired(false); 
            crta.setCostAllowed(true); 
            crta.setPowerRequirement(Criteria.POWER_LOW); 
            String provider = locationManager.getBestProvider(crta, true); 

         //String provider = LocationManager.GPS_PROVIDER; 
            Location location = locationManager.getLastKnownLocation(provider); 
            updateWithNewLocation(location); 
           LocationListener locationListener = new LocationListener() 
         { 

         @Override 
         public void onLocationChanged(Location location) { 
         updateWithNewLocation(location); 
         } 

         @Override 
         public void onProviderDisabled(String provider) { 
         updateWithNewLocation(null); 
         } 

         @Override 
         public void onProviderEnabled(String provider) { 
         } 

         @Override 
         public void onStatusChanged(String provider, int status, Bundle extras) { 
         } 

         };
         locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); 
         Looper.loop();

        return addressString;
    }
     @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result); 
            p.dismiss();                    

    }   }
 private void updateWithNewLocation(Location location) { 
     String latLong;
     TextView myLocation; 
      addressString = "Sorry  No Address Found"; 
     if(location!=null) { 
    double lat = location.getLatitude(); 
     double lon = location.getLongitude(); 
     latLong = "Lat:" + lat + "\nLong:" + lon; 
     double lattitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     Geocoder gc = new Geocoder(this,Locale.getDefault()); 
     try { 
     List<Address> addresses= gc.getFromLocation(lattitude, longitude, 1); 
     StringBuilder sb = new StringBuilder(); 
     if(addresses.size()>0) { 
     Address address=addresses.get(0);
     for(int i=0;i<address.getMaxAddressLineIndex();i++)
     sb.append(address.getAddressLine(i)).append("\n");
     sb.append(address.getLocality()).append("\n"); 
     sb.append(address.getPostalCode()).append("\n"); 
     sb.append(address.getCountryName()); 

     } 
     addressString = sb.toString(); 
     } 
     catch (Exception e) { 
     } 
     } else { 
     latLong = " NO Location Found "; 
     } 
Toast.makeText(getApplicationContext(), "Current Position is :\n"+ latLong + "\n"+  addressString ,Toast.LENGTH_LONG).show();
  //  myLocation.setText("Current Position is :\n"+ latLong + "\n"+  addressString ); 
        }

}

//here is my logcat

    10-01 22:34:13.720: E/WindowManager(2868): Activity com.example.sc.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411dd3c8 that was originally added here
10-01 22:34:13.720: E/WindowManager(2868): android.view.WindowLeaked: Activity com.example.sc.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@411dd3c8 that was originally added here
10-01 22:34:13.720: E/WindowManager(2868):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
10-01 22:34:13.720: E/WindowManager(2868):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
10-01 22:34:13.720: E/WindowManager(2868):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
10-01 22:34:13.720: E/WindowManager(2868):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
10-01 22:34:13.720: E/WindowManager(2868):  at android.view.Window$LocalWindowManager.addView(Window.java:547)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.Dialog.show(Dialog.java:277)
10-01 22:34:13.720: E/WindowManager(2868):  at com.example.sc.MainActivity$Getlocation.onPreExecute(MainActivity.java:68)
10-01 22:34:13.720: E/WindowManager(2868):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
10-01 22:34:13.720: E/WindowManager(2868):  at android.os.AsyncTask.execute(AsyncTask.java:534)
10-01 22:34:13.720: E/WindowManager(2868):  at com.example.sc.MainActivity.onCreate(MainActivity.java:51)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.Activity.performCreate(Activity.java:5008)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-01 22:34:13.720: E/WindowManager(2868):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-01 22:34:13.720: E/WindowManager(2868):  at android.os.Looper.loop(Looper.java:137)
10-01 22:34:13.720: E/WindowManager(2868):  at android.app.ActivityThread.main(ActivityThread.java:4745)
10-01 22:34:13.720: E/WindowManager(2868):  at java.lang.reflect.Method.invokeNative(Native Method)
10-01 22:34:13.720: E/WindowManager(2868):  at java.lang.reflect.Method.invoke(Method.java:511)
10-01 22:34:13.720: E/WindowManager(2868):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-01 22:34:13.720: E/WindowManager(2868):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-01 22:34:13.720: E/WindowManager(2868):  at dalvik.system.NativeStart.main(Native Method)
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
Chaitanya Sai
  • 101
  • 1
  • 13
  • You'll need to post the LogCat error in order for anyone to be able to help you. My first guess is that you haven't added permission to use location in your android manifest xml – Paul D'Ambra Oct 01 '12 at 16:59
  • @PaulD'Ambra i already added all permissions required and it is working i general main thread where it comes to async its not working – Chaitanya Sai Oct 01 '12 at 17:08
  • @PaulD'Ambra plz see my total edited question – Chaitanya Sai Oct 01 '12 at 17:29
  • @RaghavSood plz see my total edited question – Chaitanya Sai Oct 01 '12 at 17:32
  • I think that the error listed is to do with the ProgressBar being incorrectly used (I've never seen a ProgressBar declared that way at least). Android is complaining when you try to show a ProgressBar that isn't actually on screen. – Paul D'Ambra Oct 01 '12 at 17:43

2 Answers2

1

This looks like the classic "creating Handler in a non-Looper thread" exception. Basically, you're creating a Handler that's to receive location messages to your LocationListener object which was created in it's own thread. Threads that run doInBackground() die as soon as the method returns. Thus, the LocationManager is sending data to a dead object in a dead thread and you get an exception.

A good sample on Loopers is here:

What is the purpose of Looper and how to use it?

You can continue to use the AsyncTask if you put Looper.prepare() at the top of doInBackground() and Looper.loop() at the bottom. Looper.loop() is just an empty while loop that will keep your thread open forever.

In order for it to die, you must call Looper.myLooper().quit() in your thread to kill it. The easiest way to do that is immediately after Looper.prepare(), save the Looper by calling Looper.myLoop(). Then kill it in a method that is to be called when you want to stop the updates.

class LooperAsyncTask extends AsyncTask<Void, Void, Void> {

    private mThreadLooper;

    @Override
    protected String doInBackground(String... params) {
      Looper.prepare();
      mThreadLooper = Looper.myLooper();
      **setup code**
      Looper.loop();
    }

    public void stopUpdates() {
      **cleanup code**
      if(mThreadLooper != null)
        mThreadLooper.quit();
    }
}
Community
  • 1
  • 1
DeeV
  • 35,865
  • 9
  • 108
  • 95
  • I think it will be better to change the AsynTask to a Service or IntentService to force the Update of the Location. You can still use the code above to get the getLastKnownLocation, also you have to add check for not null if any location provider don't match your Criteria. – Anis BEN NSIR Oct 01 '12 at 17:20
  • im not getting plz post the code with required modifications plz and see my new uppdated question – Chaitanya Sai Oct 01 '12 at 17:31
  • im checking if(location!=null) – Chaitanya Sai Oct 01 '12 at 17:32
  • There could be other problems too. I just noticed this one. You're going to have to look for the exception that Logcat spits out. It's there. I promise. @Anis: You really only need a service if you jump from Activity to Activity or if you want it to keep updating when the app is paused. If he's just sitting in the main Activity, then a regular Thread is fine. – DeeV Oct 01 '12 at 17:37
  • @Deev , I have the location update problem using GPS_PROVIDER. My link is http://stackoverflow.com/questions/20112140/location-manager-is-not-working-without-internet . Is it the same reason as i am using some other activity than main activity ?? – SSS Nov 22 '13 at 09:41
  • No. GPS is global to the system. It doesn't matter what Activity or Service retrieves it. The only thing that would prevent you from getting a location via GPS is you aren't getting a lock within the Criteria that you specified. GPS stinks and is unreliable. Network is much faster and can usually get you within a block's worth of accuracy. – DeeV Nov 22 '13 at 18:54
0

Your LocationManager and LocationListener don't need to be in an AsyncTask. They should be in the Activity (or some other class that the Activity references if you want to share them between Activities).

Registering the LocationListener in the AsyncTask isn't the correct approach because that listener dies with the AsyncTask so won't be around to listen for updates.

Incidentally, your updateWithNewLocation() method is creating a TextView that it isn't using.

By calling Toast in the updateWithNewLocation() you're effectively calling it in doInBackground which isn't running on the UI thread so Toast will be funky to setup unless you pass in a context when you instantiate the AsyncTask.

If it is a slow process then you could reverse geocode in an AsyncTask when your Activity catches a location change and then show a Toast (or update a TextView) by passing the result of the doInBackground reverse geocoding to onPostExecute which does run on the UI thread and so can safely and easily update views and show Toasts.

class ReverseGeocodeAsyncTask extends AsyncTask<Void, Void, Void> {

    private Location location;

    public ReverseGeocodeAsyncTask(Location l) { location = l; }

    @Override
    protected String doInBackground(String... params) {
     //do reverse geocoding and return the result
    }

     @Override
     protected void onPostExecute(String result) {
        // update the UI with the result of the reverse geocoding                   
    }
}
Paul D'Ambra
  • 7,629
  • 3
  • 51
  • 96