user2755646
user2755646

Reputation: 31

Using AsyncTask to get location information

I'm trying to get user's current location coordinates and address using reverse geocoding. As This process takes some time, I want to show a progress bar during that time, so I'm using AsyncTask. So, what basically I'm doing is, from one activity's onClick event I start the AsyncTask which finds me the location informations and then from that AsyncTask I start another activity which uses that Information.

This is my First Activity where onClick event starts the AsyncTask:

public void onClickGirl(View view)
{
  (new MyAsyncTask(MainActivity.this)).execute();
}

This is the AsyncTask:

public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
  private Context ContextAsync;
  public MyAsyncTask (Context context){
    this.ContextAsync = context.getApplicationContext();
  }

  Dialog progress;
  private String providerAsync;
  private LocationManager locationManagerAsync;  
  double   latAsync=0.0;
  double lonAsync=0.0;
  String thikanaAsync="Scan sms for location";

  String AddressAsync="";
  Geocoder GeocoderAsync;

  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    progress = ProgressDialog.show(null, "Loading data", "Please wait...");

  }

  @Override
  protected Void doInBackground(Void... arg0) {
    // TODO Auto-generated method stub
    locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setCostAllowed(false);
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    providerAsync = locationManagerAsync.getBestProvider(criteria, false);

    if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      providerAsync = LocationManager.GPS_PROVIDER;
    } else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
      providerAsync = LocationManager.NETWORK_PROVIDER;
      /*AlertDialog.Builder alert = new AlertDialog.Builder(this);
      alert.setTitle("GPS is disabled in the settings!");
      alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
      alert.setPositiveButton("OK", null);
      alert.show();*/     
    } else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
      providerAsync = LocationManager.PASSIVE_PROVIDER;
      Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
    }    

    Location location = locationManagerAsync.getLastKnownLocation(providerAsync);
    // Initialize the location fields
    if (location != null) {
      //  System.out.println("Provider " + provider + " has been selected.");
      latAsync = location.getLatitude();
      lonAsync = location.getLongitude();
      onLocationChanged(location);
    } else {
      Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
    }

    List<Address> addresses = null;
    GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
    try {
       addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);

       String address = addresses.get(0).getAddressLine(0);
       String city = addresses.get(0).getAddressLine(1);
       String country = addresses.get(0).getCountryName();
       AddressAsync = Html.fromHtml(
               address + ", " + city + ",<br>" + country).toString();
    } catch (Exception e) {
       e.printStackTrace();
       AddressAsync = "Refresh for the address";
    }

    return null;
  }

  @Override
  protected void onPostExecute(Void result) {  

  super.onPostExecute(result);
  progress.dismiss();
  Intent intentAsync = new Intent(ContextAsync,Emerg.class);
    intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intentAsync.putExtra("calculated_Lat", latAsync);
    intentAsync.putExtra("calculated_Lon", lonAsync);
    intentAsync.putExtra("calculated_address", AddressAsync);
    ContextAsync.startActivity(intentAsync);  
  }

  @Override
  public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
      locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
  }

  @Override
  public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

  }

}

This is the Second Activity which run after AsyncTask:`

Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");

And This is the LogCat:

02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.view.View$1.onClick(View.java:3814)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.view.View.performClick(View.java:4424)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Handler.handleCallback(Handler.java:733)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Handler.dispatchMessage(Handler.java:95)

02-01 17:15:26.734: E/AndroidRuntime(2587):     at android.os.Looper.loop(Looper.java:137)

I have spent hours after this but can't find the problem. Can anyone please help me finding out what I'm missing??

Upvotes: 0

Views: 4585

Answers (2)

sUndeep
sUndeep

Reputation: 360

Please find the updated code and test it at your end and let me know in case you have any query:

package com.example.tabhost;

import java.util.List;
import java.util.Locale;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;

public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
    private Context ContextAsync;
    public MyAsyncTask (Context context){
        this.ContextAsync = context;
    }

    Dialog progress;
    private String providerAsync;
    private LocationManager locationManagerAsync;  
    double   latAsync=0.0;
    double lonAsync=0.0;
    String thikanaAsync="Scan sms for location";

    String AddressAsync="";
    Geocoder GeocoderAsync;

    Location location;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");

    }


    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);


        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        providerAsync = locationManagerAsync.getBestProvider(criteria, false);


        if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            providerAsync = LocationManager.GPS_PROVIDER;
        } else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            providerAsync = LocationManager.NETWORK_PROVIDER;
            /*AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("GPS is disabled in the settings!");
            alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
            alert.setPositiveButton("OK", null);
            alert.show();*/         
        } else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            providerAsync = LocationManager.PASSIVE_PROVIDER;
            //Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
        }    

        location = locationManagerAsync.getLastKnownLocation(providerAsync);
        // Initialize the location fields
        if (location != null) {
            //  System.out.println("Provider " + provider + " has been selected.");
            latAsync = location.getLatitude();
            lonAsync = location.getLongitude();

        } else {
            //Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
        }



        List<Address> addresses = null;
        GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
        try {
            addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);

            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getCountryName();
            AddressAsync = Html.fromHtml(
                    address + ", " + city + ",<br>" + country).toString();
        } catch (Exception e) {
            e.printStackTrace();
            AddressAsync = "Refresh for the address";
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void result) {  

        super.onPostExecute(result);
        progress.dismiss();
        onLocationChanged(location);
        Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
        Intent intentAsync = new Intent(ContextAsync,Emerg.class);
        intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);   
        intentAsync.putExtra("calculated_Lat", latAsync);
        intentAsync.putExtra("calculated_Lon", lonAsync);
        intentAsync.putExtra("calculated_address", AddressAsync);

        ContextAsync.startActivity(intentAsync);

    }



    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

Upvotes: 3

michal.luszczuk
michal.luszczuk

Reputation: 2903

instead of using this.ContextAsync = context.getApplicationContext(); ContextAsync should have Activity instance, no ApplicationContext so use this.ContextAsync = context

Upvotes: 1

Related Questions