How to get value from StringBuilder and pass it to another activity? - java

I have a StringBuilder variable from which I want to get the final value and pass it to the another activity. And I want to display the final string value in edit text view.
I have tried to get the value using toString() method but I am unable to see the value in text view its blank.
String value=str.toString();
intent.putExtra("value",value);
startActivity(intent);
By this I have got the value and sending to 2nd activity.
Intent intent = this.getIntent();
String data = intent.getStringExtra("keyName");
edtxt_from.setText(data);
Using this I am getting the value in 2nd activity.
Whats going wrong??
Please help...
I am not getting the updated address in edit text view..
ChooseFromMapActivity
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
String value=str.toString();
intent.putExtra("value",value);
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSend
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
Location l=new Location();
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
//Bundle bundle = getIntent().getParcelableExtra("bundle");
// double fromPosition = bundle.getParcelable("from_position");
// edtxt_from.setText(fromPosition);
/* Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("Longitude");
edtxt_from.setText(String.valueOf(latitude));*/
Intent intent = this.getIntent();
String data = intent.getStringExtra("value");
edtxt_from.setText(data);
// Bundle bundle = intent.getExtras();
// Serializable value =bundle.getSerializable("value");
// edtxt_from.setText(String.valueOf(longitude));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}

Change
String data = intent.getStringExtra("keyName");
to
String data = intent.getStringExtra("value");
You were using the wrong key.

simply do :
Replace keyName by value

Related

Getting My Location Null pointer in Fragment in GoogleMap API v2

I'm trying to get my location on click of save button & store that in
database.
Problem:
When I'm trying to get my location it shows me null pointer exception.
Can anyone tell me whats wrong in my code?
My code:
public class OthersFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
View view;
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Double latitude;
Double longitude;
String strplace;
public static OthersFragment newInstance() {
OthersFragment fragment = new OthersFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mGoogleApiClient = new GoogleApiClient.Builder(getContext())
// .addApi(LocationServices.API)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this)
// .build();
view = inflater.inflate(R.layout.fragment_other, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location mylocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
ShowPopUp(mylocation);
return true;
}
});
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
private void ShowPopUp(final Location mylocation) {
int popupWidth = 300;
int popupHeight = 150;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout)view.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow();
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 30;
int OFFSET_Y = 30;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, + OFFSET_X, OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
Button save = (Button) layout.findViewById(R.id.save);
Button retrieve = (Button) layout.findViewById(R.id.retrieve);
final EditText place = (EditText)layout.findViewById(R.id.place);
final EditText phone = (EditText)layout.findViewById(R.id.phone);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "save";
String strplace = place.getText().toString();
String strphone = phone.getText().toString();
new storePoints().execute(strplace,String.valueOf(mylocation.getLatitude()), String.valueOf(mylocation.getLongitude()), action);
popup.dismiss();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "retrieve";
strplace = place.getText().toString();
String strphone = phone.getText().toString();
new retrievePoints().execute(strplace, action);
popup.dismiss();
}
});
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class storePoints extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
// String phone = (String) params[1];
String latitude = (String) params[1];
String longitude = (String) params[2];
String action = (String) params[3];
String link = "http://192.168.0.152/prestige/saveCoord.php";
// String link = "http://10.0.2.2/coordinates/coord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
// data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
data += "&" + URLEncoder.encode("latitude", "UTF-8") + "=" + URLEncoder.encode(latitude, "UTF-8");
data += "&" + URLEncoder.encode("longitude", "UTF-8") + "=" + URLEncoder.encode(longitude, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(OthersFragment.this.getContext(), result, Toast.LENGTH_LONG).show();
}
}
private class retrievePoints extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
String phone = (String) params[1];
String link = "http://192.168.0.152/prestige/retCoord.php";
// String link = "http://10.0.2.2/coordinates/retCoord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
try {
mMap.clear(); // clear all the markers on the map.
JSONArray loc_arr = new JSONArray(result);
for (int i = 0; i < loc_arr.length(); i++){
JSONObject loc_obj = loc_arr.getJSONObject(i);
Double latitude = Double.valueOf((loc_obj.getString("latitude")));
Double longitude = Double.valueOf((loc_obj.getString("longitude")));
String place = loc_obj.getString("station_name");
// Toast.makeText(MainActivity.this, "latitude: "+latitude +"\t Longitude: " + longitude+"\t Place: "+place, Toast.LENGTH_SHORT).show();
Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Place: "+place).snippet("Latitude: " +latitude+",Longitude: "+longitude));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),28));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Error Log:
06-20 12:30:42.740 6682-6682/com.example.barbegambino.apslocate E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.barbegambino.apslocate, PID: 6682
java.lang.NullPointerException
at com.example.barbegambino.apslocate.fragments.OthersFragment$2.onClick(OthersFragment.java:166)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18789)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
For example try to get last-known location like below,
public class MapExample extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// work with your last location.
} else {
Toast.makeText(this, R.string.no_location, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
I added this and it worked for me.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_entry, null, false);
//added
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(getContext(), "Google Play Services is not available", Toast.LENGTH_LONG).show();
getActivity().finish();
}
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
This also i added
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
Toast.makeText(getContext(), "Google Play Services is not Available", Toast.LENGTH_LONG).show();
return false;
}
}

