I try to send data from fragment to activity based on this reference. So i implement this code to send data to activity :
In MapFragment.java
@Override //::LocationListener (Interface)
public void onLocationChanged(Location location)
{
mCurrentLocation = location;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), 15);
googleMap.animateCamera(cameraUpdate);
double x = location.getLatitude();
double y = location.getLongitude();
String request = url+x+","+y;
Log.d("log1=",request);
StringRequest stringRequest = new StringRequest(Request.Method.GET, request,
new Response.Listener<String>() {
@Override
public void onResponse(String _response) {
Log.d("log_res=",_response);
sendData(_response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Error handling
Log.d("log_err=", error.toString());
}
});
Volley.newRequestQueue(activity.getBaseContext()).add(stringRequest);
Toast.makeText(activity, "Update location user ==>" + mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Current Location :" + mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude());
}
//===send data to activity===
private void sendData(String _Output)
{
try {
Log.d("output",_output);
Intent intent = new Intent(getActivity().getBaseContext(), MainActivity.class);
intent.putExtra("message", latd.toString() + "," + lang.toString());
Log.d("msg=", latd.toString() + "," + lang.toString());
activity.startActivity(intent);
}
catch (Exception jsoe){
Log.e("err=>", jsoe.toString());
}
}
//===interface===
OnFragmentChangedListener mCallback;
// Container Activity must implement this interface
public interface OnFragmentChangedListener {
public void onMapChanged(String name);
}
@Override //::BaseFragment (Class)
public void onAttach(Activity _activity) {
super.onAttach(_activity);
this.activity = _activity;
try {
mCallback = (OnFragmentChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
in MainAcitvity.java
@Override
public void onMapChanged(String name) {
Log.d("act=>", name);
Intent intent = getIntent();
String message = intent.getStringExtra("message");
}
A Little explanation about above code : in fragment, everytime GPS detect new coordinat, i capture latitude and longitude, then i try to send to activity.
However, evertime i call activity.startActivity(intent)
; then this application reopen new Activity unlimitedly.