Android: Getting null value after onPostExecute - android

This question is continuation of my previous question. The link is https://stackoverflow.com/questions/12499941/android-getting-wrong-info-on-parsing-json-data#comment16829891_12499941
The problem I am facing is, in doInBackground of Async Task, I am able to put data in NearLocation[]. Then, I passed this array to onPostExecute(). There I printed the data in NearLocation[], and it gave me the result whatever it had in array. This array, I am using in SitesOverlay class. Also, I am using this array in onCreate of activity to check whether it contains value. If not, it should give me an alert message. When I run my app, it showed NearLocation[] is null and gave me alert. But, at that time value was there in the array, I checked the same in onPostExecute. Now, I am not understanding, how the array became null, when it was having value in onPostExecute(). Did, i did anything wrong. I tried and searched a lot but couldn't come up with solution. I am posting my updated code below as well as.
Activity class
public class TrackDriverActivity extends MapActivity {
Button btnCurrLoc;
EditText txtPickAddress;
MapView map;
MapController mc;
GeoPoint p;
boolean foundValidLocation = true;
public NearLocation[] nearLocations;
public String driverLatitude;
public String driverLongitude;
private MyLocationOverlay me=null;
private static final String TAG = "TrackDriverActivity";
String tripstatus;
/**
* Nitish
* Tue 11 Sep 2012 06:57 PM
* */
private final String url = "http://towncarapp.com/android/near_driver.php?email="+ UserProfile.email;
JSONObject jsonObject;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.trackdriver);
Log.v(TAG,"Inside Pick Location Activity");
new LoadDriverDetailsAsyncTask(TrackDriverActivity.this, url).execute();
map = (MapView) findViewById(R.id.mapLocation);
if(nearLocations!=null && nearLocations.length !=0)
{
for(int i = 0; i < nearLocations.length; i++)
{
NearLocation driverLocation = nearLocations[i];
driverLatitude = driverLocation.lat;
driverLatitude = driverLocation.lon;
Log.d(TAG, "Latitude = " +driverLatitude);
Log.d(TAG, "Latitude = " +driverLongitude);
}//for
Log.d(TAG, "onCreate nearLocation if");
}//if
else
{
TownCarDialogManager.showOkOnlyDialog(TrackDriverActivity.this, "Message", "No Driver assigned yet.");
map.getController().setCenter(getPoint(39.83,-98.58));
map.setBuiltInZoomControls(true);
Log.d(TAG, "onCreate nearLocation else");
}//else
// First Get the current location
Location currentLocation = getCurrentLocation();
Log.v(TAG,"Till Current Location");
if (currentLocation != null)
{
map.getController().setCenter(getPoint(currentLocation.getLatitude(), currentLocation.getLongitude()));
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
try {
map.getOverlays().add(new SitesOverlay(marker, getPoint(currentLocation.getLatitude(), currentLocation.getLongitude())));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.invalidate();
}//if
else
{
Log.v("","No Current Location Found");
}//else
Drawable marker=getResources().getDrawable(R.drawable.marker2); //Driver Marker
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
try {
map.getOverlays().add(new SitesOverlay(marker, null));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.getController().setZoom(17);
map.setBuiltInZoomControls(true);
map.invalidate();
/***/
if (nearLocations == null || nearLocations.length <= 0)
{
//showDialog("Sorry!!!","No driver has been assigned yet.",this);
TownCarDialogManager.showOkOnlyPostProcessingDialog(TrackDriverActivity.this, "Message", "No Driver assigned yet.", 3);
map.getController().setCenter(getPoint(39.83,-98.58));
//map.getController().zoomToSpan(Integer.parseInt(nearLocations[0].lat),Integer.parseInt(nearLocations[0].lon));
map.setBuiltInZoomControls(true);
}//if
}//onCreate
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return false;
}//isRouteDisplayed
public Location getCurrentLocation()
{
LocationManager locationManager = (LocationManager) TrackDriverActivity.this.getSystemService(Context.LOCATION_SERVICE);
Criteria locCriteria = new Criteria();
locCriteria.setAccuracy(Criteria.ACCURACY_FINE);
Location lastLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(locCriteria, true));
return lastLocation;
}//getCurrentLocation
public String getCurrentLocationAddess()
{
Location currentLocation = getCurrentLocation();
String addressString = null;
if(currentLocation!=null)
{
Geocoder gc = new Geocoder(TrackDriverActivity.this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 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.getCountryName());
}//if
addressString = sb.toString();
}//try
catch (IOException e)
{
Log.v("SelectPickupLocation","getCurrentLocationAddress::IOException ");
}//catch
}//if
return addressString;
}//getCurrentLocationAddress
private double getDouble(String dbl){
Double d;
try{
d = Double.valueOf(dbl);
} catch (Exception e) {
return 0;
}
System.out.println("***"+d);
return d.doubleValue();
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker, GeoPoint center) throws InterruptedException, ExecutionException {
super(marker);
boundCenterBottom(marker);
if (center != null){
items.add(new OverlayItem(center, "" , ""+getCurrentLocationAddess()));
} else {
//nearLocations = getNearLocations(jsonObject);
if (nearLocations != null && nearLocations.length > 0 ) {
Log.v("","+"+nearLocations.length);
for (int i = 0; i < nearLocations.length; i++){
NearLocation loc = nearLocations[i];
Log.v(TAG,"*"+loc.lat+"*"+loc.lon);
items.add(new OverlayItem(getPoint(getDouble(driverLatitude), getDouble(driverLongitude)),"", "Driver Location"));
}
}
}
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(TrackDriverActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
private class LoadDriverDetailsAsyncTask extends AsyncTask<String, Void, NearLocation[]>
{
private ProgressDialog pd;
Context ctx;
String url;
public LoadDriverDetailsAsyncTask(Context ctx, String url)
{
this.ctx = ctx;
this.url = url;
}//Constructor
protected void onPreExecute()
{
super.onPreExecute();
pd=new ProgressDialog(ctx);
pd.setMessage("Please Wait...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}//onPreExecute
protected NearLocation[] doInBackground(String... params)
{
JSONObject jObject = JSONParser.getJSONObjectDataFromURL(url);
nearLocations = getNearLocations(jObject);
return nearLocations;
}//doInBackground
protected void onPostExecute(NearLocation[] nearLocations)
{
for(int i = 0; i < nearLocations.length; i++){
NearLocation loc = nearLocations[i];
Log.d("LoadDriverAsyncTaskDriverlATITUDE", loc.lat);
Log.d("LoadDriverAsyncTaskDriverlongitude", loc.lon);
}
pd.dismiss();
}//onPostExecute
}//LoadMapAsyncTask
public NearLocation[] getNearLocations(JSONObject jObject)
{
NearLocation[] nearLocation = null;
try
{
if(jObject!=null)
{
JSONArray jsonArray = jObject.getJSONArray("statement");
if (jsonArray != null)
{
nearLocation = new NearLocation[jsonArray.length()];
Log.v(TAG, "::::::&&&&&&&&&&&&&::::::NearLocations "
+ nearLocation.length);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject e = jsonArray.getJSONObject(i);
NearLocation loc = new NearLocation(
e.getString("latitude"),
e.getString("longitude"));
nearLocation[i] = loc;
Log.v("Driver latitude:", loc.lat);
Log.v("Driver longitude:", loc.lon);
}//for
}//if
}//if
else
{
TownCarDialogManager.showOkOnlyDialog(TrackDriverActivity.this, "Sorry", "There is problem in internet connection");
}//else
}//try
catch (JSONException e)
{
e.printStackTrace();
}//catch
return nearLocation;
}//getNearLocations
}

I'm not sure I understand the problem you have, but here are some issues with your code, see if they solve the problem. They way you setup the code(especially the AsyncTask) might work in some cases but it will fail in most. In the onCreate method you instantiate the task and then you call execute() to start it. At this moment the code in the onCreate method will continue to be run(and the task will do the same), but as the task most likely hasn't finished getting the data, the nearlocations array will be null. So the problem is that you don't wait to let the task to finish getting the data so you end up using the null nearLocations variable. One way to avoid this is to use a callback system. Below is an example:
// this is an interface that the TrackDriverActivity will implement
interface OnLoadDriverDetails {
onLoadDriverDetails(NearLocation[] data);
}
this callback will be called from the AsyncTask when it finishes loading the data:
private class LoadDriverDetailsAsyncTask extends AsyncTask<String, Void, NearLocation[]> {
OnLoadDriverDetails mListener;
public LoadDriverDetailsAsyncTask(Context ctx, String url) {
this.ctx = ctx;
this.url = url;
mListener = (OnLoadDriverDetails) ctx;
}
protected NearLocation[] doInBackground(String... params) {
JSONObject jObject = JSONParser.getJSONObjectDataFromURL(url);
return getNearLocations(jObject);
}
protected void onPostExecute(NearLocation[] nearLocations) {
mListener.onLoadDriverDetails(newrLocations);
}
// the rest of the task's code
In the activity you'll move the code from onCreate that needs the valid nearLocations array in the onLoadDriverDetails callback:
public class TrackDriverActivity extends MapActivity implements OnLoadDriverDetails {
// ...
public void onLoadDriverDetails(NearLocation[] data) {
nearLocations = data;
// here do the things you do in the onCreate method like setting those SitesOverlay items on the map
}

Related

java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

it is giving me very strange output.On my first input the map camera shows the toast msg "address not found" and on my second input it takes me to my first location...and by continuing this process i am given the exception stated above...any hints , helps ,links would be highly appreciated...thankx..`
public void geolocation(View v) throws IOException {
if (check_connection()==false)
{
alert_user();
}
hidesoftkeyboard(v);
EditText et = (EditText) findViewById(R.id.edit_text1);
location= et.getText().toString();
gc = new Geocoder(this);
new my_second_thread().execute();
if (list == null )
{
Toast.makeText(this,"address not found",Toast.LENGTH_SHORT).show();
return;
}
else if ( list.size() > 0)
{
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this,"moving..", Toast.LENGTH_SHORT).show();
double latitude = add.getLatitude();
double longitude = add.getLongitude();
gotoloc(latitude, longitude, zoom);
add_markers(latitude, longitude, locality);
}
}
//the above function uses asyntask which is:
class my_second_thread extends AsyncTask<String, String, List<Address>>{
#Override
protected List<Address> doInBackground(String... params) {
try {
return gc.getFromLocationName(location, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Address> result) {
list = result;
}
}``

Application not responding error

I have a tracking app that does tracking based on gps and cell id at every 2 minutes. I have started a service from MainActivity using setRepeting() of AlarmManager. Then inside that service I have written an asynctask.In onPreExecute() I fetch latitude and longitude using gps or cellid. And in doInBackground() i am fetching data from sqlite db and send to server. Even after writing all network related code in asynctask app sometimes says application not responding. and on pressing ok it restart. What can I do to avoid this.
public class SendDataAsync extends Service {
Logger logger ;
Context con;
String level1;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Toast.makeText(getApplicationContext(),"in onReceive of GPSLoggerService",
// Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
level1 = String.valueOf(level * 100 / scale);
}
}; // battery level
#Override
public void onCreate() {
// TODO Auto-generated method stub
LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "logs"+ File.separator + "log4j.txt");
logConfigurator.setRootLevel(Level.INFO);
logConfigurator.setLevel("org.apache", Level.INFO);
logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
logConfigurator.setMaxFileSize(1024 * 1024 * 5);
logConfigurator.setImmediateFlush(true);
logConfigurator.configure();
logger = Logger.getLogger(SendDataAsync.class);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try
{
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
}
catch (Exception e) {
// TODO: handle exception
logger.info(e);
}
return super.onStartCommand(intent, flags, startId);
}
FetchCordinates
public class FetchCordinates extends AsyncTask<String, Integer, String> {
private Timer monitoringTimer = null;
private static final int TIMER_DELAY = 1000;
private LocationManager locManager;
private static final int gpsMinTime = 1000;
private static final int gpsMinDistance = 1;
private double latitude = 0.0;
private double longitude = 0.0;
private double altitude = 0.0;
float mps;
float kmh;
SendDataAsync sda;
Runtime runtime1;
Process proc1;
int returnVal1 = 0;
int data_mode = 0;
int myLatitude, myLongitude;
String imeiCellID, datetimeCellID;
String latitude_cellID, longitude_cellID;
public String gpslatitude = null;
public String gpslongitude = null;
public String gpsaltitude = null;
private String speed = null;
private String datetime = null;
private String imeino = null;
private String datatype = null;
private CountDownTimer countDownTimer = null;
DBAdapter db;
int flag;
Context context;
boolean didFindLocation = false;
long id;
public static final String PREFS_NAME = "bp";
public LocationManager mLocationManager;
#Override
protected void onPreExecute() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
data_mode = settings.getInt("data_mode", 1);
startLoggingService();
startMonitoringTimer();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
sendData();
} catch (ClientProtocolException e) {
logger.info(e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.info(e.toString());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
protected void removeGps()
{
locManager.removeUpdates(locationListener);
}
private void startLoggingService() {
db = new DBAdapter(SendDataAsync.this);
if (locManager == null) {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
//ma = new MainActivity();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setSpeedRequired(true);
criteria.setBearingRequired(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0) {
locManager.requestLocationUpdates(bestProvider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
} else {
final List<String> providers = locManager.getProviders(true);
for (final String provider : providers) {
locManager.requestLocationUpdates(provider, gpsMinTime,
gpsMinDistance, locationListener);
startTimer();
}
}
}
private void startTimer() {
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
countDownTimer = new CountDownTimer(20000L, 1000L) {// 15 seconds max
#Override
public void onTick(long millisUntilFinished) {
if (didFindLocation) {
countDownTimer.cancel();
}
}
#Override
public void onFinish() {
if (!didFindLocation) {
removeGps();
if(data_mode==1)
{
monitoringTimer.cancel();
cellID();
}
else {
Toast.makeText(getApplicationContext
(),"GPS : Cant find Location", Toast.LENGTH_LONG).show();
}
stopLoggingService();
}//if
}//inFin
};
countDownTimer.start();
}
// class location listener
private final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location) {
didFindLocation = true;
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
// Toast.makeText(getApplicationContext(),"lat :"+latitude+"longi :"+longitude,
// Toast.LENGTH_LONG).show();
gpsaltitude = String.valueOf(altitude);
gpslatitude = String.valueOf(latitude);
gpslongitude = String.valueOf(longitude);
mps = location.getSpeed();
kmh = (float) (mps * 3.6);
speed = Float.toString(kmh);
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetime = sdfDateTime.format(new Date(location.getTime()));
}
#Override
public void onProviderDisabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderDisabled().");
logger.info("onLocationChanged, ");
}
#Override
public void onProviderEnabled(String provider) {
AppLog.logString("GPSLoggerService.onProviderEnabled().");
logger.info("onProviderEnabled, ");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
AppLog.logString("GPSLoggerService.onStatusChanged().");
logger.info("onStatusChanged, ");
}
};
public void saveData() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeino = tm.getDeviceId();
DBAdapter db=new DBAdapter(SendDataAsync.this);
setFlag();
datatype = String.valueOf(flag);
// --add contact----
db.open();
id = db.insertData(imeino, gpslatitude, gpslongitude, datetime,
gpsaltitude, speed, level1, datatype, "1");
db.close();
}// end of saveData() function
private void startMonitoringTimer() {
monitoringTimer = new Timer();
monitoringTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (longitude != 0.0 && latitude != 0.0) {
monitoringTimer.cancel();
monitoringTimer = null;
// turnGPSOn();
//didFindLocation=false;
saveData();
removeGps();
stopLoggingService();
}
}
},TIMER_DELAY,TIMER_DELAY);
}
public boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
return true;
} else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
public int setFlag() {
final SharedPreferences settings = getSharedPreferences(PREFS_NAME,
MODE_PRIVATE);
boolean firstRecord = settings.getBoolean("firstRecord", false);
boolean firstRecordAfterBoot = settings.getBoolean("justBooted", false);
if (firstRecord == true) {
flag = 0;
// Toast.makeText(getBaseContext(),"1st record after installation : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("firstRecord", false).commit();
} else if (firstRecordAfterBoot == true) {
flag = 1;
// Toast.makeText(getBaseContext(),"1st record after boot : "+flag,Toast.LENGTH_LONG
// ).show();
settings.edit().putBoolean("justBooted", false).commit();
} else {
flag = 2;
// Toast.makeText(getBaseContext(),"regular : "+flag,Toast.LENGTH_LONG
// ).show();
}
return flag;
}
public void cellID() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager
.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
SimpleDateFormat sdfDateTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
datetimeCellID = sdfDateTime.format(new Date());
// Toast.makeText(getBaseContext(),"cellid="+cell_Id+"\nGsm Location Area Code:"+gsm_Loc_Area_Code,Toast.LENGTH_LONG
// ).show();
CellidAsync cellasy=new CellidAsync();
String pass = null;
try {
pass = cellasy.execute(cid,lac).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] arr=pass.split(",");
if (Boolean.valueOf(arr[0])) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imeiCellID = tm.getDeviceId();
myLatitude=Integer.valueOf(arr[1]);
myLongitude=Integer.valueOf(arr[2]);
latitude_cellID = String.valueOf((float) myLatitude / 1000000);
longitude_cellID = String.valueOf((float) myLongitude / 1000000);
// Toast.makeText(getBaseContext(),"Lat:"+latitude_cellID+"Long:"+longitude_cellID,Toast.LENGTH_LONG
// ).show();
// DBAdapter db=new DBAdapter(this);
// --add contact----
db.open();
setFlag();
datatype = String.valueOf(flag);
id = db.insertData(imeiCellID, latitude_cellID, longitude_cellID,
datetimeCellID, "null", "null", level1, datatype, "0");
db.close();
// --get all contacts----------
/*db.open();
Cursor c = db.getAllData();
if (c.moveToFirst()) {
do {
//DisplayData(c);
} while (c.moveToNext());
}
db.close();*/
}// if
else {
Toast.makeText(getBaseContext(), "CellID : Can't find Location",
Toast.LENGTH_LONG).show();
}// else
}// cellID
public void sendData() throws ClientProtocolException, IOException
{
//Toast.makeText(getApplicationContext(),"in sendData", Toast.LENGTH_LONG).show();
enableInternet();
setAirplaneMode();
runtime1 = Runtime.getRuntime();
proc1 = runtime1.exec("ping -c 1 some ip");
try {
returnVal1 = proc1.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean reachable1 = (returnVal1==0);
if(reachable1==true)
{
if(isInternetOn())
{
JSONObject jObject=new JSONObject();
try
{
//DBAdapter db=new DBAdapter(this);
db.open();
Cursor cursor=db.getAllData();
if(cursor.moveToFirst())
{
do{
jObject = new JSONObject();
jObject.put("Imei", cursor.getString(1));
jObject.put("Lat", cursor.getString(2));
jObject.put("Long", cursor.getString(3));
jObject.put("Gpsdatetime", cursor.getString(4));
jObject.put("Altitude",cursor.getString(5));
jObject.put("Speed", cursor.getString(6));
jObject.put("Battery", cursor.getString(7));
jObject.put("DataType", cursor.getString(8));
jObject.put("DataSource", cursor.getString(9));
//------------------------------------------------------------------------
String dt=cursor.getString(4).replace(" ","*");
String datatoServer=cursor.getString(1)+","+cursor.getString(2)+","+cursor.getString(3)+","+dt+","+cursor.getString(5)+","+cursor.getString(6)+","+cursor.getString(7)+","+cursor.getString(8)+","+cursor.getString(9);
//Toast.makeText(getApplicationContext(),datatoServer, Toast.LENGTH_LONG).show();
HttpEntity entity1;
HttpClient client1 = new DefaultHttpClient();
String url1 ="http:/url="+datatoServer;
HttpPost request1 = new HttpPost(url1);
StringEntity se1 = new StringEntity(datatoServer);
se1.setContentEncoding("UTF-8");
se1.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
entity1 = se1;
//request1.setEntity(entity1);
HttpResponse response1 = client1.execute(request1);
entity1 = response1.getEntity();
//----------------------------------------------------------------
db.deleteContacts(cursor.getLong(0));
}while(cursor.moveToNext());
}//if
db.close();
}//try
catch (JSONException e)
{
e.printStackTrace();
logger.info(""+e);
}
catch(Exception e)
{
logger.info(""+e);
}
}//if
}//if ping
} //method
public void setAirplaneMode()
{
// Check for Airplane Mode
boolean isEnabled = Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0) == 1;
if (isEnabled) {
// toggle airplane mode
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
}
}
public void enableInternet()
{
try{
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
boolean isEnabled;
if(telephonyManager.getDataState() ==
TelephonyManager.DATA_CONNECTED){
//Toast.makeText(GPSLoggerService.this, "true", Toast.LENGTH_LONG).show();
isEnabled = true;
}else{
//Toast.makeText(GPSLoggerService.this, "false", Toast.LENGTH_LONG).show();
isEnabled = false;
}
if (isEnabled) {
} else {
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod
("setMobileDataEnabled", boolean.class);dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);
}
}
catch(Exception e){
logger.info(""+e);
}
}//enable internet
}//async
private void stopLoggingService() {
this.unregisterReceiver(this.mBatInfoReceiver);
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should be fetching the lat and long in the doInBackground() method, and not in preExecute().
Fetching the location might take some time, and should be done in the background. That is why you have this problem.

getting address in android using web service

iam new to android development.
i have tried to get location address using web service but i got class not found exception when i lunched this code.if any one could please suggest me proper solution for this..
code for service class....
public class MWService extends Service implements LocationListener {
private LocationManager myLocationManager;
private LocationProvider myLocationProvider;
private NotificationManager myNotificationManager;
private long frequency;
private double total_distance = 0;
private Location currentLocation;
public static final String BROADCAST_ACTION = "com.motorvehicle.android";
private final Handler handler = new Handler();
Intent intent;
private GeocoderHelper geocoder = new GeocoderHelper();
private boolean isStart=true;
private Location startLocation,endLocation;
private String startAddress="";
private String endAddress="";
private JSONArray jarray = new JSONArray();
private boolean isInternet;
//private final Handler handler = new Handler();
public void onLocationChanged(Location newLocation) {
try {
System.out.println("latitude current :"+currentLocation.getLatitude());
System.out.println("latitude current :"+currentLocation.getLongitude());
System.out.println("latitude new :"+newLocation.getLatitude());
System.out.println("latitude new :"+newLocation.getLongitude());
System.out.println("distance total :"+total_distance);
//System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
double diff = 0.0;
diff = currentLocation.getLatitude()- newLocation.getLatitude();
System.out.println("difference ::"+diff);
if(diff != 0){
total_distance = total_distance + currentLocation.distanceTo(newLocation);
}
if(isStart){
isStart = false;
startLocation = newLocation;
/* if(InternetAvailable()){
//startAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("start address:"+startAddress);
}*/
}else{
endLocation = newLocation;
/*if(InternetAvailable()){
//endAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("endAddress :"+endAddress);
}*/
}
currentLocation = newLocation;
} catch (Exception e) {
currentLocation = newLocation;
e.printStackTrace();
}
}
public boolean InternetAvailable() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// while(isStopMe){
System.out.println("This is inside ................. :");
try {
if (!checkConnection()) {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("First");
} else {
if (inetAddr()) {
System.out.println("Net Connectivity is Present");
isInternet = true;
System.out.println("Second");
} else {
if (mobileConnect()) {
System.out.println("THIRD");
if (inetAddr()) {
System.out
.println("Net Connectivity is Present");
isInternet = true;
System.out.println("FOURTH");
} else {
System.out
.println("No Internet Connectivity");
isInternet = false;
System.out.println("FIFTH");
}
} else {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("SIX");
}
}
}
} catch (Exception ex) {
System.out.println("Leak ko catch");
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isInternet;
}
public boolean checkConnection() {
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
public boolean inetAddr() {
boolean x1 = false;
try {
Socket s = new Socket();
s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
InputStream is = s.getInputStream();
Scanner scan = new Scanner(is);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
x1 = true;
}
} catch (IOException e) {
x1 = false;
}
return x1;
}
public boolean mobileConnect() {
boolean conn = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNet != null) {
conn = true;
} else {
conn = false;
}
return conn;
}
#SuppressWarnings("deprecation")
private void myNotify(String text) {
Notification notif = new Notification(R.drawable.ic_launcher, text, System
.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
notif.setLatestEventInfo(this, "MotorVehicleApp", text, contentIntent);
// notif.defaults = Notification.DEFAULT_VIBRATE;
myNotificationManager.notify((int) System.currentTimeMillis(), notif);
}
#Override
public void onCreate() {
super.onCreate();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
intent = new Intent(BROADCAST_ACTION);
android.util.Log.d("MWD", "creating");
myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("location manager:"+myLocationManager.getAllProviders());
myLocationProvider = myLocationManager.getProvider("gps");
myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
updatePreferences();
handler.post(new Runnable() {
#Override public void run() {
Toast.makeText(getApplicationContext(), "Address:"+startAddress, Toast.LENGTH_LONG).show(); } });
}
public void updatePreferences() {
// sync local variables with preferences
android.util.Log.d("NWD", "updating preferences");
frequency = 10;
// update the LM with the new frequency
myLocationManager.removeUpdates(this);
myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
}
#Override
public void onDestroy() {
super.onDestroy();
/////------set edittext editable
android.util.Log.d("NWD", "destroying");
System.out.println("Inside on destroy of MWService");
myLocationManager.removeUpdates(this);
//myNotify("stopping");
InsertTripDetails_AsyncTask insert = new InsertTripDetails_AsyncTask();
insert.execute();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
handler.removeCallbacks(sendUpdatesToUI);
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
android.util.Log.d("NWD", "starting");
currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
//myNotify("starting");
handler.postDelayed(sendUpdatesToUI, 3000); // 1 sec
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
System.out.println("total_distance::"+total_distance);
intent.putExtra("distance",(total_distance/1000));
sendBroadcast(intent);
handler.postDelayed(this, 3000);
}
};
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public IBinder onBind(Intent arg0) {
return null; // this is for heavy IPC, not used
}
private class InsertTripDetails_AsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
try {
//InternetAvailable()
if(InternetAvailable()){
startAddress = geocoder.fetchCityName(getApplicationContext(),startLocation);
System.out.println("start address:"+startAddress);
endAddress = geocoder.fetchCityName(getApplicationContext(),endLocation);
System.out.println("end address:"+endAddress);
}else{
System.out.println("internet not available");
}
// Internet not available when data are store in latitude and longitute format
if(startAddress.equalsIgnoreCase("") && endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("1 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+",lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
}else if(startAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("2 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+","+endAddress);
}else if(endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
try {
System.out.println(startAddress+",3 lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
System.out.println(startAddress+" "+ endAddress);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("In catch of webservice thus no internet");
}
return "dfs";
}
#Override
protected void onPostExecute(String result) {
}
}
}
code for geocoder class
public class GeocoderHelper
{
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeocoderHelper.class.getName());
private String address="";
private Location i_Location;
private Context i_Context;
public String fetchCityName(final Context contex, final Location location)
{
i_Location = location;
i_Context = contex;
try {
return new Address().execute().get();
} catch (Exception e) {
return address;
}
}
public class Address extends AsyncTask<Void, Void, String>
{
#SuppressWarnings("unused")
#Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
System.out.println("location latitude is"+i_Location.getLatitude());
System.out.println("location longitude is"+i_Location.getLongitude());
Geocoder geocoder = new Geocoder(i_Context, Locale.getDefault());
List<android.location.Address> addresses = geocoder.getFromLocation(i_Location.getLatitude(), i_Location.getLongitude(), 1);
if (addresses.size() > 0)
{
//cityName = addresses.get(0).getLocality();
address = addresses.get(0).getLocality();
System.out.println("geocoder inside present address is"+address);
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
try
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + i_Location.getLatitude() + ","
+ i_Location.getLongitude() + "&sensor=false&language=fr";
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
address = result.getString("formatted_address");
System.out.println("map address:"+address);
break;
/* if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String ROUTE= null;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
address = cityName;
return cityName;
}
}
}
}*/
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return address;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
}
code for MAinActivity class
public class MainActivity extends Activity {
//private final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(MainActivity.this,MWService.class));
}
#Override
protected void onPause() {
super.onPause();
stopService(new Intent(MainActivity.this,MWService.class));
}
}
i have use permission in my menifest file for both internet and AccessFineLocation
my logcat msg.....
10-31 13:40:41.937: ERROR/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.address2/com.example.android.MainActivity}: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
10-31 13:40:41.937: ERROR/AndroidRuntime(825): Caused by: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
code for my menifest file....
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.android.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>
<service android:name="MWService"></service>
</application>

ProgressDialog freezes in async task

I am reading lat/lon from file, creating polygon and adding it to the map in AsyncTask. Everything is working fine - except progressDialog allways freezes at start of the action and dismissed after action is completed.This is my code:
UPDATED CODE:
private class shpLoading extends AsyncTask<GoogleMap, List<LatLng>, String> {
private ProgressDialog dialog;
private String path;
private int loaded;
public void setPath(String p){
this.path = p;
}
#Override
protected String doInBackground(GoogleMap... params) {
final ShpReader shpRead = new ShpReader();
try {
shpRead.read(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidShapeFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.setMax(shpRead.daugiakampiai().size());
int i = 0;
for(List<LatLng> a: shpRead.polygons()){
function.arAntLinijos(a);
for(int h = 0; h < a.size()-1; h++){
LatLng point = function.midPoint(a.get(h), a.get(h+1));
a.add(h+1, point);
h++;
if(i > 3000){
message("You reached max count!");
break;
}
}
publishProgress(a);
i++;
}
return "Done";
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Measuring.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(getString(R.string.loading));
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.show();
}
}
#Override
protected void onProgressUpdate(List<LatLng>... values) {
dialog.setProgress(loaded++);
Polygon daug = mMap.addPolygon(new PolygonOptions()
.addAll(values[0])
.strokeWidth(1)
.strokeColor(Color.RED)
.fillColor(0x3F00FF00));
plotai.add(new Polygons(db.getMaxFieldID()+1, daug));
daug = null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
Because you should draw your polygons not in onProgressUpdate method, but in doInBackground method. In onProgressUpdate method you have to update progress in your ProgressDialog object (in your code ProgressDialog is showed, but not updated its progress at all).

Handling the case when you have missed a turn in Google Maps

I am working on an Android navigation application for blind people. So naturally no use of displaying map on the screen. My code for now gets the path by building an url and then parsing the html document. I want to make this live i.e. i want to handle the case when he/she goes off the path or goes in the wrong direction, i want my app to alert him.
Is such a thing possible using a Google Maps feature? If possible please give details about that feature or if no such feature exists then is it possible to use existing feature and use it in some way to help solve the problem.
This is my present code:
public class GPSTracking extends Activity implements
TextToSpeech.OnInitListener
{
protected static final int RESULT_SPEECH_start = 1;
protected static final int RESULT_SPEECH_end = 2;
protected static final int RESTART_ALL = 3;
//total distance travelled till last turn
Float totalDistance;
//distance to be travelled from present point to the next point
Float obtainedDistance;
//upper button
Button btnShowLocation;
//bottom button
Button btnShowLocationNo;
//to narate what user should do.
TextToSpeech tts;
//used to get name of current location
Geocoder geocoder;
//used to find positioning feature
GPS gps;
//start and position of the journey
String startPosition=null, endPosition=null;
//strings containing the path.
String[] string = null;
//vibrate the mobile
Vibrator viberator;
//indexing the present value of string which contains the path
int i = 0;
//to maintain proper order of events
int steps=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button on top
btnShowLocation = (Button) findViewById(R.id.trueButton);
//button on the lower side
btnShowLocationNo = (Button) findViewById(R.id.falseButton);
//initialising the text to speech
tts = new TextToSpeech(this, this);
//initialising the vibrator.
viberator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//to know what the current location
btnShowLocation.setOnClickListener(new View.OnClickListener() {
//to avoid start of multiple threads
boolean mytaskStarted=false;
String str=null;
#Override
public void onClick(View v) {
if(steps==0){
//to make sure values are reset
totalDistance=(float)0;
obtainedDistance=(float)0;
mytaskStarted=false;
string=null;
str=null;
i=0;
//only ask for initial position if not set
if(startPosition == null){
speakOut("Please enter the start position");
//takes the input using speech to text
intentGenerator(RESULT_SPEECH_start);
}
else{
//to enter the destination
speakOut("press the button again");
steps=1;
}
}
else if(steps==1){
//to enter the destination
speakOut("Please enter the destination");
intentGenerator(RESULT_SPEECH_end);
}
else if(steps==2){
//for a impatient user
speakOut("please wait");
//to avoid start of many asynchronous task
if(!mytaskStarted){
mytaskStarted=true;
//asynchronous task to find the path to be followed
new GetPath().execute();
}
}
else if(steps==3){
if (string != null && i < string.length) {
if(gps!=null && gps.isGpsEnabled()){
speakOut(i + 1 + " " + string[i]);
if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" m ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" m ")+3);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" km ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" km ")+4);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
obtainedDistance*=1000;
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i==0 ){
i++;
}
}
else if(gps!=null){
gps.resetDistance();
gps.stopUsingGPS();
//if gps not working.
speakOut(i + 1 + " " + string[i]);
i++;
}
else{
speakOut(i + 1 + " " + string[i]);
i++;
}
} else if (string != null && i >= string.length) {
i = 0;
}
}
}
});
//to get present location
btnShowLocation.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(gps==null){
gps = new GPS(AndroidGPSTrackingActivity.this);
}
if (gps.canGetLocation()) {
double longitude = gps.getLongitude();
double latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
//obtain the address of present location
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
if (listAddresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < listAddresses.size(); i++){
Address address = listAddresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
if(address.getAddressLine(x)!=null){
result.append(address.getAddressLine(x));
result.append(",");
}
}
if(address.getLocality()!=null){
result.append(address.getLocality());
result.append("\n\n");
}
}
//if position accurate
if(gps.isGpsEnabled()){
speakOut(result.toString()+" is Your current location");
startPosition=result.toString();
Toast.makeText(
getApplicationContext(),startPosition,
Toast.LENGTH_LONG).show();
} else if(gps.isNetworkEnabled()){
speakOut(result.toString()+" is Your current approximate location. You have to give input of your present location on your own.");
Toast.makeText(
getApplicationContext(),result.toString(),
Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
startPosition=null;
speakOut(" please turn on gps");
}
return false;
}
});
//to know what the previous direction string
btnShowLocationNo.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View arg0) {
if(string!=null && j<string.length){
speakOut(j + 1 + " " + string[j]);
j++;
}
else if(string!=null && j>=string.length){
j=0;
}
}
});
//to reset all values for fresh start
btnShowLocationNo.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
speakOut("Values reset");
steps=0;
string=null;
i=0;
startPosition=null;
gps.stopUsingGPS();
gps=null;
endPosition=null;
return false;
}
});
}
//function to handle he text obtained from speech to text.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//set the start
case RESULT_SPEECH_start:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
startPosition = text.get(0);
steps=1;
//speakOut("please press button again");
}
else{
steps=0;
}
break;
//to set the end
case RESULT_SPEECH_end:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
endPosition = text.get(0);
steps=2;
}
else{
steps=1;
}
break;
}
}
//function to generate intent to take speech input
public void intentGenerator(int code) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, code);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
speakOut("Opps! Your device doesn't support Speech to Text");
}
}
//mobile gives instruction.
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//asynchronous task to get the path. THIS IS USED TO AVOID OVERLOAD THE MAIN THRED AND AVOID FORCE CLOSE OF THE APPLICATION
private class GetPath extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
string=null;
String html="";
//forming url
URL net = new URL(("http://maps.google.com/maps?saddr="+startPosition+" &daddr= "+endPosition).replaceAll(" ","%20"));
URLConnection netConnection = null;
netConnection = net.openConnection();
//to take the input from google maps
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(netConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
html+=inputLine;
}
//jsoup parser to parse the document obtained from google maps
Document doc = Jsoup.parse(html);
//obtain necessary part of the document
Elements el = doc.getElementsByClass("dir-mrgnr");
//to remove html tags
String str = el.text();
str = str.replaceAll("[0-9]+[.] ", "\n");
string = str.split("\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//so that on press of button again mobile can read the directions to users
steps=3;
}
}
#Override
public void onDestroy() {
//shutdown
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onStart() {
gps = new GPS(AndroidGPSTrackingActivity.this);
super.onStart();
}
#Override
protected void onStop() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
if(gps!=null){
gps.stopUsingGPS();
}
super.onStop();
}
#Override
public void onInit(int status) {
//initialising the text to speech
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnShowLocation.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}

Categories

Resources