My app is crashing when i give Space bar in autocompletetextview

My app is crashing when i give space bar in autocompletetextview.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
LocationListener, AdapterView.OnItemClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker,FindMarker;
LocationRequest mLocationRequest;
AutoCompleteTextView atvPlaces;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
LatLng latLng;
final int PLACES = 0;
final int PLACES_DETAILS = 1;
ListView lv;
ImageButton remove;
private boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onLocationChanged(mLastLocation);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
remove = (ImageButton)findViewById(R.id.place_autocomplete_clear_button);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (AutoCompleteTextView) findViewById(R.id.id_search_EditText);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
if (!atvPlaces.getText().toString().equals("")){
lv.setVisibility(View.VISIBLE);
remove.setVisibility(View.VISIBLE);
}else {
lv.setVisibility(View.GONE);
remove.setVisibility(View.GONE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Setting an item click listener for the AutoCompleteTextView dropdown list
/* atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
});*/
lv=(ListView)findViewById(R.id.list);
lv.setOnItemClickListener(this);
setListenerOnWidget();
}
private void setListenerOnWidget() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
atvPlaces.setText("");
}
};
remove.setOnClickListener(listener);
}
#Override
public void onBackPressed() {
if(exit){
finish();
}else {
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
ListView lv = (ListView) adapterView;
SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(i);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str.replace(' ',','));
lv.setVisibility(view.GONE);
}
private String getPlaceDetailsUrl(String ref) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyCQNRAkYhQ4CDwDV-0Oh-kNFdrUY1NwSI0";
// reference of place
String reference = "reference=" + ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;
return url;
}
private String getAutoCompleteUrl(String place) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyCQNRAkYhQ4CDwDV-0Oh-kNFdrUY1NwSI0";
// place to be be searched
String input = "input=" + place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
return url;
}
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;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(1000);
//mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(mCurrLocationMarker != null){
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOption);
Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
loadNearByPlaces(location.getLatitude(), location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void loadNearByPlaces(double latitude, double longitude) {
//YOU Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works
String type = "liquor";
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
}
private void parseLocationResult(JSONObject result) {
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try {
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK)) {
//mMap.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(ATM_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
vicinity = place.getString(VICINITY);
}
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
markerOptions.snippet(vicinity);
mMap.addMarker(markerOptions);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View myContentsView = getLayoutInflater().inflate(R.layout.marker, null);
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
});
}
Toast.makeText(getBaseContext(), jsonArray.length() + " ATM_FOUND!",
Toast.LENGTH_SHORT).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No ATM found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
}
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
//atvPlaces.setAdapter(adapter);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.row,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
loadNearByPlaces(address.getLatitude(), address.getLongitude());
}
}
}
}
Add trim() while getAutoCompleteUrl()
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString().trim());
....
}
add this line:
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
}
for(int i=0;i<addresses.size();i++){
....

Map showing starting point. And start point then end point is the same.

Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?
this code Map.java
public class Map extends FragmentActivity implements LocationListener {
SQLiteDatabase SQL;
GoogleMap map;
myDBClass DB;
Cursor cursor;
ArrayList<LatLng> MarkerPoint = new ArrayList<LatLng>();
double latitude = 0;
double longtitude = 0;
GMapV2Direction md = new GMapV2Direction();
Document document;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_map);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
//map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Destination Marker from Database SQLite
if (MarkerPoint.size() > 1) {
String Name = getIntent().getStringExtra("Name");
DB = new myDBClass(this);
SQL = DB.getWritableDatabase();
cursor = SQL.rawQuery("SELECT *" + " FROM "
+ myDBClass.TABLE_NAME + " WHERE " + myDBClass.NAME
+ " ='" + Name + "'", null);
cursor.moveToFirst();
/**String name = cursor.getString(cursor.getColumnIndex(myDBClass.NAME));
double lat_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
double lng_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
map.addMarker(new MarkerOptions()
.position(new LatLng(lat_db, lng_db)) .title(name));**/
latitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
longtitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
cursor.moveToNext();
//MarkerPoint.clear();
//map.clear();
LatLng strpoint = new LatLng(latitude, longtitude);
drawMarker(strpoint);
}
}
DrawRouteTask drawroute = new DrawRouteTask();
drawroute.execute();
}
private class DrawRouteTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(Map.this);
Dialog.setMessage("Loading");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
// Get All Route values
if (MarkerPoint.size() >= 2) {
LatLng Start = MarkerPoint.get(0);
LatLng End = MarkerPoint.get(1);
document = md.getDocument(Start, End,GMapV2Direction.MODE_DRIVING);
response = "Success";
}
return response;
}
#Override
protected void onPostExecute(String result) {
try {
if (response.equalsIgnoreCase("Success")) {
ArrayList<LatLng> directionPoint = md.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
} catch (Exception e) {
// TODO:ERROR TRACE ROUTE
}
Dialog.dismiss();
}
}
private void drawMarker(LatLng point) {
MarkerPoint.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (MarkerPoint.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoint.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
map.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (MarkerPoint.size() < 2) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
LatLng point = new LatLng(latitude, longtitude);
map.moveCamera(CameraUpdateFactory.newLatLng(point));
map.animateCamera(CameraUpdateFactory.zoomTo(6));
drawMarker(point);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
http://i.stack.imgur.com/SXq5P.jpg
Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?

Positing user current location and show it in Google maps

I am developing an android application that contains 3 activities and one of them is map. I am using google maps
what I want:
When the user opens the activity (map) it shows the user her location not the coordinate.
The user should also be able to posit(pining) any place by using a pin and my app must store the coordinates for this pin in a variable so i can use it later.
public class LActivity extends MapActivity
{
/** Called when the activity is first created. */
MapView mapView;
GeoPoint geo;
MapController mapController;
LocationManager locationManager;
CustomPinpoint itemizedoverlay;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// create a map view
//LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
mapView.setBuiltInZoomControls(true);
// Either satellite or 2d
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
this is CustomPinpoint class
public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {
static int maxNum = 3;
OverlayItem overlays[] = new OverlayItem[maxNum];
int index = 0;
boolean full = false;
CustomPinpoint itemizedoverlay;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
#Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (index < maxNum) {
overlays[index] = overlay;
} else {
index = 0;
full = true;
overlays[index] = overlay;
}
index++;
populate();
}
}
I have implemented the same thing you want. I am providing you the sample code. In this I have also implemented the ProgressDialog when fetching the location.
This is the starting point for getting the location. I named this AndroidLocationActivity. This is the 1st activity which starts when your app starts.
String provider;
public double latitude, longitude = 0;
CurrentPositionTask getCurrentLocation;
Location currentLocation;
LocationListener locationListener;
LocationManager locationManager;
private long time=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setCriteria();
currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(provider);
if (currentLocation == null) {
currentLocation = new Location(provider);
}
time = currentLocation.getTime();
if (latitude == 0 && longitude == 0) {
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
Toast.makeText(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
Here set the time if time is not more than 1minute than i am not updating the location.
if (time >= 100000) {
latitude = 0;
longitude = 0;
}
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
runAsyncTask();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
locationManager.removeUpdates(locationListener);
}
public void setCriteria() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
provider = locationManager.getBestProvider(criteria, true);
Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
if (provider == null) {
provider = LocationManager.GPS_PROVIDER;
}
}
public void runAsyncTask() {
// TODO Auto-generated method stub
if (getCurrentLocation == null) {
getCurrentLocation = new CurrentPositionTask();
}
if (getCurrentLocation != null) {
getCurrentLocation.execute("Searching for Location");
}
}
public boolean checkConnection()
{
//ARE WE CONNECTED TO THE NET
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (AndroidLocationActivity.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private class CurrentPositionTask extends AsyncTask<String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(AndroidLocationActivity.this);
private boolean flag = true;
public CurrentPositionTask() {
locationListener = new MyLocationListener();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
try {
if (checkConnection()) {
Dialog.setTitle("Loading");
Dialog.setMessage("Searching for Location");
Dialog.show();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
else {
Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
while (flag) {
if (latitude !=0 && longitude != 0) {
flag=false;
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidLocationActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
if (Dialog != null && Dialog.isShowing()) {
Dialog.dismiss();
time=0;
Intent homeIntent = new Intent(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);
set the lat & lng here and start new activity
homeIntent.putExtra("lat", latitude);
homeIntent.putExtra("lng", longitude);
startActivity(homeIntent);
}
locationManager.removeUpdates(locationListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is the function in which i am displaying the Map. This is the HomeMenuActivity
public static Context context;
onCreate(..) {
context = getApplicationContext(); // it will be used in Itemized Overlay
latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
longitude = getIntent().getDoubleExtra("lng", 0);
}
public void showMap() {
// TODO Auto-generated method stub
try {
geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));
mapview = (MapView)findViewById(R.id.mapview);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapview.setTraffic(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(your pic....);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ItemizedOverlay Class
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
Hope this will help.....
Remove your method onCreate and add this code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
initMap(); // This is the method which initialize the map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
#Override
public void onResume()
{
super.onResume();
try
{
initMyLocation();
}catch(Exception e){}
}
/**
* Inits the map.
*/
protected void initMap()
{
mapView = (MyMapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapView.setStreetView(false);
mapController = mapView.getController();
mapOverlay = new MapOverlay();
List<Overlay> overlays = mapView.getOverlays();
overlays.add(mapOverlay);
mapController.setZoom(14);
mapView.invalidate();
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map.
*/
public void initMyLocation() {
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location l = LocationService.getLastKnownLocation(lm);
int lat = (int)(l.getLatitude()*1E6);
int lng = (int)(l.getLongitude()*1E6);
mapController.setCenter(new GeoPoint(lat , lng));
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
mapController.setCenter(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
findMe();
}
/**
* This method will animate to my current position
*/
public void findMe()
{
try
{
mapController.animateTo(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
}
Then to store the Overlays for future use you can either use SharedPreferences or SQLite. There are loads of tutorials for each of them.

Making a Toast message from a separate Thread

I try to send a Toast Message from a Thread to the UIThread when clicking a button.
However, every time I click the button the Toast does not appear.
I am using a Handler to do this.
This is the full code, in case I made a major mistake somewhere:
package google.map.activity;
//imports
public class GoogleMapActivity extends MapActivity {
int lat = 0;
int lng = 0;
Location location;
MapController mc;
GeoPoint p;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.googlemapactivity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(false);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(19);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5,
0, new GeoUpdateHandler());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5, 0, new GeoUpdateHandler());
// //////---Switch to
// Start/////////////////////////////////////////////////////////////////////////////
Button switchToMain = (Button) findViewById(R.id.switchtomain);
switchToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// ////--Call a
// Cab/////////////////////////////////////////////////////////////////////////////////////
Button getCab = (Button) findViewById(R.id.GetCab); // create the Button
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
getCab.setOnClickListener(new View.OnClickListener() {
String bestProvider = locationManager.getBestProvider(criteria,
true);
Location locationTest = locationManager
.getLastKnownLocation(bestProvider); // get
// last
// known
// location fix from
// locationManager
public void getAddress() {
String msg = null;
Looper.prepare();
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());// create
// new
// GeoCoder
String result = null; // initialize result
try { // try to get Address list from location of bestProvider
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", "
+ address.getLocality();// set result
// to
// Streetname+Nr.
// and City
}
} catch (IOException e) {
msg = String.format("IOException!!");
} finally {
if (result != null) {
msg = String.format(result);
// Looper.loop();
} else
msg = String.format("Keine Position");
}
Message myMessage = new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", msg);
myMessage.obj = resBundle;
handler.sendMessage(myMessage);
}
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Looper.myLooper();
// Looper.prepare();
getAddress(); // get the Address
Location locationTest = locationManager
.getLastKnownLocation(bestProvider);
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location2 = locationManager
.getLastKnownLocation(bestProvider);
int lat = (int) (location2.getLatitude() * 1E6); // get
// position
// for GeoPoint
int lng = (int) (location2.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng); // create
// GeoPoint
// for
// mapController
mapController.animateTo(point);
}
}).start();
// toast.show();
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), msg.toString(),
Toast.LENGTH_LONG);
}
};
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Thank you in advance!
Edit: Solved it by using this:
Handler toastHandler = new Handler();
Runnable toastRunnable = new Runnable() {public void run() {Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();}};
In the UIThread and this:
toastHandler.post(toastRunnable);
in the background thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
// Here you can make a Toast
}
});
Your toast needs to be done in the UI thread. Here's how to do that:
Note: ClassName.this is needed because this by itself will refer to your anonymous Runnable class.
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(ClassName.this, R.string.something, Toast.LENGTH_LONG).show();
}
});

Categories

Resources