unreachable statement after using .getActivity( ) in a Fragment

给你一囗甜甜゛ 提交于 2019-12-18 17:32:13

问题


I want to use .getSystemService in a Fragment. When i use .getActivity() to get the context of my activity, Android Studio tells me in the same line that this is a "unreachable statement".

When there is a line above the line where i use "getActivity()", it will show that this line on top is unreachable.

Why and how to fix this?

public class NewNodeFragment extends Fragment {

//GPS SIGNAL
double pLat;
double pLong;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.newnode_layout, container,false);

    //GPS SIGNAL
    LocationManager gpsmanager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastLocation = gpsmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (lastLocation != null) {
        pLat = lastLocation.getLatitude();
        pLong = lastLocation.getLongitude();
    }

    LocationListener gpslistener = new mylocationListener();
    gpsmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslistener);
}

回答1:


You have a return statement as the first line in your method, right above the line that has your comment //GPS SIGNAL...

Anything after a return statement is of course unreachable code.




回答2:


You would have to put all your code before the return statement.

public class NewNodeFragment extends Fragment {

//GPS SIGNAL
double pLat;
double pLong;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


    //GPS SIGNAL
    LocationManager gpsmanager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastLocation = gpsmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (lastLocation != null) {
        pLat = lastLocation.getLatitude();
        pLong = lastLocation.getLongitude();
    }

    LocationListener gpslistener = new mylocationListener();
    gpsmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslistener);

    return inflater.inflate(R.layout.newnode_layout, container,false);
}


来源:https://stackoverflow.com/questions/28332605/unreachable-statement-after-using-getactivity-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!