Error Playing File: NullPointerException in Android - java

I want to play an mp3 file in android, but i get this error:
java.lang.NullPointerException at HelloAndroid.playMusic
My code below
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.net.Uri;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
public MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
Log.i(DebugTag, "Info about my app na");
}
public void playMusic () {
try {
Uri fileName = Uri.parse("http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3");
mp= MediaPlayer.create(this, fileName);
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
What will i do to fix this error?
Thanks
UPDATE
package com.bestvalue.hello;
/*import android.util.Log;*/
import android.app.Activity;
//import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.media.AudioManager;
import android.media.MediaPlayer;
public class HelloAndroid extends Activity {
public static final String DebugTag = "LogInfo";
private MediaPlayer mp = new MediaPlayer();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("keke napep");
playMusic();
setContentView(tv);
}
public void playMusic () {
try {
String url = "http://www.perlgurl.org/podcast/archives/podcasts/PerlgurlPromo.mp3";
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(url);
mp.prepare();
mp.start();
} catch (Exception e){
Log.e(DebugTag, "Error Playing File", e);
}
}
#Override
protected void onStop() {
if (mp != null) {
mp.stop();
mp.release();
}
super.onStop();
}
}
After implementing some of the answers, i now get this error: java.io.IOException: Prepare Failed .: status = 0x1

add mp.prepare(); before mp.start();

Your issue is you aren't checking mp before you call methods on it. According to the documentation, if MediaPlayer.create fails, it will return null.
Rule of thumb with NullPointerExceptions: go back and check your returns. Something is usually returning null when you aren't expecting it to, and you try to call a method on it. In this case, you aren't calling anything on fileName, so that's safe. You're calling something on mp, so that's probably what's doing you in.
[edit]
Why the audio isn't playing:
You aren't calling setAudioStreamType(AudioManager.STREAM_MUSIC); and the use of URIs in the creation of a MediaPlayer instance is only for locally stored media. Network media needs to have its location set by calling setDataSource(context, uri);.
From the (very good) documentation:
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();`

Related

Create a listener, pass value from a BroadcastReceiver

I'm with some doubt how I can execute one action.
When receive one income call, I want to pass the number for my class it manager the Bluetooth connection with Arduino.
After send the number, I'd like to send it by bluetooth connection
I tried use intent but maybe I am using deprecated version.
Android Api 7.1
Brodcaster Receiver Class
package com.jidea.glass;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class TelephonyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
try {
if (intent != null && intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
//Toast.makeText(context, "Outgoign call", 1000).show();
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
} else {
//get the phone state
String newPhoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
Bundle bundle = intent.getExtras();
if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//read the incoming call number
String phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("PHONE RECEIVER", "Telephone is now ringing " + phoneNumber);
//Toast.makeText(arg0, "Tele disponivel " + phoneNumber, Toast.LENGTH_LONG).show();
if(phoneNumber!=null | phoneNumber.equals("")){
PASS HERE TO BLUETOOTH
}
}
Bluetooth class
package com.jidea.glass;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.UUID;
public class CustomProcess extends AppCompatActivity
{
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//observable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
}
public void isConnected() {//View view
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("Conectado".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
public void haveCall(String Phone) {//View view
Object aLig="Ligação \n"+Phone;
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(aLig.toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(CustomProcess.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Conectado");
isBtConnected = true;
isConnected();
}
progress.dismiss();
}
}
}
First you should create an intent in your BroadcastReceiver and then use LocalBroadcastManager in order to be able to send that intent wherever you want to listen.
val intent = Intent(ACTION)
intent.putExtra("DATA KEY", DATA)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
don't forget to register your broadcast receiver in where you want to listen
LocalBroadcastManager.getInstance(context).registerReceiver(your broadcast receiver instance, IntentFilter(ACTION))
I solved it done a Java Internal Listener with Interface the codes.
package com.jidea.glass;
public interface TelephonyListener
{
/**
* To call this method when new message received and send back
* #param message Message
*/
void callReceived(String message);
}
public class CustomProcess extends AppCompatActivity implements MessageListener, TelephonyListener
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MessageReceiver.bindListener(this);
TelephonyReceiver.bindListener(this);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
#Override
public void messageReceived(String message)
{
Toast.makeText(this, "Nova Mensagem: " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void callReceived(String message) {
Toast.makeText(this , "Tele disponivel " + message, Toast.LENGTH_LONG).show();
haveCall(message);
}
Continues in my class Receiver it extends BroadcastReceiver I Donw
public class TelephonyReceiver extends BroadcastReceiver
{
private static TelephonyListener mListener;
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
}
public static void bindListener(TelephonyListener listener){
mListener = listener;
}

How to play music using MusicPlayService

I'm a student and just started learning java and android(currently using android studio). I have been following a tutorial with video streaming and music streaming. but I'm currently following with music streaming.
Code is fine but the problem is It won't stream the music. Also there's no error showing that I missed something or anything in the program. It is running on the emulator but it just wont play the music.
Below is my code for the MainActivity.java:
package com.name.package.yb;
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
private Button btnPlayStop;
private boolean boolMusicPlaying = false;
Intent myService;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
myService = new Intent(MainActivity.this, MusicPlayService.class);
initViews();
setListeners();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void initViews() {
btnPlayStop = (Button) findViewById(R.id.myButton);
btnPlayStop.setText("Stream Music");
}
private void setListeners() {
btnPlayStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnPlayStopClick();
}
});
}
private void btnPlayStopClick() {
if (!boolMusicPlaying) {
btnPlayStop.setText("Pause Streaming");
playAudio();
boolMusicPlaying = true;
} else {
if(boolMusicPlaying){
btnPlayStop.setText("Play Stream");
stopPlayService();
boolMusicPlaying = false;
}
}
}
private void stopPlayService() {
try {
stopService(myService);
} catch (Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
boolMusicPlaying = false;
}
private void playAudio() {
try {
startService(myService);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getClass().getName() + " " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
And My Service named MusicPlayService.java (I want to play the music in background like the music player on phone):
package com.name.package.yb;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;
public class MusicPlayService extends Service {
private MediaPlayer mediaPlayer = new MediaPlayer();
private static final String AUDIO_STRING = "http://musicsite.streammusic.com/file";
#Override
public void onCreate(){
super.onCreate();
//mediaPlayer.setOnCompletionListener(this);
//mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setVolume(100,100);
//mediaPlayer.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(AUDIO_STRING);
// Prepare mediaplayer
mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
public IBinder onBind(Intent arg0) {
return null;
}
public IBinder onUnBind(Intent arg0) {
return null;
}
}
P.S apk was succefully installed in the emulator and button is clickable. It just wont' play the music.
Your code seems fine, perhaps do you add service to your Manifest?
<service android:enabled="true" android:name=".MusicPlayService" />
[
Welcome to programming in Android, the best way to debug Android Code is by adding logs to your codes. You can use Log.d, Log.e etc to print the value of the variable pass by methods.
]
try this out:
1: the code
mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();
you can try
mediaPlayer.setDataSource(AUDIO_STRING);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
You also need to permission for INTERNET if you play music online or READ_EXTERNAL_STORAGE if you play music from memory.

After 'takePicture' call, 'onPictureTaken' response is dependent on location in app...why?

I'm trying to build an app which will periodically call the Camera to take a picture and save it.
My problem is that unless I put the 'takePictuce' call in the 'onCreate' the response to 'takePicture' (onPictureTaken) is never called.
I've broken down the app as simply as possible to illustrate.
if a class to handle the camera is partially defined as:
public class CameraHandler {
private Camera mCamera;
public CameraHandler(){
mCamera = Camera.open();
mCamera.setPreviewTexture(new SurfaceTexture(10));
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
}
};
Then when I put the following code into MainActivity.java, 'onPictureTaken' IS called when CameraHandler is instantiated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraHandler cameraHandler = new CameraHandler();
}
However, putting the call to instantiate CameraHandler in a click event in the MainActivity.java will NOT call 'onPictureTaken' in response to the takePicture call.
(This snippet is located in MainACtivity.java)
public void onClickListener(View view){
CameraHandler cameraHandler = new CameraHandler();
}
So why is this occurring, and how can I get the call to take a picture in the class where it belongs and not in the 'main' of the program?
All help welcome
Finally figured out how to set the phone to take timed pics without any screen display.
There were 2 main issues I struggled with. First, I wanted to take the pics without displaying to screen. Along those lines, I found an example where they used :
mCamera.setPreviewTexture(new SurfaceTexture(10));
and nothing showed on the screen when using this preview method. It appears that some sort of preview is required. Another method was to set the preview to 1 pixel. This method had examples online which appeared to work as well, but I did not try it.
The second and bigger problem had to do with 'onPictureTaken' method. This method processes your picture after the 'takePicture' call.
It seemed that no matter what looping method I used, or where in the code the call to 'takePicture' was located, all of the 'onPictureTaken' methods were queued up and called one after another once the parent of the 'takePicture' caller ended.
Although the picture data processed by onPictureTaken were in a proper time sequence, I could see that having several hundred pics stored and waiting to process could cause problems, and a method needed to be found where on pic was processed and stored before the next pic was taken.
Along those lines, I stumbled upon the AlarmManager and coupled that with the BroadcastReceiver and Future classes to solve the problem.
What I've done is set the alarmManger to go off at a set time or time frequency. The BroadcaseReceiver captures this call & in turn calls a method which creates
a thread where a 'Future' object makes the call to take a picture.
'Future' object is nice, because it will wait for the physical camera to take the picture (takePicture) and then process it (onPictureTaken). This all occurs in one thread, then terminates. So no queuing of pics to process and each picture sequence is handled separately.
Code is contained below. Note that some of the default 'Overrides' have been left out to save space. Also, the visible screen was basically a button which captured the click event...very basic.
MainActivity.java:
package myTest.com.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MainActivity extends Activity {
CameraHandler cameraHandler;
public BroadcastReceiver br;
public PendingIntent pi;
public AlarmManager am;
final static private long LOOPTIME = 20000;
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
try{
cameraHandler = new CameraHandler();
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
//Toast.makeText(c, "Taking a pic!", Toast.LENGTH_LONG).show();
TryAThread();
}
};
registerReceiver(br, new IntentFilter("com.timedActivity.activity") );
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.timedActivity.activity"), 0);
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
catch (Exception e){ }
}
private void TryAThread() {
try{
CameraCaller cameraCaller = new CameraCaller(cameraHandler);
Future future = threadpool.submit(cameraCaller);
while (!future.isDone()) {
try {
Thread.sleep(5000);
} catch (Exception ex) { }
}
}
catch (Exception e){ }
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
public void onClickListener(View view){
try{
am.setRepeating(am.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), LOOPTIME, pi);
}
catch (Exception e){ }
}
}
CameraCaller.java:.
package myTest.com.test;
import java.util.concurrent.Callable;
public class CameraCaller implements Callable {
private CameraHandler cameraHandler;
public CameraCaller(CameraHandler ch){
cameraHandler = ch;
}
#Override
public Object call() throws Exception {
cameraHandler.takeAPic();
return true;
}
}
CameraHandler.java:.
package myTest.com.test;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import junit.runner.Version;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){
}
public Boolean takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) {Log.e(Version.id(), e1.getMessage());
}
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
return true;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
try {
Thread.sleep(2000);
}catch (Exception ex){}
}
public static File getOutputMediaFile() {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File mediaStorageDir = new File(file, "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}

android when url audio streaming, music didn't stop

Codes in below. when i add mediaplayer.stop();, media player hasn't stop. same thing for mediaplayer.pause(); if works. because icon is changing. But music hasn't stop. And i can't do debuging in android studio. Thanksi in advance.
package ceyhun.musicpuzzle.com;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
Button PlayPause;
private boolean boolMusicPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Baslamak();
}
private void Baslamak() {
PlayPause = (Button)findViewById(R.id.PlayPause);
PlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oynatim();
}
});
}
private void oynatim() {
final MediaPlayer mediaPlayer = new MediaPlayer();
if (!boolMusicPlaying) {
boolMusicPlaying = true;
PlayPause.setBackgroundResource(R.drawable.ic_action_pause);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getString(R.string.rihanna));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Baslamak();
}
else {
mediaPlayer.stop();
//there is a problem. music hasn't stop.
mediaPlayer.reset();
PlayPause.setBackgroundResource(R.drawable.ic_action_play);
boolMusicPlaying = false;
Baslamak();
}
}
}
Each time you run the "oynatim" method, you're instantiating a new class.
final MediaPlayer mediaPlayer = new MediaPlayer();
The line above should only be run once and not every time the method is run. I ran into the same problem when using Android Studio.
On a side note, you have to call mediaPlayer.prepare() or mediaPlayer.prepareAsync() if you want to get mediaPlayer out of a "stopped" states. This happens when you call mediaPlayer.stop().
Edit: Put the final MediaPlayer in the class and not the methods.
private void stopPlaying {
if ( mediaPlayer != null ) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
mediaPlayer is the instance of MediaPlayer in android that you first assign your URL and start play music :)

android.app.SuperNotCalledException: Activity did not call through to super.onCreate()

Here is my Android Media player code. I don't know what I am missing in this code, when I run with breakpoint at line MediaPlayer mp = new MediaPlayer() in Debug mode. All the files in zip folder is played. But when I run the application in normal mode the first file is played and then I get this error:
android.app.SuperNotCalledException: Activity {com.example.mediaplayer/com.example.mediaplayer.MainActivity} did not call through to super.onCreate()
Code:
package com.example.mediaplayer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
//final String file_loc= Environment.getExternalStorageDirectory().toString();
//Log.i("location",file_loc);
ZipFile zip = new ZipFile("/storage/emulated/0/AjeshDocument/sample.zip");
for(int i=1;i<7;i++){
ZipEntry entry = zip.getEntry("sample/rihanna_"+i+".mp3");
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
File f = tempFile;
try {
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
MediaPlayer mp = new MediaPlayer();
FileInputStream fis = new FileInputStream(f);
mp.setDataSource(fis.getFD());
mp.prepare();
//mp.setLooping(false);
mp.start();
//mp.stop();
// mp.release();
Log.i(MAIN_TAG,"Pronounciation finished!");
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
catch (IOException e)
{
Log.i(MAIN_TAG,e.toString());
}
}
else {
// no such entry in the zip
}
} //for end
mp.release();
}
catch (Exception e) {
// handle your exception cases...
Log.i(MAIN_TAG,e.toString());
}
}
#Override
protected void onResume() {
Log.w("Info", "App Resume");
super.onResume();
}
#Override
protected void onStop() {
Log.w("Info", "App stopped");
super.onStop();
}
#Override
protected void onDestroy() {
Log.w("Info", "App destoryed");
super.onDestroy();
}
}
You didn't call the Activity's onCreate() method, i.e the super class' one. Add the call to MainActivity's onCreate() method:
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // this line is missing
// your code below ...

Categories