本文介绍了无法实例化活动:尝试调用虚拟方法 android.content.Context.getResources()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我是初学者.首先说我看过以前的帖子但没有回答.我尝试测试一个音频播放器,但是当我尝试运行该应用程序时,它会因为空对象引用而立即崩溃.这是 Logcat:(此日志说:错误在 java 代码的第 28 行)例外:主要进程:ir.pluto.mediaplayer,PID:19100java.lang.RuntimeException:无法实例化活动 ComponentInfo{ir.pluto.mediaplayer/ir.pluto.mediaplayer.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法 'android.content.res.Resources android.content.Context.getResources()' 在空对象引用上在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)在 android.app.ActivityThread.access$1100(ActivityThread.java:229)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:148)在 android.app.ActivityThread.main(ActivityThread.java:7325)在 java.lang.reflect.Method.invoke(Native Method)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法android.content.res.Resources android.content.Context.getResources()"在 android.content.ContextWrapper.getResources(ContextWrapper.java:92)在 android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)在 android.view.View.(View.java:4054)在 android.view.View.(View.java:4186)在 android.widget.ProgressBar.(ProgressBar.java:313)在 android.widget.AbsSeekBar.(AbsSeekBar.java:188)在 android.widget.SeekBar.(SeekBar.java:85)在 android.widget.SeekBar.(SeekBar.java:81)在 android.widget.SeekBar.(SeekBar.java:77)在 android.widget.SeekBar.(SeekBar.java:73)在 ir.pluto.mediaplayer.MainActivity.(MainActivity.java:28)在 java.lang.Class.newInstance(本机方法)在 android.app.Instrumentation.newActivity(Instrumentation.java:1096)在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)在 android.app.ActivityThread.access$1100(ActivityThread.java:229)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:148)在 android.app.ActivityThread.main(ActivityThread.java:7325)在 java.lang.reflect.Method.invoke(Native Method)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 我的部分 java 代码是:import android.app.Activity;导入 android.content.Intent;导入 android.media.MediaPlayer;导入 android.os.Bundle;导入 android.os.Handler;导入 android.view.View;导入 android.widget.ImageButton;导入 android.widget.SeekBar;导入 android.widget.TextView;导入 android.widget.Toast;导入 java.io.IOException;导入 java.util.ArrayList;导入 java.util.HashMap;导入 java.util.Random;公共类 MainActivity 扩展 Activity 实现 MediaPlayer.OnCompletionListener {ImageButton btnPlay;ImageButton btnForward;ImageButton btnBackward;ImageButton btnNext;ImageButton btnPrevious;ImageButton btnPlaylist;ImageButton btnRepeat;ImageButton btnShuffle;SeekBar songProgressBar=new SeekBar(this);TextView 歌曲标题标签;TextView songCurrentDurationLabel;TextView songTotalDurationLabel;//媒体播放器媒体播放器 mp;//用于更新 UI 计时器、进度条等的处理程序.Handler mHandler = new Handler();SongsManager 歌曲管理器;实用工具;int seekForwardTime = 5000;//5000 毫秒int seekBackwardTime = 5000;//5000 毫秒int currentSongIndex = 0;boolean isShuffle = false;boolean isRepeat = false;ArrayList>SongList = 新的 ArrayList();@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnPlay = (ImageButton) findViewById(R.id.btnPlay);btnForward = (ImageButton) findViewById(R.id.btnForward);btnBackward = (ImageButton) findViewById(R.id.btnBackward);btnNext = (ImageButton) findViewById(R.id.btnNext);btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);SongProgressBar = (SeekBar) findViewById(R.id.songProgressBar);SongTitleLabel = (TextView) findViewById(R.id.songTitle);songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);//媒体播放器mp = 新媒体播放器();歌曲管理器 = 新歌曲管理器();utils = 新的实用程序();//监听器SongProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {@覆盖public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {} ...第 28 行是:SeekBar songProgressBar=new SeekBar(this);感谢您的回答...通过@PavneetSingh 回答更新我的代码后,发生了同样的错误再次但这次是在第 70 行,它是:songProgressBar.setOnSeekBarChangeListener(this);//重要的第一个回答编辑后的主要活动的完整代码是:package ir.pluto.mediaplayer;导入 android.app.Activity;导入 android.content.Intent;导入 android.media.MediaPlayer;导入 android.os.Bundle;导入 android.os.Handler;导入 android.view.View;导入 android.widget.ImageButton;导入 android.widget.SeekBar;导入 android.widget.TextView;导入 android.widget.Toast;导入 java.io.IOException;导入 java.util.ArrayList;导入 java.util.HashMap;导入 java.util.Random;公共类 MainActivity 扩展 Activity 实现 MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener {ImageButton btnPlay;ImageButton btnForward;ImageButton btnBackward;ImageButton btnNext;ImageButton btnPrevious;ImageButton btnPlaylist;ImageButton btnRepeat;ImageButton btnShuffle;SeekBar songProgressBar;TextView 歌曲标题标签;TextView songCurrentDurationLabel;TextView songTotalDurationLabel;//媒体播放器媒体播放器 mp;//用于更新 UI 计时器、进度条等的处理程序.Handler mHandler = new Handler();SongsManager 歌曲管理器;实用工具;int seekForwardTime = 5000;//5000 毫秒int seekBackwardTime = 5000;//5000 毫秒int currentSongIndex = 0;boolean isShuffle = false;boolean isRepeat = false;ArrayList>SongList = 新的 ArrayList();@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnPlay = (ImageButton) findViewById(R.id.btnPlay);btnForward = (ImageButton) findViewById(R.id.btnForward);btnBackward = (ImageButton) findViewById(R.id.btnBackward);btnNext = (ImageButton) findViewById(R.id.btnNext);btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);SongProgressBar = (SeekBar) findViewById(R.id.songProgressBar);SongTitleLabel = (TextView) findViewById(R.id.songTitle);songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);//媒体播放器mp = 新媒体播放器();歌曲管理器 = 新歌曲管理器();utils = 新的实用程序();//监听器songProgressBar.setOnSeekBarChangeListener(this);//重要的mp.setOnCompletionListener(this);//重要的//获取所有歌曲列表songList = songManager.getPlayList();/*播放列表点击事件的按钮点击事件启动显示歌曲列表的列表活动*/btnPlaylist.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){Intent i = new Intent(getApplicationContext(), PlayListActivity.class);startActivityForResult(i, 100);}});/*前进按钮点击事件转发歌曲指定秒数*/btnForward.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){//获取当前歌曲位置int currentPosition = mp.getCurrentPosition();//检查seekForward 时间是否小于歌曲持续时间if(currentPosition + seekForwardTime 0){playSong(currentSongIndex - 1);currentSongIndex = currentSongIndex - 1;}别的{//播放最后一首歌曲playSong(songsList.size() - 1);currentSongIndex = SongsList.size() - 1;}}});/** 重复按钮的按钮单击事件* 启用重复标志为真*/btnRepeat.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){如果(是重复){isRepeat = false;Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_LONG).show();btnRepeat.setImageResource(R.drawable.btn_repeat);}别的{//使重复为真isRepeat = true;Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_LONG).show();//将 shuffle 设为 falseisShuffle = false;btnRepeat.setImageResource(R.drawable.btn_repeat);btnShuffle.setImageResource(R.drawable.btn_shuffle);}}});/** 随机播放按钮的按钮点击事件* 启用 shuffle 标志为真*/btnShuffle.setOnClickListener(new View.OnClickListener() {@覆盖公共无效 onClick(查看 arg0){如果(isShuffle){isShuffle = false;Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();btnShuffle.setImageResource(R.drawable.btn_shuffle);}别的{//使重复为真isShuffle=真;Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();//将 shuffle 设为 falseisRepeat = false;btnShuffle.setImageResource(R.drawable.btn_shuffle);btnRepeat.setImageResource(R.drawable.btn_repeat);}}});}//************在onCreate()之外**************/*** 从播放列表视图接收歌曲索引* 并播放歌曲**/@覆盖protected void onActivityResult(int requestCode,int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);如果(结果代码 == 100){currentSongIndex = data.getExtras().getInt("songIndex");//播放选定的歌曲playSong(currentSongIndex);}}/*** 播放歌曲的功能* @param songIndex - 歌曲索引* */public void playSong(int songIndex){//播放歌曲尝试 {mp.reset();mp.setDataSource(songsList.get(songIndex).get("songPath"));mp.prepare();mp.start();//显示歌曲名称String songTitle = SongsList.get(songIndex).get("songTitle");SongTitleLabel.setText(songTitle);//更改按钮图像以暂停图像btnPlay.setImageResource(R.drawable.btn_pause);//设置进度条值SongProgressBar.setProgress(0);SongProgressBar.setMax(100);//更新进度条更新进度条();} catch (IllegalArgumentException | IllegalStateException | IOException e) {e.printStackTrace();}}/*** 更新搜索栏上的计时器**/公共无效updateProgressBar(){mHandler.postDelayed(mUpdateTimeTask, 100);}/*** 后台可运行线程* */private Runnable mUpdateTimeTask = new Runnable() {公共无效运行(){long totalDuration = mp.getDuration();长 currentDuration = mp.getCurrentPosition();//显示总持续时间songTotalDurationLabel.setText(utils.milliSecondsToTimer(totalDuration));//显示播放完成的时间SongCurrentDurationLabel.setText(utils.milliSecondsToTimer(currentDuration));//更新进度条int progress = utils.getProgressPercentage(currentDuration, totalDuration);//Log.d("Progress", ""+progress);SongProgressBar.setProgress(progress);//100 毫秒后运行此线程mHandler.postDelayed(this, 100);}};/** 在歌曲播放完成* 如果重复打开再次播放同一首歌曲* 如果 shuffle 是 ON 播放随机歌曲*/@覆盖公共无效 onCompletion(MediaPlayer mp) {//检查repeat是ON还是OFF如果(是重复){//重复播放同一首歌曲playSong(currentSongIndex);} else if(isShuffle){//shuffle 开启 - 随机播放一首歌曲随机 rand = new Random();currentSongIndex = rand.nextInt((songsList.size() - 1) + 1);playSong(currentSongIndex);} 别的{//没有重复或随机播放 - 播放下一首歌曲if(currentSongIndex < (songsList.size() - 1)){playSong(currentSongIndex + 1);currentSongIndex = currentSongIndex + 1;}别的{//播放第一首歌曲播放歌曲(0);当前歌曲索引 = 0;}}}@覆盖public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}/** 当用户开始移动进度处理器时*/@覆盖公共无效 onStartTrackingTouch(SeekBar seekBar) {//从更新进度条中删除消息处理程序mHandler.removeCallbacks(mUpdateTimeTask);}/** 当用户停止移动进度条时*/@覆盖公共无效 onStopTrackingTouch(SeekBar seekBar) {mHandler.removeCallbacks(mUpdateTimeTask);int totalDuration = mp.getDuration();int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);//前进或后退到特定秒mp.seekTo(currentPosition);//再次更新定时器进度更新进度条();}}完整的错误细节是(MainActivity.java:70):例外:主要进程:ir.pluto.mediaplayer,PID:28285java.lang.RuntimeException: 无法启动活动 ComponentInfo{ir.pluto.mediaplayer/ir.pluto.mediaplayer.MainActivity}: java.lang.NullPointerException: 尝试调用虚拟方法 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' 在一个空对象引用上在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)在 android.app.ActivityThread.access$1100(ActivityThread.java:229)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:148)在 android.app.ActivityThread.main(ActivityThread.java:7325)在 java.lang.reflect.Method.invoke(Native Method)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)"在 ir.pluto.mediaplayer.MainActivity.onCreate(MainActivity.java:70)在 android.app.Activity.performCreate(Activity.java:6904)在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)在 android.app.ActivityThread.access$1100(ActivityThread.java:229)在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)在 android.os.Handler.dispatchMessage(Handler.java:102)在 android.os.Looper.loop(Looper.java:148)在 android.app.ActivityThread.main(ActivityThread.java:7325)在 java.lang.reflect.Method.invoke(Native Method)在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)设计在这个文件下:播放器.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/player_background"><!--另一个代码--><!-- 进度条/搜索栏 --><搜索栏android:id="@+id/songProgressBar"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_above="@id/player_footer_bg"机器人:layout_marginBottom="1dp"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"机器人:paddingLeft =6dp"机器人:paddingRight="6dp"android:progressDrawable="@drawable/seekbar_progress"android:thumb="@drawable/seekbar_thumb"/><!--另一个代码--></相对布局> 解决方案 this 没有任何意义,因为在 onCreate 之前它会是 null> 因为 Activity 在 onCreate 被调用所以移动你的 songProgressBar=new SeekBar(this); 在 Oncreate public class MainActivity extends Activity 实现 MediaPlayer.OnCompletionListener {//..SeekBar songProgressBar;//..@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);songProgressBar=new SeekBar(this);更新:您正在使用 findViewById 从 XML 初始化 songProgressBar 引用,因此您根本不需要这部分songProgressBar=new SeekBar(this);这样做public class MainActivity extends Activity 实现 MediaPlayer.OnCompletionListener {//.. 代码SeekBar songProgressBar;//.. 代码@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//.. 代码SongProgressBar = (SeekBar) findViewById(R.id.songProgressBar);//.. 代码更新 2 : 使用 setContentView(R.layout.Player); 而不是 setContentView(R.layout.activity_main); 虽然你必须重命名 XML 文件转成小写 i am a beginner.I try to test a audio player,But when I try to run the app, it instantly crashes because of a null object reference.This is Logcat:(this log say: Error is in Line 28 of java code)EXCEPTION: main Process: ir.pluto.mediaplayer, PID: 19100 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{ir.pluto.mediaplayer/ir.pluto.mediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) at android.app.ActivityThread.access$1100(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.content.ContextWrapper.getResources(ContextWrapper.java:92) at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81) at android.view.View.<init>(View.java:4054) at android.view.View.<init>(View.java:4186) at android.widget.ProgressBar.<init>(ProgressBar.java:313) at android.widget.AbsSeekBar.<init>(AbsSeekBar.java:188) at android.widget.SeekBar.<init>(SeekBar.java:85) at android.widget.SeekBar.<init>(SeekBar.java:81) at android.widget.SeekBar.<init>(SeekBar.java:77) at android.widget.SeekBar.<init>(SeekBar.java:73) at ir.pluto.mediaplayer.MainActivity.<init>(MainActivity.java:28) at java.lang.Class.newInstance(Native Method) at android.app.Instrumentation.newActivity(Instrumentation.java:1096) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)  at android.app.ActivityThread.access$1100(ActivityThread.java:229)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:7325)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) And part of my java code is:import android.app.Activity;import android.content.Intent;import android.media.MediaPlayer;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;import android.widget.TextView;import android.widget.Toast;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.Random;public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener { ImageButton btnPlay; ImageButton btnForward; ImageButton btnBackward; ImageButton btnNext; ImageButton btnPrevious; ImageButton btnPlaylist; ImageButton btnRepeat; ImageButton btnShuffle; SeekBar songProgressBar=new SeekBar(this); TextView songTitleLabel; TextView songCurrentDurationLabel; TextView songTotalDurationLabel; // Media Player MediaPlayer mp; // Handler to update UI timer, progress bar etc,. Handler mHandler = new Handler(); SongsManager songManager; Utilities utils; int seekForwardTime = 5000; // 5000 milliseconds int seekBackwardTime = 5000; // 5000 milliseconds int currentSongIndex = 0; boolean isShuffle = false; boolean isRepeat = false; ArrayList<HashMap<String, String>> songsList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnPlay = (ImageButton) findViewById(R.id.btnPlay); btnForward = (ImageButton) findViewById(R.id.btnForward); btnBackward = (ImageButton) findViewById(R.id.btnBackward); btnNext = (ImageButton) findViewById(R.id.btnNext); btnPrevious = (ImageButton) findViewById(R.id.btnPrevious); btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist); btnRepeat = (ImageButton) findViewById(R.id.btnRepeat); btnShuffle = (ImageButton) findViewById(R.id.btnShuffle); songProgressBar = (SeekBar) findViewById(R.id.songProgressBar); songTitleLabel = (TextView) findViewById(R.id.songTitle); songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel); songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel); // Media player mp = new MediaPlayer(); songManager = new SongsManager(); utils = new Utilities(); // Listeners songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }...and line 28 is:SeekBar songProgressBar=new SeekBar(this);Thank you for your answers ...songProgressBar.setOnSeekBarChangeListener(this); // Importantpackage ir.pluto.mediaplayer;import android.app.Activity;import android.content.Intent;import android.media.MediaPlayer;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.widget.ImageButton;import android.widget.SeekBar;import android.widget.TextView;import android.widget.Toast;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.Random;public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener { ImageButton btnPlay; ImageButton btnForward; ImageButton btnBackward; ImageButton btnNext; ImageButton btnPrevious; ImageButton btnPlaylist; ImageButton btnRepeat; ImageButton btnShuffle; SeekBar songProgressBar; TextView songTitleLabel; TextView songCurrentDurationLabel; TextView songTotalDurationLabel; // Media Player MediaPlayer mp; // Handler to update UI timer, progress bar etc,. Handler mHandler = new Handler(); SongsManager songManager; Utilities utils; int seekForwardTime = 5000; // 5000 milliseconds int seekBackwardTime = 5000; // 5000 milliseconds int currentSongIndex = 0; boolean isShuffle = false; boolean isRepeat = false; ArrayList<HashMap<String, String>> songsList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnPlay = (ImageButton) findViewById(R.id.btnPlay); btnForward = (ImageButton) findViewById(R.id.btnForward); btnBackward = (ImageButton) findViewById(R.id.btnBackward); btnNext = (ImageButton) findViewById(R.id.btnNext); btnPrevious = (ImageButton) findViewById(R.id.btnPrevious); btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist); btnRepeat = (ImageButton) findViewById(R.id.btnRepeat); btnShuffle = (ImageButton) findViewById(R.id.btnShuffle); songProgressBar = (SeekBar) findViewById(R.id.songProgressBar); songTitleLabel = (TextView) findViewById(R.id.songTitle); songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel); songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel); // Media player mp = new MediaPlayer(); songManager = new SongsManager(); utils = new Utilities(); // Listeners songProgressBar.setOnSeekBarChangeListener(this); // Important mp.setOnCompletionListener(this); // Important // Getting all songs list songsList = songManager.getPlayList(); /* Button Click event for Play list click event Launches list activity which displays list of songs */ btnPlaylist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), PlayListActivity.class); startActivityForResult(i, 100); } }); /* Forward button click event Forwards song specified seconds */ btnForward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // get current song position int currentPosition = mp.getCurrentPosition(); // check if seekForward time is lesser than song duration if(currentPosition + seekForwardTime <= mp.getDuration()){ // forward song mp.seekTo(currentPosition + seekForwardTime); }else{ // forward to end position mp.seekTo(mp.getDuration()); } } }); /* Backward button click event Backward song to specified seconds */ btnBackward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // get current song position int currentPosition = mp.getCurrentPosition(); // check if seekBackward time is greater than 0 sec if(currentPosition - seekBackwardTime >= 0){ // forward song mp.seekTo(currentPosition - seekBackwardTime); }else{ // backward to starting position mp.seekTo(0); } } }); /* Next button click event Plays next song by taking currentSongIndex + 1 */ btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // check if next song is there or not if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex + 1); currentSongIndex = currentSongIndex + 1; }else{ // play first song playSong(0); currentSongIndex = 0; } } }); /* Back button click event Plays previous song by currentSongIndex - 1 */ btnPrevious.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(currentSongIndex > 0){ playSong(currentSongIndex - 1); currentSongIndex = currentSongIndex - 1; }else{ // play last song playSong(songsList.size() - 1); currentSongIndex = songsList.size() - 1; } } }); /* * Button Click event for Repeat button * Enables repeat flag to true */ btnRepeat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(isRepeat){ isRepeat = false; Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_LONG).show(); btnRepeat.setImageResource(R.drawable.btn_repeat); }else{ // make repeat to true isRepeat = true; Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_LONG).show(); // make shuffle to false isShuffle = false; btnRepeat.setImageResource(R.drawable.btn_repeat); btnShuffle.setImageResource(R.drawable.btn_shuffle); } } }); /* * Button Click event for Shuffle button * Enables shuffle flag to true */ btnShuffle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if(isShuffle){ isShuffle = false; Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show(); btnShuffle.setImageResource(R.drawable.btn_shuffle); }else{ // make repeat to true isShuffle= true; Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show(); // make shuffle to false isRepeat = false; btnShuffle.setImageResource(R.drawable.btn_shuffle); btnRepeat.setImageResource(R.drawable.btn_repeat); } } }); } //************Outside of onCreate()************** /** * Receiving song index from playlist view * and play the song **/ @Override protected void onActivityResult(int requestCode,int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == 100){ currentSongIndex = data.getExtras().getInt("songIndex"); // play selected song playSong(currentSongIndex); } } /** * Function to play a song * @param songIndex - index of song * */ public void playSong(int songIndex){ // Play song try { mp.reset(); mp.setDataSource(songsList.get(songIndex).get("songPath")); mp.prepare(); mp.start(); // Displaying Song title String songTitle = songsList.get(songIndex).get("songTitle"); songTitleLabel.setText(songTitle); // Changing Button Image to pause image btnPlay.setImageResource(R.drawable.btn_pause); // set Progress bar values songProgressBar.setProgress(0); songProgressBar.setMax(100); // Updating progress bar updateProgressBar(); } catch (IllegalArgumentException | IllegalStateException | IOException e) { e.printStackTrace(); } } /** * Update timer on seekbar **/ public void updateProgressBar() { mHandler.postDelayed(mUpdateTimeTask, 100); } /** * Background Runnable thread * */ private Runnable mUpdateTimeTask = new Runnable() { public void run() { long totalDuration = mp.getDuration(); long currentDuration = mp.getCurrentPosition(); // Displaying Total Duration time songTotalDurationLabel.setText(utils.milliSecondsToTimer(totalDuration)); // Displaying time completed playing songCurrentDurationLabel.setText(utils.milliSecondsToTimer(currentDuration)); // Updating progress bar int progress = utils.getProgressPercentage(currentDuration, totalDuration); //Log.d("Progress", ""+progress); songProgressBar.setProgress(progress); // Running this thread after 100 milliseconds mHandler.postDelayed(this, 100); } }; /* * On Song Playing completed * if repeat is ON play same song again * if shuffle is ON play random song */ @Override public void onCompletion(MediaPlayer mp) { // check for repeat is ON or OFF if(isRepeat){ // repeat is on play same song again playSong(currentSongIndex); } else if(isShuffle){ // shuffle is on - play a random song Random rand = new Random(); currentSongIndex = rand.nextInt((songsList.size() - 1) + 1); playSong(currentSongIndex); } else{ // no repeat or shuffle ON - play next song if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex + 1); currentSongIndex = currentSongIndex + 1; }else{ // play first song playSong(0); currentSongIndex = 0; } } } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } /* * When user starts moving the progress handler */ @Override public void onStartTrackingTouch(SeekBar seekBar) { // remove message Handler from updating progress bar mHandler.removeCallbacks(mUpdateTimeTask); } /* * When user stops moving the progress hanlder */ @Override public void onStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); int totalDuration = mp.getDuration(); int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); // forward or backward to certain seconds mp.seekTo(currentPosition); // update timer progress again updateProgressBar(); }}EXCEPTION: main Process: ir.pluto.mediaplayer, PID: 28285 java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.pluto.mediaplayer/ir.pluto.mediaplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) at android.app.ActivityThread.access$1100(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference at ir.pluto.mediaplayer.MainActivity.onCreate(MainActivity.java:70) at android.app.Activity.performCreate(Activity.java:6904) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)  at android.app.ActivityThread.access$1100(ActivityThread.java:229)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:7325)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)  <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/player_background"> <!--another codes--> <!-- Progress Bar/Seek bar --> <SeekBar android:id="@+id/songProgressBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/player_footer_bg" android:layout_marginBottom="1dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:paddingLeft="6dp" android:paddingRight="6dp" android:progressDrawable="@drawable/seekbar_progress" android:thumb="@drawable/seekbar_thumb" /><!--another codes--> </RelativeLayout> 解决方案 this doesn't mean anything because before onCreate it will be null because Activity gets it's context(which you are referring as this ) from Application when onCreate get called so move your songProgressBar=new SeekBar(this); inside Oncreate public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener { //.. SeekBar songProgressBar; //.. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); songProgressBar=new SeekBar(this);Update : you are initializing the songProgressBar reference from XML using findViewById so you don't need this part at all songProgressBar=new SeekBar(this);so do thispublic class MainActivity extends Activity implements MediaPlayer.OnCompletionListener { // .. code SeekBar songProgressBar; // .. code @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // .. code songProgressBar = (SeekBar) findViewById(R.id.songProgressBar); // .. codeUpdate 2 : Use setContentView(R.layout.Player); instead of setContentView(R.layout.activity_main); although it's you must rename XML file to lowercase letters 这篇关于无法实例化活动:尝试调用虚拟方法 android.content.Context.getResources()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 21:48