android错误在与地图片段一起使用时膨胀类片段

时间:2017-05-10 05:59:19

标签: android google-maps android-fragments fragment

我正在尝试在片段中显示谷歌地图。位置在地图内正确绘制但当我在映射位置后按回来显示另一个片段并再次按下显示膨胀异常。

注意: - 我只使用了一个活动,所有其他页面都是碎片。

下面给出了片段的代码片段(用于显示gmap)

   <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map_container"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

logcat的: -

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.integral.loqal, PID: 15338                                                   
android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class fragment
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                                                   at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111)
                                                   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                   at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979)
                                                   at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670)
                                                   at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577)
                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                   at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                   at android.os.Looper.loop(Looper.java:148)
                                                   at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                Caused by: android.view.InflateException: Binary XML file line #84: Error inflating class fragment
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                                                   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
                                                   at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111) 
                                                   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
                                                   at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979) 
                                                   at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670) 
                                                   at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577) 
                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
                                                   at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
                                                   at android.os.Handler.handleCallback(Handler.java:739) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                   at android.os.Looper.loop(Looper.java:148) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                                                Caused by: java.lang.IllegalArgumentException: Binary XML file line #84: Duplicate id 0x7f0b0119, tag null, or parent id 0x7f0b00bb with another fragment for com.google.android.gms.maps.SupportMapFragment
                                                   at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
                                                   at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                   at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
                                                   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
                                                   at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111) 
                                                   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
                                                   at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979) 
                                                   at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670) 
                                                   at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577) 
                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
                                                   at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
                                                   at android.os.Handler.handleCallback(Handler.java:739) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                   at android.os.Looper.loop(Looper.java:148) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

java代码: -

 import android.support.v4.app.Fragment;
 import android.text.Editable;
 import android.text.TextWatcher;
 import android.util.Log;
 import android.view.InflateException;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.WindowManager;
 import android.widget.AdapterView;
 import android.widget.AutoCompleteTextView;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.SimpleAdapter;
 import android.widget.TextView;
 import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
 import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;

import com.google.android.gms.maps.MapFragment;
 import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.integral.loqal.CheckNetworkConnection;
