【问题标题】:Method tabLayout.setupWithViewPager(viewPager) crashes app方法 tabLayout.setupWithViewPager(viewPager) 使应用程序崩溃
【发布时间】:2021-05-16 05:55:58
【问题描述】:

我最近将我的代码从 android 更新到了 andoidx。现在,我的应用程序在我成功登录后崩溃。我在MainActivity.class 中使用 Viewpager 和 Tablayout。我正在使用MainActivityFragmentsAdapter.class 来获取片段。

经过大量研究,有人建议使用finishUpdate 方法,但我的应用仍然崩溃。

@Override public void finishUpdate(ViewGroup container) {
try{ 
   super.finishUpdate(container);
}
catch (NullPointerException nullPointerException){
    System.out.println("Catch the NullPointerException in MainActivityFragmentsAdapter.finishUpdate");
    } 
}

我也尝试将代码 tabLayout.setupWithViewPager(viewPager); 替换为下面的代码,但发生了同样的错误

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });

我在 logcat 上收到此错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.tabs.TabLayout.setupWithViewPager(androidx.viewpager.widget.ViewPager)' on a null object reference
    at com.fyp.selfzenapp.MainActivity.onCreate(MainActivity.java:44)

MainActivity.class

package com.fyp.selfzenapp;

import android.content.Intent;
import android.os.PersistableBundle;
import androidx.viewpager.widget.ViewPager;
import androidx.core.app.ActivityCompat;
import com.fyp.selfzenapp.adapters.MainFragmentAdapter;
import com.google.android.material.tabs.TabLayout;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

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

    mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());

    viewPager = findViewById(R.id.main_view_pager);
    viewPager.setAdapter(mainActivityFragmentsAdapter);
    if(savedInstanceState != null ) {
        position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
        viewPager.setCurrentItem(position);
    }
    final TabLayout tabLayout = findViewById(R.id.main_tab_layout);
    tabLayout.setupWithViewPager(viewPager); // ERROR LINE
    viewPager.setOffscreenPageLimit(4);
    setTabIcons(tabLayout);
    ActivityCompat.requestPermissions(MainActivity.this, new String[]
            {android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
        
int position;
@Override
protected void onPause() {
    super.onPause();
    position = viewPager.getCurrentItem();
}

@Override
protected void onResume() {
    super.onResume();
    viewPager.setCurrentItem(position);
}

public void setTabIcons(TabLayout tabLayout) {
    int icons[]= {
            R.drawable.ic_calendar,
            R.drawable.ic_task_complete,
            R.drawable.ic_alarm_clock,
            R.drawable.ic_man_user
    };
    for(int i = 0; i < icons.length; i++) {
        tabLayout.getTabAt(i).setIcon(icons[i]);
    }
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Log.d("MAIN ACTIVITY", "Saving instance state");
    outState.putInt(SAVE_INSTANCE_STATE_KEY, viewPager.getCurrentItem());
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

MainActivityFragmentsAdapter.class

public class MainActivityFragmentsAdapter extends FragmentStatePagerAdapter {
int FRAGMENT_COUNT = 4;

public MainActivityFragmentsAdapter(FragmentManager fm) {
    super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}

@NonNull
@Override
public Fragment getItem(int i) {
    AlarmFragment fragment = null;
    Bundle args = new Bundle();
    switch (i) {
        case 0: ScheduleFragment.getInstance(); break;
        case 1: new TaskFragment(); break;
        case 2: new AlarmFragment(); break;
        case 3: new UserFragment(); break;
        default: new UserFragment(); break;
    }
    // The object is just an integer
    return fragment;
}

public int getCount() {
    return FRAGMENT_COUNT;
}


@Override
public CharSequence getPageTitle(int position) {
    String titles[] = {
            "SCHED",
            "TASK",
            "ALARM",
            "USER"
    };
    return titles[position];
}

@Override 
public void finishUpdate(ViewGroup container) { //I try this method to fix this error but nothing changes
    try{
        super.finishUpdate(container);
    } catch (NullPointerException nullPointerException){
        System.out.println("Catch the NullPointerException in FragmentPagerAdapter.finishUpdate");
    }
}
}

build.gradle(应用程序)

apply plugin: 'com.android.application'

android {
    signingConfigs {
        config {
            keyAlias 'androiddebugkey'
            keyPassword 'android'
            storeFile file('debug.keystore')
            storePassword 'android'
        }
    }
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.fyp.selfzenapp"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            signingConfig signingConfigs.config
        }
    }
    compileOptions {
        targetCompatibility = "8"
        sourceCompatibility = "8"
    } // No static method metafactory
}

apply plugin: 'com.android.application'

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.android.support.constraint:constraint-layout:2.0.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.firebase:firebase-firestore:23.0.0'
    implementation 'com.google.firebase:firebase-storage:20.0.0'
    implementation 'com.google.firebase:firebase-functions:20.0.0'
    implementation 'com.google.firebase:firebase-core:19.0.0'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-database:20.0.0'
    implementation 'com.google.firebase:firebase-iid:21.1.0'
    implementation 'com.google.firebase:firebase-messaging:20.2.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services-auth:19.0.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.pes.materialcolorpicker:library:1.2.0'
    implementation 'com.google.android.gms:play-services-location:18.0.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.1'
    implementation 'com.google.android.material:material:1.4.0-beta01'

    // Import the Firebase BoM
    implementation platform('com.google.firebase:firebase-bom:27.1.0')

    // Add the dependency for the Firebase SDK for Google Analytics
    // When using the BoM, don't specify versions in Firebase dependencies
    implementation 'com.google.firebase:firebase-analytics'
}
apply plugin: 'com.google.firebase.crashlytics'
apply plugin: 'com.google.gms.google-services'

