I have implemented media player. I have only one Activity. When I'm starting the activity, my music starts to play and when I press the back button the music clip is in pause state, and again when I resume my activity, the music resumes properly. But there is error after I try to resume my Application after song got over. The app crashed, and I'm getting exception for IllegalStateException in back-press method( mp.pause();).
Please have a look at below code and suggest if I am doing something wrong.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
Log.e("Current ","Position -> " + length);
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause()
{
super.onStop();
SharedPreferences. Editor prefsEdit = prefs.edit();
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
f(mp.isPlaying())
{
mp.pause();
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Here is my Log Cat
07-09 11:52:01.057: I/System.out(6854): Music is over and Button is enable !!!!!!
07-09 11:52:03.297: D/AndroidRuntime(6854): Shutting down VM
07-09 11:52:03.297: W/dalvikvm(6854): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-09 11:52:03.339: E/AndroidRuntime(6854): FATAL EXCEPTION: main
07-09 11:52:03.339: E/AndroidRuntime(6854): java.lang.IllegalStateException
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.media.MediaPlayer.isPlaying(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.audio_demo.Audio_Activity.onKeyDown(Audio_Activity.java:203)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.KeyEvent.dispatch(KeyEvent.java:2609)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.app.Activity.dispatchKeyEvent(Activity.java:2375)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1847)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.os.Looper.loop(Looper.java:137)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-09 11:52:03.339: E/AndroidRuntime(6854): at java.lang.reflect.Method.invokeNative(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854): at java.lang.reflect.Method.invoke(Method.java:511)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-09 11:52:03.339: E/AndroidRuntime(6854): at dalvik.system.NativeStart.main(Native Method)
07-09 11:52:28.787: I/Process(6854): Sending signal. PID: 6854 SIG: 9
As I Understand the problem is about mp.seekTo(posiotion) in onResume() or mp.getCurrentPosition in onPause() method. That exception can because of not initializing the media player. According to the listener when the song finished you make your player stop and released and in onResume on line mp.seekTo(position) caused that exception. Remove mp.release() line in OnCompletion() method and in onResume and onpPause methods.
There's another thing you need to do. use a boolean value in your code to understand whether your mediaplayer finished playing or not. Change your onCreat like below:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
Log.e("Current ","Position -> " + length);
mp.setLooping(false);
mp.start();
prefsEdit.putInt("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
prefsEdit.putInt("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
#Override
public void onPause()
{
super.onStop();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying){
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying){
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
}
}
Related
I'm trying to make a simple audio player. When I create it in the main activity without service, it works correctly, music is playing (it works if I press power button to turn off the screen) and this is still working correctly after turn on the screen. But if I use service for playing music in the background, my app shuts down when I press power button for turn on the screen.
public class MainActivity extends AppCompatActivity {
static ArrayList<HashMap<String, Object>> listSongs = new ArrayList<>();
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listSongs = getAllMusicInfo();
intent = new Intent(this, BackgroundPlayer.class);
Button buttonStart = (Button) findViewById(R.id.startService);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(intent);
Toast.makeText(MainActivity.this, "It's started", Toast.LENGTH_SHORT).show();
}
});
Button buttonStop = (Button) findViewById(R.id.StopService);
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(intent);
Toast.makeText(MainActivity.this, "It's stopped", Toast.LENGTH_SHORT).show();
}
});
}
public class BackgroundPlayer extends Service implements MediaPlayer.OnCompletionListener {
MediaPlayer player;
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
try {
player.setDataSource((String) MainActivity.listSongs.get(0).get("path"));
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
#Override
public void onCompletion(MediaPlayer mp) {}
}
06-05 09:58:54.206 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer: start
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: message received msg=6, ext1=0, ext2=0
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: Received MEDIA_STARTED
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: callback application
06-05 09:58:54.206 31873-31885/com.vitaliylevashov.serviceplayer V/MediaPlayer: back from callback
06-05 09:58:54.236 31873-31873/com.vitaliylevashov.serviceplayer I/MediaPlayer: Don't send intent. msg.arg1 = 0, msg.arg2 = 0
06-05 09:58:54.236 31873-31873/com.vitaliylevashov.serviceplayer E/MediaPlayer: Should have subtitle controller already set
06-05 09:58:54.256 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer-JNI: getCurrentPosition: 192 (msec)
06-05 09:58:54.256 31873-31873/com.vitaliylevashov.serviceplayer V/MediaPlayer-JNI: isPlaying: 1
<<
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer D/AndroidRuntime: Shutting down VM
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41660bc0)
06-05 09:59:25.526 31873-31873/com.vitaliylevashov.serviceplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vitaliylevashov.serviceplayer, PID: 31873
android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.database.BulkCursorToCursorAdaptor.throwIfCursorIsClosed(BulkCursorToCursorAdaptor.java:64)
at android.database.BulkCursorToCursorAdaptor.requery(BulkCursorToCursorAdaptor.java:133)
at android.database.CursorWrapper.requery(CursorWrapper.java:186)
at android.app.Activity.performRestart(Activity.java:5346)
at android.app.ActivityThread.handleSleeping(ActivityThread.java:3487)
at android.app.ActivityThread.access$3000(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1428)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
add a service tag in Manifest ,may be you havent added that in manifest
<service android:name=".MyService" />
request to post error log/logcat
I have 2 animations, slide[1] and slide[3], and when I try to cancel them when the animation repeats itself, it causes a crash. here is some relevant code:
slide[1].setDuration(500); slide[1].setStartDelay(500);
slide[3].setDuration(500); slide[3].setStartDelay(500);
slide[1].addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
if (!start) {
table[2][2].setBackgroundResource(R.drawable.black);
slide[1].setDuration(1000);
slide[1].setStartDelay(0);
slide[3].setDuration(1000);
slide[3].setStartDelay(0);
slide[1].removeAllListeners();
slide[3].cancel();
slide[1].cancel();
}
}
#Override
public void onAnimationEnd(Animator animation) {
}
}); slide[1].start(); slide[3].start();
The line which causes the crash is "slide[1].cancel();", and I don't know why.
Apparently the crash is being caused when the phone is running on JellyBean, but not Marshmallow for example.
How can I solve this problem?
Thanks!
UPDATE: here is the logcat:
03-13 16:18:01.943 1623-1623/com.example.ohad.squerz E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:603)
at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:524)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This crash has been fixed in AOSP in this commit.
If you want to support API 16, you need to cancel your animations somewhere else than in onAnimationUpdate/onAnimationRepeat.
In your case (if it matters, because this answer comes a long time after your question), you probably want to avoid the repeat on your first animator, using setRepeatCount(0).
I know this has been posted multiple times now, but nothing seemed to fix my problem. I create a Loading Dialog on the UI thread, then start another thread which is doing some networking stuff and via interface, the class gets a callback, when networking is done. The problem is, after its done, i cant remove the loading dialog, even with "runOnUIThread". Here is the code:
public void onClickLoginButton (View view) {
if (!((EditText)findViewById(R.id.textNickname)).getText().toString().isEmpty() &&
!((EditText)findViewById(R.id.textPassword)).getText().toString().isEmpty()) {
loggingIn = new ProgressDialog(this);
loggingIn.setTitle("Login");
loggingIn.setMessage("Wait while logging in...");
loggingIn.show();
final LoginInterface callbackInterface = this;
new Thread(new Runnable() {
public void run() {
Networking net = new Networking();
net.Login(((EditText) findViewById(R.id.textNickname)).getText().toString(), ((EditText) findViewById(R.id.textPassword)).getText().toString(), callbackInterface);
}
}).start();
}
}
And this is the function that gets called by the networking stuff, after its done:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
loggingIn.hide();
loggingIn = null;
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
And this is the stack trace:
04-17 17:06:11.313 13018-13121/com.assigame.nidhoegger.assigame E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-1422
Process: com.assigame.nidhoegger.assigame, PID: 13018
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6122)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:850)
at android.view.View.requestLayout(View.java:16431)
at android.view.View.setFlags(View.java:8908)
at android.view.View.setVisibility(View.java:6036)
at android.app.Dialog.hide(Dialog.java:299)
at com.assigame.nidhoegger.assigame.Login.LoginCallback(Login.java:72)
at com.assigame.nidhoegger.assigame.Networking.Login(Networking.java:134)
at com.assigame.nidhoegger.assigame.Login$1.run(Login.java:64)
at java.lang.Thread.run(Thread.java:841)
04-17 17:06:11.719 13018-13018/com.assigame.nidhoegger.assigame E/WindowManager﹕ android.view.WindowLeaked: Activity com.assigame.nidhoegger.assigame.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42284588 G.E..... R......D 0,0-684,324} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:366)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.assigame.nidhoegger.assigame.Login.onClickLoginButton(Login.java:56)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You are calling the loggingIn.hide() method twice, and the first time not on the UI thread. Change your code to this:
#Override
public void LoginCallback(final boolean loginSuccess, final boolean isActivated) {
final Context context = this;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loginSuccess && isActivated) {
loggingIn.hide();
loggingIn = null;
finish();
} else if (loginSuccess == false) {
Toast.makeText(context, "Login failed! User/Password wrong", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Login failed! Account not activated", Toast.LENGTH_SHORT).show();
}
}
});
}
I am trying to make an application that passes through the audio samples obtained at the microphone to the speaker. This is the source code:
public class MainActivity extends Activity {
AudioManager am = null;
AudioRecord record =null;
AudioTrack track =null;
final int SAMPLE_FREQUENCY = 44100;
final int SIZE_OF_RECORD_ARRAY = 1024;
boolean isPlaying = false;
class MyThread extends Thread{
#Override
public void run(){
recordAndPlay();
}
}
MyThread newThread;
private void init() {
int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, min);
int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
init();
newThread.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void recordAndPlay() {
short[] lin = new short[SIZE_OF_RECORD_ARRAY];
int num = 0;
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
record.startRecording();
track.play();
while (true) {
num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
track.write(lin, 0, num);
}
}
public void passStop(View view){
Button playBtn = (Button) findViewById(R.id.playBtn);
// /*
if(!isPlaying){
record.startRecording();
track.play();
isPlaying = true;
playBtn.setText("Pause");
}
if(isPlaying){
record.stop();
track.pause();
isPlaying=false;
playBtn.setText("Pass through");
}
// */
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy(){
newThread.stop();
}
}
Unfortunately, this program stops as soon as I try to run it through eclipse. This is wht I get in the logcat but I am not sure what it all means:
08-19 18:58:43.365: D/AndroidRuntime(27915): Shutting down VM
08-19 18:58:43.365: W/dalvikvm(27915): threadid=1: thread exiting with uncaught exception (group=0x4161f700)
08-19 18:58:43.365: E/AndroidRuntime(27915): FATAL EXCEPTION: main
08-19 18:58:43.365: E/AndroidRuntime(27915): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mypassthrough/com.example.mypassthrough.MainActivity}: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Looper.loop(Looper.java:137)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-19 18:58:43.365: E/AndroidRuntime(27915): at dalvik.system.NativeStart.main(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): Caused by: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.example.mypassthrough.MainActivity.onCreate(MainActivity.java:46)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Activity.performCreate(Activity.java:5133)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-19 18:58:43.365: E/AndroidRuntime(27915): ... 11 more
What could be the reason for this code crashing, and how can it be debugged? I am pretty sure it has something to do with Thread, because my other versions of this code where I have not included Thread at all do not crash on startup.
Variable newThread is not initialized in oncreate() method that's why it is giving nullpointer exception
add this in your init() method it will work
newThread=new Thread();
You are getting a null pointer exception because newThread has not been initialized yet and it is null when you try to start it. The thread doesn't have anything to do also. You should look at implementing a runnable, handler, and timer into your activity instead of a thread.
Use sub class with extending AsyncTask Class
class TestActivity extends AsyncTask <String, Void, String > {
protected String doInBackground(String... urls) {
// execution
}
protected void onPostExecute(String result) {
// post execution
}
protected void onPreExecute() {
super.onPreExecute();
// initial activities
}
}
When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.