[英]Accessing method from a Fragment in Button Click from MainActivity
Folks, 伙计们,
I am trying to send users current latitude and longitude from a button click in MainActivity to MapFragment(Fragment). 我试图通过MainActivity中的按钮单击向用户发送当前纬度和经度到MapFragment(片段)。 I use interface from fragment implemented inMainActivity but when i try to acess the method from the Fragment onButtonClick i get a
我使用fromMainActivity中实现的片段接口,但是当我尝试从Fragment onButtonClick获取方法时,我得到了一个
at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.xtechkid.blah.threadingapplication.MapDemoActivity.setupCurrlocation(com.google.android.gms.maps.model.LatLng)' on a null object reference at com.xtechkid.sudheej.threadingapplication.MainActivity.findLocation(MainActivity.java:67)
在android.app.ActivityThread.main(ActivityThread.java:5221)的java.lang.reflect.Method.invoke(Native Method),位于com.android的java.lang.reflect.Method.invoke(Method.java:372) .internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)引起:java.lang.NullPointerException:尝试调用虚方法'com.xtechkid.sudheej.threadingapplication.MainActivity.findLocation(MainActivity.java)上的空对象引用上的'void com.xtechkid.blah.threadingapplication.MapDemoActivity.setupCurrlocation(com.google.android.gms.maps.model.LatLng)' :67)
My code is below 我的代码如下
Here is the Map fragment 这是Map片段
public class MapDemoActivity extends Fragment {
final LatLng MU = new LatLng(40.8874245, 67.0200729);
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
CommInter mCallback;
public interface CommInter {
public void communicatesWithActivity(double lati,double longi);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
// if (context instanceof Activity){
a=(Activity) context;
//}
try{
mCallback = (CommInter) a;
}catch (ClassCastException e){
throw new ClassCastException(a.toString());
}
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
//setUpMapIfNeeded();
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
return view;
}
//This method when called from Main is throwing Exception
public void setupCurrlocation(LatLng MUSEUM) {
makeText(getContext(), "I am inside the function ", Toast.LENGTH_LONG).show();
System.out.println("I am inside the function");
/*CameraPosition cameraPosition = new CameraPosition.Builder()
.target(MUSEUM)
.zoom(10)
.bearing(70)
.tilt(25)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
*/
}
}
Code from Main Activity 主要活动的代码
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements MapDemoActivity.CommInter {
private TextView txtLocation;
private String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void communicatesWithActivity(double lati, double longi) {
MapDemoActivity mapFrag = (MapDemoActivity)getSupportFragmentManager().findFragmentById(R.id.map);
final LatLng MUSEU = new LatLng(38.8874245, 77.0200729);
//final LatLng MUSEU = new LatLng(lati, longi);
mapFrag.setupCurrlocation(MUSEU);
}
public void findLocation(View v) {
//final LatLng setLoc = new LatLng(38.8874245, -77.0200729);
//// MapDemoActivity fragment;
// Fragment t = (Fragment)getSupportFragmentManager()findViewById(R.id.map);
// fragment.setupCurrlocation(v,setLoc);
txtLocation = (TextView) findViewById(R.id.textViewLocation);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isLocEnabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isLocEnabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
GPSTracker gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
txtLocation.setText("Lat: " + latitude + "Long: " + longitude);
//System.out.println(MUS);
//The PROBLEM IS HERE I DONT KNOW THE FIX
communicatesWithActivity(latitude,long);
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
}
You are not using google maps. 您没有使用谷歌地图。 You need to have all these imports where you are calling setupcurrlocation.
您需要在调用setupcurrlocation的地方拥有所有这些导入。
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
// et al...
public void setupCurrlocation(LatLng MUSEUM) {
GoogleMap googleMap = ((MapFragment) fragmentManager.
findFragmentById(R.id.map)).getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Marker marker = googleMap.addMarker(new MarkerOptions().position(latLng).title(null));
CameraPosition cameraPosition = new CameraPosition.Builder().target(MUSEUM).zoom(10).bearing(70).tilt(25)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Basically I would have this method within the activity that the fragments are attached to. 基本上我会在片段附加到的活动中使用此方法。 You need to then manage the visibility of the google map.
然后,您需要管理Google地图的可见性。 As it will remain on top of other fragments.
因为它将保持在其他片段之上。
By controlling the visibility of the framelayouts, you control the visibility of the map within it's framelayout. 通过控制framelayouts的可见性,您可以在其framelayout中控制地图的可见性。
Example: 例:
// your activity layout here:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
//TO DO/>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/myrellayout">
// ALL THE THINGS IN YOUR ACTIVTY
</RelativeLayout>
// THE FRAMELAYOUTS MANAGE YOUR MAP FRAGMENT AND OTHER FRAGMENTS VISIBILITY
<FrameLayout
android:id="@+id/firstfrag"
android:layout_below="@+id/myrellayout"
android:layout_height="fill_parent"
android:layout_width="match_parent"
android:visibility="gone"/>
<FrameLayout
android:id="@+id/secondfrag"
android:layout_below="@+id/myrellayout"
android:layout_height="fill_parent"
android:layout_width="match_parent"
android:visibility="gone"/>
<fragment
android:id="@+id/map"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</FrameLayout>
</RelativeLayout>
https://developers.google.com/maps/documentation/android-api/ https://developers.google.com/maps/documentation/javascript/examples/ https://developers.google.com/maps/documentation/android-api/ https://developers.google.com/maps/documentation/javascript/examples/
The Exception is happening in the Activity, due of findFragmentById
returning null. 由于
findFragmentById
返回null,因此在Activity中发生异常。 Accordingly to the code you posted, you have declared your Fragment
in your xml. 根据您发布的代码,您已在xml中声明了
Fragment
。 Since you are using getSupportFragmentManager
, please make sure you declared it with com.google.android.gms.maps.SupportMapFragment
and not with com.google.android.gms.maps.MapFragment
. 由于您使用的是
getSupportFragmentManager
,因此请确保使用com.google.android.gms.maps.SupportMapFragment
声明它,而不是使用com.google.android.gms.maps.MapFragment
声明它。 This could be one of the causes you are getting null. 这可能是您获得null的原因之一。 on The other hand you could use a transactin
另一方面,你可以使用transactin
private MapDemoActivity mFragment; 私有的MapDemoActivity mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mFragment = new MapDemoActivity();
getSupportFragmentManager().beginTransaction().replace(R.id.container, mFragment, "TAG").commit();
}
}
and then you can use mFragment
. 然后你可以使用
mFragment
。 In your xml you have to replace your <fragment
with a normal ViewGroup, a FrameLayout
eg with id container
在您的xml中,您必须使用普通的ViewGroup替换
<fragment
,使用id container
替换FrameLayout
Hi you can try another way like Create a public static method in your fragment class and from your activity class On button click call this method with desired latitude and longitude. 您好,您可以尝试其他方式,如在您的片段类中创建一个公共静态方法,并从您的活动类On按钮单击调用此方法所需的纬度和经度。
/*
* Get User Desired Location in fragment class */
public static void getLocation(double lati, double longi)
{
try {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lati, longi));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
} catch (Exception e) {
e.printStackTrace();
}
}
/* Get Desired Location in your activity class*/
btnCurrentLocation.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
ClassName.getLocation(lati, longi);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.