简体   繁体   English

android.view.InflateException:二进制XML文件第21行:膨胀类片段的错误

[英]android.view.InflateException: Binary XML file line #21: Error inflating class fragment

I'M developing nearby places on Google Maps 我正在Google地图上开发附近的地方

so i'm facing a fragment error. 所以我面临一个片段错误。 i've googled my problem but none of the proposed solutions worked for me. 我已经用谷歌搜索了我的问题,但是没有一个建议的解决方案对我有用。

This is the code 这是代码

mainactivity : 主要活动 :

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=YOUR_API_KEY");


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

    }

    @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

    }
}

place JSONParser : 放置JSONParser:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PlaceJSONParser {

    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){      

        JSONArray jPlaces = null;
        try {           
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }


    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> place = null;   

        /** Taking each place, parses and adds to list object */
        for(int i=0; i<placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return placesList;
    }

    /** Parsing the Place JSON object */
    private HashMap<String, String> getPlace(JSONObject jPlace){

        HashMap<String, String> place = new HashMap<String, String>();
        String placeName = "-NA-";
        String vicinity="-NA-";
        String latitude="";
        String longitude="";


        try {
            // Extracting Place name, if available
            if(!jPlace.isNull("name")){
                placeName = jPlace.getString("name");
            }

            // Extracting Place Vicinity, if available
            if(!jPlace.isNull("vicinity")){
                vicinity = jPlace.getString("vicinity");
            }   

            latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");            


            place.put("place_name", placeName);
            place.put("vicinity", vicinity);
            place.put("lat", latitude);
            place.put("lng", longitude);


        } catch (JSONException e) {         
            e.printStackTrace();
        }       
        return place;
    }
}

logcat : logcat:

07-25 19:47:00.691: E/AndroidRuntime(1193): FATAL EXCEPTION: main
07-25 19:47:00.691: E/AndroidRuntime(1193): java.lang.NullPointerException
07-25 19:47:00.691: E/AndroidRuntime(1193):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1410)
07-25 19:47:00.691: E/AndroidRuntime(1193):     at android.app.Activity.startActivityForResult(Activity.java:3370)
07-25 19:47:00.691: E/AndroidRuntime(1193):     at android.app.Activity.startActivityForResult(Activity.java:3331)
07-25 19:47:00.691: E/AndroidRuntime(1193):     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)

manifest : 清单:

  <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="in.wptrafficanalyzer.locationnearby"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="16" />

        <permission
            android:name="in.wptrafficanalyzer.locationnearby.permission.MAPS_RECEIVE"
            android:protectionLevel="signature"/>

        <uses-permission android:name="in.wptrafficanalyzer.locationnearby.permission.MAPS_RECEIVE"/>

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true"/>    

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="in.wptrafficanalyzer.locationnearby.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9"/>     

        </application>

    </manifest>  

activityXML: activityXML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Spinner 
        android:id="@+id/spr_place_type"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/btn_find"
        android:layout_width="wrap_content"
        android:layout_height="60dp"        
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/spr_place_type"
        android:text="@string/str_btn_find" />    

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
       android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/spr_place_type"
        class="com.google.android.gms.maps.SupportMapFragment" />   

</RelativeLayout>

please give me your best help 请给我你最好的帮助

thnaks in advance .!!! 提前致意。!!!

Try the following changes to your map fragment. 尝试对地图片段进行以下更改。

 <fragment 
       android:name="your.package.name.MainActivity"
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/spr_place_type"
        class="com.google.android.gms.maps.SupportMapFragment" />

Replace your.package.name with package containing MainActivity 用包含MainActivity的包替换your.package.name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 textview.getPaint() 出现错误“android.view.InflateException:二进制 XML 文件行 #21”“膨胀 class 片段时出错” - textview.getPaint() got error "android.view.InflateException: Binary XML file line #21" "Error inflating class fragment" android.view.InflateException:二进制XML文件第0行:二进制XML文件第0行:膨胀类片段时出错 - android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment android.view.InflateException:二进制XML文件第7行:二进制XML文件第7行:夸大类片段的错误 - android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment android.view.InflateException:二进制XML文件第0行:膨胀类错误 <unknown> 在下面的API 21的recyclerview中 - android.view.InflateException: Binary XML file line #0: Error inflating class <unknown> in recyclerview for below API 21 Android调试错误android.view.InflateException:二进制XML文件第9行:夸大类片段的错误 - Android debugging error android.view.InflateException: Binary XML file line #9: Error inflating class fragment Android-android.view.InflateException:二进制XML文件第9行:膨胀类片段的错误 - Android - android.view.InflateException: Binary XML file line #9: Error inflating class fragment android.view.InflateException:二进制XML文件行#8:错误膨胀类片段 - android.view.InflateException: Binary XML file line #8: Error inflating class fragment 无法膨胀android.view.InflateException:二进制XML文件第24行:膨胀类片段时出错 - Failed to inflate android.view.InflateException: Binary XML file line #24: Error inflating class fragment android.view.InflateException:二进制XML文件第91行:错误放大了类片段 - android.view.InflateException: Binary XML file line #91: Error inflating class fragment RuntimeException:android.view.InflateException:二进制XML文件第8行:夸大类片段的错误 - RuntimeException : android.view.InflateException: Binary XML file line #8: Error inflating class fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM