I'm new to android and I cannot figure out why my onCreate() in my activity is being called over and over.
In my MainActivity I have this function search, that is called when a button is pressed.
private void search(View v){
//Get input fields if null then dont restrict search
...
...
Intent i = new Intent(getApplicationContext(), PersonActivity.class);
i.putExtra("miles",numMiles);
i.putExtra("min",numMin);
startActivity(i);
}
Then in my PersonActivity Class I have this onCreate Method.
public class PersonActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
public ArrayList<PersonInfo> people;
private LayoutInflater inflater;
private Context _context;
public PersonInfoListAdapter _adapter;
public static ListView _list;
public int _position;
private static final String APP_ID = "4cae6e4d7d89bc4b02196b352ae91650";
// Find this in your developer console
private static final String API_KEY = "4A3243EECEA842F7B1FC6E7A4B00DA7A";
public PersonActivity() {}
#Override
protected void onCreate(Bundle savedInstanceState) {;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_person);
View listV = findViewById(R.id.friendList);
_list = (ListView) listV;
CMApiCredentials.initialize(APP_ID, API_KEY, getApplicationContext());
try {
people = new ArrayList<PersonInfo>();
Context context = _list.getContext();
_adapter = new PersonInfoListAdapter(context, people);
_list.setAdapter(_adapter);
} catch (Exception e) {
e.printStackTrace();
}
_list.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
View parentRow = (View) view.getParent();
return true;
}
});
Integer numMin = -1;
Integer numMiles = -1;
Bundle extras = getIntent().getExtras();
if (extras != null) {
numMin = extras.getInt("min");
numMiles = extras.getInt("miles");
Log.d("Person Activity", "Miles" + numMiles.toString());
}
queryForPeople(numMiles, numMin);
}
private void queryForPeople(Integer numMiles, Integer numMin){
//Get users location
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Location lastKnownLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = lastKnownLoc.getLatitude();
double lon = lastKnownLoc.getLongitude();
Intent myIntent = new Intent(this, PersonActivity.class);
startActivity(myIntent);
//search for friends
PersonInfo.searchObjects(this, SearchQuery.filter("location").near(lon, lat).within(numMiles, DistanceUnits.mi).searchQuery(),
new Response.Listener<CMObjectResponse>() {
#Override
public void onResponse(CMObjectResponse response) {
List<CMObject> objectList = response.getObjects();
for (CMObject o : objectList) {
PersonInfo p = (PersonInfo) o;
people.add(p);
Log.d(TAG, "Person was found: " + p.getName());
}
}
});
_adapter.notifyDataSetChanged();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The problem is this onCreate() in my personActivity is being called over an over. And I cannot figure out why. queryForPeople makes a call to and API that returns information that I use to populate the people ArrayList that is used in the adapter.
Any Ideas?
Your queryForPeople method calls startActivity on the activity you're already running from. So this will end up being infinitely recursive. I don't see why you would want to start yourself from anywhere in your activity, it just doesn't make sense. Unless you intended something else with those two lines, simply remove them.
Related
I've got a problem with reading data from google firebase. It seems like the method onDataChange is not called no matter if I change data in the database or not and I don't know why. What makes me curious is that I am able to write data into the database. I would be very thankful if someone could help me. Here is my code:
public class MainActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
MapView mapView;
MyLocationNewOverlay myLocationOverlay;
private static final String TAG = "MainActivity";
String content = "a";
String author = "b";
Double latitude = 53.2;
Double longitude = 11.5;
private ItemizedIconOverlay<OverlayItem> messagesOverlay;
private List<OverlayItem> items = new ArrayList<>();
private long totalNumberChilds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the mapView and show the MyLocationOverlay
mapView = findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.getController().setZoom(5);
messagesOverlay = new ItemizedIconOverlay<OverlayItem>(items, getResources().getDrawable(R.drawable.briefumschlag), null, this);
myLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(getApplicationContext()), mapView);
myLocationOverlay.enableMyLocation();
mapView.getOverlays().add(messagesOverlay);
mapView.getOverlays().add(myLocationOverlay);
GeoPoint point = this.myLocationOverlay.getMyLocation();
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
//initialize the Overlay for the Messages
//messagesOverlay.addItem(new OverlayItem(author, "", new GeoPoint(latitude, longitude)));
//declare the database variables in onCreate
//NOTE: Unless you are signed in, this will not be useable.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
messagesOverlay.removeAllItems();
Toast.makeText(MainActivity.this, "yesss", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDataChange: Successsfully called!");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Message message = new Message();
//String author1 = ds.child("messageAuthor").getValue(String.class);
//String content1 = ds.child("messageContent").getValue(String.class);
//Double latitude1 = ds.child("messageLatitude").getValue(Double.class);
//Double longitude1 = ds.child("messageLongitude").getValue(Double.class);
//messagesOverlay.addItem(new OverlayItem("by" + author1, "", new GeoPoint(latitude1, longitude1)));
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.testButton) {
addMessage();
}
}
public void addMessage() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
String id = myRef.push().getKey();
Message message = new Message(author, content, latitude, longitude);
myRef.child(id).setValue(message);
Toast.makeText(this, "Message added", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
GeoPoint point = new GeoPoint(location);
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
I just found the error, I removed the lines
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
and now the onDataChange method is called. Thank you so much for your help!
I am using this code to save key-value pair in shared preferences and its working fine on my device but on emulators and other real devices, it always returns the default values.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final String USER_PREFS = "com.aamir.friendlocator.friendlocator.USER_PREFERENCE_FILE_KEY";
SharedPreferences sharedPreferences;
private static String userKey="";
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
static final int PERMISSION_ACCESS_FINE_LOCATION = 1;
boolean FINE_LOCATION_PERMISSION_GRANTED = false;
TextView textViewLocationData;
TextView textViewKeyDisplay;
Button buttonRefresh;
Button btnCopyKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToActivityFriends();
}
});
fab.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_people_white_48dp));
textViewLocationData = (TextView) findViewById(R.id.textViewLocationData);
textViewKeyDisplay =(TextView) findViewById(R.id.tvKeyDisplay);
buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
btnCopyKey = (Button) findViewById(R.id.btnCopyKey);
sharedPreferences = getApplicationContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
String key = sharedPreferences.getString("key", "");
if(!key.equals("")) {
textViewKeyDisplay.setText(key);
}
// Create an instance of GoogleAPIClient.
buildGoogleApiClient();
//user_sp = getSharedPreferences(USER_PREFS, 0);
buttonRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
btnCopyKey.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("userKey", textViewKeyDisplay.getText().toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(getBaseContext(), "Key copied !", Toast.LENGTH_SHORT).show();
}
});
}
#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
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) mGoogleApiClient.connect();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private void displayLocation() {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if ( permissionCheck != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_ACCESS_FINE_LOCATION);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
textViewLocationData.setText(latitude + ", " + longitude);
sharedPreferences = getApplicationContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
String key = sharedPreferences.getString("key", "");
Log.d("User Key",key);
updateServers(latitude, longitude,key);
} else {
textViewLocationData
.setText("Couldn't get the location. Make sure location is enabled on the device");
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
FINE_LOCATION_PERMISSION_GRANTED = true;
//displayLocation();
} else {
FINE_LOCATION_PERMISSION_GRANTED = false;
}
return;
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
//displayLocation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public void goToActivityFriends () {
Intent intent = new Intent(this, com.aamir.friendlocator.friendlocator.Friends.class);
startActivity(intent);
}
public void updateServers(Double lat,Double lon,String Key) {
if (Key.equals("")) {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
SendLocation cleint = retrofit.create(SendLocation.class);
Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call = cleint.registerUser(String.valueOf(lat), String.valueOf(lon), Key);
call.enqueue(new Callback<com.aamir.friendlocator.friendlocator.Models.SendLocation>() {
#Override
public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
Log.d("Response", response.body().getUserKey());
if (!response.body().getUserKey().isEmpty()) {
String key_user = response.body().getUserKey();
textViewKeyDisplay.setText(key_user);
// Writing data to SharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", userKey);
if(editor.commit()){
Log.d("saved","saved");
}
}
}
#Override
public void onFailure(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Throwable t) {
Log.e("Response", t.toString());
}
});
}
else {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://demoanalysis.com/pro03/FriendLocator/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
SendLocation cleint = retrofit.create(SendLocation.class);
Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call = cleint.updateLocation(String.valueOf(lat), String.valueOf(lon), Key);
call.enqueue(new Callback<com.aamir.friendlocator.friendlocator.Models.SendLocation>() {
#Override
public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
Log.d("Response", response.body().getLocationStatus());
if (!response.body().getLocationStatus().isEmpty()) {
Toast.makeText(MainActivity.this,response.body().getLocationStatus(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Throwable t) {
Log.e("Response", t.toString());
}
});
}
}
}
On some devices, it's working perfectly. I did change context from this to getApplicationContext but no progress. I have updated the code.
Edit:
tl;dr : you write the wrong variable into the preferences.
Your variable userKey is never written and always an empty string.
In your retrofit onResponse you put userKey as value of "key" into the
preferences. This writes an empty string into the preferences. This will work and give you no error.
Please assign userKey with the value of key_user.
Your response is only stored to key_user.
Or directly remove the local variable key_user as follows:
public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
Log.d("Response", response.body().getUserKey());
if (!response.body().getUserKey().isEmpty()) {
String userKey = response.body().getUserKey();
textViewKeyDisplay.setText(userKey);
// Writing data to SharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("key", userKey);
if(editor.commit()){
Log.d("saved","saved");
}
}
}
Before:
In your code to save, you directly try to gather the previously saved value using editor.apply();
As documentation states out, apply will save your changes in background on a different thread.
Therefore your changes might not be saved at the time you try to get the value,
some lines below.
Try to use editor.commit(); instead and check if the problem is still there.
I'm share here my own Preference Class it's too easy so you can put in any project.
Put this class into your util folder or anywhere.
AppPreference.java
package util;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Pranav on 25/06/16.
*/
public class AppPreference {
public static final String PREF_IS_LOGIN = "prefIsLogin";
public static final class PREF_KEY {
public static final String LOGIN_STATUS = "loginstatus";
}
public static final void setStringPref(Context context, String prefKey, String key, String value) {
SharedPreferences sp = context.getSharedPreferences(prefKey, 0);
SharedPreferences.Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
public static final String getStringPref(Context context, String prefName, String key) {
SharedPreferences sp = context.getSharedPreferences(prefName, 0);
return sp.getString(key, "");
}
}
Set Preference Value in Login.java when user Login set value like this :
AppPreference.setStringPref(context, AppPreference.PREF_IS_LOGIN, AppPreference.PREF_KEY.LOGIN_STATUS, "0");
Then you will get Login Status Value in any Class by Calling like this :
String LoginStatus = AppPreference.getStringPref(context, AppPreference.PREF_IS_LOGIN, AppPreference.PREF_KEY.LOGIN_STATUS);
I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
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;
#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) {
}
});
}
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;
double x, y;
StringBuilder str;
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
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
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);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#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);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}
I'm having an issue stopping a service that I have started.
The service is called when the user logs in, and starts to track the user's location. This is working fine. The service is meant to stop when the user presses the logout button and is successfully logged out.
It's an android service that is being called through a JavaScript interface by a HTML button.
Here is my Main Class which contains the methods for starting and stopping the service:
public class CasesMain extends DroidGap {
Intent gpsTracking;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
appView.addJavascriptInterface(this, "StartGPS");
super.loadUrl(Config.getStartUrl());
}
public void startGPS(){
gpsTracking = new Intent(this, MyService.class);
startService(gpsTracking);
}
public void stopGPS(){
stopService( gpsTracking );
}
}
Here is the MyService class:
public class MyService extends Service {
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Handler handler = new Handler();
Thread t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT)
.show();
final Runnable r = new Runnable() {
public void run() {
location();
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(r, 10000);
return START_STICKY;
}
public void location() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
}
private class myLocationListener implements LocationListener {
double lat_old = 0.0;
double lon_old = 0.0;
double lat_new;
double lon_new;
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locManager.removeUpdates(locListener);
lon_new = location.getLongitude();
lat_new = location.getLatitude();
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
Log.v("Debug", "Latt: " + latitude + " Long: " + longitude);
Toast.makeText(getApplicationContext(),
longitude + "\n" + latitude, Toast.LENGTH_SHORT).show();
lat_old = lat_new;
lon_old = lon_new;
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
And here is my call to stop the service: window.StartGPS.stopGPS();
The start works perfectly, but when I log out, the app continues to show messages of the latt and long meaning the call to stopService() either didn't work or is not called.
Can anyone see where my mistake is or what is going wrong?
Any help would be greatly appreciated!
FIXED
Adding handler.removeCallbacksAndMessages(null); in the onDestroy() method of MyService fixed it for me.
Can anyone see where my mistake is or what is going wrong?
You have an empty onDestroy() method. You need to call removeCallbacks() on your Handler there.
If you are using any android.os.Handler in the service remember to call removeCallbacksAndMessages like this:
#Override
public void onDestroy() {
Toast.makeText(this, "service onDestroy", Toast.LENGTH_LONG).show();
Utils.cancelNotification(this);
customHandler.removeCallbacksAndMessages(null);
}
And the service will destroy successfully. It worked for me.
Here's what I would suggest
1) Put more log statements in calls leading to stopService.
2) Implement On ServiceConnection interface and see what's happening in OServiceConnected and onServiceDisconnected.
I have my own location class. I have an odds result that when I search for the GPS location using my class, I get 0, 0 back.
Whereas if I search the getLastKnown function in location manager for GPS, I get the forced value:
public Location getGPSloc(Context c){
isGPSavailable(c);
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListenerGps);
timerGPS = new Timer();
timerGPS.schedule(new GetLastLocationGPS(), 45000);
return gpsLoc;
}
This is the class that I'm calling from outside the function, I am using this.getApplicationContext() in the call. This is GetLastLocationGPS():
class GetLastLocationGPS extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
if(gps_enabled){
gpsLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);}
else{
gpsLoc = null;
}
}
}
Here is the listener:
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timerGPS.cancel();
gpsLoc = location;
lm.removeUpdates(this);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
When I call MyLocationInstance.getGPSloc(this.getApplicationContext()) the return value is always 0, 0. I have a forced value of 83 43 that I sent to the emulator and appears if I sub in LocationManagerInstance.getLastKnownLocation(LM.GPS);
I have no idea why this method won't fetch the location.
Is it because in theory the timer is still running when the call happens? That's the only way I can come up with an answer. Any other ideas?
I'm not sure what is your problem but this is my code which is under load and fully functional.
Since this class extends from Fragment then it can act as parent of your fragment.
There is a listener that your class can get new location after each interval.
public class LocationFinderFragment extends Fragment implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public interface OnNewLocationFoundListener {
public void OnNewLocationFound(Location location);
}
private static final String TAG = "LocationFinderFragment";
private static final long DEFAULT_UPDATE_LOCATION_INTERVAL = 30 * 1000; // update every 30 seconds
private static final long DEFAULT_TERMINATE_SAT_FINDING = 1 * 60 * 60 * 1000; // for 1 hour
private OnNewLocationFoundListener listener; // Listener of fragments
private OnNewLocationFoundListener listener2; // Listener of MainFragmentHolder
private Context context;
private LocationClient mLocationClient;
private static double lat = 0;
private static double lng = 0;
private static long lastTime = 0;
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(location == null)
return;
if(lat == location.getLatitude() && lng == location.getLongitude()) {
Log.e(TAG, "location not changed.");
return;
}
lat = location.getLatitude();
lng = location.getLongitude();
Log.i(TAG, "Location changed to (" + lat + ", " + lng + ")");
// Ask fragment to get new data and update screen
listener.OnNewLocationFound(location);
// Display toast notification every minute (instead of every 30 seconds)
DateTime time = new DateTime();
long currentTime = time.getMillis();
if(currentTime > lastTime + 1 * 60 * 1000) {
listener2.OnNewLocationFound(location);
lastTime = currentTime;
}
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener2 = (OnNewLocationFoundListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnNewLocationFoundListener interface.");
}
Log.i(TAG, "Fragment attached to activity.");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Getting context
context = getActivity().getApplicationContext();
// Get location manager
mLocationClient = new LocationClient(context, this, this);
}
#Override
public void onResume() {
super.onResume();
// Get location
if(mLocationClient != null)
mLocationClient.connect();
}
#Override
public void onPause() {
super.onPause();
// remove listener in order to save resource
if(mLocationClient != null)
mLocationClient.disconnect();
}
#Override
public void onDestroy() {
super.onDestroy();
// remove listener in order to save resource
if(mLocationClient != null)
mLocationClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location Connected.");
// Get last known location
Location lastLocation = mLocationClient.getLastLocation();
mLocationListener.onLocationChanged(lastLocation);
if(!SpGodMode.isLocationModeEnabled(context)) {
// Create location request
LocationRequest locationRequest = LocationRequest.create()
.setInterval(DEFAULT_UPDATE_LOCATION_INTERVAL)
.setExpirationDuration(DEFAULT_TERMINATE_SAT_FINDING)
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationClient.requestLocationUpdates(locationRequest, mLocationListener);
} else {
String strLoc = SpGodMode.getLocation(context);
if(strLoc != null) {
String lat = strLoc.substring(0, strLoc.indexOf(","));
String lng = strLoc.substring(strLoc.indexOf(",") + 1);
Location location = new Location("");
try {
location.setLatitude(Double.parseDouble(lat));
location.setLongitude(Double.parseDouble(lng));
mLocationListener.onLocationChanged(location);
} catch (NumberFormatException e) {
Log.e(TAG, "Wrong lat/lng for parsing as Double.");
Toast.makeText(context, "Wrong lat/lng", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onDisconnected() {
Log.i(TAG, "Location Disconnected.");
if(mLocationClient != null && mLocationClient.isConnected())
mLocationClient.removeLocationUpdates(mLocationListener);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed listener.");
}
public void setLocationListener(OnNewLocationFoundListener listener) {
this.listener = listener;
}
public void disconnectLocation() {
mLocationClient.disconnect();
}
}