ViewPager 为空

ViewPager is null

我创建了一个 ViewPager,但是我总是收到一个错误,说它是空的。我试过更改ViewPager,检查了R Id,XML中指定的ID。我怀疑这与我构建 XML 文件的方式有关。谢谢

这是我遇到的错误:

    E/in.mycampuscha: [qarth_debug:]  get PatchStore::createDisableExceptionQarthFile method fail.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.devin.mycampuschat, PID: 2034
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devin.mycampuschat/com.devin.MyCampusChat.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)


     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
        at com.devin.MyCampusChat.MainActivity.onCreate(MainActivity.java:63)
        at android.app.Activity.performCreate(Activity.java:7458)
        at android.app.Activity.performCreate(Activity.java:7448)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) 
        at android.os.Handler.dispatchMessage(Handler.java:112) 
        at android.os.Looper.loop(Looper.java:216) 
        at android.app.ActivityThread.main(ActivityThread.java:7625) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

这是XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
        
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

                <include layout="@layout/app_bar_layout" android:id="@+id/toolbar" />

                <com.google.android.material.tabs.TabLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/tab_layout">

                        <com.google.android.material.tabs.TabItem
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:icon="@drawable/ic_chats"
                                android:text="Chats" />

                        <com.google.android.material.tabs.TabItem
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:icon="@drawable/ic_friends"
                            android:text="Friends" />

                        <com.google.android.material.tabs.TabItem
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:icon="@drawable/ic_requests"
                            android:text="Requests" />

                </com.google.android.material.tabs.TabLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.viewpager.widget.ViewPager
            android:layout_below="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toEndOf="@+id/toolbar"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
        </androidx.viewpager.widget.ViewPager>


</androidx.coordinatorlayout.widget.CoordinatorLayout>

这是Activity:

package com.devin.MyCampusChat;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.devin.MyCampusChat.Fragments.ChatsFragment;
import com.devin.MyCampusChat.Fragments.FriendsFragment;
import com.devin.MyCampusChat.Fragments.RequestsFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

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

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth fAuth;
    private FirebaseUser fUser;
    private Toolbar mToolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    //Fragments.
    private ChatsFragment chatsFragment;
    private FriendsFragment friendsFragment;
    private RequestsFragment requestsFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout  = findViewById(R.id.tab_layout);
        viewPager  = findViewById(R.id.view_pager);
        fAuth      = FirebaseAuth.getInstance();
        mToolbar   = findViewById(R.id.toolbar);

        //fragments
        chatsFragment    = new ChatsFragment();
        friendsFragment  = new FriendsFragment();
        requestsFragment = new RequestsFragment();

        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("MyCampus Chats");

        tabLayout.setupWithViewPager(viewPager);

        ViewPagerAdapter viewPagerAdapter = new MainActivity.ViewPagerAdapter(getSupportFragmentManager(), 0);
        viewPager.setAdapter(viewPagerAdapter);
        viewPagerAdapter.addFragment(chatsFragment, "Chats");
        viewPagerAdapter.addFragment(friendsFragment, "Friends");
        viewPagerAdapter.addFragment(requestsFragment, "Requests");
    }

    @Override
    public void onStart() {
        super.onStart();
        fUser = fAuth.getCurrentUser();

        //Check to see if the current user is null or not, if so, they are not logged in.
        if(fUser == null){
            Intent startIntent = new Intent(MainActivity.this, StartActivity.class);
            startActivity(startIntent);
            finish();
        }
    }

    /** Creates the options menu **/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    /** Gets the options selected from the menu resource **/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
         super.onOptionsItemSelected(item);

            switch(item.getItemId()) {
                case R.id.log_out_btn:
                    fAuth.signOut();
                    sendToStart();

                    break;
                case R.id.all_users_btn:
                case R.id.settings_btn:
            }

         return true;
    }

    /** Simply sends the user to the startActivity (state not logged in) **/
    private void sendToStart(){
        Intent intent = new Intent(MainActivity.this, StartActivity.class);
        startActivity(intent);
        finish();
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragments = new ArrayList<>();
        private List<String>   fragmentTitles = new ArrayList<>();


        public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior) {
            super(fm, behavior);
        }

        public void addFragment(Fragment fragment, String title){
            mFragments.add(fragment);
            fragmentTitles.add(title);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

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

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

您的代码没有问题。布局有问题xml。

似乎没有提供 ViewPager 的 ID。

您将 id 设置为错误的属性 android:layout_below

必须设置成android:id

 <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toEndOf="@+id/toolbar"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
 </androidx.viewpager.widget.ViewPager>