3

Tenho um Navigation Drawer funcionando perfeitamente, mas decidi ter um fragment com 3 Tabs, mas ta dando erro, vi vídeo e peguei exemplo, mas nao consigo acetar.

//Minha Navigation Drawer

package com.example.soares.controleos_redeml;

import android.annotation.SuppressLint;


import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;


import com.example.soares.controleos_redeml.Tabs.OSAberta;
import com.example.soares.controleos_redeml.Tabs.OSFechada;
import com.example.soares.controleos_redeml.Tabs.OSOrcamento;
import com.squareup.picasso.Picasso;


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

import de.hdodenhof.circleimageview.CircleImageView;

public class TelaPrincipal extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    String UrlProfile = "http://redeml.no-ip.info/controleos/profile/15269237155b0301c3a5307.jpg";


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

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        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.addDrawerListener(toggle);
        toggle.syncState();

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

        View hView =  navigationView.getHeaderView(0);
        TextView nav_user = (TextView)hView.findViewById(R.id.textView);
        CircleImageView imagem_profile = (CircleImageView)hView.findViewById(R.id.ImageProfile);
        nav_user.setText("Mateus Soares");
        Picasso.get().load(UrlProfile).into(imagem_profile);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);



        getSupportActionBar().setDisplayHomeAsUpEnabled(true);



    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OSAberta(), "Abertas");
        adapter.addFragment(new OSFechada(), "Fehcadas");
        adapter.addFragment(new OSOrcamento(), "Orçamento");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List mFragmentList = new ArrayList();
        private final List mFragmentTitleList = new ArrayList();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(android.support.v4.app.Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }



    @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) {

        getMenuInflater().inflate(R.menu.tela_principal, menu);
        return true;
    }
*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();


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

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();
        //Fragment fr = new Fragment01();
        //FragmentManager fm = getFragmentManager();
        //FragmentTransaction fragmentTransaction = fm.beginTransaction();

        if (id == R.id.nav_cliente) {
            //fragmentTransaction.replace(R.id.container, fr);
            //fragmentTransaction.commit();
        } else if (id == R.id.nav_ordemservico) {

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

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

        }

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

//erro que recebo

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.soares.controleos_redeml, PID: 8835
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.soares.controleos_redeml/com.example.soares.controleos_redeml.TelaPrincipal}: java.lang.NullPointerException
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
                      at android.app.ActivityThread.access$800(ActivityThread.java:135)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5017)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at com.example.soares.controleos_redeml.TelaPrincipal.setupViewPager(TelaPrincipal.java:96)
                      at com.example.soares.controleos_redeml.TelaPrincipal.onCreate(TelaPrincipal.java:79)
                      at android.app.Activity.performCreate(Activity.java:5231)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:136) 
                      at android.app.ActivityThread.main(ActivityThread.java:5017) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:515) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
                      at dalvik.system.NativeStart.main(Native Method) 

os erros são sempre nha linha 96: viewPager.setAdapter(adapter);

e na linha 79: setupViewPager(viewPager);

alguém pode me Ajudar ?

1 Resposta 1

3

Não precisa olhar muito o código e já da para ver o problema, aparentemente o viewPager não está sendo inicializado de forma correta, na qual quando você tenta setar o adapter ou algo que mude ele, dará esse problema pois o viewPager está definido como Null.

Tem certeza que o viewPager é da Activity em questão? Caso tenha, inicialize ele logo depois que inicializar a activity, ou seja, depois de:

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela_principal);

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .