How can I share these variables between an Activity and a Class? - java

I have an app that uses a Service. For some reason though, the service does not recognize the variables "placeArrayList", "latitudeArrayList", "longitudeArrayList", and "destination".
What can I do here?
MainActivity.java
public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayList<String> latitudeArrayList;
ArrayList<String> longitudeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
ArrayList<Double> latitudeList;
Integer counter;
LocationManager locationManager;
String provider;
double lat;
double lng;
Place place;
static Set<String> set;
static Set<String> set1;
static Set<String> set2;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
latitudeList = new ArrayList<>();
placeArrayList = new ArrayList<String>();
latitudeArrayList = new ArrayList<String>();
longitudeArrayList = new ArrayList<String>();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final Location location = locationManager.getLastKnownLocation(provider);
final Location destination = new Location(provider);
destination.setLatitude(location.getLatitude());
destination.setLongitude(location.getLongitude());
Log.e("shit", String.valueOf(location.distanceTo(destination)));
ListView listView = (ListView) findViewById(R.id.placeListView);
SharedPreferences sharedPreferences = this.getSharedPreferences("bro", Context.MODE_PRIVATE);
set = sharedPreferences.getStringSet("names", null);
set1 = sharedPreferences.getStringSet("lats", null);
set2 = sharedPreferences.getStringSet("lngs", null);
placeArrayList.clear();
latitudeArrayList.clear();
longitudeArrayList.clear();
if (set != null) {
placeArrayList.addAll(set);
latitudeArrayList.addAll(set1);
longitudeArrayList.addAll(set2);
} else {
placeArrayList.add("Hold to delete");
set = new HashSet<String>();
set.addAll(placeArrayList);
sharedPreferences.edit().putStringSet("names", set).apply();
latitudeArrayList.add(String.valueOf("66.56083"));
set1 = new HashSet<String>();
set1.addAll(latitudeArrayList);
sharedPreferences.edit().putStringSet("lats", set1).apply();
longitudeArrayList.add(String.valueOf("39.3232"));
set2 = new HashSet<String>();
set2.addAll(longitudeArrayList);
sharedPreferences.edit().putStringSet("lngs", set2).apply();
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, placeArrayList);
listView.setAdapter(arrayAdapter);
placeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this place?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
placeArrayList.remove(position);
latitudeArrayList.remove(position);
SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("bro", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
set1 = new HashSet<String>();
set2 = new HashSet<String>();
} else {
set.clear();
set1.clear();
set2.clear();
}
set.addAll(placeArrayList);
set1.addAll(latitudeArrayList);
set2.addAll(longitudeArrayList);
sharedPreferences.edit().remove("names").apply();
sharedPreferences.edit().remove("lats").apply();
sharedPreferences.edit().remove("lngs").apply();
sharedPreferences.edit().putStringSet("names", set).apply();
sharedPreferences.edit().putStringSet("lats", set1).apply();
sharedPreferences.edit().putStringSet("lngs", set2).apply();
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
return false;
}
});
final android.os.Handler handler = new android.os.Handler();
Runnable run = new Runnable() {
#Override
public void run() {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
if (placeArrayList.size() != 0) {
for (int i = 0; i < placeArrayList.size(); i++) {
Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));
destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));
if (location.distanceTo(destination)<100) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);
} else {
}
}
}
}
handler.postDelayed(this, 10000);
}
};
handler.post(run);
arrayAdapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PLACE_PICKER_REQUEST = 1;
builder = new PlacePicker.IntentBuilder();
pickPlace();
}
});
}
public void pickPlace() {
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(data, this);
// String toastMsg = String.format("Place: %s", place.getName());
//Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
placeArrayList.add(String.valueOf(place.getName()));
latitudeArrayList.add(String.valueOf(place.getLatLng().latitude));
longitudeArrayList.add(String.valueOf(place.getLatLng().longitude));
arrayAdapter.notifyDataSetChanged();
startService(new Intent(getBaseContext(), myService.class));
SharedPreferences sharedPreferences = getSharedPreferences("bro", Context.MODE_PRIVATE);
if (set == null) {
set = new HashSet<String>();
set1 = new HashSet<String>();
set2 = new HashSet<String>();
} else {
set.clear();
set1.clear();
set2.clear();
}
arrayAdapter.notifyDataSetChanged();
set.addAll(placeArrayList);
set1.addAll(latitudeArrayList);
set2.addAll(longitudeArrayList);
sharedPreferences.edit().remove("names").apply();
sharedPreferences.edit().remove("lats").apply();
sharedPreferences.edit().remove("lngs").apply();
sharedPreferences.edit().putStringSet("names", set).apply();
sharedPreferences.edit().putStringSet("lats", set1).apply();
sharedPreferences.edit().putStringSet("lngs", set2).apply();
}
}
}
#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);
}
}
myService.java
public class myService extends Service implements LocationListener {
Double lat;
Double lng;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
if (placeArrayList.size() != 0) {
for (int i = 0; i < placeArrayList.size(); i++) {
Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));
destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));
if (location.distanceTo(destination)<100) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);
} else {
}
}
}
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Don't make variables as static. Because it can cause memory leaks. And it is not at all a good idea.
Better way is to write an Interface and implement it in MainActivity class.
This interface will have methods for assigning new values to variables.
And call the Interface methods from your service.

