-7

I'm trying to share values between a service A to a fragment B. How can I do? I used the function Shared Preferences but without results.

This is the service A:

public class GPSManager extends Service implements LocationListener {

public Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
double latitude;
double longitude;
double myLat;
double myLong;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 60000;
protected LocationManager locationManager;

SharedPreferences sharedPreferences_LAT_LONG = getApplicationContext().getSharedPreferences("Pref.PREFS_LAT_LONG", 0);

public Location getLocation() {
    try {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled)
        {
            getGeoData(LocationManager.NETWORK_PROVIDER);
        }
        else if (isGPSEnabled && location == null)
        {
            getGeoData(LocationManager.GPS_PROVIDER);
        }
        else
        {
            //no gps and network
        }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    return location;
}

private void getGeoData(String provider)
{
    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;
    }
    locationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    if (locationManager != null)
    {
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null)
        {
            latitude = location.getLatitude();
            myLat = latitude;
            longitude = location.getLongitude();
            myLong = longitude;

            /*SharedPreferences.Editor editor_LAT_LONG = sharedPreferences_LAT_LONG.edit();
            editor_LAT_LONG.putFloat(String.valueOf(myLat), 0);
            editor_LAT_LONG.putFloat(String.valueOf(myLong), 0);
            editor_LAT_LONG.apply();*/

        }
    }
}

This is the fragment B:

public class MapFragment extends Fragment {

MapView mapView;

private GoogleMap mMap;

//LatLng Fabrinao_ViaBalbo = new LatLng(43.334546, 12.903811);
LatLng Fabriano_ViaTerenzioMamiani = new LatLng(43.3355506, 12.9024512);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.map, container, false);

    mapView = (MapView) rootView.findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);

    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            Log.i("DEBUG", "onMapReady");
            mMap = googleMap;
            //mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMapToolbarEnabled(false); //Toolbar Disattivata

            /*mMap.addMarker(new MarkerOptions()
                    .position(My_Posizione)
                    .title("Wow!")
                    .snippet("Io sono qui"));*/

            mMap.addMarker(new MarkerOptions()
                    .position(Fabriano_ViaTerenzioMamiani)
                    .title("Fabriano - Via Terenzio Mamiani")
                    .snippet("Hello!")
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_logomarker)));

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Fabrinao_ViaBalbo, 15));
            //mMap.setMyLocationEnabled(true);
        }
    });

    return rootView;
}


@Override
public void onResume() {
    mapView.onResume();
    super.onResume();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

I want to save the value of Latitude(myLat) and Longitude(myLong) from service A to the fragment B so I can show my position on Map.

Thanks everybody and sorry for my bad english.

4 Answers4

1

You can use Bundle class and put_extra data to retrieve and put.

Example : put_extra

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

to read data

Bundle b = new Bundle();
b = getIntent().getExtras();
Object myParcelableObject = b.getString("name_of_extra");
Boola
  • 358
  • 3
  • 14
0

You can either use :

intent.putExtra()

or you can use

SharedPreferences

intent.putExtra() can be used when you're starting a new activity like this:

Intent intent = new Intent(activityOne, activityTwo);
intent.putExtra("TAG",VALUE);
startActivity(intent);

here the VALUE can be a String,int, Bundle.... read more about this here

and you can retreive this value in the new intent by using :

getIntent().getStringExtra(); // if your data was a String
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
0

Use Interface or Callback to send Data. Between Activity to Activity or Activity to Fragment.

Read here

Avinash Verma
  • 2,572
  • 1
  • 18
  • 22
0

in Activity A

Intent yourInent = new Intent(thisActivity.this, nextActivity.class); Bundle b = new Bundle(); b.putDouble("key", doubleVal); yourIntent.putExtras(b); startActivity(yourIntent);

in activity B

Bundle b = getIntent().getExtras(); double result = b.getDouble("key");

bhavani
  • 56
  • 1
  • 6