Related
I want to know how to send my coordinates via SMS by clicking a button. I have the following code that a message is sent, as sending the coordinates.
public class MainActivity extends AppCompatActivity {
Button Enviar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Enviar = (Button)findViewById(R.id.btnEnviar);
Enviar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EnviarMensaje("cell phone number","message");
}
});
}
private void EnviarMensaje (String Numero, String Mensaje){
try {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(Numero,null,Mensaje,null,null);
Toast.makeText(getApplicationContext(), "Mensaje Enviado.", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Mensaje no enviado, datos incorrectos.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Follow these steps
String msg_txt ="";
// Declare as global variable
Enviar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(ComposeThreadsActivity.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handle after selecting place
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (data != null) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s",
place.getName());
String address = String.valueOf(place.getAddress());
String placeName = String.valueOf(place.getName());
LatLng latLong = place.getLatLng();
String lat = String.valueOf(latLong.latitude);
String lon = String.valueOf(latLong.longitude);
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(placeName)) {
if (placeName.contains(lat)) {
sb.append("http://maps.google.com/?q=" + lat + ","
+ lon);
} else {
sb.append("Place: " + placeName);
if (!TextUtils.isEmpty(address)) {
sb.append("\nAddress: " + address);
}
sb.append("\nLink: http://maps.google.com/?q="
+ lat + "," + lon);
}
msg_txt = sb.toString();
EnviarMensaje("cell phone number", msg_txt);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
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.
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");
}
}
}
How i can show location on map by street name using android and java ?
For example: i'll type in my program street,city - and i get the location on map
i have this sample:
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:31.06221,33.781642"));
startActivity(i);
how to change this code for inserting street and city ? i try this:
something like: Uri.parse("geo:empire state building"));
but it dont work ):
Use reverse-Geocoding with Geocoder class
Example for achieving coordinates of Empire State Building:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
"empire state building", 5);
String add = "";
if (addresses.size() > 0) {
String coords = "geo:" + String.valueOf(addresses.get(0).getLatitude()) + "," + String.valueOf(addresses.get(0).getLongitude());
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(coords));
startActivity(i);
}
} catch (IOException e) {
e.printStackTrace();
}
Geocoder is great and thanks llya.
this query should be executed in a separate thread, for example, AsyncTask, here is a sample code, hope to be helpful.
public class AsyncTaskToQueryLocation extends
AsyncTask<String, Integer, LatLng> {
private WeakReference<Context> m_Context;
private WeakReference<UserLocationManager> m_Manager;
private WeakReference<OnGeoLocationQueryListener> m_Listener;
private Locale m_Locale;
private String m_ParsedLocation;
public AsyncTaskToQueryLocation(Context context,
UserLocationManager manager, OnGeoLocationQueryListener listener,
Locale locale) {
m_Context = new WeakReference<Context>(context);
m_Manager = new WeakReference<UserLocationManager>(manager);
m_Listener = new WeakReference<OnGeoLocationQueryListener>(listener);
m_Locale = locale;
m_ParsedLocation = null;
}
#Override
protected LatLng doInBackground(String... params) {
Context context = m_Context.get();
if (context == null) {
return null;
}
if ((params == null) || (params.length == 0) || (params[0] == null)) {
return null;
}
m_ParsedLocation = params[0];
Geocoder geoCoder = new Geocoder(context, m_Locale);
try {
List<Address> addresses = geoCoder.getFromLocationName(
m_ParsedLocation, 1);
if (addresses.size() > 0) {
return new LatLng(addresses.get(0).getLatitude(), addresses
.get(0).getLongitude());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(LatLng latLng) {
OnGeoLocationQueryListener listener = m_Listener.get();
if (listener != null) {
listener.onGeoLocationQueryFinished(m_ParsedLocation, latLng);
}
onCancelled();
}
#Override
protected void onCancelled() {
UserLocationManager manager = m_Manager.get();
if (manager != null) {
manager.notifyAsyncTaskFinish(AsyncTaskToQueryLocation.class
.getSimpleName());
}
clearReference();
}
private void clearReference() {
// release the weak reference.
m_Listener.clear();
m_Manager.clear();
m_Context.clear();
}
}
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
}