回到fragmentmap时,Android应用程序崩溃 - GoogleMap v2

时间:2014-05-24 00:13:00

标签: java android eclipse google-maps

在我的应用程序中,我有一个SherlockNavigationDrawer,带有一个选项列表,每个选项都有一个不同的活动,用一个片段图调用xml,当我打开一个地图并想要打开另一个时,我没有问题,但我得到了当我回到已打开的任何地图时。

这是我的代码,欢迎提出任何建议:

MainActivity.java:

public class MainActivity extends SherlockFragmentActivity {

// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
private CharSequence mDrawerTitle;
private CharSequence mTitle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from drawer_main.xml
    setContentView(R.layout.drawer_main);

    // Get the Title
    mTitle = mDrawerTitle = "¿Qué buscás?";

    // Generate title
    title = new String[] { "CORTE LÁSER", "CORTE METALES",
            "CORTE POR CHORRO DE AGUA", "CURSOS", "EQUIPOS DE VIDEO", "FICHAS  TÉCNICAS", 
            "FOTÓGRAFOS", "GRÁFICAS", "IMPRESIÓN 3D", "LIBRERÍAS Y PAPELERAS", "MAQUETAS Y PROTOTIPOS",
            "MODELADO 3D", "MODELOS", "PLÁSTICOS", "ROUTER", "SUBLIMACIÓN", "TELGOPOR", "TERMOFORMADO",
            "TORNERO MADERA", "TORNERO METALES", "VINILOS" };

    // Locate DrawerLayout in drawer_main.xml
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Locate ListView in drawer_main.xml
    mDrawerList = (ListView) findViewById(R.id.listview_drawer);

    // Set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
            GravityCompat.START);

    // Pass string arrays to MenuListAdapter
    mMenuAdapter = new MenuListAdapter(MainActivity.this, title);

    // Set the MenuListAdapter to the ListView
    mDrawerList.setAdapter(mMenuAdapter);

    // Capture listview menu item click
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        public void onDrawerClosed(View view) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            // Set the title on the action when drawer open
            getSupportActionBar().setTitle(mDrawerTitle);
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {

        if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
    }

    return super.onOptionsItemSelected(item);
}

// ListView click listener in the navigation drawer
private class DrawerItemClickListener implements
        ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    switch (position) {
    case 0:

        ft.replace(R.id.content_frame, fragment1);

        break;
    case 1:

        ft.replace(R.id.content_frame, fragment2);

        break;
    case 2:

        ft.replace(R.id.content_frame, fragment3);

        break;
    }

    ft.commit();
    mDrawerList.setItemChecked(position, true);
    // Get the title followed by the position
    setTitle(title[position]);
    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);

}


@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getSupportActionBar().setTitle(mTitle);
}}

Fragment3.java:

public class Fragment3 extends SherlockFragment {
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle   savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment3, container, false);
    return rootView;
}

@Override
public void onViewCreated(View v, Bundle savedInstanceState){
    super.onViewCreated(v, savedInstanceState);

final LatLng Initial = new LatLng(-34.673009, -58.474111);
final LatLng FADU = new LatLng(-34.542163, -58.443716);
final LatLng UNO = new LatLng(-34.524924, -58.576421);
final LatLng DOS = new LatLng(-34.755415, -58.577794);
final LatLng TRES = new LatLng(-34.787001, -58.461751);
GoogleMap googlemap;

    googlemap  = ((SupportMapFragment)  getFragmentManager().findFragmentById(R.id.map3)).getMap();

    googlemap.setMyLocationEnabled(true);
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(Initial, 10);
    googlemap.animateCamera(update);


    googlemap.addMarker(new  MarkerOptions().position(FADU).title("FADU").snippet("Facultad de Arquitectura, Diseño y  Urbanismo")
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

    googlemap.addMarker(new MarkerOptions().position(UNO).title("XXX").snippet("UNO"));
    googlemap.addMarker(new MarkerOptions().position(DOS).title("XXX").snippet("DOS"));
    googlemap.addMarker(new  MarkerOptions().position(TRES).title("XXXX").snippet("TRES"));

}}