You can make the variables static.
And then refer them by prefixing the Activity name to them.

Since the Service is a separate class it makes sense that it wouldn't be able to have access to the fields of MainAcitivity, since they are out of scope to "myService".
When you want to share information between a calling Activity and the Service being called, you'll be able to pass data in a key-value store through the intent.
You can put key-values directly into an Intent:
Intent intent = new Intent(getBaseContext(), myService.class);
itent.putExtra(key, value);
You can build a Bundle and add it to the intent also. Bundle's have a few more methods that make it easier to put rich data into them.
Bundle bundle = new Bundle();
bundle.extras.putString(key, value);
intent.putExtras(mBundle);
View more about Bundle's via the docs: http://developer.android.com/reference/android/os/Bundle.html
If you're interesting in passing a lot of data that cannot be easily represented in key value pairs then you may want to organize your data into your own Parceable class which can also be passed through an Intent. View more on making your own Parceable via the docs: http://developer.android.com/reference/android/os/Parcelable.html
and via this answer
How to send an object from one Android Activity to another using Intents?

Related

Broadcast manager not working in Fragment

I have a BroadcastReceiver which is used to receive data from a BLE device. The same code is working fine in an Activity but not in Fragment.
Here is the code:
public class HomeFragment extends Fragment implements LocationListener {
Session session;
TextView textViewName;
TextView textViewSteps;
TextView textViewCalories;
TextView textViewDistance;
TextView textViewFimos;
ImageView imageViewInfo;
public static final String TAG = "StepCounter";
private UARTService mService = null;
private BluetoothDevice evolutionDevice = null;
private static final int UART_PROFILE_CONNECTED = 20;
private static final int UART_PROFILE_DISCONNECTED = 21;
private int mState = UART_PROFILE_DISCONNECTED;
MyDatabase myDatabase;
LocationManager service;
private LocationManager locationManager;
private String provider;
double latitude, longitude;
List<Byte> listBytes = new ArrayList<>();
int rowNumber = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_home, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
init(view);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
service_init();
}
private void init(View view) {
session = new Session(getActivity());
myDatabase = new MyDatabase(getActivity());
service = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
textViewName = view.findViewById(R.id.textViewName);
textViewSteps = view.findViewById(R.id.textViewSteps);
textViewCalories = view.findViewById(R.id.textViewCalories);
textViewDistance = view.findViewById(R.id.textViewDistance);
textViewFimos = view.findViewById(R.id.textViewFimos);
imageViewInfo = view.findViewById(R.id.imageViewInfo);
try {
textViewName.setText("Hi, " + session.getUser().getUser().getName());
} catch (Exception e) {
}
}
private void service_init() {
System.out.println("---->>>>");
Intent bindIntent = new Intent(getActivity().getApplicationContext(), UARTService.class);
getActivity().bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
mService = ((UARTService.LocalBinder) rawBinder).getService();
Log.d(TAG, "onServiceConnected mService= " + mService);
if (!mService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
getActivity().finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UARTService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UARTService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UARTService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UARTService.DEVICE_DOES_NOT_SUPPORT_UART);
return intentFilter;
}
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UARTService.ACTION_GATT_CONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Connected: " + evolutionDevice.getName() + " - " + evolutionDevice.getAddress());
mState = UART_PROFILE_CONNECTED;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_DISCONNECTED)) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
System.out.println("------- Device Disconnected");
mState = UART_PROFILE_DISCONNECTED;
mService.close();
evolutionDevice = null;
}
});
}
//*********************//
if (action.equals(UARTService.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
//*********************//
if (action.equals(UARTService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UARTService.EXTRA_DATA);
List<Byte> byteList = Bytes.asList(txValue);
combineArrays(byteList);
}
//*********************//
if (action.equals(UARTService.DEVICE_DOES_NOT_SUPPORT_UART)) {
System.out.println("------- Device doesn't support UART. Disconnecting");
mService.disconnect();
}
}
};
#Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
Log.d(TAG, "onResume");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
Log.e(TAG, ignore.toString());
}
getActivity().unbindService(mServiceConnection);
mService.stopSelf();
mService = null;
}
The complete code in the same ay with a few changes in working fine in Activity. Any idea what might be the blocker.? Do I need to do something else in the fragment to receive the data from the Local Broadcast Manager.?
Please try this way :
Create class BroadcastHelper
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hossam";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And in your fragment :
private Receiver receiver;
private boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "Test":
Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
}
And to send your broadcast this this code :
BroadcastHelper.sendInform(context, "Test");
Or if you want to send data with it use :
Intent intent = new Intent("intent");
intent.putExtra("desc", desc);
intent.putExtra("name", Local_name);
intent.putExtra("code", productCode);
BroadcastHelper.sendInform(getActivity(), "Test" , intent);
I have a fragment where I do something similar. I put my code to setup the service in onCreateView and have a register and unregister in onPause() and onResume. Works good for me.
Can you check modify register receiver in service_init()
as
getActivity().registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
and for unregisterer receiver
getActivity().unregisterReceiver(UARTStatusChangeReceiver);

