我正在构建一个应用程序,我正在使用Firebase云消息传递和Location Fused Prodiver。我想用纬度和经度发送上游消息。并且按钮就在我的Dashboard Fragment上,并且我正在使用纬度和长度的功能在MainActivity上。如何将该纬度和经度传递给我的Dashboard片段上游的那个按钮?
这是我的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());
}
}
}
此功能LatitudeLongitude()用于获取纬度和经度。如何将此功能(或仅此字符串纬度和经度)传递给我的仪表板片段,其中是上游消息的按钮? 这是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());
有人可以帮助我吗?
编辑:当我使用bundle时,这是我的logcat:
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)
答案 0 :(得分:1)
在你的片段中,添加两个变量,
double lat,lng;
public void setLat(double lat){
this.lat = lat;
}
public void setLng(double lng){
this.lng = lng;
}
在活动中的片段管理器中传递变量:
YourFragment fragment = new YourFragment();
fragment.setLat(lat);
fragment.setLng(lng);
FragmentTransaction tr = activity.getSupportFragmentManager().beginTransaction();
tr.add(R.id.content_frame, fragment, null);
答案 1 :(得分:0)
所以你基本上是在谈论活动和片段之间的沟通。
您可以通过传递捆绑。
中的字符串轻松完成MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("KEY_LAT", latitude);
bundle.putString("KEY_LNG", longitude);
fragment.setArguments(fragment);
所以,这个想法非常简单。您只需将纬度和经度字符串放入包中,然后使用片段管理器将将包传递给片段,然后再替换或添加。
希望它有所帮助。
修改强>
在片段的onViewCreated()
方法中执行此操作,
String latitude, longitude;
latitude = getArguments().getString("KEY_LAT");
longitude = getArguments().getString("KEY_LNG");
这是您可以获取以前从片段中的Activity发送的数据的方法。
答案 2 :(得分:0)
你可以将它们从Activity传递给Fragment,就像@Khalid所说,但你也可以在Fragment上检索它们。
基本上片段会向活动询问纬度和经度
在您的活动中定义以下变量:
String latitude = "latitude you want";
String longitude = "longitude you want";
public Pair<String,String> getLatitudeAndLongitude(){
return new Pair<>(latitude,longitude);
}
然后,在你的片段中调用它的方法
...
Pair latitudeAndLongitude = ((YourActivity) getActivity()).getLatitudeAndLongitude();
p.first; // latitude
p.second; // longitude
...