android studio accessing properties of an object from different method - java

I am a beginner and this may be programming basics that I am missing here, but this is the only way I'll learn these things.
Below is my MainActivity code. It is trying to get details of the last location and read them into a class which I defined (class is called UserCurrentAddress) so that I can use those details.
I have declared the UserCurrentAddress class in the MainActivity class and then instantiated in the onCreate. I then use a button click (onClickView) at the bottom of the code to connect the API and get the location. The "handleNewLocation" method eventually populates the UserCurrentAddress object (and this works successfully). However when I try to read those details from the UserCurrentAddress in the buttonClick event (just using a Toast) it comes back as null. If I put that toast in the "handleNewLocation" then it is correctly populated.
Why is it that the properties of the UserCurrentAddress are not visible from the buttonClick event?
I thought by declaring it in the Activity Class it would be visible throughout.
I realise I can probably do what I need to do within the "handleNewLocation" method, but it would be preferable to have access to those properties from outside that event.
I hope I've managed to explain my issue.
Code:
package com.example.android.trainingapp;
import android.content.IntentSender;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener{
private GoogleApiClient mGoogleAPIClient;
private UserCurrentAddress userCurrentAddress;
Button bFindLocation;
private LocationRequest mlocationRequest;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bFindLocation = (Button) findViewById(R.id.show_location);
bFindLocation.setOnClickListener(this);
mGoogleAPIClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mlocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
userCurrentAddress = new UserCurrentAddress(null, null, null, null, null, 0, 0, null);
}
#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(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleAPIClient);
if(location==null){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mlocationRequest, (LocationListener) this);
}
else{
handleNewLocation(location);
}
}
public void handleNewLocation(Location location){
double currentLatitude, currentLongitude;
String addressOne, addressTwo, streetNumber, country, fullAddress, postCode, myAdress;
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(currentLatitude, currentLongitude, 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(" ");
}
streetNumber = returnedAddress.getSubThoroughfare();
addressOne = returnedAddress.getThoroughfare(); //Beech Rd
addressTwo = returnedAddress.getLocality(); //durban north
postCode = returnedAddress.getPostalCode();
country = returnedAddress.getCountryName();
myAdress = strReturnedAddress.toString();
userCurrentAddress.streetNumber = streetNumber;
userCurrentAddress.addressOne = addressOne;
userCurrentAddress.addressTwo = addressTwo;
userCurrentAddress.postCode = postCode;
userCurrentAddress.country =country ;
userCurrentAddress.latitude = currentLatitude;
userCurrentAddress.longitude = currentLongitude;
userCurrentAddress.fullAddress = myAdress;
Toast.makeText(this, userCurrentAddress.streetNumber, Toast.LENGTH_LONG).show();
}
else{
myAdress = "No Address Returned";
}
} catch (IOException e) {
e.printStackTrace();
myAdress = "Cannot get address";
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.show_location:
mGoogleAPIClient.connect();
Toast.makeText(this, userCurrentAddress.fullAddress, Toast.LENGTH_LONG).show();
}
}
}

From what you're describing, this line:
userCurrentAddress = new UserCurrentAddress(null, null, null, null, null, 0, 0, null);
must be getting executed after the handleNewLocation() call.
Try moving that line to a spot before the GoogleApiClient.Builder calls and see if that makes any difference.

Related

Update TextView after changing location on Google Maps