SharedPreferences gives default values on some devices

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);

Facing Error working with Mapsactivity (Newbie)

iam unable to get my location i dont know why ive tried everything on google as iam a newbie to android please help me solve this
package com.parkaspot.najeeb.project;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
final String TAG = "MAIN";
ArrayList<RecentData> list;
RecentAdapter recentAdapter;
LinearLayoutManager linearLayoutManager;
RecyclerView recyclerView;
Drawer result;
Toolbar toolbar;
Double lat, lng;
Location location;
SharedPreferences sharedPreferences, sharedPreferences1;
String name, password;
SpotsDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new SpotsDialog(this,"Loading...", R.style.Loading);
sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
sharedPreferences1 = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (networkEnabled) {
Log.d(TAG,"network is enabled"); //shows successfully
if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
Log.d(TAG,"permission ******************granted"); //This log Tag Never appears in logcat
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d(TAG, "Location is initialized"); //shows successfully
}
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(TAG, "getting latlng values"); //**Never shows
}else{ //******Always returning NULL HERE****
Toast.makeText(getBaseContext(),"location returning null",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
list = new ArrayList<>();
recentAdapter = new RecentAdapter(this, list);
recyclerView = (RecyclerView) findViewById(R.id.parkingRecyclerView);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recentAdapter);
setUpDrawer();
init();
}
private void setUpDrawer() {
/*
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName("Home");
*/
final ProfileDrawerItem profile1 = new ProfileDrawerItem().withName("Najeeb Pasha").withEmail("Najeeb#gmail.com");
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withName("Search By Location");
final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Your Profile");
final PrimaryDrawerItem logOut = new PrimaryDrawerItem().withName("Log Out");
final PrimaryDrawerItem gps = new PrimaryDrawerItem().withName("GPS");
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
return false;
}
})
.withCompactStyle(true)
.withHeaderBackground(R.color.drawer1)
.withCloseDrawerOnProfileListClick(true)
.withSelectionListEnabled(false)
.withTranslucentStatusBar(true)
.addProfiles(profile1)
.build();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withSelectedItem(-1)
.withRootView(R.id.drawer_container)
.withDisplayBelowStatusBar(false)
.withActionBarDrawerToggleAnimated(true)
.withCloseOnClick(true)
.withAccountHeader(headerResult)
.addDrawerItems(
item1,
profile,
logOut,
gps,
new SectionDrawerItem().withName("Others")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem == item1) {
startActivity(new Intent(getApplicationContext(), MapsActivity.class)
.putExtra("url", Constants.getPlaceUrl(lat,lng)));
} else if (drawerItem == logOut) {
logOut();
} else if (drawerItem == profile) {
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else if (drawerItem == gps) {
startActivity(new Intent(getApplicationContext(), GpsActivity.class));
}
return false;
}
})
.build();
}
private void logOut() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
SharedPreferences.Editor editor1 = sharedPreferences1.edit();
editor1.clear();
editor1.apply();
recreate();
Intent intent = new Intent(MainActivity.this, SignInActivity.class);
MainActivity.this.startActivity(intent);
}
public void init() {
new Load().execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class Load extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.show();
}
protected Void doInBackground(Void... params) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
System.out.println(Constants.getPlaceUrl(lat,lng));
Request request = new Request.Builder()
/*.url("http://192.168.0.101/parking/place.php?lat=17.308531&lng=78.5364463")*/
.url(Constants.getPlaceUrl(lat,lng))
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
System.out.println(responseData);
JSONArray jsonArray = new JSONArray(responseData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
RecentData data = new RecentData(
jsonObject.getString("name"),
jsonObject.getString("address"),
jsonObject.getString("lat"),
jsonObject.getString("lng"),
jsonObject.getString("distance"),
jsonObject.getString("filled"),
jsonObject.getString("total"),
jsonObject.getString("service"));
list.add(data);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
dialog.hide();
recentAdapter.notifyDataSetChanged();
}
}
this always returning null please help me from the scratch i dont know how to solve it and iam very very new to android and this is my college homewwork project iam unable to get the loation even with gps or net provider . **please help me with this only this thing then my project will get complete.
Returning location as Null
Iam a Newbie;
please reply me the whole code with change please.request(Noob)
Thank u very much sir
In order to get locations, you need to ask for location updates by using the method requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) on the location manager.
create a listener that will print the data, for example :
requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, new LocationListener(){
#Override
public void onLocationChanged(Location location){
Log.d("LOCATION", location.toString());
}
});
This will ask the location manager to provide me every 1000 ms (1s) and if i moved 10m from the last location a new location.

