java - Fragment类中的致命错误

java - Fragment类中的致命错误,第1张

我在GooGle map v2.project附近发现了一个发现,但没有错误但是在Logcat中找不到活动错误。

所以我认为问题出现在oncreate()方法中,我设置了适配器。

请你把我的代码弄清楚。

MainActivity.java

public class MainActivity 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_main);     

        // 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);



            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(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=9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9");


                    // 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);            

            }       

        }

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().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));

    }

Logcat:

    07-29 07:05:55.531: E/AndroidRuntime(847): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.locationnearby/in.wptrafficanalyzer.locationnearby.MainActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class fragment
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread.access0(ActivityThread.java:141)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.os.Looper.loop(Looper.java:137)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread.main(ActivityThread.java:5103)
07-29 07:05:55.531: E/AndroidRuntime(847):  at java.lang.reflect.Method.invokeNative(Native Method)
07-29 07:05:55.531: E/AndroidRuntime(847):  at java.lang.reflect.Method.invoke(Method.java:525)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-29 07:05:55.531: E/AndroidRuntime(847):  at dalvik.system.NativeStart.main(Native Method)
07-29 07:05:55.531: E/AndroidRuntime(847): Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class fragment
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.Activity.setContentView(Activity.java:1895)
07-29 07:05:55.531: E/AndroidRuntime(847):  at in.wptrafficanalyzer.locationnearby.MainActivity.onCreate(MainActivity.java:56)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.Activity.performCreate(Activity.java:5133)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
07-29 07:05:55.531: E/AndroidRuntime(847):  ... 11 more
07-29 07:05:55.531: E/AndroidRuntime(847): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 7571000 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.common.GooglePlayServicesUtil.zzaa(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.internal.zzy.zzaz(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.internal.zzy.zzay(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.SupportMapFragment$zzb.zzvu(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.SupportMapFragment$zzb.zza(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.dynamic.zza.zza(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.dynamic.zza.onInflate(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279)
07-29 07:05:55.531: E/AndroidRuntime(847):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)

最佳答案:

2 个答案:

答案 0 :(得分:0)

我认为你应该改变

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

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

有关详细信息,请查看this answer ...

答案 1 :(得分:0)

您应该在布局文件中添加这些行

           <fragment
            android:id="@ id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" />

我认为您使用的是com.google.android.gms.maps.MapFragment。

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复