fragment3.xml:

<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" >  <fragment
    android:id="@+id/map3"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"/>

正如你所看到我在抽屉列表中有21个选项都有地图,它们都有活动和相应的xml,除了标记之外唯一改变的是id地图

的AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" >

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

<permission

<uses-permission  android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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" />

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Sherlock.Light" >
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data


        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:label="@string/app_name"   android:name=".Fragment2" android:process=":processmap2">
    </activity>
    <activity android:label="@string/app_name"   android:name=".Fragment3" android:process=":processmap3">
    </activity></application></manifest>

我有一个活动过程,当我打开一张地图并想要打开另一个时会产生错误,问题就在这里,当我打开一个新的时候应该做的就是杀死地图上面的过程

即de LogCat:

  

05-23 21:54:06.906:D / AndroidRuntime(3342):关闭虚拟机

     

05-23 21:54:06.906:W / dalvikvm(3342):threadid = 1:线程退出时未捕获异常(组= 0x40015578)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):致命异常:主

     

05-23 21:54:06.937:E / AndroidRuntime(3342):android.view.InflateException:二进制XML文件行#6:错误膨胀类片段

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:587)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.view.LayoutInflater.rInflate(LayoutInflater.java:623)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.view.LayoutInflater.inflate(LayoutInflater.java:408)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.view.LayoutInflater.inflate(LayoutInflater.java:320)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at com .X.fadubusca.Fragment2.onCreateView(Fragment2.java:22)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.FragmentManagerImpl $ 1.run(FragmentManager.java:440)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.os.Handler.handleCallback(Handler.java:587)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.os.Handler.dispatchMessage(Handler.java:92)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.os.Looper.loop(Looper.java:130)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.app.ActivityThread.main(ActivityThread.java:3687)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at java.lang.reflect.Method.invokeNative(Native Method)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at java.lang.reflect.Method.invoke(Method.java:507)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:842)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):at dalvik.system.NativeStart.main(Native Method)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):引起:java.lang.IllegalArgumentException:二进制XML文件行#6:重复id 0x7f05002a,标记null或父id 0x0与另一个片段for com.google.android.gms.maps.SupportMapFragment

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:296)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):在android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)

     

05-23 21:54:06.937:E / AndroidRuntime(3342):... 19更多

很抱歉,如果我在发帖时犯了错误,这是我第一次来这里,也是因为我的英语,我注意到我是初学者编码

编辑: 我想我通过在每个片段活动结束时添加它来解决问题:

    @Override
public void onPause() {
    super.onPause();

 }
@Override
public void onDestroyView() {

    super.onDestroyView(); 
    Fragment fragment = (getFragmentManager().findFragmentById(R.id.map3));  
    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
    ft.remove(fragment);
    ft.commit();        
}

现在我可以毫无问题地在片段之间切换

2 个答案:

答案 0 :(得分:0)

该错误是因为您已经在FragmentManager中添加了片段,因此无法将相同的片段添加两次。您需要实现FragmentTransaction.replace而不是FragmentTransaction.add

    case 0:
        ft.replace(R.id.content_frame, fragment1);
        //ft.addToBackStack(null); this maybe is not necesary.
        break;
    case 1:
        ft.replace(R.id.content_frame, fragment2);
        break;
    case 2:
        ft.replace(R.id.content_frame, fragment3);
        break;
    }

答案 1 :(得分:0)

这对我来说是在原始海报编辑的背面。使用&#34; getFragmentManager()&#34;而不是&#34; getSupportFragmentManager()&#34;。

@Override
    public void onResume() {
        super.onResume();
        try {
            // Loading map
            initializeMap();

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

    @Override
    public void onDestroyView() {

        super.onDestroyView();
        Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
        FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
        ft.remove(fragment);
        ft.commit();
    }