Preventing two markers for current location in Google Maps

My MainActivity looks like this:-
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationListener {
public static GoogleMap mMap;
public boolean flag = false;
public static boolean markerAlready = false;
public static PlaceAutocompleteFragment placeAutoComplete;
private LocationManager mLocationManager = null;
private String provider = null;
Circle c;
private Marker mCurrentPosition = null;
Marker marker;
public static Location location;
CircleOptions mOptions;
public static Location l;
FancyButton button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnGuide);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Opens guides's details!", Toast.LENGTH_SHORT).show();
}
});
int perm = ContextCompat.checkSelfPermission(
MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (perm == PackageManager.PERMISSION_GRANTED) {
start();
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
} else {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
44
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == 44) { //write request
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
start();
}
}
else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
Toast.makeText(MainActivity.this, "Go to Settings and Grant the permission to use this feature.", Toast.LENGTH_SHORT).show();
}
}
public void start()
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingSearchView searchView = findViewById(R.id.floating_search_view);
searchView.setSearchHint("");
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
Fragment a = getFragmentManager().findFragmentById(R.id.place_autocomplete);
a.setUserVisibleHint(false);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
if (marker != null)
marker.remove();
flag = true;
Log.d("Maps", "Place selected: " + place.getLatLng());
marker = mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName().toString()).zIndex(800));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place.getLatLng()));
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag = false;
mMap.clear();
locateCurrentPosition();
placeAutoComplete.setText(null);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//region NavDrawer Activity
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.emergency){
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
alertDialogObject.show();
}
List<String> HelpLineNumbers = new ArrayList<>();
HelpLineNumbers.add("Women's Helpline");
HelpLineNumbers.add("Police");
HelpLineNumbers.add("Hospital");
HelpLineNumbers.add("Fire Department");
HelpLineNumbers.add("Ambulance");
HelpLineNumbers.add("Men's Helpline");
final CharSequence[] helpLine = HelpLineNumbers.toArray(new String[HelpLineNumbers.size()]);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Helpline Numbers");
mBuilder.setItems(helpLine, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedText = helpLine[i].toString();
}
});
AlertDialog alertDialogObject = mBuilder.create();
//Show the dialog
alertDialogObject.show();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.myProfile) {
// Handle the camera action
} else if (id == R.id.myTrips) {
} else if (id == R.id.fir) {
} else if (id == R.id.logout) {
} else if (id == R.id.contactus) {
} else if (id == R.id.feedback) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupBottomNavigationView()
{
Log.d("BottomNv", "setupBottomNavigationView: setting up botNavView");
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bnve);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(this,bottomNavigationViewEx);
}
//endregion
//region Maps Methods
public void onMapReady(GoogleMap googleMap) {
LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: ");
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Log.e("Error", "onMapReady: " );
}
if(!gps_enabled && !network_enabled)
{
buildAlertMessageNoGps();
}
mMap = googleMap;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (isProviderAvailable() && (provider != null))
{
locateCurrentPosition();
}
setupBottomNavigationView();
}
public void locateCurrentPosition()
{
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist, this);
l=location;
if(l != null)
placeAutoComplete.setBoundsBias(new LatLngBounds(new LatLng(l.getLatitude(),l.getLongitude()),new LatLng(l.getLatitude()+2,l.getLongitude()+2)));
}
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(!flag)
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (mMap != null && !flag)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
//*****************************************************************//
private void addBoundaryToCurrentPosition(double lat, double lang) {
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
String addressStr = "";
try {
List<Address> myList = myLocation.getFromLocation(lat,lang, 1);
Address address;
address = (Address) myList.get(0);
Log.d("LOCC", address.getAddressLine(0));
addressStr += address.getAddressLine(0) ;
} catch (IOException e) {
e.printStackTrace();
}
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
mMarkerOptions.anchor(0.5f, 0.5f);
if( mOptions == null)
{
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
else {
c.remove();
mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = mMap.addCircle(mOptions);
}
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
mCurrentPosition.setTitle(addressStr);
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
public void buildAlertMessageNoGps()
{
new MaterialDialog.Builder(this)
.title("Location")
.content("Enable Location")
.positiveText("Enable GPS!")
.negativeText("No, Thanks!")
.cancelable(false)
.positiveColor(Color.rgb(232,42,42))
.negativeColor(Color.rgb(232,42,42))
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
Toast.makeText(MainActivity.this, "Location Access Required!!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
})
.show();
}
//endregion
}
As you can see in the method addBoundaryToCurrentPosition(), below that "//******//" (it's a part of MainActivity), I've set a marker at current location towards the end of the method which is supposed to refresh after every 5000ms.
Moreover I have a bottomNavigationView which is supposed to show nearby places. It's code is as below:-
public class BottomNavigationViewHelper {
private static final String TAG = "BottomNavigationViewHel";
static Menu menu;
static MenuItem menuItem;
public static Location l;
public static void setupBottomNavigationView(BottomNavigationViewEx bottomNavigationViewEx)
{
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavView");
bottomNavigationViewEx.enableAnimation(true);
bottomNavigationViewEx.enableItemShiftingMode(false);
bottomNavigationViewEx.enableShiftingMode(false);
bottomNavigationViewEx.setTextVisibility(true);
menu = bottomNavigationViewEx.getMenu();
}
public static void enableNavigation(final Context context, BottomNavigationViewEx view)
{
view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_hospital:
menuItem = menu.getItem(0);
menuItem.setChecked(true);
String Hospital = "hospital";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Hospitals near me");
String urlhospital = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Hospital);
Object[] DataTransferhospital = new Object[2];
DataTransferhospital[0] = MainActivity.mMap;
DataTransferhospital[1] = urlhospital;
Log.d("onClick", urlhospital);
GetNearbyPlacesData getNearbyPlacesDatahospital = new GetNearbyPlacesData();
getNearbyPlacesDatahospital.execute(DataTransferhospital);
break;
case R.id.ic_police:
menuItem = menu.getItem(1);
menuItem.setChecked(true);
String Police = "police";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
locate(MainActivity.location);
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Police Stations near me");
String urlpolice = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Police);
Object[] DataTransferpolice = new Object[2];
DataTransferpolice[0] = MainActivity.mMap;
DataTransferpolice[1] = urlpolice;
Log.d("onClick", urlpolice);
GetNearbyPlacesData getNearbyPlacesDatapolice = new GetNearbyPlacesData();
getNearbyPlacesDatapolice.execute(DataTransferpolice);
break;
case R.id.ic_food:
menuItem = menu.getItem(2);
menuItem.setChecked(true);
String Restaurant = "restaurant";
Log.d("onClick", "Button is Clicked");
MainActivity.mMap.clear();
MainActivity.markerAlready = false;
MainActivity.placeAutoComplete.setText("Restaurants near me");
locate(MainActivity.location);
String urlrestaurant = getUrl(MainActivity.l.getLatitude(), MainActivity.l.getLongitude(), Restaurant);
Object[] DataTransferrestaurant = new Object[2];
DataTransferrestaurant[0] = MainActivity.mMap;
DataTransferrestaurant[1] = urlrestaurant;
Log.d("onClick", urlrestaurant);
GetNearbyPlacesData getNearbyPlacesDatarestaurant = new GetNearbyPlacesData();
getNearbyPlacesDatarestaurant.execute(DataTransferrestaurant);
break;
}
return false;
}
});
}
private static String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + 10000);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
public static void locate(Location location) {
if (location != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(12f).build();
if (MainActivity.mMap != null) {
MainActivity.mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
final MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lng));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_location));
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
CircleOptions mOptions;
final Circle c;
mOptions = new CircleOptions()
.center(new LatLng(lat, lng)).radius(5000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
c = MainActivity.mMap.addCircle(mOptions);
}
}
}
In this I've created a method locate() , towards the end, which is called in switch cases. It fetches current location from MainActivity and sets marker after clearing the map.
The problem that I face is that when I click one of the buttons in BottomNavView, at first only one marker for current location is visible (that by BottomNav) but after some random time, marker by MainActivity also starts showing up. Hence two markers for current location show up.
I've tried creating a handler to remove marker by bottomNav after 5000ms but marker of MainActivity starts showing after random amount of time.
How do I prevent two markers from showing up simultaneously while at the same time ensuring that at least on of the markers is visible at all times??
First, you need to change your Marker variable name to more a readable name because it makes you confuse:
private Marker mCurrentPosition = null;
Marker marker;
What current position means? is it location or marker? What is marker? I think the better name for the above code is following:
private Marker mMarkerCurrentPosition = null;
private Marker mMarkerSelectedPlace;
Second, you adding a marker with BottomNavigationViewHelper.locate without removing the previous marker:
public static void locate(Location location) {
...
final Marker m = MainActivity.mMap.addMarker(mMarkerOptions);
...
}
Furthermore, you should change your code so you can't access the MainActivity variable outside the class by modifying the method parameters to something like this:
public static void locate(GoogleMap map, Location location) {
}
Last, don't use GoogleMap.clear() to clear your markers. Instead, try to always removing all the markers added to the GoogleMap one by one. You can achieve it by always adding the item to a list. Then, you can remove each item by iterating the lists. For example:
List<Marker> markers;
// add 3 marker
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
markers.add(mMap.addMarker(mMarkerOptions));
// remove markers
for (Iterator<Marker> it = markers.listIterator(); it.hasNext(); ) {
Marker marker = iter.next();
// remove the marker from map
marker.remove();
// remove marker from list
iter.remove();
}

