You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用运行触发FATAL EXCEPTION: main异常求助

Android RecyclerView应用启动崩溃问题解决

运行基于RecyclerView的Android应用时触发FATAL EXCEPTION: main异常,已尝试更新Gradle、重启IDE,问题仍存在。相关代码及错误日志如下:

Gradle构建配置

plugins {
    id 'com.android.application'
}

android {
    namespace 'com.manu.smallrecyclerview'
    compileSdk 33

    defaultConfig {
        applicationId "com.manu.smallrecyclerview"
        minSdk 21
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.0'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

MainActivity代码

package com.manu.smallrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView = findViewById(R.id.recyclerView);
    RecylserAdapter adapter;

    String [] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August",
    "September", "November", "December"};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecylserAdapter(this,monthNames);
        recyclerView.setAdapter(adapter);
    }
}

RecyclerView适配器代码

package com.manu.smallrecyclerview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RecylserAdapter extends RecyclerView.Adapter<RecylserAdapter.ViewHolder> {
    String data [];
    Context context;

    public RecylserAdapter(Context context, String[] data) {
        this.data = data;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.custom_design, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(data[position]);
        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "Clicked on : ", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textNames);
        }
    }
}

错误日志

E  Could not remove dir '/data/data/com.manu.smallrecyclerview/code_cache/.ll/': No such file or directory
---------------------------- PROCESS STARTED (4931) for package com.manu.smallrecyclerview ----------------------------
2023-01-15 19:42:01.922  4931-4931  GraphicsEnvironment     com.manu.smallrecyclerview           V  ANGLE Developer option for 'com.manu.smallrecyclerview' set to: 'default'
2023-01-15 19:42:01.924  4931-4931  GraphicsEnvironment     com.manu.smallrecyclerview           V  ANGLE GameManagerService for com.manu.smallrecyclerview: false
2023-01-15 19:42:01.924  4931-4931  GraphicsEnvironment     com.manu.smallrecyclerview           V  Neither updatable production driver nor prerelease driver is supported.
2023-01-15 19:42:01.933  4931-4931  NetworkSecurityConfig   com.manu.smallrecyclerview           D  No Network Security Config specified, using platform default
2023-01-15 19:42:01.934  4931-4931  NetworkSecurityConfig   com.manu.smallrecyclerview           D  No Network Security Config specified, using platform default
2023-01-15 19:42:02.062  4931-4958  libEGL                  com.manu.smallrecyclerview           D  loaded /vendor/lib64/egl/libEGL_emulation.so
2023-01-15 19:42:02.073  4931-4958  libEGL                  com.manu.smallrecyclerview           D  loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-01-15 19:42:02.089  4931-4958  libEGL                  com.manu.smallrecyclerview           D  loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-01-15 19:42:02.399  4931-4931  AndroidRuntime          com.manu.smallrecyclerview           D  Shutting down VM
2023-01-15 19:42:02.404  4931-4931  AndroidRuntime          com.manu.smallrecyclerview           E  FATAL EXCEPTION: main
    Process: com.manu.smallrecyclerview, PID: 4931
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.manu.smallrecyclerview/com.manu.smallrecyclerview.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3591)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.app.ActivityThread.main(ActivityThread.java:7842)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:181)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
    at android.content.Context.obtainStyledAttributes(Context.java:804)
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:922)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:889)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:691)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:264)
    at com.manu.smallrecyclerview.MainActivity.<init>(MainActivity.java:12)
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
    at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1285)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3578)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842) 
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loopOnce(Looper.java:201) 
    at android.os.Looper.loop(Looper.java:288) 
    at android.app.ActivityThread.main(ActivityThread.java:7842) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
2023-01-15 19:42:02.472  4931-4931  Process                 com.manu.smallrecyclerview           I  Sending signal. PID: 4931 SIG: 9
---------------------------- PROCESS ENDED (4931) for package com.manu.smallrecyclerview ----------------------------

问题分析与修复方案

从错误日志可定位到崩溃根源:在Activity初始化阶段调用findViewById导致空指针异常。MainActivity中直接在成员变量声明时执行RecyclerView recyclerView = findViewById(R.id.recyclerView);,此时Activity尚未完成创建,Context对象为空,调用findViewById必然触发NPE。

修复步骤

将findViewById调用移至onCreate方法内部,且必须在setContentView(R.layout.activity_main);之后执行——只有加载布局后,才能找到对应的控件实例。

修改后的MainActivity代码:

package com.manu.smallrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    RecylserAdapter adapter;

    String [] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August",
    "September", "November", "December"};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 移至此处初始化RecyclerView
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecylserAdapter(this,monthNames);
        recyclerView.setAdapter(adapter);
    }
}

可选优化

适配器中的Toast可优化为显示点击的月份名称,提升用户体验:

holder.textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Clicked on : " + data[position], Toast.LENGTH_SHORT).show();
    }
});

内容的提问来源于stack exchange,提问作者Manu G Manu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:15:30