主要活动类
public class MainActivity extends Activity {
TextView textupdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textupdate = findViewById(R.id.textView1);
MediaPlayerclass mpclass = MediaPlayerclass(getApplicationContext());
mpclass.MediaPlayer_Start(R.raw.track1);
}
public void mUpdateCountv() {
System.out.println("textupdate "textupdate); //Returns null from MediaPlayerclass
textupdate.setText("MpCompleted");
}
媒体播放器类
public class MediaPlayerclass {
private Context mContext = null;
private int mResId = 0;
MainActivity mainactivity;
public MediaPlayer mCurrentPlayer = null;
public MediaPlayerclass(Context context) {
this.mContext = context;
mainactivity = new MainActivity();
}
public void MediaPlayer_Start(int resId) {
this.mResId = resId;
mCurrentPlayer = MediaPlayer.create(mContext, mResId);
mCurrentPlayer.setOnCompletionListener(onCompletionListener);
mCurrentPlayer.start();
}
public MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mCurrentPlayer.release();
//Textview Update
mainactivity.mUpdateCountv();
}
};
原木
05-01 13:00:48.258:e/androidruntime(5599):致命异常:main
05-01 13:00:48.258:E/AndroidRuntime(5599):过程:
媒体,PID:5599
05-01 13:00:48.258:E/AndroidRuntime(5599):
java.lang.NullPointerException:尝试调用虚拟方法“void
android.widget.textView.settext(java.lang.CharSequence)'在空值上
对象引用
05-01 13:00:48.258:E/AndroidRuntime(5599):在
com.example.media.mainActivity.mupdatecountv(mainActivity.java:665)
05-01 13:00:48.258:E/AndroidRuntime(5599):在
com.example.media.mediaPlayerClass$1.onCompletion(mediaPlayerClass.java:41)
05-01 13:00:48.258:E/AndroidRuntime(5599):在
android.media.mediaplayer$eventhandler.handleMessage(mediaplayer.java:2538)
当我从MediaPlayerClass调用
mUpdateCountv
方法时,textupdate
始终为空,因此无法从MediaPlayerclass
类更新我的textView。我的代码有什么问题吗?提前谢谢。 最佳答案
在mediaplayer类构造函数中执行以下操作:
mainActivity = (MainActivity) context;
在你的主要活动中,通过
getActivity()
而不是getApplicationContext()
您正在创建一个新活动,但需要旧实例。如果需要调用update方法,可以将其用作context对象(因为activity是context的子类),并将其强制转换为mainactivity。