How to get coordinates once you've navigated back from turning location on?

Whats the best way to get the getCoordinates method to run, once you return from the intent that was used in order to turn the location on. When you backpress once you have turned the location on, what happens in the activity lifecylce and where would be the best place to then call the getCoordinates method once you have returned from turning the location on, or even to first check if the location is on and only if it is then run getCoordinates method?
checkLocationOn
public void checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
getCoordinates
public void getCoordinates() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
latitude = Double.toString(lat);
longitude = Double.toString(lng);
SharedPreferences.Editor e = preferences.edit();
e.putString("myLats",latitude);
e.putString("myLngs",longitude);
e.commit();
}
});
}
onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.job_search_fragment, container, false);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
checkLocationOn();
getCoordinates();
//Please help here
return v;
}
Override onResume and call both checkLocationOn(); and getCoordinates(); from there.
If you are requesting continuous location updates, you can remove the request it in onPause method.
Thanks arsena, i just changed the checkLocationOn() to a boolean and then in the onResume() if the checkLocationOn() is true then i call the getCoordinate() like so.
public boolean checkLocationOn () {
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setCancelable(false);
dialog.setTitle("Location Needed");
dialog.setMessage("The devices location settings are not enabled, please enable it in order to use this application...");
dialog.setPositiveButton("Open Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.show();
return false;
}else{
return true;
}
}
then in onResume()
#Override
public void onResume() {
super.onResume();
if(checkLocationOn()){
getCoordinates();
}
}
its working now

Categories