This is my code....
package com.appdest.geoalarm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
@SuppressLint({ "ShowToast", "NewApi" })
public class PlacesActivity extends Activity implements LocationListener,
OnValueChangeListener {
TextView setAlarm, distance_calc;
ImageView current_location;
EditText from_location;
ImageButton track;
double dist;
Context context = null;
AutoCompleteTextView tvToLocation;
PlacesTask placesTask;
ParserTask parserTask;
LinearLayout llTrack;
String fromAddress, toAddress;
final static int RQS_1 = 1;
float lat2, log2, lat1, log1;
List<Address> list;
Double Distance;
int number;
LatLng dest, orgin;
Location locations;
LocationManager locationManager;
Location location;
Criteria criteria;
Geocoder gc;
String provider;
List<Address> address1 = null;
String s, Distances;
String PREF_FILE = "pref store";
AlertDialog Alarm, dialog;
@SuppressWarnings("static-access")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.places);
tvToLocation = (AutoCompleteTextView) findViewById(R.id.to_location);
tvToLocation.setThreshold(1);
tvToLocation.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(tvToLocation.getWindowToken(), 0);
// String Name="Mani";
//
// distance_calc.setText(Name);
if (tvToLocation != null) {
tvToLocation = (AutoCompleteTextView) findViewById(R.id.to_location);
fromAddress = from_location.getText().toString();
toAddress = tvToLocation.getText().toString();
try {
address1 = gc.getFromLocationName(toAddress, 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (address1 == null) {
return;
}
Address location1 = address1.get(0);
lat2 = (float) location1.getLatitude();
log2 = (float) location1.getLongitude();
orgin = new LatLng(lat1, log1);
dest = new LatLng(lat2, log2);
String url = getDirectionsUrl(orgin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
distance_calc.setText(null);
}
else {
distance_calc.setText(null);
}
}
});
track = (ImageButton) findViewById(R.id.trackmyway);
setAlarm = (TextView) findViewById(R.id.alarm);
distance_calc = (TextView) findViewById(R.id.distance);
llTrack = (LinearLayout) findViewById(R.id.llTrack);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
provider = locationManager.NETWORK_PROVIDER;
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
try {
lat1 = (float) location.getLatitude();
log1 = (float) location.getLongitude();
orgin = new LatLng(lat1, log1);
gc = new Geocoder(this, Locale.getDefault());
address1 = gc.getFromLocation(lat1, log1, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Geocoder geocoder = new Geocoder(getApplicationContext(),
Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat1, log1,
1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress
.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(
returnedAddress.getAddressLine(i)).append("\n");
s = new StringBuilder().append(strReturnedAddress)
.toString();
}
} else {
Toast.makeText(getApplicationContext(), "not ", 40).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Canont get Address ",
40).show();
}
}
tvToLocation.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
placesTask = new PlacesTask();
placesTask.execute(s.toString());
if (tvToLocation == null && tvToLocation.length()<=0) {
distance_calc.setText(null);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if (tvToLocation == null && tvToLocation.length()<=0) {
distance_calc.setText(null);
}
}
@Override
public void afterTextChanged(Editable s) {
if (tvToLocation == null && tvToLocation.length()<=0) {
distance_calc.setText(null);
}
}
});
// distance_calc.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
//
// if (from_location.length() == 0 && tvToLocation.length() == 0) {
// Toast.makeText(getApplicationContext(),
// "Please enter the locations", Toast.LENGTH_SHORT)
// .show();
// } else {
//
// calculateDistance();
// }
// }
// });
from_location = (EditText) findViewById(R.id.from_location);
// current location
current_location = (ImageView) findViewById(R.id.current_location);
current_location.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
from_location.setText(s);
}
});
setAlarm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final CharSequence[] items = { " By Time ", " By Distance " };
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(
PlacesActivity.this);
builder.setTitle("Set Alarm");
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
openTimePickerDialog(true);
break;
case 1:
openDistanceDialog();
break;
}
Alarm.dismiss();
}
});
Alarm = builder.create();
Alarm.show();
}
});
llTrack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (from_location.length() == 0 && tvToLocation.length() == 0) {
Toast.makeText(getApplicationContext(),
"Please Select the Locations", Toast.LENGTH_SHORT)
.show();
} else {
SharedPreferences spref = getSharedPreferences(PREF_FILE,
MODE_PRIVATE);
SharedPreferences.Editor edit = spref.edit();
edit.putString("toaddress", toAddress);
edit.putFloat("srcLat", lat1);
edit.putFloat("srcLong", log1);
edit.putFloat("destLat", lat2);
edit.putFloat("destLong", log2);
edit.putInt("distanceNumber", number);
edit.commit();
// Toast.makeText(getApplicationContext(),
// "Please select the vehicle you are travelling by",
// Toast.LENGTH_SHORT).show();
Intent map = new Intent(PlacesActivity.this,
MapTrackingActivity.class);
startActivity(map);
}
}
});
}
private void openTimePickerDialog(boolean is24r) {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(
PlacesActivity.this, onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE), is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) {
// Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
alarmSet(calSet);
Toast.makeText(getApplicationContext(), "Alarm is set",
Toast.LENGTH_SHORT).show();
}
private void alarmSet(Calendar calSet) {
// TODO Auto-generated method stub
Intent intent = new Intent(PlacesActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
pendingIntent);
}
};
private void openDistanceDialog() {
// TODO Auto-generated method stub
final Dialog dialogue = new Dialog(PlacesActivity.this);
dialogue.setTitle("Distance");
dialogue.setContentView(R.layout.dialog);
Button btset = (Button) dialogue.findViewById(R.id.btSet);
Button btcancel = (Button) dialogue.findViewById(R.id.btCancel);
final NumberPicker numberPicker = (NumberPicker) dialogue
.findViewById(R.id.numberPicker);
numberPicker.setMaxValue(10); // max value 10
numberPicker.setMinValue(0); // min value 1
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(this);
btset.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
number = numberPicker.getValue();
// Toast.makeText(getApplicationContext(), "the Value is"+number
// , 50).show();
dialogue.dismiss();
}
});
btcancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialogue.dismiss(); // dismiss the dialog
}
});
dialogue.show();
dialogue.getWindow().setLayout(400, 550);
}
public class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
@Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
// TODO Auto-generated method stub
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
// Getting the parsed data as a List construct
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
@Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] { "description" };
int[] to = new int[] { android.R.id.text1 };
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result,
android.R.layout.simple_list_item_1, from, to);
tvToLocation.setAdapter(adapter);
}
}
public class PlacesTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... place) {
// TODO Auto-generated method stub
String data = "";
String key = "key=AIzaSyCX9JAUF6C_U0FGCvGMM26bLyGptYtl3Ok";
String input = "";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String types = "types=geocode";
String sensor = "sensor=false";
String parameters = input + "&" + types + "&" + sensor + "&" + key;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
+ output + "?" + parameters;
try {
// Fetching the data from web service in background
data = downloadUrl(url);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Creating ParserTask
parserTask = new ParserTask();
// Starting Parsing the JSON string returned by Web Service
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
protected void calculateDistance() {
// TODO Auto-generated method stub
tvToLocation = (AutoCompleteTextView) findViewById(R.id.to_location);
fromAddress = from_location.getText().toString();
toAddress = tvToLocation.getText().toString();
try {
address1 = gc.getFromLocationName(toAddress, 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (address1 == null) {
return;
}
Address location1 = address1.get(0);
lat2 = (float) location1.getLatitude();
log2 = (float) location1.getLongitude();
orgin = new LatLng(lat1, log1);
dest = new LatLng(lat2, log2);
String url = getDirectionsUrl(orgin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng orgin, LatLng dest) {
// TODO Auto-generated method stub
String str_origin = "origin=" + orgin.latitude + "," + orgin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
private String downloadUrl1(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
String data = "";
try {
// Fetching the data from web service
data = downloadUrl1(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
RouteParser parserTask = new RouteParser();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
public class RouteParser extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
@Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
// TODO Auto-generated method stub
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
// PolylineOptions lineOptions = null;
// MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(getBaseContext(), "No Points",
Toast.LENGTH_SHORT).show();
return;
}
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
// lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
// duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
if (tvToLocation.length() > 0 && tvToLocation != null) {
distance_calc.setText(distance);
}
else
distance_calc.setText(null);
}
}
}
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "" + newVal, 50).show();
}
}
Вот в этом коде, когда я даю текущее местоположение нормально и назначение из автозаполнения TextView расстояния автоматически появился в текстовом ..Как очистить текст в другом текстовом виде, когда я ввел текст в автоматический полный текст и очистил его в Android?
Так что, когда я очистить текст в автозаполнении TextView, автоматически уже появился расстояние должно быть очищено ? Может у объяснить?
Спасибо и его работы ... Я использовал this..as Что у Said..public пустота afterTextChanged (редактируемые s) { \t \t \t \t если (s.length() == 0) { \t \t \t \t \t distance_calc.setText («Показать расстояние»); \t \t \t \t} \t \t \t} –