I have a problem with my code which should display the latitude and longitude of the current position. I have tried simply setting the text in TextView object, unfortunately, it displays mentioned values just one time (at the beginning). I would like to ask you how can I change this behavior to have "live" coordinates update.
There is my code
package com.example.currentplacedetailsonmap;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.PlaceLikelihood;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import org.w3c.dom.Text;
import java.util.Arrays;
import java.util.List;
import static com.example.currentplacedetailsonmap.R.id.coordinates;
/**
* An activity that displays a map showing the place at the device's current location.
*/
public class MapsActivityCurrentPlace extends AppCompatActivity
implements OnMapReadyCallback {
private static final String TAG = MapsActivityCurrentPlace.class.getSimpleName();
private GoogleMap map;
// The entry point to the Places API.
private PlacesClient placesClient;
// The entry point to the Fused Location Provider.
private FusedLocationProviderClient fusedLocationProviderClient;
// A default location (Sydney, Australia) and default zoom to use when location permission is
// not granted.
private final LatLng defaultLocation = new LatLng(-33.8523341, 151.2106085);
private static final int DEFAULT_ZOOM = 15;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private boolean locationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location lastKnownLocation;
// Keys for storing activity state.
// [START maps_current_place_state_keys]
private static final String KEY_CAMERA_POSITION = "camera_position";
private static final String KEY_LOCATION = "location";
// [END maps_current_place_state_keys]
// Used for selecting the current place.
private static final int M_MAX_ENTRIES = 5;
private String[] likelyPlaceNames;
private String[] likelyPlaceAddresses;
private List[] likelyPlaceAttributions;
private LatLng[] likelyPlaceLatLngs;
// [START maps_current_place_on_create]
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// [START_EXCLUDE silent]
// [START maps_current_place_on_create_save_instance_state]
// Retrieve location and camera position from saved instance state.
if (savedInstanceState != null) {
lastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
}
// [END maps_current_place_on_create_save_instance_state]
// [END_EXCLUDE]
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_maps);
// [START_EXCLUDE silent]
// Construct a PlacesClient
Places.initialize(getApplicationContext(), BuildConfig.MAPS_API_KEY);
placesClient = Places.createClient(this);
// Construct a FusedLocationProviderClient.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
// Build the map.
// [START maps_current_place_map_fragment]
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// [END maps_current_place_map_fragment]
// [END_EXCLUDE]
}
// [END maps_current_place_on_create]
/**
* Saves the state of the map when the activity is paused.
*/
// [START maps_current_place_on_save_instance_state]
#Override
protected void onSaveInstanceState(Bundle outState) {
if (map != null) {
outState.putParcelable(KEY_CAMERA_POSITION, map.getCameraPosition());
outState.putParcelable(KEY_LOCATION, lastKnownLocation);
}
super.onSaveInstanceState(outState);
}
// [END maps_current_place_on_save_instance_state]
/**
* Sets up the options menu.
* #param menu The options menu.
* #return Boolean.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.current_place_menu, menu);
return true;
}
/**
* Handles a click on the menu option to get a place.
* #param item The menu item to handle.
* #return Boolean.
*/
// [START maps_current_place_on_options_item_selected]
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.option_get_place) {
showCurrentPlace();
}
return true;
}
// [END maps_current_place_on_options_item_selected]
/**
* Manipulates the map when it's available.
* This callback is triggered when the map is ready to be used.
*/
// [START maps_current_place_on_map_ready]
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
// [START_EXCLUDE]
// [START map_current_place_set_info_window_adapter]
// Use a custom info window adapter to handle multiple lines of text in the
// info window contents.
this.map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
// Return null here, so that getInfoContents() is called next.
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Inflate the layouts for the info window, title and snippet.
View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
(FrameLayout) findViewById(R.id.map), false);
TextView title = infoWindow.findViewById(R.id.title);
title.setText(marker.getTitle());
TextView snippet = infoWindow.findViewById(R.id.snippet);
snippet.setText(marker.getSnippet());
return infoWindow;
}
});
// [END map_current_place_set_info_window_adapter]
// Prompt the user for permission.
getLocationPermission();
// [END_EXCLUDE]
// Turn on the My Location layer and the related control on the map.
updateLocationUI();
// Get the current location of the device and set the position of the map.
getDeviceLocation();
}
// [END maps_current_place_on_map_ready]
/**
* Gets the current location of the device, and positions the map's camera.
*/
// [START maps_current_place_get_device_location]
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (locationPermissionGranted) {
Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
lastKnownLocation = task.getResult();
if (lastKnownLocation != null) {
TextView coordinates = (TextView) findViewById(R.id.coordinates);
LatLng latLng = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
coordinates.setText(latLng.toString());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
map.moveCamera(CameraUpdateFactory
.newLatLngZoom(defaultLocation, DEFAULT_ZOOM));
map.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage(), e);
}
}
// [END maps_current_place_get_device_location]
/**
* Prompts the user for permission to use the device location.
*/
// [START maps_current_place_location_permission]
private void getLocationPermission() {
/*
* Request location permission, so that we can get the location of the
* device. The result of the permission request is handled by a callback,
* onRequestPermissionsResult.
*/
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
// [END maps_current_place_location_permission]
/**
* Handles the result of the request for location permissions.
*/
// [START maps_current_place_on_request_permissions_result]
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
locationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true;
}
}
}
updateLocationUI();
}
// [END maps_current_place_on_request_permissions_result]
/**
* Prompts the user to select the current place from a list of likely places, and shows the
* current place on the map - provided the user has granted location permission.
*/
// [START maps_current_place_show_current_place]
private void showCurrentPlace() {
if (map == null) {
return;
}
if (locationPermissionGranted) {
// Use fields to define the data types to return.
List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME, Place.Field.ADDRESS,
Place.Field.LAT_LNG);
// Use the builder to create a FindCurrentPlaceRequest.
FindCurrentPlaceRequest request =
FindCurrentPlaceRequest.newInstance(placeFields);
// Get the likely places - that is, the businesses and other points of interest that
// are the best match for the device's current location.
#SuppressWarnings("MissingPermission") final
Task<FindCurrentPlaceResponse> placeResult =
placesClient.findCurrentPlace(request);
placeResult.addOnCompleteListener (new OnCompleteListener<FindCurrentPlaceResponse>() {
#Override
public void onComplete(#NonNull Task<FindCurrentPlaceResponse> task) {
if (task.isSuccessful() && task.getResult() != null) {
FindCurrentPlaceResponse likelyPlaces = task.getResult();
// Set the count, handling cases where less than 5 entries are returned.
int count;
if (likelyPlaces.getPlaceLikelihoods().size() < M_MAX_ENTRIES) {
count = likelyPlaces.getPlaceLikelihoods().size();
} else {
count = M_MAX_ENTRIES;
}
int i = 0;
likelyPlaceNames = new String[count];
likelyPlaceAddresses = new String[count];
likelyPlaceAttributions = new List[count];
likelyPlaceLatLngs = new LatLng[count];
for (PlaceLikelihood placeLikelihood : likelyPlaces.getPlaceLikelihoods()) {
// Build a list of likely places to show the user.
likelyPlaceNames[i] = placeLikelihood.getPlace().getName();
likelyPlaceAddresses[i] = placeLikelihood.getPlace().getAddress();
likelyPlaceAttributions[i] = placeLikelihood.getPlace()
.getAttributions();
likelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
i++;
if (i > (count - 1)) {
break;
}
}
// Show a dialog offering the user the list of likely places, and add a
// marker at the selected place.
MapsActivityCurrentPlace.this.openPlacesDialog();
}
else {
Log.e(TAG, "Exception: %s", task.getException());
}
}
});
} else {
// The user has not granted permission.
Log.i(TAG, "The user did not grant location permission.");
// Add a default marker, because the user hasn't selected a place.
map.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(defaultLocation)
.snippet(getString(R.string.default_info_snippet)));
// Prompt the user for permission.
getLocationPermission();
}
}
// [END maps_current_place_show_current_place]
/**
* Displays a form allowing the user to select a place from a list of likely places.
*/
// [START maps_current_place_open_places_dialog]
private void openPlacesDialog() {
// Ask the user to choose the place where they are now.
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// The "which" argument contains the position of the selected item.
LatLng markerLatLng = likelyPlaceLatLngs[which];
String markerSnippet = likelyPlaceAddresses[which];
if (likelyPlaceAttributions[which] != null) {
markerSnippet = markerSnippet + "\n" + likelyPlaceAttributions[which];
}
// Add a marker for the selected place, with an info window
// showing information about that place.
map.addMarker(new MarkerOptions()
.title(likelyPlaceNames[which])
.position(markerLatLng)
.snippet(markerSnippet));
// Position the map's camera at the location of the marker.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
DEFAULT_ZOOM));
}
};
}
// [END maps_current_place_open_places_dialog]
/**
* Updates the map's UI settings based on whether the user has granted location permission.
*/
// [START maps_current_place_update_location_ui]
private void updateLocationUI() {
if (map == null) {
return;
}
try {
if (locationPermissionGranted) {
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(true);
} else {
map.setMyLocationEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
lastKnownLocation = null;
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
// [END maps_current_place_update_location_ui]
}
Especially part with my failed textbox update
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (locationPermissionGranted) {
Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
lastKnownLocation = task.getResult();
if (lastKnownLocation != null) {
TextView coordinates = (TextView) findViewById(R.id.coordinates);
LatLng latLng = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
coordinates.setText(latLng.toString());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
map.moveCamera(CameraUpdateFactory
.newLatLngZoom(defaultLocation, DEFAULT_ZOOM));
map.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage(), e);
}
}
Thanks in advance for your responses.

how i can run the onNavigationItemSelected method in background thread

The app crashes when I write mNavigationView.setNavigationItemSelectedListener(this); in the code
and if it is not added it removes the functionality of the item in the navigation bar. Which method I should run in a background thread to reduce the effect on the main thread.
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.eggheadgames.aboutbox.AboutConfig;
import com.eggheadgames.aboutbox.IAnalytic;
import com.eggheadgames.aboutbox.IDialog;
import com.eggheadgames.aboutbox.activity.AboutActivity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class EarthquakeActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener, SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks<List<Earthquake>>, NavigationView.OnNavigationItemSelectedListener {
public static final String MyPrefs = "MyPrefs";
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mToogle;
/** URL for earthquake data from the USGS dataset */
private static final String USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query";
/**
* Constant value for the earthquake loader ID. We can choose any integer.
* This really only comes into play if you're using multiple loaders.
*/
private static final int EARTHQUAKE_LOADER_ID = 1;
/** Adapter for the list of earthquakes */
private EarthquakeAdapter mAdapter;
/** TextView that is displayed when the list is empty */
private TextView mEmptyStateTextView;
SwipeRefreshLayout swipe;
private static final String LOG_TAG = EarthquakeActivity.class.getSimpleName();
private ListView earthquakeListView;
private static final String TWITTER_USER_NAME = "vaibhav_khulbe";
private static final String WEB_HOME_PAGE = "https://about.me/vaibhav_khulbe";
private static final String APP_PUBLISHER = "https://play.google.com/store/apps/developer?id=Vaibhav%20Khulbe&hl=en";
private static final String EMAIL_ADDRESS = "khulbevaibhavdev#gmail.com";
private static final String EMAIL_SUBJECT = "Quake Info app acknowledgements and/or issues";
private static final String EMAIL_BODY = "Please explain your experience with this app here...This may include bugs" +
" or issues you may be facing or what you liked about the app along with improvements. :) (MAKE SURE to clear out these lines before sending the mail to us)";
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
mdrawerlayout=(DrawerLayout)findViewById(R.id.drawer);
mToogle=new ActionBarDrawerToggle(this,mdrawerlayout,R.string.open,R.string.close);
mdrawerlayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView=(NavigationView)findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
swipe = findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(this);
swipe.setColorSchemeColors(getResources().getColor(R.color.colorAccent));
/* Start the intro only once */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class);
startActivity(intent);
}
//Call and launch About activity
initAboutActivity();
// Find a reference to the {#link ListView} in the layout
earthquakeListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
earthquakeListView.setEmptyView(mEmptyStateTextView);
// Create a new adapter that takes an empty list of earthquakes as input
mAdapter = new EarthquakeAdapter(this, new ArrayList<Earthquake>());
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(mAdapter);
// Obtain a reference to the SharedPreferences file for this app
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// And register to be notified of preference changes
// So we know when the user has adjusted the query settings
prefs.registerOnSharedPreferenceChangeListener(this);
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected earthquake.
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current earthquake that was clicked on
Earthquake currentEarthquake = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri earthquakeUri = Uri.parse(currentEarthquake.getUrl());
// Create a new intent to view the earthquake URI
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);
// Send the intent to launch a new activity
startActivity(websiteIntent);
}
});
getSupportLoaderManager().initLoader(EARTHQUAKE_LOADER_ID, null, this);
}
/*Code to launch About activity */
public void initAboutActivity()
{
/* Create About activity */
AboutConfig aboutConfig = AboutConfig.getInstance();
aboutConfig.appName = getString(R.string.app_name);
aboutConfig.appIcon = R.mipmap.ic_launcher;
aboutConfig.version = "1.0.0";
aboutConfig.author = "Vaibhav Khulbe";
aboutConfig.aboutLabelTitle = "About";
aboutConfig.packageName = getApplicationContext().getPackageName();
aboutConfig.appPublisher = APP_PUBLISHER;
aboutConfig.twitterUserName = TWITTER_USER_NAME;
aboutConfig.webHomePage = WEB_HOME_PAGE;
aboutConfig.dialog = new IDialog() {
#Override
public void open(AppCompatActivity appCompatActivity, String url, String tag) {
// handle custom implementations of WebView. It will be called when user click to web items. (Example: "Privacy", "Acknowledgments" and "About")
}
};
aboutConfig.analytics = new IAnalytic() {
#Override
public void logUiEvent(String s, String s1) {
// handle log events.
}
#Override
public void logException(Exception e, boolean b) {
// handle exception events.
}
};
// set it only if aboutConfig.analytics is defined.
aboutConfig.logUiEventName = "Log";
// Contact Support email details
aboutConfig.emailAddress = EMAIL_ADDRESS;
aboutConfig.emailSubject = EMAIL_SUBJECT;
aboutConfig.emailBody = EMAIL_BODY;
aboutConfig.shareMessage = getString(R.string.share_message);
aboutConfig.sharingTitle = getString(R.string.sharing_title);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(getString(R.string.settings_min_magnitude_key)) ||
key.equals(getString(R.string.settings_order_by_key))){
// Clear the ListView as a new query will be kicked off
mAdapter.clear();
// Hide the empty state text view as the loading indicator will be displayed
mEmptyStateTextView.setVisibility(View.GONE);
// Show the loading indicator while new data is being fetched
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.VISIBLE);
// Restart the loader to requery the USGS as the query settings have been updated
getSupportLoaderManager().restartLoader(EARTHQUAKE_LOADER_ID, null, this);
}
}
#Override
public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String minMagnitude = sharedPrefs.getString(
getString(R.string.settings_min_magnitude_key),
getString(R.string.settings_min_magnitude_default));
String orderBy = sharedPrefs.getString(
getString(R.string.settings_order_by_key),
getString(R.string.settings_order_by_default)
);
String region = sharedPrefs.getString(
getString(R.string.settings_narrow_by_region_key),
getString(R.string.settings_narrow_by_region_default)
);
String radius = sharedPrefs.getString(
getString(R.string.settings_maximum_radius_key),
getString(R.string.settings_maximum_radius_default)
);
List<Country> countries = new ArrayList<>();
try {
countries = Utils.generateCountryList(this);
} catch (IOException e) {
e.printStackTrace();
}
Double latitude = 0.0;
Double longitude = 0.0;
for (Country country : countries) {
if(country.getName().equalsIgnoreCase(region)){
latitude = country.getLatitude();
longitude = country.getLongitude();
}
}
Uri baseUri = Uri.parse(USGS_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("format", "geojson");
uriBuilder.appendQueryParameter("limit", "100");
uriBuilder.appendQueryParameter("minmag", minMagnitude);
uriBuilder.appendQueryParameter("orderby", orderBy);
if(latitude != 0.0 && longitude != 0.0){
uriBuilder.appendQueryParameter("latitude", String.valueOf(latitude.intValue()));
uriBuilder.appendQueryParameter("longitude", String.valueOf(longitude.intValue()));
uriBuilder.appendQueryParameter("maxradius", radius);
}
String url = uriBuilder.toString();
return new EarthquakeLoader(this, url);
}
#Override
public void onLoadFinished(Loader<List<Earthquake>> loader, List<Earthquake> earthquakes) {
swipe.setRefreshing(false);
// Hide loading indicator because the data has been loaded
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
if (earthquakes != null && !earthquakes.isEmpty()) {
this.showResults(earthquakes);
} else {
this.hideResults();
}
}
#Override
public void onLoaderReset(Loader<List<Earthquake>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
/**
* method to show results
*/
private void showResults(List<Earthquake> earthquakeList) {
mAdapter.clear();
earthquakeListView.setVisibility(View.VISIBLE);
mEmptyStateTextView.setVisibility(View.GONE);
mAdapter.setNotifyOnChange(false);
mAdapter.setNotifyOnChange(true);
mAdapter.addAll(earthquakeList);
}
/**
* method to hide results also checks internet connection
*/
private void hideResults() {
earthquakeListView.setVisibility(View.GONE);
mEmptyStateTextView.setVisibility(View.VISIBLE);
// Get a reference to the ConnectivityManager to check state of network connectivity
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
mEmptyStateTextView.setText(R.string.no_earthquakes);
Log.e(LOG_TAG, "no earthquakes data");
} else {
mEmptyStateTextView.setText(R.string.no_internet_connection);
Log.e(LOG_TAG, "no internet");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToogle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onRefresh() {
getSupportLoaderManager().restartLoader(EARTHQUAKE_LOADER_ID, null, this);
Toast.makeText(this, R.string.list_refreshed, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
if (id == R.id.action_about) {
Intent actionIntent = new Intent(this, AboutActivity.class);
startActivity(actionIntent);
return true;
}
if (id == R.id.action_did_you_feel_it){
Intent feelItIntent = new Intent(this, DidYouFeel.class);
startActivity(feelItIntent);
return true;
}
if (id == R.id.action_more_apps){
Uri uri = Uri.parse( "https://play.google.com/store/apps/developer?id=Vaibhav+Khulbe" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
}
if (id == R.id.fork_project){
Uri uri = Uri.parse( "https://github.com/Kvaibhav01/Quake-Info" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
}
if (id == R.id.notification){
Intent notificationIntent = new Intent(this, EarthquakeNotification.class);
startActivity(notificationIntent);
}
return true;
}
}
I think it can be done by running the method in a background thread but I am not sure how to do that. Thanks for helping
you can use sample code like this:
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
//run another thread
}
});
or if you are familiar with RxJava you can use it.
consider that most of the time you should perform a function that you will call it after the click, not the click method.

I want to push a notification when exiting a Geofence in android studio

I am creating an app for my university that is supposed to push a notification when entering or exiting a geofence in android studio. The problem is that i can not think any way to code for sending a notification when exiting the geofence but the notification when entering a geofence works fine. here is my code thanks in advance
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GeofenceController.getInstance().init(this);
NamedGeofense geofence = new NamedGeofense();
geofence.name ="abbott";
geofence.latitude =38.037847; //your lati and longii :)
geofence.longitude =23.70083;
geofence.radius =100;
GeofenceController.getInstance().addGeofence(geofence);
}
#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);
}
NamedGeofence class
package com.example.adeeb.webviewfordigitalwaiter;
import com.google.android.gms.location.Geofence;
import java.util.UUID;
public class NamedGeofense {
public String id;
public String name;
public double latitude;
public double longitude;
public float radius;
// end region
// region Public
public Geofence geofence() {
id = UUID.randomUUID().toString();
// UUID is universal unique identifer. ref for you
// : https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
return new Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(latitude, longitude, radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
}
}
Geofence Controller class
package com.example.adeeb.webviewfordigitalwaiter;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GeofenceController {
// region Properties
private final String TAG = GeofenceController.class.getName();
private Context context;
private GoogleApiClient googleApiClient;
private Gson gson;
private SharedPreferences prefs;
private GeofenceControllerListener listener;
private List<NamedGeofense> namedGeofences;
private Geofence geofenceToAdd;
private NamedGeofense namedGeofenceToAdd;
// endregion
// region Shared Instance
private static GeofenceController INSTANCE;
public static GeofenceController getInstance() {
if (INSTANCE == null) {
INSTANCE = new GeofenceController();
}
return INSTANCE;
}
// endregion
// region Public
//we call this from main activity (in main activity we mde an instance of geofence controller
// using static method getInstance() (like this GeofenceController.getInstance().init(this);)
public void init(Context context) {
this.context = context.getApplicationContext();
gson = new Gson();
// namedGeofences is arraylist of my defined class name (namedGeofences)
// i will discuss namedGeofences class .. wait a moment.. :P
namedGeofences = new ArrayList<>();
prefs = this.context.getSharedPreferences(Constants.SharedPrefs.Geofences, Context.MODE_PRIVATE);
// prefs is shared prefrence (shared is a class or local storage where we store data so that
// our data might not lost when we move to other class or activity)
// variable.we assign our shared prefrence name which is define in Constants class
//public static String Geofences = "SHARED_PREFS_GEOFENCES";
loadGeofences();
// loadGeofences(); is my define method where we load geofences data if they are store
// in our sharedprefrences
}
// region ConnectionCallbacks
private GoogleApiClient.ConnectionCallbacks connectionAddListener = new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Intent intent = new Intent(context, AreWeThereIntentService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingResult<Status> result = LocationServices.GeofencingApi.
addGeofences(googleApiClient, getAddGeofencingRequest(), pendingIntent);
result.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
saveGeofence();
} else {
Log.e(TAG, "Registering geofence failed: " + status.getStatusMessage() + " : " + status.getStatusCode());
sendError();
}
}
});
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "Connecting to GoogleApiClient suspended.");
sendError();
}
};
public void addGeofence(NamedGeofense namedGeofence) {
this.namedGeofenceToAdd = namedGeofence;
this.geofenceToAdd = namedGeofence.geofence();
connectWithCallbacks(connectionAddListener);
}
// endregion
private GeofencingRequest getAddGeofencingRequest() {
List<Geofence> geofencesToAdd = new ArrayList<>();
geofencesToAdd.add(geofenceToAdd);
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(geofencesToAdd);
return builder.build();
}
private void saveGeofence() {
namedGeofences.add(namedGeofenceToAdd);
String json = gson.toJson(namedGeofenceToAdd);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(namedGeofenceToAdd.id, json);
editor.apply();
}
public interface GeofenceControllerListener {
void onGeofencesUpdated();
void onError();
}
public List<NamedGeofense> getNamedGeofences() {
return namedGeofences;
}
// endregion
// region Private
private void loadGeofences() {
// Map<String, ?> is A Map is a data structure consisting of a set of keys and values
// in which each key is mapped to a single value.
// we load geofences data if they are store
// in our sharedprefrences
Map<String, ?> keys = prefs.getAll();
// Loop over all geofence keys in prefs and add to namedGeofences
for (Map.Entry<String, ?> entry : keys.entrySet()) {
String jsonString = prefs.getString(entry.getKey(), null);
// gson is a library where we can store our whole class instance,
// below we assign previously store NamedGeofence class , and jsonString is key of that
// class
NamedGeofense namedGeofence = gson.fromJson(jsonString, NamedGeofense.class);
// than here we just add namedGeofence instance to our array list
namedGeofences.add(namedGeofence);
}
// Sort namedGeofences by name
}
private void connectWithCallbacks(GoogleApiClient.ConnectionCallbacks callbacks) {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(callbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
googleApiClient.connect();
}
private void sendError() {
if (listener != null) {
listener.onError();
}
}
// endregion
// region OnConnectionFailedListener
private GoogleApiClient.OnConnectionFailedListener connectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connecting to GoogleApiClient failed.");
sendError();
}
};
// endregion
// region Interfaces
// end region
}
Constant class
public class Constants {
public static class SharedPrefs {
public static String Geofences = "SHARED_PREFS_GEOFENCES";
}
}
ARE WE THERE YES SERVICE (HERES IS THE WHERE THE NOTIFICATIONS SHOULD BE PUT)
package com.example.adeeb.webviewfordigitalwaiter;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AreWeThereIntentService extends IntentService {
// region Properties
private final String TAG = AreWeThereIntentService.class.getName();
private SharedPreferences prefs;
private Gson gson;
// endregion
// region Constructors
public AreWeThereIntentService() {
super("AreWeThereIntentService");
}
// endregion
// region Overrides
#Override
protected void onHandleIntent(Intent intent) {
prefs = getApplicationContext().getSharedPreferences(Constants.SharedPrefs.Geofences, Context.MODE_PRIVATE);
gson = new Gson();
Log.e(TAG, "on handle :)");
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
if (event != null) {
Log.e(TAG, "event not null :) ");
if (event.hasError()) {
onError(event.getErrorCode());
} else {
int transition = event.getGeofenceTransition();
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<String> geofenceIds = new ArrayList<>();
for (Geofence geofence : event.getTriggeringGeofences()) {
geofenceIds.add(geofence.getRequestId());
}
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
onEnteredGeofences(geofenceIds);
Log.e(TAG, "transition enter :) ");
}
}
}
}
}
// endregion
// region Private
private void onEnteredGeofences(List<String> geofenceIds) {
Log.e(TAG, "on entergeofense: ");
for (String geofenceId : geofenceIds) {
String geofenceName = "";
// Loop over all geofence keys in prefs and retrieve NamedGeofence from SharedPreference
Map<String, ?> keys = prefs.getAll();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
String jsonString = prefs.getString(entry.getKey(), null);
NamedGeofense namedGeofence = gson.fromJson(jsonString, NamedGeofense.class);
if (namedGeofence.id.equals(geofenceId)) {
geofenceName = namedGeofence.name;
break;
}
}
// Set the notification text and send the notification
//String contextText = String.format("you entered in meeting room", geofenceName);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, GeofenceMain.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.pizaper2)
.setContentTitle("Welcome to geofense")
.setContentText("hello KOKALIS")
.setContentIntent(pendingNotificationIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText("hello KOKALIS"))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build(); // id
notificationManager.notify(0, notification);
Log.e(TAG, "notifications: ");
}
}
private void onError(int i) {
Log.e(TAG, "Geofencing Error: " + i);
}
// endregion
}
In your NamedGeofence class, change .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER) to .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT). Otherwise, you'd only monitor the enter events.
Transition types should be set as a bit-wise OR, as stated here.

