Reputation:
I am building an app where I am using Firebase cloud messaging and Location Fused Prodiver. I want to send upstream message with latitude and longitude. And button for that is on my Dashboard Fragment, and function where I am getting lat and long is on MainActivity. How to pass that latitude and longitude to that button for upstream on my Dashboard fragment?
This is my MainActivity:
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
protected void createLocationRequest(){
mLocationRequest=new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
if(!isGooglePlayServiceAvailable()){
finish();
}
createLocationRequest();
mGoogleApiClient=new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
@Override
protected void onResume() {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d("OnResume", "Location update resumed .....................");
}
readTokenFromSharedPreferences();
super.onResume();
}
public void readTokenFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences("Token_pref", MODE_PRIVATE);
final String strPref = sharedPreferences.getString("token", null);
if(strPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private boolean isGooglePlayServiceAvailable(){
int status= GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(ConnectionResult.SUCCESS == status){
return true;
}else{
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates(){
PendingResult<Status> pendingResult=LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mCurrentLocation=location;
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d("Lokacije", "Location update stopped .......................");
}
private void LatitudeLongitude(){
if(mCurrentLocation!=null){
String latitude=String.valueOf(mCurrentLocation.getLatitude());
String longitude=String.valueOf(mCurrentLocation.getLongitude());
}
}
}
This function LatitudeLongitude() is for getting latitude and longitude. How to pass this function(or just this strings latitude and longitude) to my Dashboard fragment where is a button for upstream message? This is my upstream message button on Dashboard frgament:
String latitude, longitude;
Bundle bundle=getArguments();
latitude=bundle.getString("KEY_LAT");
longitude=getArguments().getString("KEY_LNG");
Log.d("LONGITUDE", "Longitude je: " + latitude);
Gson data_json = new Gson();
String json=data_json.toJson(data);
FirebaseMessaging fm=FirebaseMessaging.getInstance();
fm.send(new RemoteMessage.Builder(SENDER_ID + "@gcm.googleapis.com")
.setMessageId(UUID.randomUUID().toString())
.addData("action","message")
.addData("data","{\"message\":\"Upstream Message\"}")
.addData("object", json)
.addData("sss", latitude)
.addData("latitude", latitude)
.build());
Could anyone help me?
EDIT:This is my logcat when I use bundle:
08-08 10:01:41.195 27695-27695/com.telnet.asp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.telnet.asp.presentation.view.fragments.DashboardFragment.getObjectEvent(DashboardFragment.java:125)
at com.telnet.asp.presentation.view.adapters.DashboardGridAdapter.getDataObject(DashboardGridAdapter.java:145)
at com.telnet.asp.presentation.view.adapters.DashboardGridAdapter$3.onClick(DashboardGridAdapter.java:128)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Upvotes: 0
Views: 2093
Reputation: 15625
So you are basically talking about communication between Activity and Fragment.
You can do so easily by passing the strings in Bundle.
MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("KEY_LAT", latitude);
bundle.putString("KEY_LNG", longitude);
fragment.setArguments(fragment);
So, the idea if pretty simple. You just put the latitude and longitude strings into the bundle and pass the bundle to the fragment before replacing or adding it using the fragment manager.
Hope it helps.
EDIT
In the fragment's onViewCreated()
method do this,
String latitude, longitude;
latitude = getArguments().getString("KEY_LAT");
longitude = getArguments().getString("KEY_LNG");
This is how you can fetch the data previously send from the Activity inside the Fragment.
Upvotes: 0
Reputation: 1818
You can pass them from the Activity to the Fragment like @Khalid said, but you can also retrieve them on the Fragment.
Basically the Fragment asks the Activity for the Latitude and Longitude.
Have the following variables defined on your Activity:
String latitude = "latitude you want";
String longitude = "longitude you want";
public Pair<String,String> getLatitudeAndLongitude(){
return new Pair<>(latitude,longitude);
}
and then, in your fragment call it the method for it
...
Pair latitudeAndLongitude = ((YourActivity) getActivity()).getLatitudeAndLongitude();
p.first; // latitude
p.second; // longitude
...
Upvotes: 0
Reputation: 3313
in your fragment, add two variables,
double lat,lng;
the make there setters, getters:
public void setLat(double lat){
this.lat = lat;
}
public void setLng(double lng){
this.lng = lng;
}
andin your fragment manager in the activity, pass the variables:
YourFragment fragment = new YourFragment();
fragment.setLat(lat);
fragment.setLng(lng);
FragmentTransaction tr = activity.getSupportFragmentManager().beginTransaction();
tr.add(R.id.content_frame, fragment, null);
Upvotes: 1