-3

Hello guys I have Fragment activity which shows Google map and I want to send latitude and longitude values to one of my activities. But how can I do this except putExtra. I can't use putExtra because I can't startActivity after data are complete. I have BottomNavigation activity which shows map fragment and also Settings activity in another fragment too. And I want to collect data from Map fragment and use it in this second fragment. Thanks.

Asaf
  • 5
  • 1

2 Answers2

1

You can use Shared Preference to do that.

Example:

Put value inside Shared Preference in your fragment activity.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putDouble("latitude", latitude);
editor.putDouble("longitude", longitude);
editor.apply();

get value from Shared Preference in your second activity.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
double latitude = sharedPref.getDouble("latitude");
double longitude = sharedPref.getDouble("longitude");

Hope it helps:)

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66
  • How can this solve my problem, please? I don't want to set values in my second activity. I want to send values from Map fragment activity to my second activity. – Asaf Aug 14 '17 at 17:24
  • Thanks, I also had this idea but do you think it is a good solution for let's say 20 latitudes and longitudes? Thanks. – Asaf Aug 14 '17 at 17:57
  • Y don't you make a Singleton to archive this? – Bhuvanesh BS Aug 14 '17 at 18:01
  • I download data(latitude and longitude) from Firebase database and then send it to another activity when needed – Asaf Aug 14 '17 at 18:17
  • Yeah you can store it temporarily in Singleton object and use it in another activity – Bhuvanesh BS Aug 14 '17 at 18:26
0

You can do this:

public class MyFragment extends Fragment{
    private MyActivity myActivity = null;

    public void setActivity(MyActivity myActivity){
        this.myActivity = myActivity;
    }

    //Call this method when you want to pass the values to the activity
    private void passLatLong(String lat, String longt){
        if(myActivity!=null){
            myActivity.setLatLong(lat,longt);
        }
    }
}

And in your Activity:

public class MyActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         //MyFragment myFragment = ... Define your fragment instance
         myFragment.setActivity(this);
    }

    public void setLatLong(String lat, String  longt){
         //Fragment will call this method
    }
}
Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34