WebService Login with android not working

I'm trying to login to a webservice from android studio linked to SQLserver
here's my Webservice.java:
package comt.example.user.sql_login_test_2;
import android.content.Context;
import android.widget.Toast;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class WebService {
public static String SOAP_ACTION = "http://tempuri.org/Logins";
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://localhost:3284/Service1.asmx";
public static boolean invokeLoginWS(String userName,String passWord, String webMethName) {
boolean loginStatus = false;
// Create request
SoapObject request = new SoapObject(NAMESPACE, webMethName);
// Property which holds input parameters
PropertyInfo unamePI = new PropertyInfo();
PropertyInfo passPI = new PropertyInfo();
// Set Username
unamePI.setName("Login");
// Set Value
unamePI.setValue(userName);
// Set dataType
unamePI.setType(String.class);
// Add the property to request object
request.addProperty(unamePI);
//Set Password
passPI.setName("UserPWD");
//Set dataType
passPI.setValue(passWord);
//Set dataType
passPI.setType(String.class);
//Add the property to request object
request.addProperty(passPI);
// Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// Set output SOAP object
envelope.setOutputSoapObject(request);
// Create HTTP call object
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
// Invoke web service
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
// Get the response
Object response = (Object) envelope.getResponse();
// Assign it to boolean variable variable
loginStatus = Boolean.parseBoolean(response.toString());/* HOW boolean from response to string ? */
} catch (Exception e) {
//Assign Error Status true in static variable 'errored'
CheckLoginActivity.errored = true;
e.printStackTrace();
}
//Return booleam to calling object
return loginStatus;
}
}
and That's my Main.java :
package comt.example.user.sql_login_test_2;
import android.content.Intent;
import android.os.AsyncTask;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity { /*input here function */
public static String OPERATION_NAME = "Logins"; /*hayde el Function Name*/
static boolean errored = false;
Button b;
TextView statusTV;
EditText userNameET , passWordET;
ProgressBar webservicePG;
String editTextUsername;
String editTextPassword;
boolean loginStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userNameET = (EditText) findViewById(R.id.editText1);
passWordET = (EditText) findViewById(R.id.editText2);
//Display Text control
statusTV = (TextView) findViewById(R.id.tv_result);
//Button to trigger web service invocation
b = (Button) findViewById(R.id.button1);
//Display progress bar until web service invocation completes
webservicePG = (ProgressBar) findViewById(R.id.progressBar1);
//Button Click Listener
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Check if text controls are not empty
Toast.makeText(getApplicationContext(),
"Waiting Please...", Toast.LENGTH_LONG).show();
if (userNameET.getText().length() != 0 && userNameET.getText().toString() != "") {
if (passWordET.getText().length() != 0 && passWordET.getText().toString() != "") {
editTextUsername = userNameET.getText().toString();
editTextPassword = passWordET.getText().toString();
statusTV.setText("");
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
task.execute(editTextUsername,editTextPassword);
}
//If Password text control is empty
else {
Toast.makeText(getApplicationContext(),
"please enter your Passwrod??", Toast.LENGTH_LONG).show();
}
//If Username text control is empty
} else {
Toast.makeText(getApplicationContext(),
"Please enter Username??", Toast.LENGTH_LONG).show();
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
//Call Web Method
loginStatus = WebService.invokeLoginWS(editTextUsername,editTextPassword,OPERATION_NAME);
//authenticateUser
return loginStatus;
}
#Override
//Once WebService returns response
public void onPostExecute(Boolean result) {
//Make Progress Bar invisible
webservicePG.setVisibility(View.INVISIBLE);
Intent intObj = new Intent(Main.this,Home.class);
//Error status is false
if(!errored){
//Based on Boolean value returned from WebService
Toast.makeText(getApplicationContext(),"still waiting", Toast.LENGTH_LONG).show();
if(loginStatus){
//Navigate to Home Screen
startActivity(intObj);
Toast.makeText(getApplicationContext(),
"LOGIN SUCCESSFUL", Toast.LENGTH_LONG).show();
}else{
//Set Error message
Toast.makeText(getApplicationContext(),
"Login Failed, try again", Toast.LENGTH_LONG).show();
}
//Error status is true
}else{
Toast.makeText(getApplicationContext(),
"Error occured in invoking webservice", Toast.LENGTH_LONG).show();
}
//Re-initialize Error Status to False
}
#Override
//Make Progress Bar visible
protected void onPreExecute() {
webservicePG.setVisibility(View.VISIBLE);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#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);
}
}
The app opens but always give me LoginFailed Please try again ....
the problem is probably the loginStatus Boolean ... it's not changing ...when I set the initial as true, the app says LOGINSUCCESFULL but when the initial is false it doesn't ... I can't find what's wrong :/

