Android 片段NullPointerException中的MapFragment

Android 片段NullPointerException中的MapFragment,android,android-fragments,navigation-drawer,google-maps-android-api-2,Android,Android Fragments,Navigation Drawer,Google Maps Android Api 2,我试图在另一个带有include标记的片段中显示mapfragment,当我执行项目时,我得到了NullPointerException,有人能告诉我我做错了什么吗?代码如下: 主要抽屉类别: public class DrawerPrincipal extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFra

我试图在另一个带有include标记的片段中显示mapfragment,当我执行项目时,我得到了
NullPointerException
,有人能告诉我我做错了什么吗?代码如下:

主要抽屉类别:

public class DrawerPrincipal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_principal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        
        //cargar fragment principal usuario

        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalUsuario();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //fragmento del chofer
/*
        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalChofer();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();*/
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.cuenta) {

            Fragment fragmento= null;
            fragmento = new OpcionDrawerUsuario();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();

        } else if (id == R.id.historial_viajes) {
            Fragment fragmento= null;
            fragmento = new FragmentoViajesAcumulados();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();


        } else if (id == R.id.contacto) {
            String emailAdress[] = {"gastondelacruz@gmail.com"};
            Intent email= new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
            email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
            email.setType("text/plain");
            email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
            startActivity(email);


        } else if (id == R.id.compartir) {
            String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
            Intent intento= new Intent();
            intento.setAction(Intent.ACTION_SEND);
            intento.putExtra(Intent.EXTRA_TEXT, texto);
            intento.setType("text/plain");
            startActivity(intento);

        } else if (id == R.id.version) {
            String prueba="aceptar";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("prueba") //
                    .setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
                    .setPositiveButton(prueba, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // TODO
                            dialog.dismiss();
                        }
                    }); //

            builder.show();

        } else if (id == R.id.salir) {

            finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }


}
包含地图的片段:

public class DrawerPrincipal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_principal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        
        //cargar fragment principal usuario

        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalUsuario();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //fragmento del chofer
/*
        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalChofer();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();*/
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.cuenta) {

            Fragment fragmento= null;
            fragmento = new OpcionDrawerUsuario();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();

        } else if (id == R.id.historial_viajes) {
            Fragment fragmento= null;
            fragmento = new FragmentoViajesAcumulados();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();


        } else if (id == R.id.contacto) {
            String emailAdress[] = {"gastondelacruz@gmail.com"};
            Intent email= new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
            email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
            email.setType("text/plain");
            email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
            startActivity(email);


        } else if (id == R.id.compartir) {
            String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
            Intent intento= new Intent();
            intento.setAction(Intent.ACTION_SEND);
            intento.putExtra(Intent.EXTRA_TEXT, texto);
            intento.setType("text/plain");
            startActivity(intento);

        } else if (id == R.id.version) {
            String prueba="aceptar";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("prueba") //
                    .setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
                    .setPositiveButton(prueba, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // TODO
                            dialog.dismiss();
                        }
                    }); //

            builder.show();

        } else if (id == R.id.salir) {

            finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }


}
public class MapaPrincipal extends FragmentActivity implements OnMapReadyCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapa_principal);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
管理地图的类:

public class DrawerPrincipal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_principal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        
        //cargar fragment principal usuario

        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalUsuario();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //fragmento del chofer
/*
        Fragment fragmento= null;
        fragmento = new FragmentoPrincipalChofer();
       getSupportFragmentManager().beginTransaction()
               .replace(R.id.content_main, fragmento)
               .commit();*/
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.cuenta) {

            Fragment fragmento= null;
            fragmento = new OpcionDrawerUsuario();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();

        } else if (id == R.id.historial_viajes) {
            Fragment fragmento= null;
            fragmento = new FragmentoViajesAcumulados();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .commit();


        } else if (id == R.id.contacto) {
            String emailAdress[] = {"gastondelacruz@gmail.com"};
            Intent email= new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
            email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
            email.setType("text/plain");
            email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
            startActivity(email);


        } else if (id == R.id.compartir) {
            String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
            Intent intento= new Intent();
            intento.setAction(Intent.ACTION_SEND);
            intento.putExtra(Intent.EXTRA_TEXT, texto);
            intento.setType("text/plain");
            startActivity(intento);

        } else if (id == R.id.version) {
            String prueba="aceptar";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("prueba") //
                    .setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
                    .setPositiveButton(prueba, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // TODO
                            dialog.dismiss();
                        }
                    }); //

            builder.show();

        } else if (id == R.id.salir) {

            finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }


}
public class MapaPrincipal extends FragmentActivity implements OnMapReadyCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapa_principal);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        // Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}
地图片段布局:

<fragment 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"
    android:id="@+id/map"
    tools:context=".MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

包含地图的片段布局:

<FrameLayout 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=".FragmentoPrincipalUsuario">

    <!-- TODO: Update blank fragment layout -->


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|top">

        <include layout="@layout/mapa_principal"/>

    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="149dp"
        android:layout_gravity="center_horizontal|bottom">

        <Button
            android:layout_width="117dp"
            android:layout_height="wrap_content"
            android:text="pedir taxi"
            android:id="@+id/pedirTaxi"
            android:layout_gravity="center_horizontal" />

    </LinearLayout>

</FrameLayout>

您的问题在于:

Fragment fragmento= null;
这是导致空指针的原因,请删除这两行 只需在
OnCreate
like之前声明它

Fragment fragmento;

如果仍然存在问题,请告诉我

将其声明为类变量,无需将其初始化为null, java会自动做到这一点:

Fragment fragmento;
删除您声明的每一行:

Fragment fragmento= null;
在oncreate中,以add not replace开始,因为可能没有要替换的内容:

getSupportFragmentManager().beginTransaction()
           .add(R.id.content_main, fragmento)
           .commit();
不管你做什么,不要在oncreate中使用两次(我看到它被注释掉了)


请将您的stacktrace发布到npe