将活动转换为片段第一次尝试需要错误建议

时间:2016-04-05 18:32:29

标签: java android android-fragments android-studio android-activity

主要的Activity类 活动类:

public class MapsActivity extends FragmentActivity implements LocationListener {

    GoogleMap mGoogleMap;
    Spinner mSprPlaceType;

    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;

    double mLatitude=0;
    double mLongitude=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = ( Button ) findViewById(R.id.btn_find);


        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());


        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting Google Map
            mGoogleMap = fragment.getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);

尝试将活动类转换为片段类。 片段类:

public class MapsActivity extends Fragment implements LocationListener{

    GoogleMap mGoogleMap;
    Spinner mSprPlaceType;

    String[] mPlaceType=null;
    String[] mPlaceTypeName=null;

    double mLatitude=0;
    double mLongitude=0;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_main, container, false);
        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) getView().findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        Button btnFind;

        // Getting reference to Find Button
        btnFind = ( Button ) getView().findViewById(R.id.btn_find);
        return rootView;


        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());


        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            SupportMapFragment fragment = ( SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);


            // Getting Google Map
            mGoogleMap = fragment.getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);


        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        // Setting click event lister for the find button
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                String type = mPlaceType[selectedPosition];


                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("&key=AIzaSyBArXqaJg8mngPxdCjt_sckPkKd2GJohmA");


                // Creating a new non-ui thread task to download Google place json data
                PlacesTask placesTask = new PlacesTask();

                // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());


            }
        });

    }

}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);


        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }

    return data;
}


/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }

}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String,String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            /** Getting the parsed data as a List construct */
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String,String>> list){

        // Clears all the existing markers
        mGoogleMap.clear();

        for(int i=0;i<list.size();i++){

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

            // Placing a marker on the touched position
            mGoogleMap.addMarker(markerOptions);

        }

    }

}




public boolean OnCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng = new LatLng(mLatitude, mLongitude);

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

} 得到的错误 错误:(82,7)错误:无法访问的语句 错误:(154,2)错误:缺少返回语句

代码:

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

我从活动更改为片段类的内容,为什么应用程序崩溃?

活动类:

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

btnFind = ( Button ) findViewById(R.id.btn_find);

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);

SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

片段类:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);


mSprPlaceType = (Spinner) getView().findViewById(R.id.spr_place_type);

btnFind = ( Button ) getView().findViewById(R.id.btn_find);

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);

SupportMapFragment fragment = ( SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);

LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

logcat的:

 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationnearby/in.wptrafficanalyzer.locationnearby.MainActivity}: java.lang.ClassCastException: in.wptrafficanalyzer.locationnearby.MainActivity cannot be cast to android.app.Activity
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2515)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                         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:1399)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                                      Caused by: java.lang.ClassCastException: in.wptrafficanalyzer.locationnearby.MainActivity cannot be cast to android.app.Activity
                                                                                         at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723) 
                                                                                         at android.app.ActivityThread.access$900(ActivityThread.java:172) 
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422) 
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                         at android.os.Looper.loop(Looper.java:145) 
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:5832) 
                                                                                         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:1399) 
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 

1 个答案:

答案 0 :(得分:0)

您需要将return rootView移到onCreateView()的最后一行,因为return语句之后的任何内容都无法访问,因此错误。

您还需要使用rootView.findViewById()代替getView().findViewById(),因为当您使用该方法时尚未创建视图,因此getView()会返回null,并且您的应用程序可能会崩溃。

代码

mSprPlaceType = (Spinner) rootView.findViewById(R.id.spr_place_type);
btnFind = ( Button ) rootView.findViewById(R.id.btn_find); 

注意:这不会解决以后可能出现的任何其他问题并导致您的应用崩溃。