【问题讨论】:

    标签: java android-studio android-viewpager android-tablayout


    【解决方案1】:

    写在 MainActivity.class 中:

    tabLayout.addTab(tabLayout.newTab().setText("SCHED"));
    tabLayout.addTab(tabLayout.newTab().setText("TASK"));
    tabLayout.addTab(tabLayout.newTab().setText("ALARM"));
    tabLayout.addTab(tabLayout.newTab().setText("USER"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    

    【讨论】:

    • 我按照建议输入了您的代码,不幸的是它仍然停止响应。
    • 所以你的适配器类有问题
    • 根据我发送的链接编写适配器类代码就可以了
    • 我更新了我的MainActivity.class 代码,请查看可能是其他功能导致问题的原因。
    • 我检查了代码。现在Logcat出现了什么问题?
    【解决方案2】:

    您的代码中的所有内容似乎都是正确的。但是我认为在您的应用程序中出现了一些错误。

    IN MainActivity.class :

    尝试删除tabLayout.setupWithViewPager(viewPager);

    并且编辑替换mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());

    mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(this, getSupportFragmentManager(), tabLayout.getTabCount());

    IN MainActivityFragmentsAdapter.class :

    替换

    int FRAGMENT_COUNT = 4;
    
    public MainActivityFragmentsAdapter(FragmentManager fm) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }
    

    通过

    private Context mycontext;
    int FRAGMENT_COUNT = 4;
    
    public MainActivityFragmentsAdapter(Context context, FragmentManager fm, int totaltabs) {
        super(fm);
        mycontext = context;
        this.totaltabs= totaltabs;
    }
    

    如果仍然无法正常工作,请查看我的答案第一行中给出的链接。

    build.gradle(应用程序)

    apply plugin: 'com.android.application'
    
    android {
        signingConfigs {
            config {
                keyAlias 'androiddebugkey'
                keyPassword 'android'
                storeFile file('debug.keystore')
                storePassword 'android'
            }
        }
        compileSdkVersion 29
        buildToolsVersion "29.0.3"
        defaultConfig {
            applicationId "com.fyp.selfzenapp"
            minSdkVersion 21
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
            debug {
                signingConfig signingConfigs.config
            }
        }
        compileOptions {
            targetCompatibility = "8"
            sourceCompatibility = "8"
        } // No static method metafactory
    }
    
    apply plugin: 'com.android.application'
    
    dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'androidx.appcompat:appcompat:1.2.0'
        implementation 'com.android.support.constraint:constraint-layout:2.0.4'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        implementation 'com.google.firebase:firebase-firestore:23.0.0'
        implementation 'com.google.firebase:firebase-storage:20.0.0'
        implementation 'com.google.firebase:firebase-functions:20.0.0'
        implementation 'com.google.firebase:firebase-core:19.0.0'
        implementation 'com.google.firebase:firebase-auth:21.0.1'
        implementation 'com.google.firebase:firebase-database:20.0.0'
        implementation 'com.google.firebase:firebase-iid:21.1.0'
        implementation 'com.google.firebase:firebase-messaging:20.2.3'
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.android.gms:play-services-auth:19.0.0'
        implementation 'com.google.code.gson:gson:2.8.6'
        implementation 'com.pes.materialcolorpicker:library:1.2.0'
        implementation 'com.google.android.gms:play-services-location:18.0.0'
        implementation 'com.google.android.gms:play-services-maps:17.0.1'
        implementation 'com.google.android.material:material:1.4.0-beta01'
    
        // Import the Firebase BoM
        implementation platform('com.google.firebase:firebase-bom:27.1.0')
    
        // Add the dependency for the Firebase SDK for Google Analytics
        // When using the BoM, don't specify versions in Firebase dependencies
        implementation 'com.google.firebase:firebase-analytics'
    }
    apply plugin: 'com.google.firebase.crashlytics'
    apply plugin: 'com.google.gms.google-services'
    

    【讨论】:

    • 嗨!感谢您的回答。我已经尝试实施您的建议,但是我收到了 ShortcutKeysTabsAdapterInvalid method declaration; return type required 的错误。而TabLayout.getTabCount() 得到错误Non-static method 'getTabCount()' cannot be referenced from a static context
    • 对不起,实际上我昨天正在制作并意外粘贴了该代码,我忘了替换它。请用您的适配器类名称替换它。
    • 我编辑了我的代码。感谢您实施我的建议
    • 用tabLayout替换tablayout。
    • 我试图让您的建议有效,但我的应用程序仍然崩溃。这是来自 Logcat 的错误状态:Attempt to invoke virtual method 'int com.google.android.material.tabs.TabLayout.getTabCount()' on a null object reference
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多