import com.integral.loqal.Model.LocationItems;
import com.integral.loqal.PlaceDetailsJSONParser;
import com.integral.loqal.PlaceJSONParser;
import com.integral.loqal.R;
import com.integral.loqal.SessionManager;
import com.integral.loqal.Util.Utility;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
  import java.util.Locale;


   public class AddLocationFragment extends Fragment implements OnMapLongClickListener, OnMarkerDragListener {

          @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View v = inflater.inflate(R.layout.fragment_google_map, container, false);

        mapTextView = (TextView) v.findViewById(R.id.mapTextView);
        doneTextView = (TextView) v.findViewById(R.id.doneTextView);



        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();
        googleMap.setOnMarkerDragListener(this);
        googleMap.setOnMapLongClickListener(this);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);


        atvPlaces = (AutoCompleteTextView) v.findViewById(R.id.searchLoc);

        atvPlaces.setThreshold(1);
        atvPlaces.showDropDown();



        latlong = latitude + "," + longitude;
        LatLng latLng = new LatLng(latitude, longitude);


        marker = googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude)));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));

        backarrowImageView = (ImageView) v.findViewById(R.id.backArrowImageView);
        Bundle bundle = this.getArguments();
        int myInt = bundle.getInt("key", 0);

        if (myInt != 0 && myInt == 1) {
            mapTextView.setVisibility(View.INVISIBLE);


            backarrowImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getFragmentManager().popBackStack();

            });
            doneTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Boolean inet = new CheckNetworkConnection().isNetworkAvailable(getContext());
                    if (inet == true) {
                        if (atvPlaces.getText().toString().equals("")) {
                            Toast.makeText(getContext(), "Please choose a location", Toast.LENGTH_SHORT).show();
                        } else {
                            updateLocation();
                            utility.registerUserResponse(jsonObject, UserLocationSet_URL,
                                    "UserLocationSet", getContext());
                        }

                    } else {
                        Toast.makeText(getContext(), "Check your internet connection", Toast.LENGTH_SHORT).show();
                    }


                }
            });

        atvPlaces.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Creating a DownloadTask to download Google Places matching "s"
                placesDownloadTask = new DownloadTask(PLACES);

                // Getting url to the Google Places Autocomplete api
                String url = getAutoCompleteUrl(s.toString());

                // Start downloading Google Places
                // This causes to execute doInBackground() of DownloadTask class
                placesDownloadTask.execute(url);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });
        atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index,
                                    long id) {

                ListView lv = (ListView) arg0;
                SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();

                HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);

                // Creating a DownloadTask to download Places details of the selected place
                placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);

                // Getting url to the Google Places details api
                String url = getPlaceDetailsUrl(hm.get("reference"));

                // Start downloading Google Place Details
                // This causes to execute doInBackground() of DownloadTask class
                placeDetailsDownloadTask.execute(url);

            }
        });

        return v;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();

    public String getAutoCompleteUrl(String place) {

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=";

        // place to be be searched
        String input = "input=" + place;

        // place type to be searched
        String types = "types=geocode";

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = input + "&" + types + "&" + sensor + "&" + key;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;

        return url;
    }

    private String getPlaceDetailsUrl(String ref) {

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=";

        // reference of place
        String reference = "reference=" + ref;
        Log.d("TAg", reference);
        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = reference + "&" + sensor + "&" + key;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;

        return 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();
            System.out.println(data);
            String s[] = data.split(",");
            String pl = s[0];
            System.out.println(pl);
            br.close();

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

    @Override
    public void onMapLongClick(LatLng arg0) {


        if (marker != null) {
            marker.remove();
        }
        marker = googleMap.addMarker(new MarkerOptions()
                .position(
                        new LatLng(arg0.latitude,
                                arg0.longitude))
                .draggable(true).visible(true));


    }

    @Override
    public void onMarkerDragStart(Marker arg0) {

    }

    @Override
    public void onMarkerDrag(Marker arg0) {

    }

    @Override
    public void onMarkerDragEnd(Marker arg0) {

        LatLng dragPosition = arg0.getPosition();
        latitude = dragPosition.latitude;
        longitude = dragPosition.longitude;
        dataloc = latitude + "," + longitude;

        String name = getCompleteAddressString(latitude, longitude);
        editor.putString("latitudeKey", Double.toString(latitude));
        editor.putString("longitudeKey", Double.toString(longitude));
        editor.putString("LocationName", name);
        editor.commit();

        latlong = latitude + "," + longitude;


        Log.i("info", "on drag end :" + latitude + " dragLong :" + longitude);
        Toast.makeText(getContext(), "Marker Dragged..!", Toast.LENGTH_SHORT).show();
    }

    private class DownloadTask extends AsyncTask<String, Void, String> {

        private int downloadType = 0;

        // Constructor
        public DownloadTask(int type) {
            this.downloadType = type;
        }

        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            String data = "";

            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);

            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            switch (downloadType) {
                case PLACES:
                    // Creating ParserTask for parsing Google Places
                    placesParserTask = new ParserTask(PLACES);

                    // Start parsing google places json data
                    // This causes to execute doInBackground() of ParserTask class
                    placesParserTask.execute(result);

                    break;

                case PLACES_DETAILS:
                    // Creating ParserTask for parsing Google Places
                    placeDetailsParserTask = new ParserTask(PLACES_DETAILS);

                    // Starting Parsing the JSON string
                    // This causes to execute doInBackground() of ParserTask class
                    placeDetailsParserTask.execute(result);
            }
        }
    }

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

        int parserType = 0;

        public ParserTask(int type) {
            this.parserType = type;
        }

        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            JSONObject jObject;
            List<HashMap<String, String>> list = null;

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

                switch (parserType) {
                    case PLACES:
              list = placeJsonParser.parse(jObject);
                        break;
                    case PLACES_DETAILS:
                        PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
                        // Getting the parsed data as a List construct
                        list = placeDetailsJsonParser.parse(jObject);
                        System.out.println(list);
                }

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

        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {
            try {
                switch (parserType) {
                    case PLACES:
                        String[] from = new String[]{"description"};
                        int[] to = new int[]{android.R.id.text1};
                        if (getActivity() != null) {
                            adapter = new SimpleAdapter(getActivity(), result, android.R.layout.simple_list_item_1, from, to);
                            atvPlaces.setAdapter(adapter);
                        }

                        break;
                    case PLACES_DETAILS:
                        HashMap<String, String> hm = result.get(0);

                        // Getting latitude from the parsed data
                        double newlatitude = Double.parseDouble(hm.get("lat"));

                        // Getting longitude from the parsed data
                        double newlongitude = Double.parseDouble(hm.get("lng"));
                        latlong = newlatitude + "," + newlongitude;
                        // Getting reference to the SupportMapFragment of the activity_main.xml
                        SupportMapFragment fm = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container);

                        // Getting GoogleMap from SupportMapFragment
                        googleMap = fm.getMap();

                        LatLng point = new LatLng(newlatitude, newlongitude);

                        CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(point);
                        CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(15);
                        dataloc = latitude + "," + longitude;

                        // Utility.locationChange = latlong;


                        System.out.println(atvPlaces.getText().toString());
                        String s = atvPlaces.getText().toString();
                        String p[] = s.split(",");
                        String pla = p[0];



                        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, zoomLevel));
                        MarkerOptions options = new MarkerOptions();
                        options.position(point);
                        options.title("Position");
                        options.snippet("Latitude:" + newlatitude + ",Longitude:" + newlongitude);
                        if (marker != null)
                            marker.remove();
                        // Adding the marker in the Google Map
                        marker = googleMap.addMarker(options);

                        break;
                }

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







    public void onBackPressed() {
        getFragmentManager().popBackStack();

    }


    @Override
    public void onResume() {
        super.onResume();
    }
    }

我不知道为什么会出现错误。有人帮我找到解决方案吗?

2 个答案:

答案 0 :(得分:0)

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map_container"
 class="com.google.android.gms.maps.SupportMapFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />

答案 1 :(得分:0)

请查看此GOOGLE MAP DOCUMENTATION

的链接

活动类

 /**
 * init map fragment and get map async task
 */
private void initMapFragment() {
    AppUtils.showLog(TAG, "initMapFragment");
    try {
        SupportMapFragment mapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

XML文件

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mapwithmarker.MapsMarkerActivity" />