Android:无法暂停活动:java.lang.NullPointerException:空对象引用

时间:2019-05-09 20:19:26

标签: java android

我的应用程序一切正常,但是当我按下“后退”按钮(我的意思是退出应用程序)时,应用程序崩溃了。我不知道为什么?我尝试了几种解决方案,但没有任何效果。这是一个声音/铃声应用程序。

我是Android的新手,我需要一些建议,例如“删除此” /“添加此”

这是我的代码

package com.app.trying;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.app.trying.tabs.Tab3;
import com.app.trying.tabs.Tab1;
import com.app.trying.tabs.Tab2;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    public MediaPlayer mp;
    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;


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


        // Banner Ad
        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        toolbarTabs();
        sidebar();
        externalStorageAccess();

    }

    // Creates sidebar and sets onClickListeners
    public void sidebar(){
        mNavigationView = (NavigationView) findViewById(R.id.navigationView);
        mNavigationView.setItemIconTintList(null);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();

                switch (menuItem.getItemId()){
                    case R.id.sounds:
                        FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                        xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
                        break;

                    case R.id.share:
                        Intent shareIntent = new Intent(Intent.ACTION_SEND);
                        shareIntent.setType("text/plain");
                        shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.app_name));
                        shareIntent.putExtra(Intent.EXTRA_TEXT, getText(R.string.share_text) + " " +  getText(R.string.app_name) + "\n\n" + getText(R.string.playstore_link));
                        startActivity(Intent.createChooser(shareIntent,  getText(R.string.share_via)));
                        break;

                }
                return false;
            }

        });
    }


    // Is listening which sound on Tab1 has been clicked
    public void TabOneItemClicked(int position) {
        cleanUpMediaPlayer();
        mp=MediaPlayer.create(MainActivity.this, Tab1.soundfiles[position]);
        mp.start();

    }

    // Is listening which sound on Tab2 has been clicked
    public void TabTwoItemClicked(int position) {
        cleanUpMediaPlayer();
        mp=MediaPlayer.create(MainActivity.this, Tab2.soundfiles[position]);
        mp.start();
    }

    // Is listening which sound on Tab3 has been clicked
    public void TabThreeItemClicked ( int position){
        cleanUpMediaPlayer();
        mp=MediaPlayer.create(MainActivity.this, Tab3.soundfiles[position]);
        mp.start();
    }


    // Cleans MediaPlayer
    public void cleanUpMediaPlayer() {
        if (mp != null) {
            try {
                mp.stop();
                mp.release();
                mp = null;
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();

            }
        }
    }

    // Access external storage
    public void externalStorageAccess(){
        final File FILES_PATH = new File(Environment.getExternalStorageDirectory(), "Android/data/"+ getText(R.string.package_name) +"/files");
        if (Environment.MEDIA_MOUNTED.equals(
                Environment.getExternalStorageState())) {
            if (!FILES_PATH.mkdirs()) {
                Log.w("error", "Could not create " + FILES_PATH);
            }
        } else {
            Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    // Creates toolbar Tabs
    public void toolbarTabs(){
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
                R.string.app_name);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }


    @Override
    protected void onPause() {
        super.onPause();
        stopMediaPlayer();
    }

    public void stopMediaPlayer()
    {
        mp.stop();
    }
}


这是我的错误日志。


2019-05-09 19:13:22.296 704-704/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2019-05-09 19:13:32.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4
2019-05-09 19:13:39.537 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:40.333 24095-24175/? E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2019-05-09 19:13:43.035 443-2253/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2019-05-09 19:13:43.116 24095-24095/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.app.trying, PID: 24095
    java.lang.RuntimeException: Unable to pause activity {com.app.trying/com.app.trying.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
        at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3735)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675)
        at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649)
        at android.app.ActivityThread.-wrap16(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6111)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
        at com.app.trying.MainActivity.stopMediaPlayer(MainActivity.java:155)
        at com.app.trying.MainActivity.onPause(MainActivity.java:150)
        at android.app.Activity.performPause(Activity.java:6917)
        at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1323)
        at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3724)
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3701) 
        at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3675) 
        at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3649) 
        at android.app.ActivityThread.-wrap16(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1487) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6111) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapAllocatedSize18887424
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, NativeHeapSize35651584
2019-05-09 19:13:43.736 2484-2484/? E/Launcher3: Meminfo, getNativeHeapFreeSize16764160
2019-05-09 19:13:51.682 704-704/? E/cnss-daemon: Stale or unreachable neighbors, ndm state: 4

如何解决此错误?任何帮助都会很棒。谢谢。

2 个答案:

答案 0 :(得分:0)

您的MediaPlayer实例为null,如堆栈跟踪所示,所以:

    public void stopMediaPlayer()
    {
        if (mp != null) {
            mp.stop();
        }
    }

答案 1 :(得分:-1)

您的MediaPlayer实例永远不会初始化。因此,您必须处理它。