onTap event in overlay [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Anyone who can help me to implement ontap() event using this code?
That code below will display the current location of the user's and bar
location in google map. that code works fine. but my problem is I don't know on how
to implement ontap() event. Is it posible to implement onTap event even my overlay
is outside of oncreate bundle?
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class BarLocatorActivity extends MapActivity {
Button map1,login1,menu1,power1;
// Creating JSON Parser object
JSONNorman jNorman = new JSONNorman();
private static String url_all_bar =
"http://xxx.xxx.xxx.xxx/xampp/BARANDROID/get_all_bars.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BARS = "bars";
private static final String TAG_BARLAT = "bar_lat";
private static final String TAG_BARLONG = "bar_long";
// bars JSONArray
JSONArray bars = null;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyLocationOverlay myLocationOverlay;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.map); // bind the layout to the activity
// Configure the Map
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
// enable Street view by default
mapView.setStreetView(true);
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapController = mapView.getController();
mapController.setZoom(15); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
new LoadAllBars().execute();
}
/* Initiating Menu XML file (menu.xml) */
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.view:
BarLocatorActivity.this.finish();
Intent intent1 = new Intent(getApplicationContext(),
AllBarActivity.class);
startActivity(intent1);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
return true;
case R.id.map1:
BarLocatorActivity.this.finish();
Intent intent2 = new Intent(getApplicationContext(), BarLocatorActivity.class);
startActivity(intent2);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
return true;
case R.id.login:
BarLocatorActivity.this.finish();
Intent intent3 = new Intent(getApplicationContext(),
SignInActivity.class);
startActivity(intent3);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
return true;
case R.id.exit:
BarLocatorActivity.this.finish();
// The following makes the Android Gods frown upon me
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
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 void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
//bar location
class LoadAllBars extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jNorman.makeHttpRequest(url_all_bar, "GET", params);
Log.d("All bars: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
bars = json.getJSONArray(TAG_BARS);
for (int i = 0; i < bars.length(); i++) {
JSONObject c = bars.getJSONObject(i);
String bar_lat = c.getString(TAG_BARLAT);
String bar_long = c.getString(TAG_BARLONG);
double latt = Double.parseDouble(bar_lat);
double lngg = Double.parseDouble(bar_long);
GeoPoint points = new GeoPoint((int) (latt * 1E6),(int) (lngg *
1E6));
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(points);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
//end bar location
//overlay
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint points) {
pointToDraw = points;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
thanks in advance:)

Categories